UNIT 3: Java Programming
1. Fundamental Java Concepts
Java as an Object-Oriented Language
Java is purely object-oriented because:
-
Everything is an object (except primitives).
-
Programs are organized around objects that interact.
-
Core OOP principles:
-
Encapsulation: Bundling data (fields) and methods (behaviour) into a single unit (class), with access control via modifiers.
-
Inheritance: A class (
subclass) can acquire properties and methods of another class (superclass) usingextends. -
Polymorphism: Ability of an object to take many forms. Achieved via method overloading (compile-time) and method overriding (runtime).
-
Abstraction: Hiding implementation details, showing only functionality. Achieved via abstract classes and interfaces.
-
Control Statements
Iteration Statements:
-
for(init; condition; update) { ... }– Entry-controlled, known iterations. -
while(condition) { ... }– Entry-controlled, unknown iterations. -
do { ... } while(condition);– Exit-controlled, executes at least once. -
Enhanced
forloop:for(type var : array/collection) { ... }– For arrays/collections, no index.
Jump Statements:
-
break: Exits the innermost loop orswitch. -
continue: Skips current iteration, proceeds to next. -
return: Exits the current method, optionally returns a value.
[!TIP] Common Pitfall:
breakonly exits the immediate loop; use labeled break for outer loops.
Constructors
-
Special method to initialize objects.
-
Types:
-
Default Constructor: No parameters, provided by JVM if no other constructor exists.
-
Parameterized Constructor: Takes arguments to initialize fields.
-
Copy Constructor: Not built-in; implemented by taking an object of the same class as parameter.
-
-
Example: Area of Circle using Constructor.
class Circle {
double radius;
Circle(double r) { radius = r; } // Parameterized
double area() { return Math.PI * radius * radius; }
}
static and final Keywords
-
static:-
Class-level member (one copy per class).
-
staticvariables: Shared among all objects. -
staticmethods: Can be called without object (usingClassName.method()). Cannot access instance members directly.
-
-
final:-
Variable: Constant (value cannot be changed after initialization).
-
Method: Cannot be overridden by subclasses.
-
Class: Cannot be inherited (e.g.,
Stringclass).
-
[!TIP]
staticmethods are often used as utility methods (e.g.,Math.sqrt()).finalvariables are typicallystatic(e.g.,Math.PI).
2. Object-Oriented Programming - Advanced Features
Method Overloading vs Method Overriding
| Feature | Overloading | Overriding |
|---|---|---|
| Definition | Multiple methods with same name but different parameters in same class. | Subclass provides specific implementation of a method already defined in superclass. |
| Parameters | Must differ in type/number/order. | Must be identical to superclass method. |
| Return Type | Can be different. | Must be covariant (same or subclass). |
| Access Modifier | Can be any. | Cannot be more restrictive (e.g., public → private invalid). |
| Static/Final | Can overload static/final methods. |
Cannot override static (hiding) or final methods. |
| Binding | Compile-time (early binding). | Runtime (dynamic dispatch). |
| Example | add(int, int), add(double, double) |
@Override void display() in subclass. |
Dynamic Method Dispatch
-
Mechanism where overridden method is called at runtime based on the actual object type, not reference type.
-
Enables runtime polymorphism.
-
Example:
class Animal { void sound() { System.out.println("Animal"); } }
class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } }
class Cat extends Animal { @Override void sound() { System.out.println("Meow"); } }
public class Test {
public static void main(String[] args) {
Animal a;
a = new Dog(); a.sound(); // Output: Bark
a = new Cat(); a.sound(); // Output: Meow
}
}
Abstract Classes
-
Declared with
abstractkeyword. -
May contain abstract methods (no body) and concrete methods.
-
Cannot be instantiated; must be subclassed.
-
When to use:
-
Share common code among related classes.
-
Define a template with partial implementation.
-
Force subclasses to implement specific methods (via abstract methods).
-
-
vs Concrete Classes: Concrete classes have no abstract methods and can be instantiated.
Interfaces
-
Contract of methods (implicitly
public abstract). -
Achieve multiple inheritance (a class can
implementmultiple interfaces). -
From Java 8:
-
Default methods:
default void method() { ... }– provide implementation. -
Static methods:
static void method() { ... }– interface-specific utility.
-
-
vs Abstract Classes:
-
Interface: All methods public abstract by default (except default/static). Fields
public static final. -
Abstract Class: Can have any access modifiers, constructors, instance variables.
-
Use interface for pure abstraction and multiple inheritance; abstract class for shared code among closely related classes.
-
Inheritance and Polymorphism in Practice
-
Inheritance:
extendskeyword. Supports code reuse and hierarchical classification. -
Polymorphism: Used via method overriding (dynamic dispatch) and method overloading (compile-time).
-
Practical Example: Shape hierarchy with
area()method overridden inCircle,Rectangle.
3. Packages and Access Control
Creating Packages
-
Use
package package_name;as first statement in Java file. -
Directory structure must match package name (e.g.,
com.example→ foldercom/example). -
Example:
// File: com/myapp/Calculator.java
package com.myapp;
public class Calculator { ... }
Importing Packages
-
import package.ClassName;– imports single class. -
import package.*;– imports all classes (not subpackages). -
Static import:
import static package.ClassName.staticMember;– allows direct use of static members without class name.
Access Modifiers
| Modifier | Class | Package | Subclass (same pkg) | Subclass (diff pkg) | World |
|---|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ | ✓ |
protected |
✓ | ✓ | ✓ | ✓ (via inheritance) | ✗ |
| default (no modifier) | ✓ | ✓ | ✓ | ✗ | ✗ |
private |
✓ | ✗ | ✗ | ✗ | ✗ |
[!TIP]
protectedallows access in subclasses only through inheritance (not via reference in different package).
4. Exception Handling
Exception Hierarchy
Throwable
├── Error (JVM errors, e.g., OutOfMemoryError) – not handled
└── Exception
├── RuntimeException (unchecked, e.g., NullPointerException)
└── Checked Exceptions (must be handled, e.g., IOException)
try-catch-finally
try {
// risky code
} catch (ExceptionType1 e1) {
// handle
} catch (ExceptionType2 e2) {
// handle
} finally {
// always executes (even if return in try/catch)
}
-
Multiple catch blocks: Order from specific to general.
-
finally: For cleanup (e.g., closing files, DB connections).
throw vs throws
throw |
throws |
|---|---|
| Used inside method to raise an exception. | Used in method signature to declare exceptions that method might throw. |
Followed by an exception object (e.g., throw new IOException();). |
Followed by exception class names (e.g., void read() throws IOException). |
| Can throw one exception at a time. | Can declare multiple exceptions (comma-separated). |
Custom Exceptions
- Extend
Exception(checked) orRuntimeException(unchecked).
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) { super(msg); }
}
Assertions (assert)
-
Used for debugging.
-
Syntax:
assert condition : "message"; -
Disabled by default; enable with
-eaJVM option. -
Use cases: Validate assumptions, check invariants. Not for production error handling.
[!TIP] Always handle checked exceptions; unchecked exceptions indicate programming bugs.
5. Multithreading
Thread Creation
-
Extend
Threadclass:class MyThread extends Thread { public void run() { ... } } new MyThread().start(); -
Implement
Runnableinterface (preferred, as Java doesn't support multiple inheritance):class MyRunnable implements Runnable { public void run() { ... } } new Thread(new MyRunnable()).start();
Thread Lifecycle
-
New: Thread object created, not started.
-
Runnable:
start()called; ready to run (may be running or waiting CPU). -
Running: Thread is executing.
-
Blocked/Waiting: Waiting for resource (I/O, lock,
sleep(),wait()). -
Terminated:
run()completed orstop()(deprecated).
Thread Synchronization
-
Purpose: Prevent race conditions when multiple threads access shared resources.
-
synchronizedkeyword:-
Method:
synchronized void method() { ... }– lock onthis. -
Block:
synchronized(object) { ... }– lock on specified object.
-
-
Example: Synchronized counter.
class Counter {
private int count = 0;
public synchronized void increment() { count++; }
}
Inter-Thread Communication
-
Methods:
wait(),notify(),notifyAll()– called from synchronized context. -
wait(): Releases lock, thread enters waiting state. -
notify()/notifyAll(): Wakes up waiting thread(s); lock not released immediately. -
Example: Producer-Consumer problem.
Thread Priorities and Scheduling
-
Priorities:
MIN_PRIORITY (1)toMAX_PRIORITY (10), defaultNORM_PRIORITY (5). -
Scheduling: OS-dependent; higher priority threads get CPU time more often, but not guaranteed.
[!TIP] Always use
synchronizedwhen callingwait()/notify()to avoidIllegalMonitorStateException.
6. Input/Output Streams
Stream Concept
-
Byte Streams: Handle raw binary data (8-bit bytes). Classes:
InputStream,OutputStream. -
Character Streams: Handle text data (16-bit Unicode). Classes:
Reader,Writer.
Byte Streams
FileInputStream/FileOutputStream: Read/write raw bytes.
FileInputStream fis = new FileInputStream("file.txt");
int data;
while ((data = fis.read()) != -1) {
// process byte
}
fis.close();
Character Streams
-
FileReader/FileWriter: Read/write characters (uses default encoding). -
BufferedReader/BufferedWriter: Buffered for efficiency (read/write arrays). -
PrintWriter: Convenientprint()/println()methods.
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
Taking Input from User
-
Scanner(simple, token-based):Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String s = sc.nextLine(); -
BufferedReader(faster for large input):BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String input = br.readLine();
[!TIP] Always close streams in
finallyblock or use try-with-resources (Java 7+).
7. Networking in Java
Socket Programming
-
Server:
ServerSocketlistens on a port. -
Client:
Socketconnects to server. -
Communication:
InputStream/OutputStreamover socket.
Example: Simple Client-Server Message Exchange.
// Server
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept(); // waits for client
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
String msg = in.readLine();
out.println("Echo: " + msg);
s.close(); ss.close();
// Client
Socket s = new Socket("localhost", 1234);
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
out.println("Hello Server");
System.out.println(in.readLine());
s.close();
8. Graphical User Interface (GUI) Programming
AWT (Abstract Window Toolkit)
-
Components:
Button,Label,TextField– lightweight. -
Containers:
Frame,Panel,Applet– hold components. -
Layout Managers: Arrange components (e.g.,
FlowLayout,BorderLayout,GridLayout). -
Event Handling Model:
-
Event Source: Component generating event (e.g., button click).
-
Event Object: Encapsulates event details (e.g.,
ActionEvent). -
Event Listener: Interface with handler methods (e.g.,
ActionListenerwithactionPerformed()). -
Adapter Classes: Provide empty implementations (e.g.,
WindowAdapter).
-
Swing
-
Lightweight components (pure Java, drawn on screen).
-
Pluggable Look and Feel: Can change UI appearance (e.g., Windows, Metal).
-
Example: Sum of Two Numbers.
import javax.swing.*;
import java.awt.event.*;
public class SumGUI {
public static void main(String[] args) {
JFrame f = new JFrame("Sum");
JTextField t1 = new JTextField(10);
JTextField t2 = new JTextField(10);
JButton b = new JButton("Add");
JLabel res = new JLabel();
b.addActionListener(e -> {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
res.setText("Sum: " + (a+b));
});
JPanel p = new JPanel();
p.add(t1); p.add(t2); p.add(b); p.add(res);
f.add(p); f.pack(); f.setVisible(true);
}
}
Applets
-
Life Cycle:
-
init(): First call, initialize resources. -
start(): Called afterinit(), or when applet becomes visible. -
stop(): Called when applet is obscured (e.g., browser minimized). -
destroy(): Final cleanup before garbage collection. -
paint(Graphics g): Render graphics (called onstart()and when repainted).
-
-
Applet vs Application:
-
Applet: Runs in browser, no
main(), security restrictions. -
Application: Standalone, has
main(), full system access.
-
9. Database Connectivity (JDBC)
JDBC Architecture
-
DriverManager: Manages JDBC drivers. -
Connection: Represents DB connection. -
Statement/PreparedStatement: Execute SQL queries. -
ResultSet: Holds query results.
Steps for Database Access
-
Load driver:
Class.forName("com.mysql.jdbc.Driver");(JDBC 4.0+ often not needed). -
Establish connection:
Connection con = DriverManager.getConnection(url, user, pass); -
Create statement:
Statement stmt = con.createStatement(); -
Execute query:
-
ResultSet rs = stmt.executeQuery("SELECT * FROM table");(forSELECT) -
int rows = stmt.executeUpdate("INSERT INTO ...");(forINSERT/UPDATE/DELETE)
-
-
Process results:
while(rs.next()) { ... } -
Close resources:
rs.close(); stmt.close(); con.close();(in reverse order).
JDBC-ODBC Bridge
-
Purpose: Allowed Java to access ODBC data sources (via
sun.jdbc.odbc.JdbcOdbcDriver). -
Deprecated in Java 8; removed in later versions. Use pure Java JDBC drivers instead.
10. Advanced Java Features
Java Beans
-
Component Architecture: Reusable software components.
-
Properties: Private fields with getter/setter methods (e.g.,
getX(),setX()). -
Events: Follow listener pattern (e.g.,
addActionListener()). -
Introspection: Mechanism to discover bean properties/events/methods at runtime.
-
BeanInfointerface: Implemented by bean designer to explicitly expose features. -
getBeanInfo(beanClass): ReturnsBeanInfoobject;getPropertyDescriptors()etc.
-
Java Naming and Directory Interface (JNDI)
-
API for accessing naming/directory services (e.g., LDAP, DNS).
-
Naming Context Methods:
-
bind(String name, Object obj): Binds name to object. -
rebind(String name, Object obj): Replaces existing binding. -
createSubcontext(String name): Creates new subcontext. -
getAttributes(String name): Returns attributes of named object. -
modifyAttributes(String name, Attributes attrs): Modifies attributes.
-
Garbage Collection
-
Mechanism: JVM automatically reclaims memory from unreachable objects.
-
System.gc(): Suggestion to JVM to run GC; not guaranteed. -
finalize(): Called by GC before object is collected (deprecated in Java 9+; usetry-with-resourcesorCleaner).
Copy Constructor in Java
- Not built-in; implemented manually:
class Student {
int id;
String name;
Student(Student s) { // Copy constructor
this.id = s.id;
this.name = s.name;
}
}
[!TIP] Prefer
clone()(fromCloneable) or copy constructors for object duplication; both have pitfalls (shallow vs deep copy).