CMP228 Advanced Programming with Java

Advanced Programming with JavaUnit 19 min read

Java Fundamentals: Syntax, Compilation, OOP Basics, and Core APIs

Unit 1 of Advanced Programming with Java: This note covers Java’s syntax, structure, compilation process, core data types, operators, control flow, and introduction to object-oriented programming concepts (classes, objects, and basic APIs) with practical examples and visualizations.

TAKEAWAYS:

  • Understand Java’s syntax, structure, and compilation process (source → bytecode → JVM execution).
  • Master primitive data types, variables, and operators with practical examples.
  • Learn control flow (loops, conditionals) and their real-world applications in algorithms.
  • Introduce OOP concepts (classes, objects, constructors) with visual diagrams.
  • Explore core Java APIs (e.g., Math, String) and their use in real-world apps.
  • Write and debug Java programs using IDEs like IntelliJ or Eclipse.

1. Introduction to Java

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

Key Features of Java

mindmap
  root((Java Features))
    PlatformIndependence
    ObjectOriented
    StronglyTyped
    Multithreaded
    Robust
    Secure
    Portable

Java’s Execution Model

Java programs are compiled into bytecode (.class files) and executed by the Java Virtual Machine (JVM). This ensures write once, run anywhere (WORA).

flowchart TD
    A["Source Code (.java)"] -->|"Compiled by javac"| B["Bytecode (.class)"]
    B -->|"Loaded by JVM"| C["JVM Execution"]
    C --> D["Output"]

2. Java Syntax and Structure

Java programs consist of classes, which contain methods and variables.

Basic Structure of a Java Program

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Key Components:

  • public class: Defines a class (filename must match class name).
  • public static void main(String[] args): Entry point of the program.
  • System.out.println(): Prints output to the console.

3. Data Types and Variables

Java supports primitive and non-primitive (reference) data types.

Primitive Data Types

Type Size (bits) Range Example
byte 8 -128 to 127 byte b = 100;
short 16 -32,768 to 32,767 short s = 500;
int 32 -2³¹ to 2³¹-1 int i = 1000;
long 64 -2⁶³ to 2⁶³-1 long l = 1000L;
float 32 ~3.4e-38 to 3.4e+38 float f = 3.14f;
double 64 ~1.7e-308 to 1.7e+308 double d = 3.14;
char 16 Unicode characters char c = 'A';
boolean 1 true or false boolean b = true;

Non-Primitive (Reference) Types

  • Strings (String), arrays (int[]), objects (Object).

4. Operators in Java

Java supports arithmetic, relational, logical, bitwise, and assignment operators.

Arithmetic Operators

Operator Example Description
+ a + b Addition
- a - b Subtraction
* a * b Multiplication
/ a / b Division (integer division)
% a % b Modulus (remainder)
++ a++ Increment
-- a-- Decrement

Relational Operators

Operator Example Description
== a == b Equal to
!= a != b Not equal to
> a > b Greater than
< a < b Less than
>= a >= b Greater than or equal to
<= a <= b Less than or equal to

Logical Operators

Operator Example Description
&& a && b Logical AND
|| a || b Logical OR
! !a Logical NOT

5. Control Flow Statements

Java uses conditionals (if-else, switch) and loops (for, while, do-while) for decision-making and iteration.

If-Else Statement

int num = 10;
if (num > 0) {
    System.out.println("Positive");
} else if (num < 0) {
    System.out.println("Negative");
} else {
    System.out.println("Zero");
}

Switch Statement

int day = 3;
switch (day) {
    case 1: System.out.println("Monday"); break;
    case 2: System.out.println("Tuesday"); break;
    case 3: System.out.println("Wednesday"); break;
    default: System.out.println("Invalid day");
}

Loops

flowchart TD
    A["Start"] --> B{"Condition"}
    B -->|"True"| C["Execute Loop Body"]
    C --> D["Increment/Decrement"]
    D --> B
    B -->|"False"| E["End"]

Example: For Loop

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Example: While Loop

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

6. Introduction to Object-Oriented Programming (OOP)

OOP is a paradigm that organizes code into objects (instances of classes) and methods (functions).

Key OOP Concepts

  1. Class: Blueprint for objects.
  2. Object: Instance of a class.
  3. Constructor: Special method to initialize objects.
  4. Inheritance: Mechanism to reuse code.
  5. Polymorphism: Ability to take many forms.
  6. Encapsulation: Data hiding.
  7. Abstraction: Hiding complexity.

Example: Class and Object

class Car {
    String model;
    int year;

    // Constructor
    Car(String m, int y) {
        model = m;
        year = y;
    }

    // Method
    void display() {
        System.out.println("Model: " + model + ", Year: " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Car myCar = new Car("Toyota", 2020);
        myCar.display();
    }
}

Output:

Model: Toyota, Year: 2020

7. Core Java APIs

Java provides built-in libraries (APIs) for common tasks.

Math Class

public class MathExample {
    public static void main(String[] args) {
        double sqrt = Math.sqrt(25); // 5.0
        double pow = Math.pow(2, 3); // 8.0
        System.out.println("Square root: " + sqrt);
        System.out.println("Power: " + pow);
    }
}

String Class

public class StringExample {
    public static void main(String[] args) {
        String str = "Hello";
        System.out.println(str.length()); // 5
        System.out.println(str.concat(" World")); // "Hello World"
    }
}

In the Real World

  1. eSewa (Nepal): Uses Java for backend services to process transactions securely. The Math API is used for calculating transaction fees and interest rates.

    • Example: If a user transfers ₹1000, eSewa calculates a 0.5% fee using Math.round(1000 * 0.005).
  2. Khalti (Nepal): Implements Java for payment gateways. The String API is used to validate user input (e.g., email formats) before processing payments.

    • Example: str.matches("^[\\w.-]+@[\\w.-]+\\.[a-z]{2,}$") checks if an email is valid.
  3. Google (Worldwide): Uses Java in backend services like Google Drive. The File I/O API (covered later) is used to manage file storage and retrieval.

    • Example: When a user uploads a file, Java reads/writes data in binary format using FileInputStream and FileOutputStream.

8. Compilation and Execution

Java follows a two-step process:

  1. Compilation: javac converts .java to .class (bytecode).
  2. Execution: java runs the bytecode on the JVM.

Example: Compile and Run

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

9. Debugging and IDEs

  • IntelliJ IDEA and Eclipse are popular IDEs for Java development.
  • Debugging Tools: Breakpoints, step-through execution, and variable inspection.

Exam Tip

  • Focus on:
    • Writing correct Java syntax (classes, methods, loops).
    • Understanding primitive vs. reference types.
    • Implementing simple OOP concepts (classes, objects, constructors).
    • Using core APIs (Math, String) in problems.
  • Common Mistakes:
    • Forgetting semicolons (;).
    • Incorrect variable scoping.
    • Misusing == vs .equals() for objects.
  • Practice:
    • Write small programs (e.g., calculator, grade checker).
    • Debug provided code snippets.
    • Understand the JVM execution flow.

Visual Summary

mindmap
  root((Java Fundamentals))
    SyntaxAndStructure
      ClassesAndMethods
      MainMethod
    DataTypes
      PrimitiveTypes
      ReferenceTypes
    Operators
      Arithmetic
      Relational
      Logical
    ControlFlow
      Conditionals
      Loops
    OOPBasics
      ClassesAndObjects
      Constructors
      Methods
    APIs
      MathClass
      StringClass
    Compilation
      javac
      JVM

Based on the PU BE Computer (PU) syllabus for Advanced Programming with Java (CMP228), unit 1.

Discussion

Loading…