CBSE Class 12 IT (802) — Unit 3: Fundamentals of Java Programming
IT

CBSE Class 12 • Code 802

Unit 3: Java Programming

CBSE Class 12 — Information Technology (Subject Code 802)

Unit 3: Fundamentals of Java Programming

Comprehensive Study Notes with Complete Example Programs & Outputs

Showing all 10 study modules
3.1

Introduction to Java & Program Structure

  • Computer Program & Programming: A computer program is a sequence of instructions given to a computer to accomplish a specific task. Programming is the preparation and writing of these instructions in a high-level language (such as Java, C++, or Python).
  • Java Bytecode & JVM (Platform Independence): Unlike traditional compilers that convert code directly into platform-specific machine code, the Java compiler translates Java source code (.java) into highly optimized Java Bytecode (.class). At runtime, the Java Virtual Machine (JVM) acts as an interpreter that translates Bytecode into native machine code for the host OS (Windows, Linux, or macOS). This makes Java platform-independent and portable.
  • NetBeans IDE Workflow: Projects are created via File > New Project (Ctrl + Shift + N) > Java > Java Application. Saving a file (Ctrl + S) automatically compiles it (Compile on Save). Programs are executed via Run > Run Project (F6) or Run > Run File (Shift + F6).

Anatomy of a Basic Java Program

  • Package Statement: Declares a group of related classes that can share data and code (e.g., package helloworld;).
  • Class Declaration: The public class name must exactly match the .java source filename (e.g., HelloWorld.java defines public class HelloWorld).
  • Comments: Ignored by the compiler. Single-line comments start with // and multi-line comments are enclosed between /* and */.
  • main() Method & Output: Execution begins at public static void main(String[] args). All statements end with a semicolon (;). System.out.println() prints text followed by a newline, whereas System.out.print() keeps the cursor on the same line.
Example Program 3.1: HelloWorld.java (Basic Program Structure & Output)
package helloworld;

/* Multi-line comment: First Java Program */
public class HelloWorld {
    public static void main(String[] args) {
        // Single-line comment
        System.out.println("Hello World");
    }
}

Console Output

Hello World
3.2

Data Types and Variables

  • Variables: Named storage locations in memory whose values can change during program execution. Variables declared inside a method are local variables and are accessible only inside that method.
  • Variable Naming Rules: Must be a single word (no spaces); can begin with a letter, underscore (_), or dollar sign ($); can contain letters, digits, and underscores; cannot be a Java reserved keyword (e.g., int); and are strictly case-sensitive (percentage differs from Percentage).

Java’s 8 Primitive Data Types

Data Type Category Size Usage / Example
byteInteger8-bitSmall whole numbers
shortInteger16-bitMedium whole numbers
intInteger32-bitStandard integers (int total_marks = 400;)
longInteger64-bitLarge integers
floatFloating Point32-bitSingle-precision fractional numbers
doubleFloating Point64-bitDouble-precision decimals (double avg = 86.5;)
charCharacter16-bitSingle character in single quotes (char grade = 'M';)
booleanLogical1-bitStores only true or false

String Variables & Concatenation: Multi-character text is stored using the String class enclosed in double quotes (e.g., String name = "Mayank";). When used with numbers, + performs arithmetic addition; when used with Strings, + concatenates (joins) them together.

Example Program 3.2: PercentageCalculator.java (Variables, Data Types & Operators)
package helloworld;

public class PercentageCalculator {
    public static void main(String[] args) {
        int total_marks = 400;
        double marks_obtained = 346;
        double percentage = 0.0;

        percentage = (marks_obtained / total_marks) * 100;
        System.out.println("Student1's Percentage = " + percentage);

        marks_obtained = 144;
        percentage = (marks_obtained / total_marks) * 100;
        System.out.println("Student2's Percentage = " + percentage);
    }
}

Console Output

Student1's Percentage = 86.5
Student2's Percentage = 36.0
3.3

Operators in Java

1. Arithmetic Operators (Example: int a = 20, b = 30)

Operator Name Description Example Result
+AdditionAdds two operandsa + b50
–SubtractionSubtracts second operand from firsta – b-10
*MultiplicationMultiplies both operandsa * b600
/DivisionReturns integer quotient (truncates decimal)b / a1
%ModulusReturns remainder of divisiona % b20
++IncrementIncreases operand value by 1a++ or ++a21
—DecrementDecreases operand value by 1b– or –b29

2. Relational, Assignment & Logical Operators

Category Operators Purpose & Behavior
Relational ==, !=, >, <, >=, <= Compare two values and return a boolean result (true or false).
Assignment =, +=, -=, *=, /=, %= Assign values. Compound operators perform operation & assign (e.g., a += b means a = a + b).
Logical && (AND), || (OR), ! (NOT) Combine boolean expressions: && is true if both are true; || is true if at least one is true; ! reverses truth value.
3.4

Control Flow Structures

A. Selection Structures (if-else & switch)

  • if, if-else, and Nested if: Evaluates a boolean condition inside parentheses. Executes the if block when true and the optional else block when false. Placing an if-else inside another if or else forms a nested if.
  • switch Statement: Matches a variable or expression (must evaluate to byte, short, int, or char) against multiple constant case labels. Each case ends with break; to exit the switch block. If no case matches, the optional default block runs.
Example Program 3.4(a): NewPercentageCalculator.java (Nested if-else Statement)
package helloworld;

public class NewPercentageCalculator {
    public static void main(String[] args) {
        int total_marks = 400;
        double marks_obtained = 346;
        double percentage = (marks_obtained / total_marks) * 100;

        System.out.println("Student1's Percentage = " + percentage);

        if (percentage >= 40) {
            System.out.println("PASSED");
            if (percentage >= 75) {
                System.out.println("With Distinction!");
            }
        } else {
            System.out.println("FAILED");
        }
    }
}

Console Output

Student1's Percentage = 86.5
PASSED
With Distinction!
Example Program 3.4(b): SwitchDemo.java (Multi-Branch switch Statement)
public class SwitchDemo {
    public static void main(String[] args) {
        int today = 5;
        String day = "";

        switch (today) {
            case 1: day = "Monday"; break;
            case 2: day = "Tuesday"; break;
            case 3: day = "Wednesday"; break;
            case 4: day = "Thursday"; break;
            case 5: day = "Friday"; break;
            case 6: day = "Saturday"; break;
            case 7: day = "Sunday"; break;
            default: day = "Incorrect Day!"; break;
        }
        System.out.println(day);
    }
}

Console Output

Friday

B. Repetition Structures (while, do-while, and for Loops)

  • Loop Terminology: Repeating a block of statements until a test condition fails is called looping. A single pass through the loop body is an iteration.
  • for Loop: Best suited when the exact number of iterations is known: for (initialization; test_condition; update) { statements }. Loop counters declared inside the header are scoped strictly within the loop body.
Feature while Loop do-while Loop
Control Type Entry-controlled (checks condition before running body) Exit-controlled (checks condition after running body)
Minimum Executions 0 times (may never run if condition is initially false) At least 1 time (always executes body once)
Syntax while (condition) { statements } do { statements } while (condition); (Semicolon required)
Example Program 3.4(c): WhileDemo.java & For Loop Comparison
public class WhileDemo {
    public static void main(String[] args) {
        int number = 1;
        while (number <= 5) {
            System.out.println("Square of " + number + " = " + (number * number));
            ++number;
        }

        // Equivalent for loop:
        // for (int num = 1; num <= 5; ++num) {
        //     System.out.println("Square of " + num + " = " + (num * num));
        // }
    }
}

Console Output

Square of 1 = 1
Square of 2 = 4
Square of 3 = 9
Square of 4 = 16
Square of 5 = 25
Common Coding Errors in Loops (Board Exam Hotspots)
  1. Infinite Loop: Forgetting to update the loop counter inside a while loop causes it to run forever.
  2. Misplaced Semicolon: Writing while (x <= 5); or for (int i=1; i<=5; i++); creates an empty null loop body.
  3. Off-by-One Error: Using < instead of <= (or vice versa), causing one extra or one fewer iteration.
  4. Out-of-Scope Counter: Accessing a for-loop counter variable outside the loop’s closing brace.
3.5 – 3.6

Arrays & User-Defined Methods

  • Arrays: An array is a collection of multiple values of the same data type stored under a single variable name. Array indexing starts at 0 and runs up to n - 1 for an array of size n.
  • Declaration, Allocation & length: Dynamic allocation: double[] marks = new double[5]; | Static initialization: double[] marks = {346, 144, 103, 256.5, 387.5};. marks.length returns the total capacity (5). Accessing an index >= length throws ArrayIndexOutOfBoundsException.
  • User-Defined Methods: A reusable block of code grouped to perform a specific task: return_type method_name(parameter_list) { statements; return value; }. Use void if no value is returned. Declaring a method as static allows calling it without creating an object.
Example Program 3.5: ArrayDemo.java (Array Traversal & Class Report)
package helloworld;

public class ArrayDemo {
    public static void main(String[] args) {
        double[] marks = {346, 144, 103, 256.5, 387.5};
        double total_marks = 400;

        System.out.println("RollNo\tMarks\tPercentage\tResult");
        for (int i = 0; i < marks.length; i++) {
            double percentage = (marks[i] / total_marks) * 100;
            String result = (percentage >= 40) ? "Passed" : "Failed";
            System.out.println((i + 1) + "\t" + marks[i] + "\t" + percentage + "\t\t" + result);
        }
    }
}

Console Output

RollNo  Marks   Percentage      Result
1       346.0   86.5            Passed
2       144.0   36.0            Failed
3       103.0   25.75           Failed
4       256.5   64.125          Passed
5       387.5   96.875          Passed
Example Program 3.6: MethodDemo.java (Static User-Defined Method with Return Value)
package helloworld;

public class MethodDemo {
    static double rectangle_area(double length, double breadth) {
        return (length * breadth);
    }

    public static void main(String[] args) {
        double a = rectangle_area(45.5, 78.5);
        System.out.println("Area of the rectangle = " + a);
    }
}

Console Output

Area of the rectangle = 3571.75
3.7 – 3.8

Object-Oriented Programming (OOP)

  • Class & Object: A class is a logical blueprint defining attributes (data members) and behaviors (method members). An object is a specific instance of a class created using the new keyword (Book b1 = new Book();). Members are accessed via the dot (.) operator. All Java classes implicitly inherit from the base Object class.
  • Constructors: A special method with the exact same name as the class and no return type, invoked automatically when an object is instantiated via new to initialize data members. Defining a parameterized constructor disables the default no-argument constructor unless you explicitly define a parameter-less constructor alongside it.
  • Access Modifiers (public vs. private) & Getters/Setters: Members declared public are accessible both inside and outside the class. Members declared private are visible only within their own class. Public getter and setter methods provide controlled read/write access to private data members.
Example Program 3.8: Book.java & BookTest.java (Encapsulation, Constructor, Getter & Setter)
package javaprograms;

public class Book {
    private String title, author, publisher, genre;
    private double price;

    // Parameterized Constructor
    Book(String t, String a, String p, String g, double pr) {
        title = t; author = a; publisher = p; genre = g; price = pr;
    }

    double getPrice() { return price; }

    void setPrice(double newprice) {
        if (newprice < 100)
            System.out.println("Price cannot be lower than 100!");
        else
            price = newprice;
    }

    void display() {
        System.out.println("Title: " + title + " | Author: " + author + " | Price: " + price);
    }
}

public class BookTest {
    public static void main(String[] args) {
        Book book1 = new Book("Game of Thrones", "George R Martin", "Harper Collins", "Fiction", 450.0);
        book1.display();
        double discounted = book1.getPrice() - (20 * book1.getPrice() / 100);
        book1.setPrice(discounted);
        System.out.println("New discounted price: " + book1.getPrice());
    }
}

Console Output

Title: Game of Thrones | Author: George R Martin | Price: 450.0
New discounted price: 360.0
3.9

Java Libraries (java.util & java.lang)

  • Importing Packages: Prebuilt classes outside java.lang must be imported using the import keyword before the class definition (e.g., import java.util.Scanner;). Classes in java.lang (such as String, Integer, System) are imported automatically.
  • User Input (java.util.Scanner): Create a Scanner object attached to standard keyboard input: Scanner sc = new Scanner(System.in);. Use sc.next() to read a String token and Integer.parseInt(sc.next()) to read integer values.
  • Array Manipulation (java.util.Arrays): Arrays.sort(arr) sorts numeric arrays in ascending order and String arrays alphabetically. Arrays.binarySearch(arr, key) searches for key in a sorted array and returns its 0-based index (or -1 if not found).
Example Program 3.9(a): DataInputDemo.java (Console Input with Scanner & Integer.parseInt)
package javaprograms;
import java.util.Scanner;

public class DataInputDemo {
    public static void main(String[] args) {
        Scanner user_input = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = user_input.next();

        System.out.print("Enter your age: ");
        int age = Integer.parseInt(user_input.next());

        System.out.println("Hello " + name);
        System.out.println("In 5 years you will be " + (age + 5) + " years old.");
    }
}

Sample Console Output

Enter your name: Krishan
Enter your age: 21
Hello Krishan
In 5 years you will be 26 years old.
Example Program 3.9(b): ArraySortAndSearch.java (Using java.util.Arrays)
package javaprograms;
import java.util.Arrays;

public class ArraySortAndSearch {
    public static void main(String[] args) {
        double[] marks = {346, 144, 103, 256.5, 387.5};
        Arrays.sort(marks); // Sorts to: {103.0, 144.0, 256.5, 346.0, 387.5}

        System.out.println("Lowest: " + marks[0] + ", Highest: " + marks[marks.length - 1]);
        int index = Arrays.binarySearch(marks, 346);
        System.out.println("346 found at index: " + index);
    }
}

Console Output

Lowest: 103.0, Highest: 387.5
346 found at index: 3

Commonly Used String Class Methods (java.lang.String)

Method Signature Description Example (s = "Hello World") Output
charAt(int index)Returns character at specified 0-based indexs.charAt(6)‘W’
concat(String str)Appends str to the end of the strings.concat(” Today”)“Hello World Today”
contains(String s)Returns true if substring existss.contains(“Hell”)true
endsWith(String suf)Tests whether string ends with suffixs.endsWith(“old”)false
equals(Object obj)Case-sensitive equality comparisons.equals(“hello world”)false
equalsIgnoreCase(s)Case-insensitive equality comparisons.equalsIgnoreCase(“hello world”)true
indexOf(ch / str)Returns index of first occurrences.indexOf(‘W’) / s.indexOf(“rld”)6 / 8
isEmpty()Returns true if string length is 0s.isEmpty()false
length()Returns total number of characterss.length()11
replace(old, new)Replaces all occurrences of char or Strings.replace(‘l’, ‘*’)“He**o Wor*d”
toLowerCase()Converts all characters to lowercases.toLowerCase()“hello world”
toUpperCase()Converts all characters to uppercases.toUpperCase()“HELLO WORLD”
3.10

Exception Handling

  • What is an Exception? An unexpected runtime error (such as integer division by zero throwing ArithmeticException or invalid indexing throwing ArrayIndexOutOfBoundsException) that disrupts normal execution and terminates the program prematurely. (Note: Floating-point division by zero evaluates to Infinity instead of throwing an error).
  • try-catch-finally Mechanism: The try block encloses statements that might generate an exception. The catch block receives the exception object (e.g., catch (Exception e)) and handles it gracefully using methods like e.getMessage(). The optional finally block always executes when the try block exits—whether an exception occurred or not—and is used for resource cleanup.
Example Program 3.10: ExceptionDemo.java (Handling Division by Zero)
package javaprograms;

public class ExceptionDemo {
    static int divide(int dividend, int divisor) {
        return dividend / divisor;
    }

    public static void main(String[] args) {
        try {
            int quotient = divide(10, 0);
            System.out.println(quotient);
        } catch (Exception e) {
            System.out.println("Error caught: " + e.getMessage());
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

Console Output

Error caught: / by zero
Execution completed.
3.11

MySQL Database Connectivity (JDBC)

  • NetBeans Setup Steps: (1) Open Services tab > Right-click Databases > Register MySQL Server (configure localhost, port 3306, username root, password, and paths to mysqladmin/mysqld). (2) Right-click the registered server and click Connect. (3) In Projects tab > Right-click Libraries > Add JAR/Folder and add mysql-connector-java-*.jar.
  • 4-Step JDBC Execution Flow: Import classes from java.sql.*, establish a Connection via DriverManager.getConnection(), create a Statement object, run the SQL query using executeQuery() to get a ResultSet, and iterate rows with rs.next().
Example Program 3.11: MySQLDemo.java (Fetching Records from MySQL Table ‘book’)
package javaprograms;
import java.sql.*;

public class MySQLDemo {
    public static void main(String[] args) {
        String dbURL = "jdbc:mysql://localhost:3306/bookstore";
        String username = "root", password = "password";
        try {
            Connection dbCon = DriverManager.getConnection(dbURL, username, password);
            Statement stmt = dbCon.createStatement();
            ResultSet rs = stmt.executeQuery("select * from book");
            while (rs.next()) {
                for (int i = 1; i <= 5; i++) {
                    System.out.print(rs.getString(i) + " | ");
                }
                System.out.println();
            }
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Console Output

Effective Java | Joshua Bloch | Pearson | Educational | 500 |
Fundamentals of Database Systems | Shamkant Navathe | Pearson | Educational | 400 |
Game of Thrones | George R Martin | Harper Collins | Fiction | 450 |
3.12

Assertions, Threads, & Wrapper Classes

  • Assertions: Used during testing/debugging to verify logical assumptions: assert age >= 18 : "Age not Valid";. If false, Java throws an AssertionError. Disabled by default; enable via command line (java -ea ClassName) or NetBeans Project Properties > Run > VM Options (-ea).
  • Multithreading: Allows concurrent execution of multiple independent parts (threads) of a program. Created either by extending the Thread class or implementing the Runnable interface and overriding run(). Calling start() launches the thread. Control methods include setPriority(1–10), sleep(ms), and wait().
  • Wrapper Classes: Predefined classes in java.lang that wrap primitive data types into objects so they can be passed by reference or manipulated with helper methods: Boolean, Byte, Character, Integer, Float, Double, Long, and Short. Common methods include b.intValue(), Integer.parseInt("345"), and Integer.toString(3456).
Example Program 3.12(a): AssertionDemo.java (Validating Conditions with assert)
package javaprograms;
import java.util.Scanner;

public class AssertionDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the age of the client: ");
        int age = scanner.nextInt();

        assert age >= 18 : "Age not Valid";
        System.out.println("Age is " + age);
    }
}

Console Output (when input is 13 with -ea enabled)

Exception in thread "main" java.lang.AssertionError: Age not Valid
Example Program 3.12(b): ExtendThread.java & RunnableDemo.java (Creating Threads)
// Method 1: Extending Thread Class
public class ExtendThread extends Thread {
    public void run() {
        for (int count = 1; count <= 3; count++)
            System.out.println("Count = " + count);
    }

    public static void main(String[] args) {
        ExtendThread t1 = new ExtendThread();
        ExtendThread t2 = new ExtendThread();
        t1.start();
        t2.start();
    }
}

// Method 2: Implementing Runnable Interface
// RunnableDemo r = new RunnableDemo();
// Thread t1 = new Thread(r); t1.start();

Console Output (Concurrent execution alternates between threads)

Count = 1  |  Count = 1  |  Count = 2  |  Count = 2  |  Count = 3  |  Count = 3

CBSE Class 12 Information Technology (Subject Code 802) • Unit 3 Revision Notes

Scroll to Top