I. Introduction to Java
Features of Java:
-
Simple: Syntax similar to C/C++, but eliminates pointers and operator overloading.
-
Secure: No explicit pointers, bytecode verification, sandbox execution.
-
Portable: Bytecode runs on any JVM (Write Once, Run Anywhere).
-
Object-Oriented: Everything is an object (except primitives); supports encapsulation, inheritance, polymorphism, abstraction.
-
Robust: Strong memory management, exception handling, type checking.
-
Multithreaded: Built-in support for concurrent programming.
-
Distributed: Supports RMI and socket programming.
-
Dynamic: Classes loaded at runtime, reflection API.
Java Virtual Machine (JVM) & Bytecode:
-
Java source code (
.java) → Compiler → Bytecode (.class). -
JVM interprets bytecode into machine-specific instructions.
-
JVM provides platform independence, security, and automatic garbage collection.
Platform Independence:
-
Bytecode is platform-neutral; JVM is platform-specific.
-
\boxed{\text{Write Once, Run Anywhere (WORA)}}
Java as OOP Language:
-
Encapsulation: Bundling data and methods, access control via modifiers.
-
Inheritance:
extendskeyword for code reuse. -
Polymorphism: Method overloading (compile-time) and overriding (runtime).
-
Abstraction: Abstract classes and interfaces hide implementation.
[!TIP]
Common Pitfall: Java is not purely object-oriented due to primitive types (e.g.,
int,char). Use wrapper classes (Integer,Character) for pure OOP.
II. Data Types, Variables, and Operators
Primitive Data Types:
| Type | Size (bits) | Range | Default Value |
|---|---|---|---|
byte |
8 | -128 to 127 | 0 |
short |
16 | -32,768 to 32,767 | 0 |
int |
32 | -2³¹ to 2³¹-1 | 0 |
long |
64 | -2⁶³ to 2⁶³-1 | 0L |
float |
32 | ~7 decimal digits | 0.0f |
double |
64 | ~15 decimal digits | 0.0d |
char |
16 | Unicode 0 to 65,535 | '' |
boolean |
1 | true/false |
false |
Reference Data Types:
-
Classes, interfaces, arrays. Store references (memory addresses).
-
Default value:
null.
Variable Types:
-
Local: Inside method/block, no default value, must initialize.
-
Instance: Non-static fields, per-object, default values.
-
Static: Class-level, shared among objects, default values.
Operators:
-
Arithmetic:
+,-,*,/,%,++,--. -
Relational:
==,!=,>,<,>=,<=. -
Logical:
&&,||,!. -
Bitwise:
&,|,^,~,<<,>>,>>>. -
Assignment:
=,+=,-=, etc. -
Ternary:
condition ? expr1 : expr2.
[!TIP]
Common Pitfall:
==compares references for objects; use.equals()for value comparison.
III. Control Statements
Selection Statements:
-
if,if-else, nestedif. -
switch: Works withbyte,short,int,char,String(Java 7+),enum.casevalues must be constants.
Iteration Statements:
-
for(init; condition; update) { } -
while(condition) { } -
do { } while(condition);// Executes at least once. -
Enhanced
for:for(type var : array/collection) { }// For arrays/collections only.
Jump Statements:
-
break: Exits loop orswitch. -
continue: Skips current iteration, proceeds to next. -
return: Exits method, returns value (if any).
[!TIP]
Common Pitfall:
continueindo-whilejumps to condition check, not loop start. Labeledbreak/continuefor nested loops.
IV. Arrays and Strings
Arrays:
-
Declaration:
int[] arr;orint arr[]; -
Initialization:
-
int[] arr = new int[5];// Default 0s. -
int[] arr = {1,2,3}; -
int[] arr = new int[]{1,2,3};
-
-
Multi-dimensional:
int[][] matrix = new int[3][4];// Jagged arrays possible.
String Class:
-
Immutable: Cannot change content; operations create new objects.
-
Common Methods:
length(),charAt(index),substring(begin, end),equals(),equalsIgnoreCase(),indexOf(),toUpperCase(),toLowerCase(),trim(),split(regex).
-
String Literals: Stored in String Pool; identical literals share same reference.
StringBuffer vs StringBuilder:
| Feature | StringBuffer |
StringBuilder |
|---|---|---|
| Mutability | Mutable | Mutable |
| Thread-Safety | Synchronized (thread-safe) | Not synchronized (faster) |
| Performance | Slower | Faster |
| Use Case | Multi-threaded environments | Single-threaded environments |
[!TIP]
Common Pitfall:
Stringconcatenation in loops (+) creates many temporary objects; useStringBuilderfor efficiency.
V. Classes and Objects
Defining a Class:
class ClassName {
// fields (instance/static)
// methods
// constructors
}
Creating Objects:
ClassName obj = new ClassName();//newallocates memory, calls constructor.
Instance vs Static Members:
-
Instance: Per-object, accessed via object reference.
-
Static: Class-level, accessed via
ClassName.memberor object. One copy per class.
this Keyword:
-
Refers to current object.
-
Used to disambiguate instance variables from parameters, call constructors (
this()), pass current object as argument.
Constructors:
-
Default Constructor: No-args, provided by compiler if no other constructor exists. Initializes primitives to default, objects to
null. -
Parameterized Constructor: Takes arguments, used to initialize fields.
-
Copy Constructor: Not built-in; user-defined:
Class(Class other) { this.field = other.field; }.
Method Overloading:
-
Same method name, different parameter lists (type, number, order).
-
Compile-time polymorphism.
-
Return type can differ, but not sufficient for overloading.
[!TIP]
Common Pitfall: Constructor name must match class name exactly; no return type (not even
void).
VI. Inheritance and Polymorphism
Inheritance (extends):
-
Subclass inherits superclass members (except private).
-
Single inheritance for classes; multiple via interfaces.
super Keyword:
-
Refers to parent class.
-
super()calls parent constructor (must be first statement). -
super.method()calls parent method. -
super.fieldaccesses parent field.
Method Overriding:
-
Subclass redefines superclass method with same signature.
-
Used for runtime polymorphism.
-
@Overrideannotation (optional but recommended). -
Access modifier cannot be more restrictive.
-
finalmethods cannot be overridden.
Dynamic Method Dispatch (Runtime Polymorphism):
-
Superclass reference can refer to subclass object.
-
Overridden method call resolved at runtime based on actual object type.
Animal a = new Dog();
a.sound(); // Calls Dog.sound() if overridden.
Abstract Classes and Methods:
-
Abstract class: Cannot instantiate; may contain abstract methods (no body) and concrete methods.
-
Abstract method: Must be implemented by concrete subclasses.
-
Class must be
abstractif it has any abstract method.
Interfaces:
-
Definition:
interface InterfaceName { abstract methods (implicitly public abstract), static/final fields, default/static methods (Java 8+). } -
Implementation:
class MyClass implements Interface1, Interface2 { }// Multiple inheritance. -
All methods are
public abstractby default (pre-Java 8). -
Variables are
public static finalby default.
final Keyword:
-
final class: Cannot be subclassed (e.g.,
String,Integer). -
final method: Cannot be overridden.
-
final variable: Constant; cannot reassign (but object state can change if mutable).
Multiple Inheritance in Java:
-
Not allowed for classes (diamond problem).
-
Achieved via interfaces: class can implement multiple interfaces; interfaces can extend multiple interfaces.
[!TIP]
Common Pitfall: Overriding method must have same signature (including return type, which can be covariant).
staticmethods are hidden, not overridden.
VII. Packages and Access Protection
Creating Packages:
-
package com.example.myapp;// First statement in.javafile. -
Directory structure must match package hierarchy.
-
Compile:
javac -d . MyClass.java// Createscom/example/myapp/MyClass.class.
Importing Packages:
-
import com.example.myapp.MyClass;// Single type. -
import com.example.myapp.*;// All types (except subpackages). -
Static import:
import static java.lang.Math.PI;// Access static members without class name.
Access Modifiers:
| Modifier | Class | Package | Subclass (outside) | Everywhere |
|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ |
protected |
✓ | ✓ | ✓ | ✗ |
| default (no modifier) | ✓ | ✓ | ✗ | ✗ |
private |
✓ | ✗ | ✗ | ✗ |
Levels of Access Protection:
-
Within class: All members accessible.
-
Within package:
public,protected, default accessible. -
Outside package (subclass):
public,protectedaccessible (via inheritance). -
Outside package (non-subclass): Only
publicaccessible.
Access for Classes/Interfaces:
-
Top-level classes/interfaces: Only
publicor default. -
Nested classes: All modifiers allowed.
[!TIP]
Common Pitfall:
protectedallows access in subclasses even if in different package, but only through inheritance (not via reference of parent class from different package).
VIII. Exception Handling
Exception Types:
-
Checked Exceptions: Subclasses of
Exception(excludingRuntimeException). Must be handled or declared (e.g.,IOException,SQLException). -
Unchecked Exceptions: Subclasses of
RuntimeExceptionorError. Not required to handle (e.g.,NullPointerException,ArithmeticException).
try-catch-finally:
try {
// Code that may throw exception
} catch (ExceptionType1 e1) {
// Handler
} catch (ExceptionType2 e2) {
// Handler
} finally {
// Always executes (even if return in try/catch), for cleanup
}
-
Multiple
catchblocks; more specific first. -
trywith resources (Java 7+):try (FileReader fr = new FileReader("file.txt")) { }// Auto-close.
throw vs throws:
-
throw: Used to raise an exception explicitly.throw new IllegalArgumentException(); -
throws: Used in method signature to declare exceptions that method might throw.void read() throws IOException { }
Custom Exceptions:
-
Extend
Exception(for checked) orRuntimeException(for unchecked). -
Provide constructors (no-arg, with message, with cause).
Assertions (assert):
-
assert condition;orassert condition : message; -
Enabled at runtime with
-ea(or-enableassertions). Disabled by default. -
Used for debugging, not for production error handling.
[!TIP]
Common Pitfall:
finallyblock executes even ifreturnintry/catch, but not ifSystem.exit()called. Catch blocks should be specific; avoid empty catch blocks.
IX. Multithreading
Thread Creation:
-
Extend
Threadclass:class MyThread extends Thread { public void run() { /* task */ } } MyThread t = new MyThread(); t.start(); // Calls run() in new thread -
Implement
Runnableinterface (preferred for multiple inheritance):class MyRunnable implements Runnable { public void run() { /* task */ } } Thread t = new Thread(new MyRunnable()); t.start();
Thread Lifecycle:
Thread Methods:
-
start(): Starts thread, callsrun(). -
run(): Entry point for thread logic. -
sleep(ms): Pauses thread (static method). -
join(): Waits for thread to die. -
isAlive(): Checks if thread is alive (New or Terminated → false). -
setPriority(int): 1 (MIN) to 10 (MAX). -
setDaemon(boolean): Daemon threads (background) die when main thread ends.
Thread Synchronization:
-
Purpose: Prevent race conditions when multiple threads access shared resources.
-
Synchronized methods:
public synchronized void method() { }// Locks onthis(instance) orClassobject (static). -
Synchronized blocks:
synchronized(lockObject) { // critical section } -
ReentrantLock(java.util.concurrent.locks): More flexible thansynchronized; explicit lock/unlock.
Inter-thread Communication:
-
Must be called from synchronized context.
-
wait(): Releases lock, enters waiting state. -
notify(): Wakes one waiting thread. -
notifyAll(): Wakes all waiting threads. -
Used for producer-consumer problems.
[!TIP]
Common Pitfall: Never call
run()directly to start a thread; usestart().sleep()is static;Thread.sleep()affects current thread.wait(),notify(),notifyAll()are inObjectclass, notThread.
X. I/O Streams
Stream Concept:
- Sequence of data. Byte streams handle binary data; character streams handle text (with encoding).
Byte Streams:
-
Abstract classes:
InputStream,OutputStream. -
File I/O:
FileInputStream,FileOutputStream. -
Buffered:
BufferedInputStream,BufferedOutputStream(efficiency via buffer). -
Standard:
System.in(InputStream),System.out(PrintStream),System.err.
Character Streams:
-
Abstract classes:
Reader,Writer. -
File I/O:
FileReader,FileWriter(uses default encoding). -
Buffered:
BufferedReader(hasreadLine()),BufferedWriter. -
Conversion:
InputStreamReader(bytes to chars),OutputStreamWriter(chars to bytes).
Difference: Byte vs Character Streams:
| Byte Streams | Character Streams |
|---|---|
| Handle raw binary data | Handle text (Unicode) |
InputStream/OutputStream |
Reader/Writer |
| No encoding/decoding | Encoding/decoding involved |
| E.g., images, audio | E.g., text files |
Capturing Input from User:
-
Scanner(java.util):Scanner sc = new Scanner(System.in); int n = sc.nextInt(); -
BufferedReader:BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); -
Scanneris easier;BufferedReaderis faster for large input.
[!TIP]
Common Pitfall: Always close streams (use try-with-resources).
FileReader/FileWriteruse platform default encoding; specify encoding withInputStreamReader/OutputStreamWriterfor portability.
XI. GUI Programming (AWT and Swing)
AWT Facilities:
-
Components: UI elements (
Button,TextField,Label,Checkbox,Choice,List). -
Containers: Hold components (
Frame,Panel,Applet,Dialog). -
Layout Managers: Arrange components:
-
FlowLayout(left to right, wraps). -
BorderLayout(North, South, East, West, Center). -
GridLayout(grid of equal-sized cells). -
GridBagLayout(flexible grid). -
CardLayout(stacked cards).
-
Swing Components:
-
Lightweight, pluggable look-and-feel.
-
Prefixed with
J:JFrame,JPanel,JButton,JTextField,JLabel,JCheckBox,JComboBox,JList,JTable, etc. -
JApplet(deprecated),JDialog.
Event Handling Model:
-
Event Source: Component that generates event (e.g.,
JButton). -
Event Object: Encapsulates event info (e.g.,
ActionEvent). -
Event Listener: Interface with callback methods (e.g.,
ActionListenerwithactionPerformed(ActionEvent e)). -
Event Adapter: Abstract class with empty implementations (e.g.,
WindowAdapter,MouseAdapter) for convenience.
Example: Sum of Two Numbers (Swing):
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SumGUI extends JFrame implements ActionListener {
JTextField t1, t2, res;
JButton add;
public SumGUI() {
t1 = new JTextField(10); t2 = new JTextField(10); res = new JTextField(10);
add = new JButton("Add");
add.addActionListener(this);
setLayout(new FlowLayout());
add(t1); add(t2); add(add); add(res);
setSize(300,200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int a = Integer.parseInt(t1.getText());
int b = Integer.parseInt(t2.getText());
res.setText(String.valueOf(a+b));
}
public static void main(String[] args) { new SumGUI(); }
}
[!TIP]
Common Pitfall: Swing components must be created/updated on Event Dispatch Thread (EDT) using
SwingUtilities.invokeLater(). AWT is heavyweight; Swing is lightweight (but mixing can cause issues).
XII. Applets
Applet vs Application:
-
Applet: Runs in browser/AppletViewer, no
main(), security restrictions, lifecycle methods. -
Application: Standalone, has
main(), full system access.
Applet Life Cycle:
-
init(): Called once when applet first loads. Initialize resources. -
start(): Called afterinit(), and whenever applet becomes visible (e.g., browser tab switched to). Start animations/threads. -
stop(): Called when applet becomes invisible (e.g., browser tab switched away). Pause threads. -
destroy(): Called when browser closes/applet removed. Cleanup resources.
Applet Tags (HTML):
<applet code="MyApplet.class" width=300 height=200>
<param name="text" value="Hello">
</applet>
-
code: Class file. -
width,height: Dimensions. -
<param>: Pass parameters viagetParameter("name").
Example Applet:
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello Applet", 50, 50);
}
}
[!TIP]
Common Pitfall: Applets are deprecated (Java 9+); use Java Web Start or other technologies. Lifecycle:
init()→start()→stop()→destroy();start()/stop()may be called multiple times.
XIII. Database Connectivity (JDBC)
JDBC Architecture:
-
JDBC API:
java.sqlandjavax.sqlpackages. -
JDBC Drivers: Type 1 (JDBC-ODBC bridge), Type 2 (native API), Type 3 (network protocol), Type 4 (pure Java, thin driver).
-
DriverManager: Manages drivers, establishes connections.
Steps to Connect:
-
Load driver:
Class.forName("com.mysql.cj.jdbc.Driver");// Registers driver. -
Establish connection:
Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/dbname", "user", "password"); -
Create statement:
-
Statement stmt = conn.createStatement();// For static SQL. -
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO table VALUES (?, ?)");// For dynamic SQL with parameters.
-
-
Execute query:
-
ResultSet rs = stmt.executeQuery("SELECT * FROM table");// For SELECT. -
int rows = stmt.executeUpdate("INSERT ...");// For INSERT/UPDATE/DELETE.
-
-
Process results:
while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); } -
Close connections:
rs.close(); stmt.close(); conn.close();// In reverse order. Use try-with-resources.
JDBC-ODBC Bridge:
-
Type 1 driver; translates JDBC calls to ODBC.
-
Requires ODBC driver installed.
-
Deprecated in Java 8; removed in Java 11.
Basic JDBC Program Structure:
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "user", "pass");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
while (rs.next()) System.out.println(rs.getInt(1) + " " + rs.getString(2));
rs.close(); stmt.close(); conn.close();
} catch (Exception e) { e.printStackTrace(); }
}
}
[!TIP]
Common Pitfall: Always close
ResultSet,Statement,Connectioninfinallyblock or try-with-resources to avoid leaks. UsePreparedStatementto prevent SQL injection.
XIV. Networking
Networking Basics:
-
IP Address: Unique identifier for device on network.
-
Port: 16-bit number (0-65535) identifying process/service.
-
Protocol: Rules for communication (TCP = reliable, connection-oriented; UDP = fast, connectionless).
Socket Programming:
-
Server:
ServerSocket server = new ServerSocket(port); Socket client = server.accept(); // Blocks until client connects // Get I/O streams: InputStream in = client.getInputStream(); OutputStream out = client.getOutputStream(); -
Client:
Socket socket = new Socket(host, port); // Get I/O streams
Client-Server Example (Echo):
Server:
import java.net.*;
import java.io.*;
public class EchoServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
String line;
while ((line = in.readLine()) != null) {
out.println("Echo: " + line);
}
s.close(); ss.close();
}
}
Client:
import java.net.*;
import java.io.*;
public class EchoClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream(), true);
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = console.readLine()) != null) {
out.println(line);
System.out.println(in.readLine());
}
s.close();
}
}
[!TIP]
Common Pitfall: Server must start before client. Use
try-with-resourcesfor sockets/streams. HandleIOException.
XV. Java Beans
Java Beans Components:
-
Properties: Private fields with public getter/setter methods (e.g.,
getX(),setX()). -
Methods: No-arg constructor, getter/setter, any business methods.
-
Events: Support event listeners (e.g.,
addActionListener(ActionListener l)).
Introspection:
-
Process of discovering bean properties, methods, events at runtime.
-
Uses reflection API.
BeanInfo Interface:
-
java.beans.BeanInfoprovides explicit bean information. -
Override methods:
getPropertyDescriptors(),getMethodDescriptors(),getEventSetDescriptors(). -
Obtain via
Introspector.getBeanInfo(BeanClass.class). -
Allows hiding properties/methods, customizing display names.
Bean Properties Types:
-
Simple: Single value,
getX(),setX(). -
Indexed: Array access,
getX(int index),setX(int index, value). -
Bound: Supports
PropertyChangeListener; firePropertyChangeEventon change. -
Constrained: Supports
VetoableChangeListener; listeners can veto change.
Bean Events:
-
Event listener registration methods (e.g.,
addActionListener). -
Corresponding removal methods (e.g.,
removeActionListener). -
Event listener interfaces (e.g.,
ActionListener).
[!TIP]
Common Pitfall: Beans must have a public no-arg constructor. Properties must follow naming conventions (
get/setfor boolean can beis).
XVI. JNDI (Java Naming and Directory Interface)
JNDI Overview:
-
API for accessing naming and directory services (e.g., LDAP, DNS, RMI registry).
-
Provides uniform interface to diverse systems.
Context Interface Methods:
-
bind(String name, Object obj): Binds name to object. -
rebind(String name, Object obj): Rebinds name (overwrites existing). -
lookup(String name): Returns object bound to name. -
unbind(String name): Removes binding. -
rename(String oldName, String newName): Renames binding. -
createSubcontext(String name): Creates subcontext. -
getAttributes(String name): Returns attributes for named object. -
modifyAttributes(String name, Attributes attrs): Modifies attributes.
JNDI Example (Naming Service):
import javax.naming.*;
import java.util.Hashtable;
public class JNDIExample {
public static void main(String[] args) throws NamingException {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
env.put(Context.PROVIDER_URL, "file:/C:/JNDI");
Context ctx = new InitialContext(env);
// Bind
ctx.bind("myObj", "Hello JNDI");
// Lookup
String value = (String) ctx.lookup("myObj");
System.out.println(value); // Hello JNDI
// Rebind
ctx.rebind("myObj", "Updated");
// Unbind
ctx.unbind("myObj");
ctx.close();
}
}
Note: Provider-specific factories and URLs required.
[!TIP]
Common Pitfall: JNDI requires provider libraries (e.g.,
fscontext.jarfor file system).lookup()returnsObject; cast appropriately.
XVII. Garbage Collection
Purpose & Mechanism:
-
Automatic memory management; reclaims memory from unreachable objects.
-
Eligibility: Object becomes eligible when no references point to it (e.g.,
obj = null;, reference goes out of scope, isolated cycles). -
Process: JVM runs GC periodically or when memory low.
-
Phases: Mark (identify reachable objects), Sweep (reclaim unreachable), Compact (optional, defragment heap).
System.gc() and Runtime.gc():
-
Suggest JVM to run GC.
-
Not guaranteed; JVM may ignore.
-
Runtime.getRuntime().gc()equivalent.
finalize() Method:
-
Called by GC on object before回收 (only once).
-
Declared in
Objectclass; override for cleanup (e.g., closing resources). -
Unreliable: May never be called, or called multiple times if object resurrected.
-
Deprecated (since Java 9); use
try-with-resourcesorCleaner(Java 9+).
Types of Garbage Collectors (Brief):
-
Serial GC: Single thread, for small apps.
-XX:+UseSerialGC -
Parallel GC (Throughput): Multi-threaded, maximizes throughput.
-XX:+UseParallelGC -
CMS (Concurrent Mark Sweep): Concurrent with app threads, low pause times (deprecated).
-
G1 (Garbage-First): Divides heap into regions, predictable pauses. Default since Java 9.
-XX:+UseG1GC -
ZGC / Shenandoah: Low-latency, scalable (Java 11+).
[!TIP]
Common Pitfall: Do not rely on
finalize()for critical cleanup; it may not run. Avoid creating unnecessary objects to reduce GC pressure. Use profiling tools to monitor GC.