IT234 Object Oriented Programming with Java

Object Oriented Programming with JavaUnit 110 min read

Java Basics: Syntax, Structure & First Program

Unit 1 of Object Oriented Programming with Java covers Java’s history, setup, basic syntax, data types, variables, operators, control structures, and writing your first program—essential foundations for all OOP concepts.

TAKEAWAYS:

  • Java is a platform-independent, object-oriented language with strict syntax rules and a "write once, run anywhere" philosophy via the JVM.
  • A Java program must start with a class containing a main() method, which is the entry point for execution.
  • Data types (primitive and reference) and operators define how variables store and manipulate data.
  • Control structures (if-else, loops) dictate program flow based on conditions or repetition.
  • Comments (//, /* */) improve code readability and documentation.
  • Compilation (javac) and execution (java) are two distinct steps in Java programming.

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 follows the "Write Once, Run Anywhere" (WORA) principle, meaning Java code can run on any device with a Java Virtual Machine (JVM).

Key Features of Java:

Feature Description
Platform Independence Java bytecode runs on any OS with a JVM (Windows, Linux, macOS, etc.).
Object-Oriented Everything in Java is an object (e.g., String, Scanner).
Strong Memory Management Automatic garbage collection removes unused objects.
Multithreading Supports concurrent execution (useful in apps like Pathao for ride requests).
Robust & Secure Strong type-checking and no explicit pointers reduce errors.

Java Virtual Machine architectureHow Java bytecode runs on different OS via JVM (Image: Dcoetzee (File:Computer-blue.svg by OpenClipart, File:Phone-, CC0, via Wikimedia Commons)


2. Setting Up Java Environment

To write and run Java programs, you need:

  1. Java Development Kit (JDK) – Download from Oracle or OpenJDK.
  2. Text Editor/IDE – Notepad++, VS Code, Eclipse, or IntelliJ IDEA.
  3. Command Prompt/Terminal – For compiling (javac) and running (java) programs.

Steps to Run a Java Program:

  1. Write code in a file (e.g., Hello.java).
  2. Compile:
    javac Hello.java
    
    → Generates Hello.class (bytecode).
  3. Run:
    java Hello
    
    → Executes the program.

Why Compilation?

  • Java is not interpreted like Python; it compiles to bytecode first.
  • The JVM executes bytecode, ensuring platform independence.

3. Basic Java Syntax & Structure

Every Java program must follow this structure:

// Single-line comment
/*
   Multi-line comment
*/
public class Main {          // Class name must match filename (Main.java)
    public static void main(String[] args) {  // Entry point
        System.out.println("Hello, World!");  // Statement ends with ;
    }
}

Key Components:

  • class – Blueprints for objects (e.g., Car, BankAccount).
  • main() method – Execution starts here (must be public static void).
  • System.out.println() – Prints output to the console.
  • ; (semicolon) – Ends every statement.

4. Variables & Data Types

Java supports two types of data:

  1. Primitive Data Types (fixed size, stored directly in memory):

    Type Size (bits) Example Values Default Value
    byte 8 -128 to 127 0
    short 16 -32,768 to 32,767 0
    int 32 -2B to 2B 0
    long 64 -9E18 to 9E18 0L
    float 32 3.4e-038 to 3.4e+038 0.0f
    double 64 1.7e-308 to 1.7e+308 0.0d
    char 16 Unicode (e.g., 'A', '₹') '\u0000'
    boolean 1 true/false false
  2. Reference Data Types (objects, stored in heap memory):

    • String, Array, Class objects (e.g., String name = "Ram";).

Variable Declaration & Initialization:

int age = 25;          // Primitive
String name = "Hari";  // Reference (String is a class)

Why int over long?

  • Use int for general counting (faster, less memory).
  • Use long for large numbers (e.g., NEPSE stock prices in billions).

5. Operators in Java

Operators perform operations on variables and values.

Category Operators Example
Arithmetic +, -, *, /, % int sum = 10 + 5;
Relational ==, !=, >, <, >=, <= if (age >= 18) { ... }
Logical && (AND), `
Assignment =, +=, -=, *=, /= x += 5; (same as x = x + 5)
Bitwise &, ` , ^, ~`, <<, >>

Example: Compound Assignment

int x = 10;
x += 5;  // x = x + 5 → x = 15

6. Control Structures

A. Decision Making (if-else)

int marks = 85;
if (marks >= 90) {
    System.out.println("Grade: A");
} else if (marks >= 80) {
    System.out.println("Grade: B");
} else {
    System.out.println("Grade: C");
}

Mermaid Diagram:

flowchart TD
    A["Start"] --> B{"marks >= 90?"}
    B -->|"Yes"| C["Print 'A'"]
    B -->|"No"| D{"marks >= 80?"}
    D -->|"Yes"| E["Print 'B'"]
    D -->|"No"| F["Print 'C'"]

B. Loops

  1. for loop (known iterations):
    for (int i = 1; i <= 5; i++) {
        System.out.println("Iteration: " + i);
    }
    
  2. while loop (unknown iterations):
    int i = 1;
    while (i <= 5) {
        System.out.println("While loop: " + i);
        i++;
    }
    
  3. do-while loop (executes at least once):
    int j = 1;
    do {
        System.out.println("Do-while: " + j);
        j++;
    } while (j <= 5);
    

Real-World Example: Daraz Order Processing

  • A for loop checks each order in a queue and updates stock.
  • A while loop waits for payment confirmation before dispatch.

7. Writing Your First Java Program

Example: Simple Calculator

import java.util.Scanner;  // For user input

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);  // Create Scanner object
        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();
        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();

        System.out.println("Sum: " + (num1 + num2));
        System.out.println("Product: " + (num1 * num2));
    }
}

Trace Table:

Step Action num1 num2 Output
1 scanner.nextInt() 10 - Waits for user input
2 User enters 10 10 - -
3 scanner.nextInt() 10 5 Waits for second input
4 User enters 5 10 5 -
5 System.out.println(num1 + num2) 10 5 Prints Sum: 15

Real-World Tie-In: Khalti Payment App

  • Uses Scanner-like input handling for PIN entry.
  • if-else checks validate transactions (e.g., sufficient balance).

8. Comments in Java

Comments improve readability and are ignored by the compiler.

// Single-line comment
/*
   Multi-line comment
   Used for explanations or disabling code blocks.
*/
public class Example {
    public static void main(String[] args) {
        // This prints "Hello"
        System.out.println("Hello, Java!");  // Ends with semicolon
    }
}

In the Real World

  1. eSewa (Nepal)

    • Uses Java’s multithreading to handle multiple payment requests simultaneously (e.g., electricity bill payments).
    • Control structures validate user inputs (e.g., checking if the phone number matches the account).
  2. Pathao (Ride-Hailing App)

    • Arrays/Loops manage ride requests in a queue (FIFO order).
    • if-else checks driver availability before assigning a ride.
  3. Ncell Recharge System

    • switch-case (covered later) routes calls to different recharge menus (e.g., 1 for talk-time, 2 for data).
    • Exception handling (Unit 6) manages invalid PIN entries.

Exam Tip

  1. Syntax is Strict – Miss a semicolon (;) or brace (})? Compilation error.

    • Always check for:
      • public class declaration.
      • main() method signature (public static void main(String[] args)).
      • Proper indentation (not required but helps grading).
  2. Trace Tables Are Key – For loops and conditionals, show step-by-step variable changes (like the Calculator trace above). Examiners love this!

  3. Common Pitfalls:

    • Forgetting import java.util.Scanner; → Error: Scanner not recognized.
    • Using == for String comparison → Wrong: Use .equals() instead.
      String a = "Hello";
      String b = "Hello";
      System.out.println(a == b);  // true (same reference in memory)
      System.out.println(a.equals(b));  // true (correct way)
      
  4. Practical Questions – Expect:

    • Write a program to check if a number is prime (use loops).
    • Calculate simple interest (formula: P * R * T / 100).
    • Print a pattern (e.g., pyramid using nested loops).
  5. Diagrams Help – For control flow, draw flowcharts (like the if-else example above). Even if not asked, it clarifies logic.


Final Note: Master the basic syntax, variables, and control structures—they form the backbone of all Java programs. Practice writing small programs (e.g., calculator, grade checker) to build confidence. Good luck!

Based on the TU BIM syllabus for Object Oriented Programming with Java (IT234), unit 1.

Discussion

Loading…