CACS204 Object Oriented Programming in Java

Object Oriented Programming in JavaUnit 18 min read

Java Basics: Setup, Syntax, and First Programs

Unit 1 of Object Oriented Programming in Java covers the foundational concepts of Java programming: its history, features, installation, basic syntax, writing and executing programs, and understanding the Java Development Kit (JDK) and Java Runtime Environment (JRE). This note includes hands-on examples, IDE setup, and


1. Introduction to Java Programming

Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now Oracle) in 1995. It is widely used for web applications, mobile apps, enterprise software, and Android development.

Key Features of Java

Java’s design principles make it powerful and versatile:

  • Platform Independence: "Write Once, Run Anywhere" (WORA) via bytecode and the Java Virtual Machine (JVM).
  • Object-Oriented: Everything in Java is an object (even primitives are wrapped in objects).
  • Robust & Secure: Strong memory management, exception handling, and no pointers (only references).
  • Multithreading Support: Built-in support for concurrent programming.
  • Automatic Memory Management: Uses Garbage Collection (GC) to free unused memory.
mindmap
  root((Java Features))
    Platform Independence
      Bytecode
      JVM
    Object-Oriented
      Classes & Objects
      Inheritance
      Polymorphism
    Robust & Secure
      Exception Handling
      No Pointers
    Multithreading
      Threads & Synchronization
    Automatic Memory Management
      Garbage Collection

2. Java Development Kit (JDK) vs. Java Runtime Environment (JRE)

JDK (Java Development Kit) JRE (Java Runtime Environment)
Includes compiler (javac), debugger, and development tools. Only includes JVM and libraries needed to run Java programs.
Required for developers to write and compile code. Required for end-users to run Java applications.
Contains bin, lib, include, and demo folders. Contains bin (JVM) and lib (class libraries).
Example: jdk-17.0.1 Example: jre-17.0.1

3. Writing and Executing a Java Program

Step-by-Step Process

  1. Write Code in a .java file (e.g., HelloWorld.java).
  2. Compile using javac (generates .class bytecode).
  3. Run using java (executes bytecode via JVM).
// Example: HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Compilation & Execution Commands:

javac HelloWorld.java   # Compiles to HelloWorld.class
java HelloWorld         # Runs the program

State After Compilation

graph LR
    A["HelloWorld.java"] -->|"javac"| B["HelloWorld.class"]
    B -->|"JVM"| C["Output: 'Hello, World!'"]

4. Basic Java Syntax Rules

Structure of a Java Program

// 1. Package declaration (optional)
package com.example;

// 2. Import statements (optional)
import java.util.*;

// 3. Class definition (public class must match filename)
public class MyProgram {
    // 4. Main method (entry point)
    public static void main(String[] args) {
        // 5. Code execution starts here
        System.out.println("Java is fun!");
    }
}

Key Syntax Rules

  • Case-Sensitive: System ≠ system.
  • Class Name Must Match Filename: MyProgram.java → public class MyProgram.
  • main Method Signature: Must be public static void main(String[] args).
  • Braces {}: Required for classes, methods, and blocks.
  • Semicolons ;: Terminate statements.

5. Common Errors and Fixes

Error Cause Solution
javac: command not found JDK not installed or not in PATH. Install JDK and add to PATH.
Class names, 'public', 'static', 'void', or 'String' must be defined Missing public class or main method. Ensure correct class and method structure.
HelloWorld.java:1: error: class, interface, or enum expected File not saved or incorrect filename. Save file with .java extension.
Exception in thread "main" java.lang.NoClassDefFoundError .class file missing or incorrect class name. Compile first (javac) and run with correct class name (java ClassName).
SyntaxError: missing ;0RuntimeException: NullPointer1LogicError: incorrect loop2
Three common Java error types with brief descriptions

## In the Real World

  1. eSewa (Nepal)

    • Java’s Platform Independence: eSewa’s backend services run on Java-based servers (e.g., Spring Boot), allowing seamless integration across different devices (web, mobile, ATMs).
    • Multithreading: Handles thousands of transactions per second using Java’s concurrent programming features.
  2. Khalti (Nepal)

    • Security & Robustness: Khalti’s payment gateway uses Java for secure transaction processing, leveraging exception handling to manage failed payments gracefully.
    • JDBC for Databases: Connects to databases (MySQL, PostgreSQL) using Java Database Connectivity (JDBC) for real-time balance updates.
  3. Android Apps (Global)

    • Java/Kotlin for Android: Most Android apps (e.g., WhatsApp, YouTube, Google Maps) use Java for backend logic, UI components (via Android SDK), and multithreading for smooth performance.
    • Example: A Pathao driver app uses Java to manage real-time location updates (via GPS) and ride queues (using Queue data structures).

## Worked Example: Bank Interest Calculator

Scenario: A bank in Nepal offers 8% annual interest on fixed deposits. Write a Java program to calculate the maturity amount after n years.

import java.util.Scanner;

public class BankInterestCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter principal amount: ");
        double principal = scanner.nextDouble();

        System.out.print("Enter years: ");
        int years = scanner.nextInt();

        double rate = 0.08; // 8% interest
        double maturityAmount = principal * Math.pow(1 + rate, years);

        System.out.printf("Maturity amount after %d years: %.2f", years, maturityAmount);
    }
}

Trace for Input: Principal = 100,000 NPR, Years = 5

Step Action Variable Values Output
1 principal = 100000 principal = 100000 "Enter principal amount: "
2 years = 5 years = 5 "Enter years: "
3 rate = 0.08 rate = 0.08 (No output)
4 maturityAmount = 100000 * (1.08)^5 maturityAmount = 146933.00 "Maturity amount after 5 years: 146933.00"

Visualization of Compound Interest Formula:

0.511.522.533.544.55yMaturity Amount = P*(1+r)^tP = 100,000A = 146,933
Compound interest growth over 5 years (P=100,000 NPR, r=8%)

## Exam Tip

  1. JDK vs. JRE: Always distinguish between development (JDK) and runtime (JRE). Exam questions may ask for the correct tool to use.
  2. Compilation vs. Execution:
    • javac → Compiles .java to .class.
    • java → Runs .class files.
    • Common mistake: Forgetting to compile (javac) before running (java).
  3. Syntax Strictness: Java is case-sensitive and requires exact method signatures (e.g., main must be public static void).
  4. Error Handling: If a program fails, check:
    • Is the class name correct?
    • Is the .class file generated?
    • Are all braces {} closed?
  5. Real-World Applications: Relate Java basics to eSewa (transactions), Khalti (security), or Android apps (multithreading) in short-answer questions.

Practice Question: Write a Java program that takes a student’s name and marks (out of 100) and prints "Pass" if marks ≥ 40, else "Fail". Use Scanner for input.

Solution:

import java.util.Scanner;

public class StudentResult {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter student name: ");
        String name = scanner.nextLine();
        System.out.print("Enter marks: ");
        int marks = scanner.nextInt();

        if (marks >= 40) {
            System.out.println(name + " Pass");
        } else {
            System.out.println(name + " Fail");
        }
    }
}

Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 1.

Discussion

Loading…