Skip to content
IT-306 · Java Programming Lab/Quick Revision Short Notes

Java Programming Lab (IT-306) - Unit 1 Short Notes

UNIT 1: FOUNDATIONS OF JAVA PROGRAMMING & BASIC SYNTAX


1.1 Introduction to Java and the Programming Environment

What is Java?

  • A high-level, platform-independent, object-oriented programming language.

  • Platform Independence: Achieved via the Java Virtual Machine (JVM). Java code (*.java) is compiled to bytecode (*.class), which runs on any JVM.

  • JRE (Java Runtime Environment): Contains JVM + libraries needed to run Java applications.

  • JDK (Java Development Toolkit): Contains JRE + development tools (like javac compiler) to develop Java applications.

Key Features:

Feature Description
Simple Syntax similar to C/C++, but eliminates complex features like pointers.
Secure Bytecode verification, no explicit pointers, runtime security checks.
Portable Bytecode runs on any OS with a JVM (Write Once, Run Anywhere).
Object-Oriented Everything is an object (except primitives). Supports classes, inheritance, etc.
Robust Strong memory management, exception handling, type checking.
Multithreaded Built-in support for concurrent programming.

Setting up the Development Environment:

  1. Install JDK: Download from Oracle/OpenJDK. Verify with java -version and javac -version.

  2. Set Environment Variables:

    • JAVA_HOME: Points to JDK installation directory.

    • PATH: Includes %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Linux/Mac) to run java/javac from any directory.

  3. IDE vs. Text Editor:

    • IDEs (Eclipse, IntelliJ IDEA, VS Code): Provide code completion, debugging, project management. Better for large projects.

    • Text Editor + Command Line: Lightweight, helps understand the compile-run process deeply.

[!TIP] EXAM TIP

  • JVM is instance-dependent (one per running program), JRE is machine-dependent, JDK is developer-dependent.
  • javac compiles source to bytecode. java executes bytecode by invoking JVM.

The Java Programming Process:


Write Source Code (HelloWorld.java)

        ↓

Compile: `javac HelloWorld.java` → Generates HelloWorld.class (bytecode)

        ↓

Run: `java HelloWorld` → JVM executes bytecode → Output


1.2 Structure of a Java Program & First Program

Anatomy of a Java Class:


[public] class ClassName {          // 'class' keyword, file must be ClassName.java

    public static void main(String[] args) { // Entry point

        // Statements

    }

}
  • File Naming: Must match the public class name exactly (case-sensitive).

  • main Method Signature: public static void main(String[] args)

    • public: Accessible by JVM.

    • static: Can be called without creating an object.

    • void: Returns nothing.

    • String[] args: Array to hold command-line arguments.

Hello World Example:


class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }

}

Steps: Save as HelloWorld.java → javac HelloWorld.java → java HelloWorld.

Common Compilation & Runtime Errors:

Error Type Example Cause
Compilation error: class HelloWorld is public, should be declared in a file named HelloWorld.java File name ≠ public class name.
error: cannot find symbol Variable/method name typo or undeclared.
Runtime Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException Accessing invalid array index.
Exception in thread "main" java.lang.NumberFormatException Scanner.nextInt() on non-integer input.

[!TIP] COMMON PITFALL

  • Forgetting ; at statement end.
  • main method signature must be exact (e.g., String args[] is okay, but string[] args is not).
  • Case sensitivity: class ≠ Class.

1.3 Basic Syntax and Language Elements

Comments:

  • Single-line: // comment

  • Multi-line: /* comment */

  • Documentation: /** comment */ (for javadoc tool).

Tokens (Smallest Individual Units):

Token Type Examples
Keywords class, public, static, void, int, if, for (reserved, lowercase).
Identifiers Names for classes, variables, methods (e.g., HelloWorld, myVariable).
Literals Fixed values: 100 (int), 3.14 (double), 'a' (char), "text" (String), true (boolean).
Operators +, -, =, ==, &&
Separators ; (statement end), {} (block), [] (array), () (method call/params).

Statements & Blocks:

  • Statement: Complete instruction ending with ; (e.g., int x = 5;).

  • Block: Group of statements within {} (defines scope).


1.4 Data Types, Variables, and Type Conversion

Primitive Data Types:

Type Size (bits) Range / Description
byte 8 -128 to 127
short 16 -32,768 to 32,767
int 32 \boxed{-2^{31} \text{ to } 2^{31}-1}
long 64 -2^{63} to 2^{63}-1 (suffix L/l, e.g., 1000L)
float 32 Single-precision (suffix F/f, e.g., 3.14F)
double 64 Double-precision (default for decimals)
char 16 Unicode character (e.g., 'a', '\u0041')
boolean 1 true or false

Variables:

  • Declaration: dataType variableName; (e.g., int age;)

  • Initialization: variableName = value; (e.g., age = 25;)

  • Declaration + Init: dataType variableName = value; (e.g., double price = 99.99;)

  • Naming Conventions:

    • Variables/methods: camelCase (e.g., studentName).

    • Constants (final): UPPER_SNAKE_CASE (e.g., MAX_VALUE).

    • Classes: PascalCase (e.g., StudentRecord).

Type Casting:

  • Implicit (Widening): Small type → Large type. Automatic, safe.

    
    int i = 100;
    
    double d = i; // int → double (safe)
    
    
  • Explicit (Narrowing): Large type → Small type. Manual, may lose precision/data.

    
    double d = 99.99;
    
    int i = (int) d; // double → int, i = 99 (fraction lost)
    
    

Scanner Class for Input:


import java.util.Scanner;

Scanner sc = new Scanner(System.in);

int num = sc.nextInt();     // Reads integer

String str = sc.next();     // Reads single word (space-delimited)

String line = sc.nextLine(); // Reads entire line (including spaces)

[!TIP] CRITICAL PITFALL

  • nextInt()/next() does not consume the newline (\n). A subsequent nextLine() will read the leftover newline as empty input. Fix: Use an extra sc.nextLine(); after nextInt() to consume the newline.

1.5 Operators and Expressions

Operator Categories:

Category Operators Example
Arithmetic +, -, *, /, % (modulo) 10 % 3 = 1
Relational ==, !=, >, <, >=, <= 5 > 3 → true
Logical && (AND), `
Assignment =, +=, -=, *=, /=, %= x += 5; (x = x + 5)
Increment/Decrement ++, -- i++ (postfix), ++i (prefix)

Prefix vs. Postfix Increment:


int i = 5;

int a = i++; // a = 5 (old value), i = 6

int b = ++i; // i = 7 (incremented first), b = 7

Operator Precedence (Highest to Lowest):

  1. (), [], .

  2. ++, --, ! (unary)

  3. *, /, %

  4. +, -

  5. >, <, >=, <=

  6. ==, !=

  7. &&

  8. ||

  9. =, +=, etc.

Use parentheses () to override precedence and improve readability.


1.6 Control Flow Statements

Decision Making:

  • if: Executes block if condition is true.

    
    if (score >= 50) { System.out.println("Pass"); }
    
    
  • if-else: Executes one of two blocks.

  • if-else-if ladder: Checks multiple conditions sequentially.

  • switch: Efficient for multiple int, char, String (Java 7+), enum values.

    
    switch (day) {
    
        case 1: System.out.println("Mon"); break; // 'break' prevents fall-through
    
        case 2: System.out.println("Tue"); break;
    
        default: System.out.println("Invalid");
    
    }
    
    

Looping:

Loop Use Case Syntax
for Known iterations for(int i=0; i<n; i++) { ... }
Enhanced for Traverse arrays/collections for(type var : array) { ... }
while Pre-test loop (may execute 0 times) while(condition) { ... }
do-while Post-test loop (executes at least once) do { ... } while(condition);

Branching Statements:

  • break: Exits innermost loop or switch.

  • continue: Skips current iteration, proceeds to next.

  • return: Exits the current method, optionally returns a value.

[!TIP] EXAM COMPARISON

  • Use for when iteration count is known (e.g., array traversal).
  • Use while/do-while when condition depends on runtime input.
  • do-while guarantees at least one execution.

1.7 Arrays (Single-Dimensional)

Declaration, Creation, Initialization:


int[] arr1;                 // Declaration

arr1 = new int[5];          // Creation (size=5, default values=0)

int[] arr2 = {10, 20, 30};  // Declaration + Init with values

int[] arr3 = new int[]{1,2,3}; // Alternate init

Access & Bounds:

  • Indexing: arr[0] (first element), arr[arr.length-1] (last).

  • ArrayIndexOutOfBoundsException: Occurs if index < 0 or >= length.

Traversal:


// Traditional for loop (with index)

for (int i = 0; i < arr.length; i++) {

    System.out.println(arr[i]);

}

// Enhanced for loop (no index)

for (int val : arr) {

    System.out.println(val);

}

Common Operations:

  • Sum/Average:

    
    int sum = 0;
    
    for (int val : arr) sum += val;
    
    double avg = (double) sum / arr.length;
    
    
  • Min/Max: Initialize min = arr[0], max = arr[0], then loop to compare.

  • Linear Search: Loop through array, compare each element with target. Return index if found, else -1. Time Complexity: O(n).

  • Reversing: Swap arr[i] with arr[n-1-i] for i from 0 to n/2.

Command-Line Arguments (String[] args):

  • Arguments passed when running: java MyProgram arg1 arg2

  • Accessed inside main: args[0] = "arg1", args[1] = "arg2".

  • args.length gives number of arguments.

[!TIP] ARRAY FUNDAMENTALS

  • Array length is fixed after creation (arr.length is final).
  • All elements are default-initialized (0 for int, 0.0 for double, false for boolean, null for objects).
  • Arrays are objects stored in heap memory. The variable holds a reference to the array.

1.8 Practical Lab Exercises & Mini-Projects

Core Exercises:

  1. Environment Setup: Install JDK, set PATH, compile/run HelloWorld.java from command line.

  2. Simple Calculator: Use Scanner to read two numbers and an operator (+, -, *, /), perform operation, handle division by zero.

  3. Number Guessing Game: Generate random number (using Math.random() or Random class), user guesses with loop until correct, give "higher/lower" hints.

  4. Number Checks:

    • Prime: Check divisibility from 2 to √n.

    • Palindrome (number/string): Reverse and compare.

    • Armstrong: Sum of digits raised to power of total digits equals number.

  5. Array Manipulation:

    • Sorting: Implement Bubble Sort (O(n²)) or Selection Sort (O(n²)).

    • Reversing: In-place swap.

    • Searching: Linear search (O(n)).

  6. Student Grade Management:

    • Store marks of n students in array.

    • Calculate average, highest, lowest.

    • Count students above/below average.

Mini-Project Idea:

  • Contact Management System: Use parallel arrays (or later, objects) for names, phones. Provide menu-driven options to Add, Display, Search, Delete contacts using array traversal and shifting.

[!TIP] LAB EXAM STRATEGY

  • Always validate input (e.g., check for negative array size, non-numeric input).
  • Modularize: Break problem into methods (e.g., int findMax(int[] arr)).
  • Test edge cases: Empty array, single element, duplicate values, zero/negative inputs.
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in