0% found this document useful (0 votes)
4 views17 pages

Java Full Revision-1

This document is a comprehensive revision guide for a Java Programming course, covering all five units of the syllabus. It includes key concepts, exam tips, and code examples related to Java basics, object-oriented programming, inheritance, exception handling, multithreading, and I/O operations. The guide emphasizes important points to remember and provides insights into exam preparation strategies for students.

Uploaded by

mafiadevill123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

Java Full Revision-1

This document is a comprehensive revision guide for a Java Programming course, covering all five units of the syllabus. It includes key concepts, exam tips, and code examples related to Java basics, object-oriented programming, inheritance, exception handling, multithreading, and I/O operations. The guide emphasizes important points to remember and provides insights into exam preparation strategies for students.

Uploaded by

mafiadevill123
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming

Full Syllabus Revision Guide

BTU [Link] IV Sem • 4CS4-06 • All 5 Units • Simple Language

Theory • Key Points • Differences • Programs • Exam Tips

MUST PREPARE IMPORTANT ★ = Key point to remember Exam Tip = Direct PYQ hint

Unit 1 — Java Basics & OOP Introduction


8 hrs | JVM, Bytecode, Operators, Casting, OOP

1.1 JVM, Bytecode & Java Features

Bytecode Intermediate .class file produced by javac compiler — NOT machine code. JVM reads this.

JVM Java Virtual Machine — reads bytecode and runs it on any operating system.

WORA Write Once Run Anywhere — same .class file runs on Windows, Linux, Mac without
recompiling.

• JDK (Java Development Kit) contains the compiler javac


• JRE (Java Runtime Environment) contains JVM + libraries
• Hierarchy: JDK > JRE > JVM

Java Features to remember:


Platform Ind Multithread High Perfor
OOP ependent Secure Robust ed Portable mance

Exam Tip: Part A: significance of bytecode = platform independence. Part C: explain JVM + list all 7 features.

1.2 OOP — 4 Pillars

Encapsulation Wrapping Abstraction Hide Inheritance Child class gets Polymorphism One name,
data + methods in a class. implementation details. fields and methods of parent many forms. Overloading =
Use private fields + Show only what is class using extends. compile-time. Overriding =
getters/setters. necessary to the user. runtime.
1.3 Operators

• Bitwise: & (AND) | (OR) ^ (XOR) ~ (NOT) << (left shift) >> (right shift)
• Logical: && (short-circuit AND) || (short-circuit OR) ! (NOT)
• Relational: == != < > <= >= — always return true or false
★ Difference: & evaluates BOTH sides always. && stops at first false (short-circuit).

int p=9, q=5; // 9=1001 binary, 5=0101 binary


int r = p | q; // OR -> 1101 = 13
int s = p & q; // AND -> 0001 = 1
[Link](r + " " + s); // Output: 13 1

Exam Tip: 2024-25 Part B exact output question: p=9, q=5. Memorise 9|5=13 and 9&5=1.

1.4 Type Casting

Type Direction How Data loss? Example

Implicit (Widening) Small to Large Automatic No int a=5; double d=a;

Explicit Large to Small Must write (type) Yes — double x=9.9; int y=(int)x; // y=9
(Narrowing) decimal cut

Exam Tip: 2024-25 Part B: difference between implicit and explicit casting — write both with example and output.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision


Unit 2 — Classes & Objects
6 hrs | Constructors, Overloading, GC, Recursion

2.1 Constructors — All 3 Types

Note: Constructor = same name as class, NO return type, called automatically when object is created.

• Default constructor: no parameters — compiler auto-provides if none written


• Parameterized constructor: accepts arguments to set field values
• Copy constructor: takes another object of same class and copies all values
• Constructor overloading: multiple constructors with different parameters in same class
★ super() must be the FIRST statement in a child class constructor to call parent constructor.

class Student {
String name; int age;
Student() { name = "Unknown"; age = 0; } // 1. default
Student(String n, int a) { name=n; age=a; } // 2. parameterized
Student(Student s) { name=[Link]; age=[Link]; } // 3. copy
void show() { [Link](name + " | " + age); }
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student("Rahul", 20);
Student s3 = new Student(s2); // copy of s2
[Link](); [Link](); [Link]();
}
}

OUTPUT:

Unknown | 0

Rahul | 20

Rahul | 20

Exam Tip: 2023-24 Part B: write all 3 constructor types in one class — easy full 4 marks.

2.2 Method Overloading

• Same method name, different parameters (type / number / order)


• Return type alone CANNOT differentiate — gives compile error
• Resolved at compile time = static polymorphism / compile-time polymorphism
★ YES main() CAN be overloaded — JVM always calls main(String[] args) specifically.

Exam Tip: 2024-25 Part B: Can we overload main()? Always answer YES with a program.

2.3 Garbage Collection

• Java automatically frees memory — no need to call free() like in C/C++


• Object becomes eligible for GC when no reference points to it
• Two ways object loses reference: (1) ref = null (2) goes out of scope
• finalize() method: called by GC just BEFORE destroying object — for cleanup
• [Link](): only a REQUEST to GC — not guaranteed to run immediately
★ Drawback: programmer has NO control over WHEN GC runs — can cause unexpected pauses
(stop-the-world).
Exam Tip: 2024-25 Part C: When eligible? Why necessary? Drawback? — write all 3 separately.

2.4 this Keyword — 3 Uses

• Use 1: Distinguish field from parameter with same name — [Link] = name
• Use 2: Call another constructor in same class — this() (must be first statement)
• Use 3: Pass current object as argument — someMethod(this)

Exam Tip: Part A: always mention ALL 3 uses for full 2 marks.

2.5 Recursion

• Recursion = method calling itself repeatedly until a condition stops it


• MUST have a base case — without it, infinite loop / stack overflow

static int factorial(int n) {


if(n == 0) return 1; // BASE CASE — stop here
return n * factorial(n-1); // recursive call
}
// How factorial(4) works:
// 4 * factorial(3) = 4 * 3 * factorial(2) = 4*3*2*1*1 = 24

OUTPUT:

factorial(5) = 120

factorial(6) = 720

Exam Tip: Aug 2023 Part B: find factorial using recursion. Trace the steps in your answer.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision


Unit 3 — Inheritance, Interfaces & Exception Handling
10 hrs | HIGHEST weightage — ALL 3 papers asked from here

3.1 Interface

Note: Interface = a pure contract. It says WHAT to do, not HOW to do it.

• All methods in interface are public abstract by default (no body)


• All variables are public static final (constants — cannot change)
• A class IMPLEMENTS an interface using implements keyword
• One class can implement MULTIPLE interfaces — solves multiple inheritance problem
• Interface reference variable = Shape s = new Circle(); — enables runtime polymorphism
★ Difference from abstract class: interface CANNOT have constructor or instance variables. Abstract class CAN.

interface Shape {
double getArea(); // abstract by default
double getPerimeter();
}
class Circle implements Shape {
double r;
Circle(double r) { this.r = r; }
public double getArea() { return [Link] * r * r; }
public double getPerimeter() { return 2 * [Link] * r; }
}
class Rectangle implements Shape {
double l, b;
Rectangle(double l, double b) { this.l=l; this.b=b; }
public double getArea() { return l * b; }
public double getPerimeter() { return 2*(l+b); }
}
Shape s = new Circle(7); // interface reference variable
[Link]("Circle Area: %.2f%n", [Link]());

OUTPUT:

Circle Area: 153.94

Exam Tip: Appeared ALL 3 papers. Prepare Shape with Circle + Rectangle — most repeated program.

3.2 Exception Handling

• Exception = a runtime error that disrupts normal program flow


• try = block of risky code | catch = handles the error | finally = ALWAYS runs
• throw = manually throw an exception | throws = declare in method signature
• Checked exceptions: compile-time — IOException, SQLException (MUST handle or declare)
• Unchecked exceptions: runtime — ArithmeticException, NullPointerException, ArrayIndexOutOfBounds
★ Multiple catch blocks: most SPECIFIC exception FIRST, general Exception LAST — opposite causes compile
error.

Feature Checked Exception Unchecked Exception

When detected Compile time Runtime

Examples IOException, SQLException ArithmeticException, NullPointerException

Must handle? YES — or use throws No — optional


Extends Exception class RuntimeException class

try {
int result = 10 / 0; // ArithmeticException here
} catch(ArithmeticException e) {
[Link]("Error: " + [Link]());
} finally {
[Link]("Finally always runs"); // even if no error
}
// throw manually:
if(age < 0) throw new ArithmeticException("Age cannot be negative");

OUTPUT:

Error: / by zero

Finally always runs

Exam Tip: 2023-24 Part B: division-by-zero program. Always write finally block. 2-mark: difference checked vs unchecked.

3.3 Method Overriding & Dynamic Method Dispatch

• Overriding = child class gives its own version of parent method (same name + same parameters)
• Rules: cannot override final, static, or private methods
• Dynamic dispatch = parent reference holds child object → child method called at RUNTIME
★ This is runtime polymorphism. Method resolved based on ACTUAL object type, not reference type.

Feature Overloading Overriding

Class Same class Parent & child class

Parameters MUST be different MUST be same

Resolved at Compile time Runtime

Return type Can differ Must be same or covariant

Also called Static polymorphism Dynamic polymorphism

final method Can overload CANNOT override

3.4 Abstract Class

• Abstract class: declared with abstract keyword — CANNOT be instantiated directly


• CAN have abstract methods (no body) AND concrete methods (with body)
• Subclass MUST implement all abstract methods or itself be abstract

Feature Abstract Class Interface

Constructor CAN have CANNOT have

Methods abstract + concrete both all abstract (default)

Variables any type public static final only

Inheritance extends (single only) implements (multiple allowed)

Use when share common code define pure contract

Exam Tip: Part A: distinguish abstract class vs concrete class — write 3 differences.

3.5 Packages

• Package = namespace to group related classes — avoids name conflicts


• Create: package mypack; (must be FIRST statement in .java file)
• Import: import [Link]; OR import mypack.*; (import all)
• Access levels: private < default(package) < protected < public
★ protected = accessible in same package AND in subclasses of other packages.

Exam Tip: Aug 2023 Part C: define package + benefits + example. Access levels table is common 2-marker.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision


Unit 4 — Multithreaded Programming
10 hrs | Thread creation, Synchronization, Priorities, Deadlock

4.1 Thread Creation — Two Ways

Note: Thread = a lightweight sub-process. Multiple threads run simultaneously in same program.

• Way 1: Extend Thread class — override run() method — call start() to launch
• Way 2: Implement Runnable interface — implement run() — pass to Thread — call start()
• Prefer Runnable when your class already extends another class (Java = single class inheritance)
★ ALWAYS call start() — NOT run(). start() creates a new thread. run() alone executes in same thread.

// WAY 1: extend Thread


class MyThread extends Thread {
public void run() { [Link]("Thread running"); }
}
new MyThread().start();
// WAY 2: implement Runnable
class MyRun implements Runnable {
public void run() { [Link]("Runnable running"); }
}
new Thread(new MyRun()).start();

Exam Tip: isAlive() = true if thread started and not dead. join() = current thread waits for that thread to finish.

4.2 Thread Lifecycle — 5 States

RUNNABLE RUNNING BLOCKED


NEW Object DEAD run()
start() called, CPU assigned, Waiting for
created, start() - - - - finished or
waiting for run() lock or
not called > > > > exception
CPU executing sleep/join

Exam Tip: Part A: List thread states = New, Runnable, Running, Blocked, Dead — very common 2-marker.

4.3 Thread Synchronization

• Problem: 2+ threads access shared data simultaneously → race condition → wrong/corrupt data
• Solution: synchronized keyword — only ONE thread can run the method at a time
• Lock/Monitor: each object has a lock; synchronized method automatically acquires it
• Synchronized method: synchronized void myMethod() { ... }
• Synchronized block: synchronized(obj) { ... } — gives finer control
• wait(): release lock and wait | notify(): wake one waiting thread | notifyAll(): wake all
★ Without synchronization: two threads can corrupt shared data. Bank account withdrawal is the classic
example.
class BankAccount {
int balance = 1000;
synchronized void withdraw(int amount) {
// only ONE thread runs this at a time
if(balance >= amount) {
balance -= amount;
[Link]("Withdrawn. Balance: " + balance);
} else {
[Link]("Insufficient balance");
}
}
}

Exam Tip: Appeared ALL 3 papers. 10-mark answer needs: WHY needed + synchronized keyword + program + lock concept.

4.4 Thread Priority, Deadlock & Daemon Thread

• Priority range: MIN_PRIORITY=1, NORM_PRIORITY=5 (default), MAX_PRIORITY=10


• setPriority(n) sets priority; getPriority() reads it
• Higher priority thread gets CPU first — but NOT guaranteed (depends on OS scheduler)
• Deadlock: Thread A holds lock X and waits for Y. Thread B holds Y and waits for X. Both stuck forever.
• 4 conditions for deadlock: Mutual exclusion | Hold & wait | No preemption | Circular wait
• Daemon thread: background service thread (like GC). setDaemon(true) MUST be called BEFORE start()
★ Daemon thread dies automatically when all non-daemon (user) threads finish.

Exam Tip: Part A: 'What is daemon thread?' | 'How assign priority?' | 'Role of deadlock?' — all common 2-markers.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision


Unit 5 — I/O Operations, Applets & Networking
6 hrs | Applets, TCP/IP, JDBC, Streams — ALL 3 papers

5.1 Applets — Lifecycle & Architecture

Note: Applet = Java program that runs inside a web browser. It has NO main() method.

• Extends [Link] class


• HTML tag to embed:
• Applet vs Application: applet runs in browser (no main), application runs standalone (has main)

init() Called start() Each paint() Draw stop() destroy()


ONCE when -> time applet -> text & -> Browser tab -> Browser
applet loads visible graphics changed/min closed

Exam Tip: Appeared ALL 3 papers. For Part C: draw this lifecycle diagram + write the applet program = easy 10 marks.

5.2 TCP/IP Sockets

• Socket = endpoint for communication between two programs over a network


• ServerSocket: server-side — binds to a port, accept() BLOCKS until client connects
• Socket: client-side — connects to server using IP address and port number
★ ALWAYS run the Server program first, THEN run the Client.
• Server steps: ServerSocket(port) -> accept() -> get streams -> read/write -> close
• Client steps: Socket(IP, port) -> get streams -> read/write -> close

Exam Tip: Appeared ALL 3 papers. Know both server-side AND client-side code.

5.3 JDBC — Database Connectivity

• JDBC = Java Database Connectivity — API to connect Java program to a database

Type Name Description Speed

1 JDBC-ODBC Bridge Uses ODBC driver — slowest, deprecated Slowest

2 Native API Uses DB native libraries on client side Medium

3 Network Protocol Connects through middleware server — good for web apps Fast

4★ Pure Java Direct DB connection — no middleware needed — MOST USED Fastest

• 6 steps: Load driver → Create Connection → Create Statement → Execute Query → Process ResultSet → Close

Exam Tip: Part A: 'Need of JDBC type 3 and type 4' = 2 marks. Type 3 = web apps via middleware. Type 4 = direct DB.

5.4 Byte Streams vs Character Streams

Feature Byte Streams Character Streams

Base classes InputStream / OutputStream Reader / Writer

Data handled Raw binary (8-bit bytes) Text (16-bit Unicode characters)

Used for Images, audio, any binary file Text files only

File classes FileInputStream / FileOutputStream FileReader / FileWriter

Buffered BufferedInputStream BufferedReader (has readLine() method)


Exam Tip: Part A: compare byte vs character streams = 2 marks. Key: Byte=binary, Char=text/Unicode.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision


6 Most Important Programs
With Simple Explanation + Code + Output + Exam Tip

These 6 programs cover approx 40 marks across Part A, B and C

Unit 3 | Part B 4m | Part C 10m


Program 1 — Exception Handling (try / catch / finally / throw) | appeared 2023-24 & Aug 2023
• try = risky code block | catch = handle error | finally = ALWAYS runs
• Checked = compile-time (IOException) | Unchecked = runtime (ArithmeticException)
• Multiple catch = most specific FIRST, general last

class ExceptionDemo {
public static void main(String[] args) {
// Example 1: division by zero
try {
int result = 10 / 0; // ERROR here — ArithmeticException
[Link](result); // this line is SKIPPED
} catch(ArithmeticException e) {
[Link]("Caught: " + [Link]());
} finally {
[Link]("Finally block — always runs");
}
// Example 2: manually throw exception
try {
int age = -5;
if(age < 0)
throw new ArithmeticException("Age cannot be negative");
} catch(ArithmeticException e) {
[Link]("Thrown: " + [Link]());
}
}
}

OUTPUT:

Caught: / by zero

Finally block — always runs

Thrown: Age cannot be negative

Exam tip: Division-by-zero is the most asked program. Always write finally block — examiners check for it.
Unit 3 | Part B 4m | Part C 10m
Program 2 — Interface (Shape with Circle & Rectangle) | appeared ALL 3 papers
• Interface = pure contract. All methods are abstract by default.
• Class implements interface using implements keyword.
• Interface reference variable: Shape s = new Circle(7); enables runtime polymorphism.

interface Shape {
double getArea();
double getPerimeter();
}
class Circle implements Shape {
double r;
Circle(double r) { this.r = r; }
public double getArea() { return [Link] * r * r; }
public double getPerimeter() { return 2 * [Link] * r; }
}
class Rectangle implements Shape {
double l, b;
Rectangle(double l, double b) { this.l=l; this.b=b; }
public double getArea() { return l * b; }
public double getPerimeter() { return 2 * (l + b); }
}
class InterfaceDemo {
public static void main(String[] args) {
Shape s1 = new Circle(7);
Shape s2 = new Rectangle(4, 5);
[Link]("Circle Area: %.2f%n", [Link]());
[Link]("Rectangle Area: %.2f%n", [Link]());
}
}

OUTPUT:

Circle Area: 153.94

Rectangle Area: 20.00

Exam tip: Appeared ALL 3 papers! Most repeated program in Unit 3. Prepare both Circle and Rectangle classes.
Unit 4 | Part C 10m | appeared
Program 3 — Thread Synchronization ALL 3 papers
• Without synchronized: two threads corrupt shared data (race condition).
• synchronized keyword allows only ONE thread to run the method at a time.
• Each object has a lock — synchronized method acquires it automatically.

class BankAccount {
int balance = 1000;
// synchronized = only 1 thread at a time
synchronized void withdraw(int amount) {
if(balance >= amount) {
[Link]([Link]().getName()
+ " withdrawing: " + amount);
balance -= amount;
[Link]("Remaining: " + balance);
} else {
[Link]("Insufficient balance");
}
}
}
class SyncDemo {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
// both threads share same account
Thread t1 = new Thread(() -> [Link](600), "T1");
Thread t2 = new Thread(() -> [Link](600), "T2");
[Link]();
[Link]();
}
}

OUTPUT:

T1 withdrawing: 600

Remaining: 400

Insufficient balance (T2 correctly blocked)

Exam tip: Appeared ALL 3 papers. 10-mark: explain WHY needed + synchronized keyword + program + lock/monitor concept.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision


Unit 4 | Part C 10m | 2024-25
Program 4 — Three Threads at Different Time Intervals exact PYQ
• [Link](ms) pauses thread for given milliseconds (1000ms = 1 second).
• [Link]() throws InterruptedException — must use try-catch around it.
• All 3 threads run independently and simultaneously.

class MessageThread extends Thread {


String message;
int delay; // in milliseconds
MessageThread(String msg, int d) {
message = msg;
delay = d;
}
public void run() {
try {
for(int i = 1; i <= 3; i++) { // print 3 times
[Link](message);
[Link](delay); // wait before printing again
}
} catch(InterruptedException e) {
[Link]("Thread interrupted");
}
}
}
class ThreeThreads {
public static void main(String[] args) {
new MessageThread("Good morning", 1000).start(); // every 1 sec
new MessageThread("Do Yoga", 2000).start(); // every 2 sec
new MessageThread("Keep healthy", 3000).start(); // every 3 sec
}
}

OUTPUT:

Good morning

Do Yoga

Good morning

Keep healthy

Good morning (output order depends on timing)

Exam tip: 2024-25 Part C Q4 EXACT question. Always wrap [Link]() in try-catch — forgetting it = compile error.
Unit 5 | Part C 10m | 2024-25
Program 5 — Applet with Three Colored Rectangles exact PYQ — appeared ALL 3
papers
• Applet extends Applet class. No main() method needed.
• paint(Graphics g) is called automatically to draw on screen.
• fillRect(x, y, width, height) draws a filled rectangle at position x,y.

import [Link].*;
import [Link].*;
/*
* HTML to run this applet:
* <applet code='[Link]' width=300 height=320></applet>
*/
public class ColorApplet extends Applet {
public void init() {
setBackground([Link]); // white background
}
public void paint(Graphics g) {
// Rectangle 1 — RED (top)
[Link]([Link]);
[Link](50, 20, 200, 70);
// Rectangle 2 — BLUE (middle)
[Link]([Link]);
[Link](50, 110, 200, 70);
// Rectangle 3 — BLACK (bottom)
[Link]([Link]);
[Link](50, 200, 200, 70);
}
}

OUTPUT:

[Applet window shows 3 equal rectangles stacked vertically]

[Top = RED | Middle = BLUE | Bottom = BLACK]

Exam tip: 2024-25 Part C Q5 exact. After writing code, also write applet lifecycle (init->start->paint->stop->destroy) = full 10
marks.
Unit 5 | Part B 4m | Part C 10m
Program 6 — TCP/IP Server and Client Socket | appeared ALL 3 papers
• ServerSocket listens on a port. accept() blocks until a client connects.
• Socket connects to server using IP address and port number.
• Run SERVER first in one terminal, then CLIENT in another terminal.

// ===== SERVER PROGRAM =====


import [Link].*; import [Link].*;
class Server {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(5000);
[Link]("Server waiting for client...");
Socket s = [Link](); // BLOCKS until client connects
[Link]("Client connected!");
DataInputStream in = new DataInputStream([Link]());
DataOutputStream out = new DataOutputStream([Link]());
[Link]("Client says: " + [Link]());
[Link]("Hello from Server!");
[Link](); [Link]();
}
}
// ===== CLIENT PROGRAM =====
class Client {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 5000);
DataOutputStream out = new DataOutputStream([Link]());
DataInputStream in = new DataInputStream([Link]());
[Link]("Hello from Client!");
[Link]("Server says: " + [Link]());
[Link]();
}
}

OUTPUT:

[Server terminal] Server waiting for client...

[Server terminal] Client connected!

[Server terminal] Client says: Hello from Client!

[Client terminal] Server says: Hello from Server!

Exam tip: Appeared ALL 3 papers. Know both programs. Steps: ServerSocket->accept->streams->read/write->close.

BTU [Link] IV Sem • 4CS4-06 Java Programming • Full Syllabus Revision

You might also like