Java Programming
UNIT-I: Java Data Types and Operators
Genesis of Java: Creation of Java, why Java is important to the internet, Java Buzzwords, an overview of Java Object-Oriented Programming. Data types: Simple types – Integers, Floating point types, characters, Booleans. Literals, Variables, Type conversion and casting, Automatic type promotion in Expressions, Strings. Arrays: One-Dimensional and Multi-Dimensional Arrays. Operators: Arithmetic, Bitwise, Relational, Boolean Logical, Assignment, Conditional, Operator Precedence.
UNIT-II: Introducing Classes, Methods, and Inheritance
Class Fundamentals, Declaring objects, Assigning object Reference variables, Introducing Methods, Constructors, Garbage collection, Finalize() Method, Stack class. Overloading Methods, Using objects as parameters, Argument passing, Returning objects, Recursion, Access control, Understanding static, Introducing final, Nested and Inner classes, String class, Using command line arguments. Inheritance Basics, Using super, creating Multilevel Hierarchy, Method overriding, Dynamic Method Dispatch, Using Abstract class, Using final with inheritance, The object class.
UNIT-III: Packages, Interfaces, Exception Handling, and Multithreading
Packages, Access Protection, Importing packages, Interfaces. Exception Handling Introduction, Exception Types, Uncaught Exceptions, Using try and catch, Multiple catch clauses, Nested try statements, throw-throws-finally, Java’s Built-in Exception, creating custom Exception subclasses. Multithreaded Programming: Java Thread Model, Main Thread, Creating a Thread, Creating Multiple Threads, Using isAlive() and join(), Thread priorities, Synchronization, Inter-thread Communication, Suspending, Resuming, and Stopping Threads, Using Multithreading.
UNIT-IV: Applets and Event Handling
I/O Basics: Reading console Input, Writing console output, The PrintWriter class, Reading and Writing Files. The Applet class: Applet Basics, Applet Architecture, Applet Skeleton, Applet Display method, Requesting Repainting, HTML APPLET tag, Passing Parameters to Applet, Audio Clip Interface. Event Handling Mechanisms: Delegation Event Model, Event classes (Action Event, Item Event, Key Event, Mouse Event), Sources of Events, Event Listener Interfaces (Action Listener, Item Listener, Key Listener, Mouse Listener), Adapter Classes.
UNIT-V: Introducing AWT and AWT Controls
AWT Classes, Window fundamentals, working with Frame Windows, working with Graphics. Using AWT controls: Labels, Buttons, Check Boxes, Check Box Group, Choice controls, Text Field, Text Area. Understanding Layout Managers (Flow Layout only), Menu Bars and Menus.

UNIT-I: Java Data Types and Operators

Genesis of Java

Java was developed by James Gosling at Sun Microsystems. Originally designed for embedded systems, Java became widely popular due to its platform independence and security features, making it ideal for web applications.

Java Buzzwords

Overview of Java OOP

Java is a pure object-oriented language where everything revolves around objects and classes. Key OOP principles include:

Data Types in Java

Java has two types of data types:

int age = 25; float marks = 92.5f; char grade = 'A'; boolean isPass = true;

Literals in Java

Literals are fixed values that appear directly in the code:

Variables in Java

Variables store values with a defined type:

int number = 100; String name = "Tony Stark";

Type Conversion and Casting

Java supports two types of type conversions:

// Widening int a = 10; double b = a; // Narrowing double x = 20.5; int y = (int) x;

Automatic Type Promotion

In expressions, Java promotes smaller data types automatically:

byte b = 42; char c = 'a'; int result = b + c; System.out.println(result); // Output: 139

Strings in Java

Strings are objects that represent sequences of characters.

String greeting = "Hello, Java!"; System.out.println(greeting.length()); // Output: 12

Arrays in Java

Java supports single and multi-dimensional arrays.

One-Dimensional Array

int[] nums = {10, 20, 30}; System.out.println(nums[1]); // Output: 20

Multi-Dimensional Array

int[][] matrix = { {1, 2}, {3, 4} }; System.out.println(matrix[1][0]); // Output: 3

Operators in Java

Java supports several types of operators:

int a = 10, b = 5; System.out.println(a + b); // 15 System.out.println(a > b); // true System.out.println((a > 0 && b > 0)); // true

Operator Precedence in Java

Operator precedence determines the order in which operators are evaluated in expressions. For example, multiplication and division have higher precedence than addition and subtraction.

Order (from highest to lowest):

  1. Postfix: expr++, expr--
  2. Unary: ++expr, --expr, +expr, -expr, ~, !
  3. Multiplicative: *, /, %
  4. Additive: +, -
  5. Shift: <<,>>, >>>
  6. Relational: <,>, <=,>=
  7. Equality: ==, !=
  8. Bitwise AND: &
  9. Bitwise XOR: ^
  10. Bitwise OR: |
  11. Logical AND: &&
  12. Logical OR: ||
  13. Conditional: ? :
  14. Assignment: =, +=, -=, *=, etc.
int result = 10 + 2 * 5; // Output: 20 (because * has higher precedence than +)

UNIT-II: Introducing Classes, Methods and Inheritance

1. Class Fundamentals

In Java, a class is a blueprint for creating objects. It can contain fields (variables) and methods to define behavior.

class TonyStark {
    int power = 100;

    void showPower() {
        System.out.println("Power level: " + power);
    }
}
        

2. Declaring Objects

Objects are instances of a class. Here's how to declare and use them:

public class Main {
    public static void main(String[] args) {
        TonyStark ironMan = new TonyStark(); // Object declaration
        ironMan.showPower();
    }
}
        

3. Constructors

Constructors are special methods used to initialize objects.

class TonyStark {
    int suitNumber;

    TonyStark(int n) {
        suitNumber = n;
    }

    void showSuit() {
        System.out.println("Mark " + suitNumber);
    }
}
        

4. Method Overloading

You can define multiple methods with the same name but different parameters.

class Jarvis {
    void greet() {
        System.out.println("Hello, Tony!");
    }

    void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }
}
        

5. Argument Passing and Returning Objects

class Reactor {
    int level;

    Reactor(int l) {
        level = l;
    }

    Reactor boost(Reactor r) {
        return new Reactor(this.level + r.level);
    }
}
        

6. Recursion

A method can call itself. This is called recursion.

class Demo {
    int factorial(int n) {
        if (n == 1) return 1;
        return n * factorial(n - 1);
    }
}
        

7. Access Control, static, final

class Lab {
    private int secret = 42;      // Access control
    static int techCount = 5;     // Static
    final int ID = 101;           // Constant
}
        

8. Nested and Inner Classes

Classes can be defined within another class.

class Avengers {
    class Suit {
        void show() {
            System.out.println("Nano Suit Ready");
        }
    }
}
        

9. String Class

public class Demo {
    public static void main(String[] args) {
        String hero = "IronMan";
        System.out.println(hero.toUpperCase()); // IRONMAN
    }
}
        

10. Command Line Arguments

public class CommandDemo {
    public static void main(String[] args) {
        System.out.println("Hello, " + args[0]);
    }
}
// Run: java CommandDemo Tony
// Output: Hello, Tony
        

11. Inheritance Basics

Inheritance allows one class to acquire properties of another.

class Hero {
    void display() {
        System.out.println("I’m a Hero");
    }
}

class IronMan extends Hero {
    void show() {
        System.out.println("I’m IronMan");
    }
}
        

12. Using super and Multilevel Hierarchy

class Avenger {
    String name = "Unknown";
}

class Stark extends Avenger {
    Stark() {
        super.name = "Tony Stark";
    }
}
        

13. Method Overriding and Dynamic Dispatch

class AI {
    void respond() {
        System.out.println("Generic AI");
    }
}

class Jarvis extends AI {
    void respond() {
        System.out.println("Yes, Mr. Stark.");
    }
}

public class Main {
    public static void main(String[] args) {
        AI system = new Jarvis();
        system.respond(); // Output: Yes, Mr. Stark.
    }
}
        

14. Abstract Class

abstract class Armor {
    abstract void activate();
}

class NanoSuit extends Armor {
    void activate() {
        System.out.println("Suit Activated!");
    }
}
        

15. Final with Inheritance

final class Shield {}

class IronShield extends Shield {  // Error! Cannot inherit final class
    // ...
}
        

16. Object Class Methods

Every class in Java inherits from Object. Common methods include:

class ArcReactor {
    public String toString() {
        return "Clean Energy Source";
    }
}
        

UNIT-III: Packages, Interfaces, Exception Handling and Multithreading

1. Packages

package tech.stark;

public class Reactor {
    public void activate() {
        System.out.println("Arc Reactor Online");
    }
}
        

2. Access Protection & Importing Packages

import tech.stark.Reactor;

public class Lab {
    public static void main(String[] args) {
        Reactor r = new Reactor();
        r.activate();
    }
}
        

3. Interfaces

interface Suit {
    void activate();
}

class NanoSuit implements Suit {
    public void activate() {
        System.out.println("NanoSuit Deployed");
    }
}
        

4. Exception Handling Introduction

public class Arc {
    public static void main(String[] args) {
        try {
            int div = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
        

5. Multiple catch clauses & Nested try

public class TryDemo {
    public static void main(String[] args) {
        try {
            try {
                int a = 30 / 0;
            } catch (ArithmeticException e) {
                System.out.println("Inner catch: " + e);
            }
            int[] arr = new int[2];
            arr[5] = 100;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Outer catch: " + e);
        }
    }
}
        

6. throw, throws, finally

public class Jarvis {
    static void greet(int id) throws Exception {
        if (id != 101) throw new Exception("Unauthorized");
    }

    public static void main(String[] args) {
        try {
            greet(100);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.println("Access Attempted");
        }
    }
}
        

7. Java's Built-in Exceptions

8. Custom Exception Subclasses

class PowerOverloadException extends Exception {
    PowerOverloadException(String msg) {
        super(msg);
    }
}

class Reactor {
    void boost(int level) throws PowerOverloadException {
        if (level > 100) throw new PowerOverloadException("Too much power!");
    }
}
        

9. Java Thread Model & Main Thread

public class MainThread {
    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName());
    }
}
        

10. Creating a Thread

class AI extends Thread {
    public void run() {
        System.out.println("AI System Activated");
    }
}

public class Lab {
    public static void main(String[] args) {
        AI jarvis = new AI();
        jarvis.start();
    }
}
        

11. Creating Multiple Threads

class Bot extends Thread {
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println(getName() + " running...");
        }
    }
}

public class Demo {
    public static void main(String[] args) {
        new Bot().start();
        new Bot().start();
    }
}
        

12. isAlive() and join()

class StarkAI extends Thread {
    public void run() {
        System.out.println("Running...");
    }
}

public class Main {
    public static void main(String[] args) throws InterruptedException {
        StarkAI s = new StarkAI();
        s.start();
        System.out.println(s.isAlive());
        s.join();
        System.out.println("Finished");
    }
}
        

13. Thread Priorities

class PriorityTest extends Thread {
    public void run() {
        System.out.println("Thread priority: " + getPriority());
    }
}

public class Main {
    public static void main(String[] args) {
        PriorityTest t = new PriorityTest();
        t.setPriority(Thread.MAX_PRIORITY);
        t.start();
    }
}
        

14. Synchronization

class Shared {
    synchronized void print(String msg) {
        System.out.println("[" + msg);
        try { Thread.sleep(500); } catch (Exception e) {}
        System.out.println("]");
    }
}
        

15. Inter-thread Communication

class Resource {
    synchronized void waitForIt() throws InterruptedException {
        wait();
    }

    synchronized void signalIt() {
        notify();
    }
}
        

16. Suspending, Resuming, and Stopping Threads

Note: Methods like suspend(), resume(), and stop() are deprecated. Use flags instead.

class Worker extends Thread {
    private boolean running = true;

    public void run() {
        while (running) {
            System.out.println("Working...");
            try { Thread.sleep(1000); } catch (Exception e) {}
        }
    }

    public void stopWorking() {
        running = false;
    }
}
        

UNIT-IV: Applets and Event Handling

1. I/O Basics

In Java, Input and Output operations are essential for interacting with the user and external files. Here are the basics of reading console input and writing console output:

        // Reading console input
        import java.util.Scanner;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        // Writing console output
        System.out.println("Hello, " + name + "!");
        

2. The PrintWriter Class

The PrintWriter class provides convenient methods for writing formatted text to files or the console:

        import java.io.PrintWriter;
        try {
            PrintWriter writer = new PrintWriter("output.txt");
            writer.println("This is a line of text.");
            writer.close();
        } catch (Exception e) {
            System.out.println("Error writing to file.");
        }
        

3. Reading and Writing Files

Reading from and writing to files can be done using classes like FileReader and FileWriter.

        import java.io.FileReader;
        import java.io.FileWriter;
        import java.io.BufferedReader;

        // Reading from file
        try {
            FileReader fr = new FileReader("input.txt");
            BufferedReader br = new BufferedReader(fr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        } catch (Exception e) {
            System.out.println("Error reading file.");
        }

        // Writing to file
        try {
            FileWriter fw = new FileWriter("output.txt");
            fw.write("This is a new line in the file.");
            fw.close();
        } catch (Exception e) {
            System.out.println("Error writing to file.");
        }
        

4. The Applet Class

An applet is a small Java program that can be embedded in a web page and run inside a browser. The basic architecture of an applet consists of the init(), start(), and paint() methods:

        import java.applet.Applet;
        import java.awt.Graphics;

        public class HelloWorldApplet extends Applet {
            public void paint(Graphics g) {
                g.drawString("Hello, Java Applet!", 50, 50);
            }
        }
        

5. Requesting Repainting

To force an applet to repaint itself, use the repaint() method:

        public void paint(Graphics g) {
            g.clearRect(0, 0, 300, 300); // Clear the area before drawing
            g.drawString("Repainting the applet", 50, 50);
        }

        // Request repaint
        repaint();
        

6. HTML APPLET Tag

The <applet> HTML tag is used to embed an applet in a web page. The applet is specified by its class file:

        
        
        

7. Passing Parameters to Applet

You can pass parameters to applets using the <param> tag in HTML:

        
            
        
        

8. Audio Clip Interface

The AudioClip interface allows applets to play sound:

        import java.applet.Applet;
        import java.applet.AudioClip;
        import java.net.URL;

        public class PlaySoundApplet extends Applet {
            AudioClip clip;
            public void init() {
                try {
                    URL sound = new URL(getCodeBase(), "sound.wav");
                    clip = getAudioClip(sound);
                } catch (Exception e) {
                    System.out.println("Error loading sound.");
                }
            }

            public void start() {
                clip.play();
            }
        }
        

9. Event Handling Mechanisms

Event handling in Java uses a delegation model. Different event types trigger methods in the event listener interfaces:

        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;

        public class ButtonClickListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button clicked!");
            }
        }
        

10. Event Listener Interfaces

Event listener interfaces capture specific events. Common examples include:

11. Adapter Classes

Adapter classes provide default implementations for event listener interfaces, allowing you to override only the methods you need:

        import java.awt.event.MouseAdapter;
        import java.awt.event.MouseEvent;

        public class MouseClickListener extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                System.out.println("Mouse clicked at " + e.getX() + ", " + e.getY());
            }
        }
        

UNIT-V: Introducing AWT and AWT Controls

1. AWT Classes

The Abstract Window Toolkit (AWT) is the foundation for building graphical user interfaces (GUIs) in Java. It contains classes for creating windows, handling events, and drawing graphics.

        import java.awt.*;

        public class AWTExample {
            public static void main(String[] args) {
                Frame frame = new Frame("AWT Window");
                frame.setSize(400, 400);
                frame.setVisible(true);
            }
        }
        

2. Window Fundamentals

In AWT, a window is represented by the Frame class. Here’s how to create a simple window:

        import java.awt.*;

        public class SimpleWindow {
            public static void main(String[] args) {
                Frame frame = new Frame("Simple Window");
                frame.setSize(300, 200);
                frame.setVisible(true);
            }
        }
        

3. Working with Frame Windows

Frames are the top-level containers for GUI elements. Here's how you can work with frames:

        import java.awt.*;

        public class FrameWindow {
            public static void main(String[] args) {
                Frame frame = new Frame("Frame Example");
                Button button = new Button("Click Me");
                frame.add(button);
                frame.setSize(400, 300);
                frame.setLayout(new FlowLayout());
                frame.setVisible(true);
            }
        }
        

4. Working with Graphics

AWT provides basic graphics capabilities. You can use the Graphics class to draw shapes, lines, and text.

        import java.awt.*;

        public class GraphicsExample extends Frame {
            public void paint(Graphics g) {
                g.setColor(Color.RED);
                g.drawLine(50, 50, 150, 150); // Draw line
                g.drawRect(200, 200, 100, 100); // Draw rectangle
                g.setColor(Color.BLUE);
                g.drawString("AWT Graphics Example", 100, 100); // Draw string
            }

            public static void main(String[] args) {
                GraphicsExample obj = new GraphicsExample();
                obj.setSize(400, 400);
                obj.setVisible(true);
            }
        }
        

5. Using AWT Controls

AWT provides several controls that can be added to frames. These include labels, buttons, checkboxes, text fields, and more.

6. Controls Fundamentals

Controls are the basic components used for interacting with users. Below is an example of adding controls to a frame:

        import java.awt.*;

        public class ControlExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Control Example");

                Label label = new Label("Enter your name:");
                TextField textField = new TextField();
                Button button = new Button("Submit");

                frame.add(label);
                frame.add(textField);
                frame.add(button);

                frame.setSize(300, 200);
                frame.setLayout(new FlowLayout());
                frame.setVisible(true);
            }
        }
        

7. Using Buttons

Buttons are commonly used for triggering actions in a GUI. Here’s how to use a button in AWT:

        import java.awt.*;
        import java.awt.event.*;

        public class ButtonExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Button Example");

                Button button = new Button("Click Me");
                button.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        System.out.println("Button clicked!");
                    }
                });

                frame.add(button);
                frame.setSize(200, 200);
                frame.setVisible(true);
            }
        }
        

8. Applying Checkboxes

Checkboxes allow users to select multiple options. Here’s an example:

        import java.awt.*;
        import java.awt.event.*;

        public class CheckboxExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Checkbox Example");

                Checkbox checkbox1 = new Checkbox("Option 1");
                Checkbox checkbox2 = new Checkbox("Option 2");

                frame.add(checkbox1);
                frame.add(checkbox2);

                frame.setSize(300, 200);
                frame.setLayout(new FlowLayout());
                frame.setVisible(true);
            }
        }
        

9. Check Box Group

Check box groups allow grouping of checkboxes for mutual exclusivity. Below is an example:

        import java.awt.*;

        public class CheckboxGroupExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Checkbox Group Example");

                CheckboxGroup group = new CheckboxGroup();
                Checkbox checkbox1 = new Checkbox("Option 1", group, false);
                Checkbox checkbox2 = new Checkbox("Option 2", group, false);

                frame.add(checkbox1);
                frame.add(checkbox2);

                frame.setSize(300, 200);
                frame.setLayout(new FlowLayout());
                frame.setVisible(true);
            }
        }
        

10. Choice Controls

Choice controls allow users to select from a list of options. Here's an example:

        import java.awt.*;

        public class ChoiceExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Choice Example");

                Choice choice = new Choice();
                choice.add("Option 1");
                choice.add("Option 2");
                choice.add("Option 3");

                frame.add(choice);
                frame.setSize(300, 200);
                frame.setVisible(true);
            }
        }
        

11. Using a Text Field

Text fields allow users to enter a single line of text. Here's how to use it:

        import java.awt.*;

        public class TextFieldExample {
            public static void main(String[] args) {
                Frame frame = new Frame("TextField Example");

                TextField textField = new TextField("Default text");
                frame.add(textField);

                frame.setSize(300, 200);
                frame.setVisible(true);
            }
        }
        

12. Using a Text Area

Text areas allow users to enter multiple lines of text. Here's an example:

        import java.awt.*;

        public class TextAreaExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Text Area Example");

                TextArea textArea = new TextArea("This is a text area.");
                frame.add(textArea);

                frame.setSize(400, 300);
                frame.setVisible(true);
            }
        }
        

13. Understanding Layout Managers (Flow Layout)

Layout managers control the positioning of components. The FlowLayout manager arranges components sequentially from left to right:

        import java.awt.*;

        public class FlowLayoutExample {
            public static void main(String[] args) {
                Frame frame = new Frame("FlowLayout Example");

                Button button1 = new Button("Button 1");
                Button button2 = new Button("Button 2");
                Button button3 = new Button("Button 3");

                frame.setLayout(new FlowLayout());
                frame.add(button1);
                frame.add(button2);
                frame.add(button3);

                frame.setSize(300, 200);
                frame.setVisible(true);
            }
        }
        

14. Menu Bars and Menus

AWT also provides support for creating menu bars and menus. Here’s how to create a simple menu:

        import java.awt.*;
        import java.awt.event.*;

        public class MenuExample {
            public static void main(String[] args) {
                Frame frame = new Frame("Menu Example");

                MenuBar menuBar = new MenuBar();
                Menu menu = new Menu("File");
                MenuItem menuItem1 = new MenuItem("Open");
                MenuItem menuItem2 = new MenuItem("Exit");

                menu.add(menuItem1);
                menu.add(menuItem2);
                menuBar.add(menu);

                frame.setMenuBar(menuBar);
                frame.setSize(300, 200);
                frame.setVisible(true);
            }
        }