[Go to site: main page, start]

0% found this document useful (0 votes)
6 views33 pages

Java Complete Notes

The document is a comprehensive study guide for Java, covering essential topics such as OOP, inheritance, exceptions, threads, GUI, networking, and JDBC. It includes detailed explanations, code snippets, diagrams, and 40 viva questions for exam preparation. Each chapter focuses on specific concepts, providing a structured approach to learning Java programming.

Uploaded by

Shaurab Singh
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)
6 views33 pages

Java Complete Notes

The document is a comprehensive study guide for Java, covering essential topics such as OOP, inheritance, exceptions, threads, GUI, networking, and JDBC. It includes detailed explanations, code snippets, diagrams, and 40 viva questions for exam preparation. Each chapter focuses on specific concepts, providing a structured approach to learning Java programming.

Uploaded by

Shaurab Singh
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

COMPLETE JAVA NOTES Comprehensive Study Guide

COMPLETE

JAVA NOTES
Comprehensive Study Guide — All Topics Covered

OOP • Inheritance • Exceptions • Threads • GUI • Networking • JDBC

✓ All 7 Chapters Covered ✓ Real-World Examples

✓ Code Snippets Included ✓ Diagrams & Tables

✓ Easy Language ✓ 40 Viva Q&A Included

Chapt
Title Topics
er

Ch 1 OOP Concepts & Java Basics Encapsulation, Abstraction, JVM, Data Types, Operators

Ch 2 OOP Deep Dive Classes, Arrays, Strings, Constructors, Overloading

Ch 3 Inheritance & Polymorphism Inheritance Types, super, final, Interfaces, Packages

Ch 4 Exception Handling & Threads try-catch-finally, Thread Lifecycle, Synchronization

Ch 5 AWT & Swing GUI AWT Components, Swing Widgets, Layouts, Event Handling

Ch 6 Networking in Java TCP/UDP, Sockets, InetAddress, URL, Client-Server

Ch 7 JDBC & Database Drivers, Connection, CRUD, ResultSet, PreparedStatement

Bonus 40 Viva Questions All Topics — Important Exam Questions with Answers

Java — Complete Study Guide Page 1 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 1

OOP Concepts & Java Basics


Object Orientation • JVM • Data Types • Operators • Control Flow

Q1.

List and Explain Object-Oriented Features of Java


Object-Oriented Programming (OOP) is a programming style where we write code around objects rather
than just functions. Java has FOUR main pillars:

1. Encapsulation
Keeping data (variables) and actions (methods) together inside a class, and hiding data from outside
access. Only specific methods allow controlled access.

■ Real World: A TV remote — buttons (methods) are visible, but the complex circuit inside (data) is hidden.

2. Abstraction
Showing only what is necessary and hiding complex details. In Java, achieved using abstract classes and
interfaces.

■ Real World: Pressing 'Send' on WhatsApp — you don't see network packets or encryption, just the
message delivered.

3. Inheritance
A child class REUSES all properties and methods of a parent class using the 'extends' keyword. Parent =
superclass, Child = subclass.

■ Real World: A Dog class inherits everything from Animal class automatically — just like a child inherits
traits from parents.

4. Polymorphism
The same method name behaves DIFFERENTLY depending on the situation. Two types: compile-time
(overloading) and runtime (overriding).

■ Real World: The word 'draw' means different things to an artist, architect, and programmer — same word,
different meaning.

class BankAccount {
private double balance = 5000; // data is hidden
public double getBalance() { // controlled access
return balance;
}
public void deposit(double amt) { balance += amt; }
}

abstract class Vehicle {

Java — Complete Study Guide Page 2 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

abstract void start(); // abstraction - no body


}
class Car extends Vehicle {
void start() { [Link]("Car engine starts!"); }
}

class Printer {
void print(int n) { [Link]("Int: " + n); }
void print(String s) { [Link]("Str: " + s); } // overloading
void print(double d) { [Link]("Dbl: " + d); }
}

Q2.

List Features of Java and Explain Any Three


Java was designed to be safe, simple, fast, and platform-independent. The 8 main features are:
Object-Oriented, Platform-Independent, Simple, Secure, Robust, Portable, Multithreaded, High
Performance.

★ Platform-Independent: Java code is compiled into Bytecode (not machine code). This bytecode
runs on ANY OS (Windows, Mac, Linux) as long as a JVM is installed. This is 'Write Once, Run
Anywhere'.
★ Robust: Java prevents common programming mistakes — no pointers (which cause crashes in
C/C++), automatic memory management via Garbage Collection, and strong exception handling.
★ Multithreaded: Java can perform multiple tasks simultaneously using threads. Excellent for
applications that need to do many things at once — like downloading while browsing.

Q3.

Write a Short Note on Java Virtual Machine (JVM)


JVM (Java Virtual Machine) is a virtual computer inside your real computer. The Java compiler (javac)
converts source code into Bytecode (.class file). The JVM then reads this bytecode and translates it into
instructions your specific machine can understand.

Step Action Description

1 Loading Reads the .class (bytecode) file and loads it into memory

2 Verification Checks bytecode — ensures it follows Java security rules

3 Execution Converts bytecode into native machine code via Interpreter or JIT

4 Memory Mgmt Automatically frees unused memory via Garbage Collection

5 Exception Manages runtime errors so programs don't crash abruptly

Java Source Code (.java)


--> Java Compiler (javac)
--> Bytecode (.class file)
--> JVM [Interpreter / JIT Compiler]

Java — Complete Study Guide Page 3 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

--> Machine Code


--> Operating System / Hardware

Q4.

How to Declare Constants in Java?


A constant is a variable whose value is SET ONCE and can NEVER be changed. In Java, use the 'final'
keyword. By convention, constant names are written in ALL_CAPS.
class AppConfig {
public static final double PI = 3.14159; // can NEVER change
public static final int MAX_LIVES = 3;
public static final String APP_NAME = "MyApp";
}
[Link]([Link]); // 3.14159
// [Link] = 3; // ERROR! Cannot assign to final variable

Q5.

Explain Java Naming Notations


Notation Used For Example Rule

camelCase Variables & Methods calculateArea, myAge Start lowercase, each new word Caps

PascalCase Class Names StudentRecord, BankAccount Every word starts with Capital

SNAKE_CASE Constants MAX_VALUE, TAX_RATE All caps, underscore between words

lowercase Packages [Link] All lowercase, use dots

Q6.

Explain Java Primitive Data Types with Memory Allocation


Primitive data types are the most basic types built into Java. They are NOT objects. Java has exactly 8
primitive types with fixed sizes (same on all machines).

Type Size Range Example

byte 1 byte -128 to 127 byte age = 25;

short 2 bytes -32,768 to 32,767 short temp = -200;

int 4 bytes -2.1B to 2.1B int salary = 50000;

long 8 bytes Very large numbers long bigNum = 9999L;

float 4 bytes ~7 decimal digits float price = 9.99f;

double 8 bytes ~15 decimal digits double pi = 3.14159;

char 2 bytes 0 to 65,535 char grade = 'A';

boolean 1 bit true or false boolean isOn = true;

Java — Complete Study Guide Page 4 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q7.

Explain Operators: Arithmetic, Relational, Logical


Operators are special symbols that tell Java to perform a specific operation on values (operands).

Arithmetic Operators — For basic math: + (Add), - (Subtract), * (Multiply), / (Divide), %


(Modulus/Remainder)

Relational Operators — For comparison (result is boolean): == != > < >= <=

Logical Operators — Combine conditions: && (AND), || (OR), ! (NOT)


int a=10, b=3;
[Link](a % b); // 1 (remainder of 10/3)
[Link](75 >= 60); // true
[Link](75 == 100); // false

boolean hasID=true, isAdult=true;


if (hasID && isAdult) [Link]("Entry OK"); // AND
if (!hasID || !isAdult) [Link]("Denied"); // OR / NOT

Q8–11.

Control Flow Statements (if-else, for, break, continue)


Control flow statements control WHICH lines run and HOW MANY TIMES. By default Java runs top to
bottom; control flow changes that.
// if-else: one condition
int num = 10;
if (num > 0) { [Link]("Positive"); }
else { [Link]("Not positive"); }

// else-if: multiple conditions


int marks = 75;
if (marks >= 90) [Link]("A Grade");
else if (marks >= 75) [Link]("B Grade"); // runs
else if (marks >= 60) [Link]("C Grade");
else [Link]("Fail");

// for loop: known count


for (int i = 1; i <= 5; i++) { [Link]("Round " + i); }

// break: exit loop immediately


for (int i=1; i<=10; i++) {
if (i == 5) break; // stops at 5
[Link](i); // prints 1 2 3 4
}

// continue: skip one iteration


for (int i=1; i<=5; i++) {
if (i == 3) continue; // skips 3
[Link](i); // prints 1 2 4 5
}

Java — Complete Study Guide Page 5 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 2

OOP Deep Dive


Objects • Arrays • Strings • Constructors • Overloading • Wrappers

Q12.

Explain Object Declaration in Java


A CLASS is a blueprint/template — it defines WHAT an object looks like. An OBJECT is an actual instance
created from the class using the 'new' keyword.

■ Real World: Class = cookie cutter mold. Object = the actual cookies baked. All have same shape (class)
but different flavors (data).
class Car {
String model;
int speed;
Car(String m, int sp) { [Link]=m; [Link]=sp; }
void display() { [Link](model + " at " + speed + " kmph"); }
}
Car car1 = new Car("Tesla", 200); // object 1
Car car2 = new Car("BMW", 180); // object 2 — same class, different data
[Link](); // Tesla at 200 kmph
[Link](); // BMW at 180 kmph

Q13.

Explain 1D and 2D Array Initialization


An array holds MULTIPLE values of the SAME TYPE in a single variable. Arrays have a FIXED SIZE.
Each element is accessed using an INDEX starting from 0.
// 1D Array — single row
int[] marks = {90, 85, 78, 92, 88};
[Link](marks[0]); // 90 (first element)
[Link]([Link]); // 5

// 2D Array — rows and columns (matrix)


int[][] matrix = {{1,2,3},{4,5,6}}; // 2 rows, 3 columns
[Link](matrix[0][1]); // row 0, col 1 = 2
[Link](matrix[1][2]); // row 1, col 2 = 6

// Traversal using nested loops


for (int i=0; i<[Link]; i++) {
for (int j=0; j<matrix[i].length; j++) {
[Link](matrix[i][j] + " ");
}
}

Q14–15.

Java — Complete Study Guide Page 6 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

String Class — Constructors and Methods


A String is a SEQUENCE OF CHARACTERS in double quotes. It is an OBJECT of the String class.
Strings are IMMUTABLE — once created, the content cannot be changed.

Method Returns Example

length() Number of chars "Hello".length() = 5

charAt(n) Char at index n "Java".charAt(0) = J

toUpperCase() All capital letters "hello".toUpperCase() = HELLO

equalsIgnoreCase(s) Compare ignoring case "java".equalsIgnoreCase("JAVA") = true

indexOf('a') First position of char "Java".indexOf('a') = 1

substring(2) String from index 2 "Hello".substring(2) = llo

trim() Remove leading/trailing spaces


" hi ".trim() = "hi"

replace('a','o') Replace all occurrences "Java".replace('a','o') = Jovo

Q17–18.

Constructors — Default and Parameterized + 'this' Keyword


A constructor has the SAME NAME as the class and NO return type. It is called AUTOMATICALLY when
you create an object. Its job is to INITIALIZE the object's data.
// Default Constructor — no parameters
class Student {
String name; int age;
Student() { name = "Unknown"; age = 0; }
}
Student s = new Student();
[Link]([Link]); // Unknown

// Parameterized Constructor — with parameters, uses 'this'


class Student {
String name; int age;
Student(String name, int age) {
[Link] = name; // '[Link]' = field, 'name' = parameter
[Link] = age;
}
}
Student s1 = new Student("Preet", 20);
Student s2 = new Student("Rajan", 25);
[Link]([Link] + " " + [Link]); // Preet 20

Q19.

Explain Method Overloading


Method overloading = MULTIPLE METHODS with the SAME NAME but DIFFERENT PARAMETERS in
the same class. Java decides which method to call based on arguments. This is compile-time

Java — Complete Study Guide Page 7 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

polymorphism.
class Calculator {
int add(int a, int b) { return a+b; } // 2 ints
int add(int a, int b, int c) { return a+b+c; } // 3 ints
double add(double a, double b) { return a+b; } // 2 doubles
String add(String a, String b) { return a+b; } // concatenate
}
Calculator c = new Calculator();
[Link]([Link](5, 10)); // 15
[Link]([Link](5, 10, 15)); // 30
[Link]([Link](2.5, 3.5)); // 6.0
[Link]([Link]("Hi ", "Java")); // Hi Java

Q21.

Wrapper Classes in Java


Wrapper classes are object versions of Java's primitive types. Needed when storing primitives in
collections (like ArrayList) which only store objects.

Primitive Wrapper Class Useful Method

int Integer [Link]("42") → 42

double Double [Link]("3.14") → 3.14

char Character [Link]('A') → true

boolean Boolean [Link]("true") → true

float Float [Link]("1.5f") → 1.5

long Long [Link]("9999") → 9999


// Autoboxing: Java automatically converts primitive <--> wrapper
int num = 42;
Integer obj = num; // autoboxing: int -> Integer
int back = obj; // unboxing: Integer -> int
String str = [Link](42); // int to String: "42"
int parsed = [Link]("99"); // String to int: 99
int max = Integer.MAX_VALUE; // 2147483647

Q16.

Explain Vector Class


Vector is like an array but SMARTER — it GROWS and SHRINKS automatically as you add/remove
elements. It is THREAD-SAFE, making it safe for multithreaded programs. Part of [Link] package.
import [Link].*;
Vector<String> fruits = new Vector<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]([Link]()); // 3
[Link]([Link]()); // 10 (default initial)

Java — Complete Study Guide Page 8 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

[Link]([Link](1)); // Banana
[Link]("Banana");
[Link]([Link]()); // 2 after removal

Q23–24.

StringBuffer vs String
String is IMMUTABLE — every modification creates a NEW String object. StringBuffer is MUTABLE — it
modifies the SAME object, making it much more memory-efficient for repeated changes.

Feature String StringBuffer

Mutable? No (immutable) Yes (mutable)

Performance Slow (new object each change) Fast (modifies same object)

Thread Safe? Yes Yes (synchronized)

Use When Value rarely changes Building/modifying strings often

StringBuffer sb = new StringBuffer("Hello");


[Link](" World"); // "Hello World"
[Link](5, ","); // "Hello, World"
[Link](5, 6); // "Hello World"
[Link](); // "dlroW olleH"
[Link](0, 5, "Hi");// "Hi olleH"
[Link]([Link]()); // convert back to String

Java — Complete Study Guide Page 9 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 3

Inheritance & Polymorphism


Inheritance Types • super • final • Interfaces • Abstract Classes • Packages

Q1.

Define Inheritance and List Its Types


Inheritance allows a child class (subclass) to ACQUIRE all properties and behaviours of a parent class
(superclass). Promotes CODE REUSE. Uses the 'extends' keyword. Java does NOT support multiple
class inheritance (Diamond Problem), but allows it through interfaces.

★ Single Inheritance: ONE parent → ONE child.


class Animal{} class Dog extends Animal{}

★ Multilevel Inheritance: Chain: Parent → Child → Grandchild.


class Animal{} class Dog extends Animal{} class Puppy extends Dog{}

★ Hierarchical Inheritance: ONE parent → MULTIPLE children.


class Animal{} class Dog extends Animal{} class Cat extends Animal{}

★ Multiple (via Interface): Class implements MULTIPLE interfaces.


class Duck implements Flyable, Swimmable{}

Q4 & 7.

Constructor Execution, super() and super Keyword


The 'super' keyword refers to the PARENT CLASS from a child class. Uses: (1) super() calls parent's
constructor, (2) [Link]() calls parent's version, (3) [Link] accesses parent's field. Parent
constructor is ALWAYS called first.
class Animal {
String name;
Animal(String n) { [Link]=n; [Link]("Animal constructor"); }
void display() { [Link]("I am " + name); }
}
class Dog extends Animal {
String breed;
Dog(String n, String b) {
super(n); // 1. call Animal's constructor FIRST
[Link] = b;
[Link]("Dog constructor");
}
void display() {
[Link](); // 2. call Animal's display()
[Link]("Breed: " + breed);
}
}

Java — Complete Study Guide Page 10 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Dog d = new Dog("Rex","Labrador");


// Output: Animal constructor -> Dog constructor
[Link](); // Output: I am Rex -> Breed: Labrador

Q5.

Method Overriding — Runtime Polymorphism


Overriding happens when a child class rewrites a parent method with the SAME NAME, SAME RETURN
TYPE, and SAME PARAMETERS. Java decides AT RUNTIME which version to execute based on the
ACTUAL object type (Dynamic Method Dispatch).
class Shape {
void area() { [Link]("Calculating area..."); }
}
class Circle extends Shape {
@Override
void area() { [Link]("Area = pi * r * r"); }
}
class Rectangle extends Shape {
@Override
void area() { [Link]("Area = length * width"); }
}
// Dynamic dispatch — decided at RUNTIME:
Shape s1 = new Circle();
Shape s2 = new Rectangle();
[Link](); // Area = pi * r * r
[Link](); // Area = length * width

Q6.

Different Uses of 'final' Keyword


The 'final' keyword has 3 uses, all about PREVENTING CHANGE:

Use Meaning Example

final variable Value cannot be changed (constant) final double PI = 3.14159;

final method Cannot be overridden by child class final void showPolicy() {...}

final class Cannot be extended/inherited final class MathUtils {...}

Q8.

Abstract Methods and Abstract Classes


An ABSTRACT METHOD has NO BODY — just declaration. Subclasses MUST implement it. An
ABSTRACT CLASS cannot be instantiated directly (cannot create object of abstract class). It can have
both abstract and regular methods.
abstract class Animal {
String name;
Animal(String n) { [Link]=n; }

Java — Complete Study Guide Page 11 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

abstract void sound(); // MUST implement


void breathe() { [Link](name+" breathes"); } // normal method
}
class Dog extends Animal {
Dog(String n) { super(n); }
void sound() { [Link](name+" barks: Woof!"); }
}
// Animal a = new Animal(); // ERROR — cannot instantiate abstract class
Animal a = new Dog("Rex"); // OK — Dog is concrete
[Link](); // Rex barks: Woof!
[Link](); // Rex breathes

Q9–12.

Interfaces in Java
An interface is a 100% abstract blueprint containing only method declarations. A class IMPLEMENTS it
using 'implements'. One class can implement MULTIPLE interfaces. All variables in an interface are
automatically public, static, and final.
interface Printable { void print(); }
interface Saveable { void save(); }

class Document implements Printable, Saveable {


public void print() { [Link]("Printing..."); }
public void save() { [Link]("Saving..."); }
}

// Interface extending another interface:


interface ColorPrintable extends Printable {
void colorPrint();
}

Feature Class Abstract Class Interface

Methods All with body Mix (abstract + normal) All abstract (default)

Fields Any type Any type Only constants

Instantiate? Yes No No

Extends 1 class 1 class Multiple interfaces

Q21.

Access Specifiers in Java


Specifier Same Class Same Package Subclass Other Packages

private Yes No No No

default Yes Yes No No

protected Yes Yes Yes No

Java — Complete Study Guide Page 12 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

public Yes Yes Yes Yes

Q13–15.

Packages in Java
A package is a FOLDER/NAMESPACE grouping related classes. Purposes: (1) organizes code into
logical folders, (2) prevents naming conflicts. Use 'package' to declare, 'import' to use.
// File: myPackage/[Link]
package myPackage;
public class MyClass {
public void greet() { [Link]("Hello from myPackage!"); }
}

// In another file:
import [Link]; // import specific class
// import myPackage.*; // import ALL classes from package
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link](); // Hello from myPackage!
}
}

Built-in packages: [Link] (auto-imported), [Link] (Vector, ArrayList), [Link] (file operations), [Link]
(networking), [Link] (GUI).

Java — Complete Study Guide Page 13 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 4

Exception Handling & Multithreading


Errors • try-catch-finally • Custom Exceptions • Thread Lifecycle

Q1.

Types of Errors in Java


Error Type When Detected Description Example

Syntax Error Compile time Grammar mistakes — compilerMissing


can't understand
semicolon, wrong spelling

Runtime Error While running Program crashes midway — called


NullPointerException,
Exceptions divide by 0

Logical Error After running Program gives WRONG results


Wrong
— hardest
formula:
to find
length+width instead of *

Q2 & 6.

try-catch Blocks and Multiple catch


try = code that might fail. catch = response to specific errors. Multiple catch blocks must be ordered from
MOST SPECIFIC (child) to MOST GENERAL (parent Exception). finally always executes.
try {
int result = 10 / 0; // might throw ArithmeticException
int[] arr = new int[3];
[Link](arr[5]); // might throw ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) { // most specific first
[Link]("Math error: " + [Link]());
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array error: " + [Link]());
} catch (Exception e) { // most general LAST
[Link]("Some error: " + [Link]());
} finally {
[Link]("This ALWAYS runs — for cleanup!");
}

Q3.

Types of Exception Classes


Type Description Common Examples

Checked Must handle at compile time. CompilerIOException,


forces try-catch
SQLException,
or throws. FileNotFoundException

Unchecked (Runtime)
Occur at runtime. Not required to handle
NullPointerException,
explicitly. ArithmeticException, ArrayIndexOutOfBoundsException

Errors Serious JVM-level problems. Do NOTOutOfMemoryError,


try to catch. StackOverflowError

Q7–8.

throws, throw, and User-Defined Exceptions

Java — Complete Study Guide Page 14 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

THROW (verb) — manually CREATE and THROW an exception inside a method. THROWS — declares
in method signature that it MIGHT throw a certain exception (caller must handle). User-defined exceptions
extend the Exception class.
// 1. Create custom exception:
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) { super(msg); }
}

// 2. Method that throws it:


static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age " + age + " is below 18!");
}
[Link]("Valid age: " + age);
}

// 3. Call and handle:


try {
checkAge(15);
} catch (InvalidAgeException e) {
[Link]("Caught: " + [Link]());
}
// Output: Caught: Age 15 is below 18!

Q9–11.

Thread Lifecycle and Creating Threads


A thread is the SMALLEST UNIT OF EXECUTION. Every Java program starts with the MAIN thread. You
can create additional threads for multitasking.

State Description

New (Born) Thread object created using 'new'. Not yet started.

Runnable start() called. Thread ready, waiting for CPU.

Running CPU scheduler picks this thread. run() method executing.

Blocked/Waiting Thread paused — waiting for I/O, lock, or sleep() to end.

Terminated run() completed or stop() called. Thread is dead.

// Method 1: Extend Thread class


class MyThread extends Thread {
public void run() {
for (int i=1; i<=5; i++)
[Link]("Thread " + getName() + ": " + i);
}
}
MyThread t = new MyThread();
[Link](); // DON'T call run() directly!

// Method 2: Implement Runnable (preferred — allows extending another class)

Java — Complete Study Guide Page 15 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

class PrintTask implements Runnable {


public void run() { [Link]("Runnable task running!"); }
}
Thread t = new Thread(new PrintTask());
[Link]();

Q13.

Thread Synchronization
When multiple threads share a resource (like a bank balance), they can INTERFERE causing race
conditions. The 'synchronized' keyword ensures only ONE THREAD accesses the shared resource at a
time.

■ Real World: ATM machine — only ONE person can use it at a time. If two people could withdraw
simultaneously, the same money might be given twice!
class BankAccount {
private int balance = 5000;
synchronized void withdraw(int amount) { // LOCK acquired
if (balance >= amount) {
balance -= amount;
[Link]("Withdrew: " + amount + " | Balance: " + balance);
} else {
[Link]("Insufficient funds!");
}
} // LOCK released — next thread can enter
}

Java — Complete Study Guide Page 16 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 5

AWT & Swing GUI Programming


GUI Components • Layouts • Event Handling • Swing Widgets

Q1.

AWT Component Class Hierarchy


AWT (Abstract Window Toolkit) is Java's original GUI library. AWT components are HEAVYWEIGHT —
they use the native (OS-specific) widgets, so they look different on each OS.

Class Type Description

Object Root Root of all Java classes

Component Abstract Superclass of all visual AWT elements — has size, position, color methods

Container extends Component Can hold other components. Examples: Panel, Frame

Frame extends Container Top-level window with title bar, borders, and menu bar

Panel extends Container Invisible container used to group components inside a Frame

Q2.

Creating GUI with Frame Class


import [Link].*;
public class MyGUI {
public static void main(String[] args) {
Frame fm = new Frame("My First Window");
Label lb = new Label("Enter your name:");
TextField tf = new TextField(20);
Button btn = new Button("Submit");

[Link](20, 50, 120, 30);


[Link](150, 50, 150, 30);
[Link](80, 100, 80, 30);

[Link](lb); [Link](tf); [Link](btn);


[Link](null);
[Link](350, 200);
[Link](true);
}
}

Q8–10.

Layouts in AWT
Layout Arrangement Real-World Analogy

Java — Complete Study Guide Page 17 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

BorderLayout 5 regions: N/S/E/W/Center Compass map directions

GridLayout Equal rows and columns Spreadsheet / calculator keyboard

FlowLayout Left-to-right, wraps next line Words in a sentence

null Layout Manual setBounds() positioning Placing furniture with a ruler

// BorderLayout:
[Link](new BorderLayout());
[Link](new Button("Top"), [Link]);
[Link](new Button("Bottom"), [Link]);
[Link](new Button("Middle"), [Link]);

// GridLayout — 2 rows, 3 columns:


[Link](new GridLayout(2, 3));
for (int i=1; i<=6; i++) [Link](new Button("B"+i));

// FlowLayout:
[Link](new FlowLayout([Link]));

Q11.

Difference Between AWT and Swing


Feature AWT Swing

Package [Link] [Link]

Components Heavyweight (OS draws them) Lightweight (Java draws them)

Look Different on each OS Same on all OS

Component names Button, Label, TextField JButton, JLabel, JTextField

Look & Feel Fixed Pluggable (customizable)

MVC Support No Yes

Q12–18.
Key Swing Components
Component Purpose Key Code

JLabel Display text/images (read-only)JLabel lbl = new JLabel("Name:");

JButton Clickable button triggers ActionEvent


JButton btn = new JButton("Submit");

JTextField Single-line text input JTextField tf = new JTextField(20);

JComboBox Drop-down selection list JComboBox<String> cb = new JComboBox<>(opts);

JRadioButton Single-select from a group ButtonGroup bg = new ButtonGroup();

JScrollPane Adds scrollbars to any component


new JScrollPane(textArea);

Java — Complete Study Guide Page 18 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

JTable Display data in rows/columns new JTable(data, columns);

Q19–20.

Event Classes and Listener Interfaces


Event-driven programming: code WAITS for user action, then responds. An EVENT is an action by the
user. A LISTENER is code that waits for that event and responds.

Event Class Listener Interface When Fired Key Method

ActionEvent ActionListener Button click, menu select actionPerformed()

KeyEvent KeyListener Key pressed or released keyPressed()

MouseEvent MouseListener Mouse click/press/enter mouseClicked()

ItemEvent ItemListener Checkbox/radio change itemStateChanged()

TextEvent TextListener Text field content changestextValueChanged()

Java — Complete Study Guide Page 19 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 6

Networking in Java
Client-Server • IP Addressing • Sockets • TCP/UDP • URLs

Q1.

Client-Server Networking
Networking is connecting computers to share data. Java networking uses the [Link] package.
CLIENT-SERVER model: SERVER provides a service, CLIENT requests it. They communicate using
PROTOCOLS.

■ Real World: You (client) search Google (server). Browser sends request → server finds results → sends
back. Happens in milliseconds.

Q3.

IP Addressing and Its Types


Class First Octet Default Subnet Used For

A 1–126 [Link] Very large (ISPs, governments) — [Link]

B 128–191 [Link] Medium networks — [Link]

C 192–223 [Link] Small (home, office) — [Link]

D 224–239 N/A Multicast groups — [Link]

E 240–255 N/A Research/experimental — [Link]

Q2.

Reserved Ports and Sockets


Port Protocol / Service

21 FTP (File Transfer)

23 Telnet (Remote Login)

25 SMTP (Email Sending)

80 HTTP (Web browsing)

443 HTTPS (Secure Web)

3306 MySQL Database

8080 Alternative HTTP / Tomcat

1024–65535 User / Custom applications

Java — Complete Study Guide Page 20 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q5–6.

InetAddress Class — Factory and Instance Methods


import [Link].*;
// FACTORY METHODS (static — create InetAddress objects):
InetAddress google = [Link]("[Link]");
InetAddress local = [Link]();
InetAddress[] all = [Link]("[Link]");

// INSTANCE METHODS (called on an InetAddress object):


[Link]([Link]()); // "[Link]"
[Link]([Link]()); // "[Link]"
[Link]([Link](3000)); // true/false
[Link]([Link]()); // "[Link]/[Link]"

Q7–8.

Socket and ServerSocket Classes (TCP)


// === SERVER ===
ServerSocket ss = new ServerSocket(12345); // listen on port 12345
[Link]("Server waiting...");
Socket client = [Link](); // BLOCKS until client connects
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
PrintWriter out = new PrintWriter([Link](), true);
String msg = [Link]();
[Link]("Echo: " + msg);

// === CLIENT ===


Socket s = new Socket("localhost", 12345);
PrintWriter out = new PrintWriter([Link](), true);
BufferedReader in = new BufferedReader(new InputStreamReader([Link]()));
[Link]("Hello Server!");
[Link]([Link]()); // Echo: Hello Server!

Q11.

TCP vs UDP Protocols


Feature TCP UDP

Connection Connection-oriented (handshake) Connectionless

Reliability Guaranteed delivery No guarantee — may lose packets

Ordering Data arrives in order May arrive out of order

Speed Slower (overhead) Faster (minimal overhead)

Java Class Socket / ServerSocket DatagramSocket / DatagramPacket

Use Case Email, web, FTP, chat Video stream, gaming, DNS, VoIP

Q9 & 17–18.

Java — Complete Study Guide Page 21 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

URL and URLConnection Classes


import [Link].*;
URL url = new URL("[Link]
[Link]([Link]()); // https
[Link]([Link]()); // [Link]
[Link]([Link]()); // 8080
[Link]([Link]()); // /[Link]
[Link]([Link]()); // id=5

URLConnection conn = [Link]();


[Link]();
[Link]("Content-Type: " + [Link]());

Java — Complete Study Guide Page 22 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER 7

JDBC & Database Connectivity


JDBC Architecture • Drivers • CRUD Operations • ResultSet

Q12.

JDBC Architecture Overview


JDBC (Java Database Connectivity) is a Java API that allows Java programs to CONNECT to and
INTERACT with databases. Acts as a BRIDGE between Java code and the database. Part of [Link]
package.

■ Real World: JDBC is like a universal power adapter — your Java code (device) plugs into ANY database
(any socket) through JDBC, regardless of DB brand.

Q2.

Four Types of JDBC Drivers


Type Name Description Speed

Type 1 JDBC-ODBC Bridge Converts JDBC → ODBC → DB. Deprecated


Slowest in Java 8.

Type 2 Native API Driver Converts JDBC → DB native C/C++ API.


SlowPlatform-dependent.

Type 3 Network Protocol Converts JDBC → Middleware protocol → DB. Needs middleware.
Medium

Type 4 Thin Driver (Pure Java) Converts JDBC directly to DB protocol.


Fastest
100% Pure Java. BEST!

Q5.

6 Standard Steps for JDBC Connectivity


Step Action Code

1 Load the JDBC Driver [Link]("[Link]");

2 Establish Connection Connection con = [Link](url, user, pass);

3 Create Statement Statement stmt = [Link]();

4 Execute SQL Query ResultSet rs = [Link]("SELECT * FROM students");

5 Process Results while ([Link]()) { [Link]([Link]("name")); }

6 Close Resources [Link](); [Link](); [Link]();

Q5,7,8,9.

CRUD Operations — Insert, Select, Update, Delete


CRUD = Create, Read, Update, Delete — the four fundamental database operations. Use
PreparedStatement for safety (prevents SQL Injection) and performance.

Java — Complete Study Guide Page 23 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

String url = "jdbc:mysql://localhost:3306/student";


Connection con = [Link](url, "root", "");

// INSERT — Create a Record


String sql = "INSERT INTO students (name, age, city) VALUES (?, ?, ?)";
PreparedStatement ps = [Link](sql);
[Link](1, "Preet Singh");
[Link](2, 20);
[Link](3, "Surat");
int rows = [Link](); // returns rows affected

// SELECT — Read Records


ResultSet rs = [Link]().executeQuery("SELECT * FROM students");
while ([Link]()) {
[Link]([Link]("id") + " | " + [Link]("name"));
}

// UPDATE — Modify a Record


ps = [Link]("UPDATE students SET city=? WHERE name=?");
[Link](1, "Mumbai"); [Link](2, "Preet Singh");
[Link]();

// DELETE — Remove a Record


ps = [Link]("DELETE FROM students WHERE name=?");
[Link](1, "Preet Singh");
[Link]();

Q4 & 6.

Statement vs PreparedStatement
Feature Statement PreparedStatement

SQL Compilation Every time (slow for repeated) Once (fast for repeated)

Parameters Direct string concatenation ? Placeholders (safe)

SQL Injection VULNERABLE PROTECTED

Use For DDL (CREATE, DROP), one-time DML


queries
(INSERT, UPDATE, DELETE, SELECT)

Q6 & 10–11.

ResultSet Interface
A ResultSet is a TEMPORARY TABLE in memory holding rows returned by SELECT. Has an internal
CURSOR starting BEFORE the first row. Call next() to move to next row.

Method Returns Example

next() true if next row exists while([Link]()) { ... }

getInt(col) int value from column [Link]("age") = 20

getString(col) String value [Link]("name") = "Preet"

Java — Complete Study Guide Page 24 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

getDouble(col) double value [Link]("salary") = 50000.0

first() Move cursor to row 1 [Link]() (scrollable only)

absolute(n) Move cursor to row n [Link](3)

close() Free resources [Link]() — always call!

Q1 & 13.

2-Tier vs 3-Tier JDBC Architecture


Feature 2-Tier (Client-Server) 3-Tier (Client-Middle-DB)

Layers 2: App + Database 3: Client + App Server + Database

Connection App directly connects to DB App Server connects to DB

Scalability Limited Highly scalable (pooled connections)

Security Less (DB exposed to client) Better (DB hidden behind app server)

Example Desktop Java app + MySQL Web app (JSP) + Tomcat + Oracle

Java — Complete Study Guide Page 25 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER ★

Quick Revision Summary


All Chapters at a Glance — Key Points to Remember

OOP Encapsulation + Abstraction + Inheritance + Polymorphism = Java's 4 Pillars

JVM Converts Bytecode to Machine Code. Makes Java 'Write Once, Run Anywhere'.

Constructor
Auto-called on object creation. Default (no params) vs Parameterized.
s

Inheritance Child gets parent features. Use extends. Types: Single/Multi/Hierarchical/Multiple (via Interface).

try-catch-finally. throw = throw exception. throws = declare may throw. Extend Exception for
Exceptions
custom.

New > Runnable > Running > Blocked > Terminated. Use start() not run()! Synchronize shared
Threads
resources.

GUI libraries. AWT = heavyweight (OS-based). Swing = lightweight (Java-drawn), names start with
AWT/Swing
J.

Networking TCP = Socket (reliable). UDP = DatagramSocket (fast). InetAddress resolves hostnames.

6 Steps: Load Driver > Connect > Statement > Execute > Process > Close. Use
JDBC
PreparedStatement always!

Java — Complete Study Guide Page 26 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

CHAPTER BONUS

40 Viva Questions & Answers


All Topics • Important Exam Questions • Covering All 7 Chapters

These 40 questions cover all important topics from all chapters. Each answer is concise and
exam-focused. Study these thoroughly for viva and written exams.

Ch 1 — OOP & Java Basics

Q1 What are the four pillars of OOP?

Ans The four pillars of OOP are: Encapsulation (bundling data and methods, hiding internal details),
Abstraction (showing only necessary details), Inheritance (child class acquiring parent properties), and
Polymorphism (one method, many forms — overloading and overriding).

Q2 What is the difference between JDK, JRE, and JVM?

Ans JVM (Java Virtual Machine) converts bytecode to machine code. JRE (Java Runtime Environment) =
JVM + libraries needed to RUN Java programs. JDK (Java Development Kit) = JRE + compiler (javac) +
development tools needed to WRITE and compile Java programs.

Q3 What is bytecode in Java?

Ans Bytecode is an intermediate format produced by the Java compiler (javac) from source code (.java). It is
stored in .class files and is platform-independent. The JVM on any OS can execute this bytecode,
enabling Java's 'Write Once, Run Anywhere' principle.

Q4 What is the 'final' keyword used for?

Ans The 'final' keyword serves three purposes: (1) final variable — creates a constant whose value cannot
be changed, (2) final method — prevents the method from being overridden in subclasses, (3) final
class — prevents the class from being inherited. All uses are about preventing change.

Q5 What is the difference between == and .equals() for Strings?

Ans == compares REFERENCES (memory addresses) — it checks if both variables point to the exact same
object in memory. .equals() compares the CONTENT (actual characters) of two String objects. For
comparing String values, always use .equals() or equalsIgnoreCase().

Ch 2 — OOP Deep Dive

Java — Complete Study Guide Page 27 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q6 What is the difference between a class and an object?

Ans A CLASS is a blueprint/template that defines attributes and behaviors — it exists only in code. An
OBJECT is an actual instance created from the class using the 'new' keyword — it has real values in
memory. Example: Car is a class; your specific car (Tesla at 200 kmph) is an object.

Q7 What is the 'this' keyword?

Ans The 'this' keyword refers to the CURRENT OBJECT inside a class. It is used to distinguish between
class instance variables and constructor/method parameters that have the same name. Example:
[Link] = name means 'this object's name field = the parameter name'.

Q8 What is method overloading? Can we overload by return type only?

Ans Method overloading means having multiple methods with the SAME NAME but DIFFERENT
PARAMETERS (different number, type, or order of parameters) in the same class. No, we CANNOT
overload by changing only the return type — the compiler cannot distinguish them and will give an error.

Q9 What is the difference between String and StringBuffer?

Ans String is IMMUTABLE — every modification creates a new String object in memory, wasting memory in
loops. StringBuffer is MUTABLE — it modifies the same object, making it faster and more
memory-efficient. StringBuffer is preferred when you need to frequently modify string content.

Q10 What is a constructor? Can a constructor have a return type?

Ans A constructor is a special method with the SAME NAME as the class that is automatically called when
an object is created. Its purpose is to initialize the object's data. NO, a constructor cannot have a return
type — not even void. If you add a return type, Java treats it as a regular method, not a constructor.

Q11 What is a Wrapper class? What is autoboxing?

Ans Wrapper classes are object versions of Java's primitive types (Integer for int, Double for double, etc.).
They are needed when primitives must be used as objects (e.g., in ArrayList). Autoboxing is Java's
automatic conversion of primitives to their Wrapper class and back (unboxing) without explicit casting.

Ch 3 — Inheritance & Polymorphism

Q12 Why doesn't Java support multiple inheritance with classes?

Ans Java does not support multiple class inheritance to avoid the 'Diamond Problem.' If class C extends
both A and B, and both A and B have a method with the same name, Java cannot determine which
version C should inherit. To avoid this ambiguity, Java restricts to single class inheritance but allows
implementing multiple interfaces.

Java — Complete Study Guide Page 28 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q13 What is the difference between method overloading and overriding?

Ans Overloading: same method name, different parameters, in the SAME class — resolved at compile time
(compile-time polymorphism). Overriding: child class rewrites parent's method with the SAME name,
SAME return type, SAME parameters — resolved at runtime (runtime polymorphism / dynamic
dispatch).

Q14 What is the use of the 'super' keyword?

Ans The 'super' keyword refers to the parent class from within a child class. It has three uses: (1) super() —
calls the parent class constructor, (2) [Link]() — calls the parent's overridden method, (3)
[Link] — accesses the parent's variable. Parent constructor is always called first automatically.

Q15 What is an abstract class? Can we create an object of an abstract class?

Ans An abstract class is a class declared with the 'abstract' keyword that contains at least one abstract
method (method with no body). NO, we CANNOT create an object of an abstract class directly. It acts
as a blueprint for subclasses, which must provide implementations of all abstract methods.

Q16 What is the difference between an abstract class and an interface?

Ans Abstract class: can have both abstract and non-abstract methods, can have instance variables,
supports constructors, a class can extend only ONE abstract class. Interface: all methods are abstract
by default (Java 8 allows default/static), variables are constants, no constructors, a class can implement
MULTIPLE interfaces.

Q17 What are access specifiers in Java?

Ans Access specifiers control visibility: private (only within the same class), default/package-private (same
package only), protected (same package + subclasses), public (accessible from everywhere). They are
fundamental to implementing encapsulation.

Ch 4 — Exception Handling & Threads

Q18 What is the difference between checked and unchecked exceptions?

Ans Checked exceptions are detected at COMPILE TIME — the compiler forces you to handle them using
try-catch or declare them with throws. Examples: IOException, SQLException. Unchecked exceptions
(RuntimeExceptions) occur at RUNTIME due to programmer errors and are not required to be explicitly
handled. Examples: NullPointerException, ArithmeticException.

Q19 What is the difference between throw and throws?

Ans throw (verb) is used INSIDE a method body to actually CREATE and THROW an exception object:
throw new ExceptionType(message). throws (noun) is used in the METHOD SIGNATURE to DECLARE
that a method might throw certain exceptions, warning the caller to handle them: void method() throws
IOException.

Java — Complete Study Guide Page 29 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q20 What is the purpose of the 'finally' block?

Ans The finally block ALWAYS executes regardless of whether an exception occurred or was caught, even if
there is a return statement in try or catch. It is used for CLEANUP code — closing database
connections, file streams, releasing resources — to ensure resources are always properly released.

Q21 What is the difference between process and thread?

Ans A PROCESS is an independent program in execution with its own memory space. A THREAD is a
lightweight unit of execution WITHIN a process. Multiple threads share the same process memory
(heap) but each has its own stack. Threads are cheaper to create and switch between than processes.

Q22 What are the two ways to create a thread in Java?

Ans Method 1: Extend the Thread class and override the run() method. Method 2: Implement the Runnable
interface and pass it to a Thread object. The Runnable approach is preferred because it allows the
class to extend another class, and it promotes better design by separating the task from thread
management.

Q23 What is thread synchronization and why is it needed?

Ans Synchronization ensures that only ONE THREAD can access a shared resource at a time. Without it,
multiple threads accessing the same resource simultaneously can cause RACE CONDITIONS and data
corruption. The 'synchronized' keyword on a method or block acquires a lock, preventing other threads
from entering until the lock is released.

Q24 What is a deadlock?

Ans A deadlock occurs when two or more threads are BLOCKED FOREVER, each waiting for a lock held by
the other. Example: Thread A holds Lock 1 and waits for Lock 2; Thread B holds Lock 2 and waits for
Lock 1 — both wait forever. Prevention: acquire locks in a consistent order, use timeout, or use
tryLock().

Ch 5 — AWT & Swing GUI

Q25 What is the difference between AWT and Swing?

Ans AWT components are HEAVYWEIGHT — they delegate rendering to the native OS, so they look
different on Windows vs Mac. Swing components are LIGHTWEIGHT — Java itself draws them, so they
look the same on all platforms. Swing also supports pluggable Look & Feel, MVC architecture, and
more complex widgets starting with 'J' (JButton, JFrame).

Q26 What is event-driven programming?

Ans In event-driven programming, code does NOT run sequentially from top to bottom. Instead, it WAITS for
user actions (events) like clicking a button or typing — and responds when that event occurs.
Components register LISTENERS (ActionListener, KeyListener, etc.) that respond to specific events.

Java — Complete Study Guide Page 30 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q27 What is a Layout Manager? Name four types.

Ans A Layout Manager automatically arranges components inside a container. The four main types are:
FlowLayout (components arranged left-to-right, wraps to next line), BorderLayout (5 regions:
N/S/E/W/Center), GridLayout (equal rows and columns grid), and null layout (manual positioning using
setBounds()).

Q28 What is the difference between Frame and Panel in AWT?

Ans Frame is the TOP-LEVEL WINDOW of a GUI application — it has a title bar, minimize/maximize/close
buttons, and borders. It is the container for your entire application. Panel is an INVISIBLE
INTERMEDIATE CONTAINER used to group and organize components inside a Frame. Panel has no
title bar or borders.

Ch 6 — Networking in Java

Q29 What is the difference between TCP and UDP?

Ans TCP (Transmission Control Protocol) is CONNECTION-ORIENTED with guaranteed delivery, ordered
packets, and error checking — used for email, web, FTP. UDP (User Datagram Protocol) is
CONNECTIONLESS with no delivery guarantee but much FASTER — used for video streaming,
gaming, DNS. TCP = registered post; UDP = throwing newspapers.

Q30 What is a socket in Java?

Ans A socket is one end of a TWO-WAY COMMUNICATION CHANNEL between programs on a network.
Java's Socket class represents the CLIENT side (connects to server). ServerSocket represents the
SERVER side (listens for incoming connections). Together they enable TCP-based client-server
communication using I/O streams.

Q31 What is the purpose of InetAddress class?

Ans InetAddress represents an IP address in Java. It resolves hostnames to IP addresses and vice versa.
Factory methods (static): getByName(host), getLocalHost(), getAllByName(host) — used to CREATE
InetAddress objects. Instance methods: getHostAddress(), getHostName(), isReachable() — called on
existing objects.

Q32 What is the difference between a port and an IP address?

Ans An IP address identifies the MACHINE on a network (like a building's street address). A PORT identifies
the specific APPLICATION or SERVICE running on that machine (like a flat/apartment number).
Example: HTTP always uses port 80 — any data arriving at IP x.x.x.x port 80 goes to the web server
application.

Ch 7 — JDBC & Database

Java — Complete Study Guide Page 31 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q33 What is JDBC and what are its main components?

Ans JDBC (Java Database Connectivity) is a Java API in the [Link] package that enables Java programs
to connect to and interact with relational databases. Main components: DriverManager (manages
database drivers), Connection (represents a connection to the DB), Statement/PreparedStatement
(executes SQL queries), ResultSet (holds query results).

Q34 What are the 4 types of JDBC drivers?

Ans Type 1: JDBC-ODBC Bridge (slowest, deprecated). Type 2: Native API Driver (uses C/C++ native
libraries, platform-dependent). Type 3: Network Protocol Driver (uses middleware server,
platform-independent). Type 4: Thin Driver / Pure Java (directly converts to DB protocol, fastest, most
commonly used — e.g., MySQL Connector/J).

Q35 What is the difference between Statement and PreparedStatement?

Ans Statement executes raw SQL strings — vulnerable to SQL Injection attacks where malicious SQL code
is injected via input. PreparedStatement uses parameterized queries with ? placeholders — the SQL is
precompiled once and values are bound safely, preventing injection. PreparedStatement is also faster
for repeated queries.

Q36 What is SQL Injection? How does PreparedStatement prevent it?

Ans SQL Injection is an attack where a malicious user enters SQL code as input (e.g., ' OR '1'='1) to
manipulate database queries. PreparedStatement prevents it by treating ALL user inputs as LITERAL
DATA, not as SQL commands — the ? placeholders are filled after the SQL structure is already
compiled, so injected SQL cannot alter the query structure.

Q37 What is a ResultSet? How do you iterate through it?

Ans A ResultSet is a temporary table in memory holding rows returned by a SELECT query. It has a cursor
starting BEFORE the first row. Use while([Link]()) to iterate — [Link]() moves the cursor to the next
row and returns false when no more rows exist. For each row, use [Link](col), [Link](col), etc. to
read values.

Q38 What is the difference between 2-tier and 3-tier JDBC architecture?

Ans 2-Tier: Java application connects DIRECTLY to the database — simpler but less scalable and secure
(DB exposed to client). Used for small desktop apps. 3-Tier: Client connects to an APPLICATION
SERVER (middleware like Tomcat) which connects to the DB — better security, scalability via
connection pooling, and used in enterprise/web applications.

Important General Questions

Java — Complete Study Guide Page 32 of 33 All Rights Reserved


COMPLETE JAVA NOTES Comprehensive Study Guide

Q39 What is garbage collection in Java?

Ans Garbage Collection (GC) is an automatic memory management process in the JVM. When objects are
no longer referenced (not used), the GC automatically identifies and removes them from heap memory,
freeing space. Java programmers do NOT need to manually delete objects. The finalize() method is
called just before an object is garbage collected. [Link]() can request (not guarantee) GC to run.

Q40 What is the difference between == and .equals()?

Ans == is the REFERENCE comparison operator — it checks if two variables point to the exact same
memory location (same object). .equals() is a METHOD that compares the actual CONTENT/VALUE of
objects. For String, Integer, and other objects, always use .equals() for value comparison. Note: for
primitives, == compares values directly.

Q41 What is an interface? Can an interface have variables?

Ans An interface is a 100% abstract blueprint defining a contract — it specifies WHAT a class must do
without saying HOW. A class uses 'implements' to follow this contract. Yes, interfaces CAN have
variables, but they are automatically public, static, and final (constants) — they cannot be instance
variables with changeable values.

Q42 What is polymorphism? Explain with example.

Ans Polymorphism means 'many forms' — the same entity behaving differently in different situations.
Compile-time polymorphism (overloading): same method name, different parameters in same class —
resolved by compiler. Runtime polymorphism (overriding): child class rewrites parent method —
resolved at runtime based on actual object type. Example: Shape s = new Circle(); [Link]() calls Circle's
area() at runtime.

Q43 What is the significance of the 'static' keyword?

Ans The 'static' keyword means a member belongs to the CLASS rather than to any specific object. static
variables are shared across all objects of a class (one copy). static methods can be called without
creating an object (e.g., [Link]()). static blocks run when the class is first loaded. The main() method
is static because JVM calls it without creating an object.

All the best for your exams! Practice code regularly and understand concepts
deeply — Java mastery comes from writing code, not just reading it.

Java — Complete Study Guide Page 33 of 33 All Rights Reserved

You might also like