JAVA Notes
---
UNIT-I DETAILED NOTES (JAVA)
1. History of Java
Developed by James Gosling at Sun Microsystems (1991–1995).
Initially called Oak, renamed to Java in 1995.
Designed for embedded systems, later used widely for web, mobile, and enterprise applications.
Key features:
Platform Independent (Write Once, Run Anywhere)
Object Oriented
Robust
Secure
Distributed
Multithreaded
High Performance (via JIT)
---
2. Basic Terms and Definitions
Term Meaning
JDK Java Development Kit (compiler + libraries + JVM)
JRE Java Runtime Environment (JVM + libraries)
JVM Java Virtual Machine (executes bytecode)
Bytecode Intermediate machine-independent code generated by compiler
Class Blueprint or template for objects
Object Instance of a class
---
3. Data Types
Primitive Data Types
1. byte – 1 byte
2. short – 2 bytes
3. int – 4 bytes
4. long – 8 bytes
5. float – 4 bytes
6. double – 8 bytes
7. char – 2 bytes (Unicode)
8. boolean – 1 bit
Non-Primitive Data Types
String
Arrays
Classes, Interfaces, Enums
---
4. Variables
Types of variables
Local variables – inside methods, no default values
Instance variables – inside class, outside method
Static variables – shared by all objects of a class
Scope and Lifetime
Local → scope within block; destroyed when block ends
Instance → scope throughout object; destroyed on garbage collection
Static → scope throughout class; destroyed at program termination
---
5. Arrays
Collection of similar data stored in contiguous memory.
Types:
One-dimensional
Multi-dimensional
Jagged arrays (arrays of arrays)
Example:
int[] a = new int[5];
int[][] b = new int[3][4];
---
6. Operators
Types of Operators
Arithmetic: +, -, *, /, %
Relational: <, >, <=, >=, ==, !=
Logical: &&, ||, !
Bitwise: &, |, ^, ~
Assignment: =, +=, -=, *= …
Unary: ++, --
Ternary: ?:
Shift: <<, >>, >>>
---
7. Expressions
Combination of variables, operators, literals, e.g.,
int c = a + b * 2;
---
8. Control Statements
Selection
if, if-else, nested if
switch
Iteration
for
while
do-while
enhanced for loop
Jump
break
continue
return
---
9. Type Conversion and Casting
Implicit (Widening)
byte → short → int → long → float → double
Explicit (Narrowing)
double → float → long → int → short → byte
double d = 10.5;
int i = (int)d; // explicit
---
10. Simple Java Program
class Hello {
public static void main(String[] args) {
System.out.println("Hello Java");
}
}
---
11. Concepts of Classes
A class is a collection of:
variables (fields)
methods
constructors
blocks
Defines the blueprint of an object.
---
12. Objects
Created using new keyword:
Student s = new Student();
Occupies memory on heap.
---
13. Constructors
Special method called at object creation.
Has same name as class.
No return type.
Types:
Default
Parameterized
Copy constructor (not built-in)
---
14. Methods
Block of code executed when called.
Syntax:
returnType methodName(parameters) { }
---
15. Access Control Modifiers
public – accessible everywhere
protected – within package + subclass
default – within package
private – within class
---
16. this Keyword
Used to refer:
current object
current class instance variable
invoke current class methods
call constructors (this())
---
17. Garbage Collection
Java automatically frees unused objects.
Methods:
System.gc() requests GC
finalize() called before destruction (deprecated now)
---
18. Overloading Methods and Constructors
Method Overloading
Same method name, different parameters.
Example:
int add(int a, int b)
double add(double a, double b)
Constructor Overloading
Multiple constructors with different parameter lists.
---
19. Method Binding
Early Binding (Compile-time)
Overloaded methods
Private, static, final methods
Late Binding (Runtime)
Overridden methods (using dynamic dispatch)
---
20. Inheritance
Mechanism of acquiring features of another class.
Types:
Single
Multilevel
Hierarchical
Hybrid (using interfaces)
Syntax:
class B extends A { }
---
21. Method Overriding
Same method name & parameters in subclass.
Runtime polymorphism.
Requires inheritance.
Uses @Override annotation.
---
22. Exceptions
Runtime errors handled using exception handling.
Keywords:
try
catch
throw
throws
finally
Types:
Checked (IOException, SQLException)
Unchecked (NullPointerException, ArithmeticException)
---
23. Parameter Passing
Java supports pass-by-value:
For primitives → value copied
For objects → reference copy passed
---
24. Recursion
Method calls itself.
Must have a base condition.
Example:
int fact(int n) {
if(n==1) return 1;
return n * fact(n-1);
}
---
25. Nested and Inner Classes
Types
1. Member Inner Class
2. Static Nested Class
3. Local Inner Class
4. Anonymous Inner Class
Used for:
event handling
logical grouping
data hiding
---
26. Exploring String Class
Immutable class in java.lang package.
Created in two ways:
String s1 = "Hello"; // String literal (String pool)
String s2 = new String("Hi"); // Heap
Common methods:
length()
charAt()
substring()
equals()
compareTo()
toUpperCase()
toLowerCase()
trim()
replace()
UNIT II: INHERITANCE, PACKAGES & INTERFACES – Complete Notes
---
1. INHERITANCE
Definition
Inheritance is a mechanism where a new class (subclass/derived class) acquires the properties and behaviors of an existing class (superclass/base class).
It supports code reusability, extensibility, polymorphism, and hierarchical relationships.
---
1.1 Hierarchical Abstractions
Abstraction in Java can be organized in a hierarchy using inheritance.
Higher-level classes contain more general behavior.
Lower-level classes provide more specific behavior.
Example:
Animal → Mammal → Dog
Each level hides details and moves from general → specific.
---
1.2 Base Class Object
The class whose features are inherited is called the base class or superclass.
Example:
class Animal { ... }
Animal is the base class.
---
1.3 Subclass
The class which inherits is called subclass or derived class.
class Dog extends Animal { ... }
---
1.4 Subtype
A subtype is a derived type that can be substituted wherever its base type is expected.
Subclass is always a subtype of superclass.
---
1.5 Substitutability (Liskov substitution principle)
Objects of subclass can replace objects of superclass without affecting correctness.
Example:
Animal a = new Dog(); // Valid
---
2. FORMS OF INHERITANCE
Java supports:
2.1 Specialization
Subclass adds more specific features to superclass.
Vehicle → Car
2.2 Specification
Subclass provides implementation of abstract methods of abstract class or interface.
2.3 Construction
Subclass constructs new behavior by adding new fields and methods.
2.4 Extension
Subclass extends the superclass functionality.
2.5 Limitation
Subclass may restrict the behavior of superclass by overriding.
2.6 Combination
Combining behaviors of multiple classes using interfaces (as Java does not support multiple inheritance).
---
3. BENEFITS OF INHERITANCE
1. Code Reusability – no need to write code again.
2. Faster Development – reuse tested classes.
3. Method Overriding & Polymorphism.
4. Extensibility – easily modify or add features.
5. Hierarchical Classification – natural mapping of real world.
---
4. COSTS OF INHERITANCE
1. Increased complexity – deep hierarchy becomes hard to manage.
2. Tight coupling between superclass and subclass.
3. Inheritance misuse may lead to poor design.
4. Performance overhead due to dynamic binding.
5. Fragile base class problem – change in base class may break subclasses.
---
5. MEMBER ACCESS RULES IN INHERITANCE
Modifier Same Class Same Package Subclass Other Package
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
---
6. USES OF super
super is used to:
1. Call superclass constructor:
super();
2. Call superclass method:
super.display();
3. Access superclass data members:
super.value;
---
7. USING final WITH INHERITANCE
final class
Cannot be inherited:
final class A {} // cannot extend
final method
Cannot be overridden:
final void show() {}
final variable
Constant; value cannot change.
---
8. POLYMORPHISM
Definition
Polymorphism means “one name, many forms”.
Types:
1. Compile-time (overloading)
2. Run-time (overriding)
---
8.1 Method Overriding
Same method name, same signature, but implemented in subclass.
Rules:
1. Must have same return type and parameters.
2. Cannot reduce visibility.
3. Cannot override final or static methods.
4. Access through base class reference leads to run-time polymorphism.
---
8.2 Abstract Classes
Cannot be instantiated.
May contain abstract methods.
abstract class Shape {
abstract void draw();
}
---
8.3 The Object Class
Root of Java class hierarchy.
All classes implicitly extend Object.
Important methods:
toString()
equals()
hashCode()
clone()
getClass()
finalize()
---
9. PACKAGES
A package in Java is a group of related classes and interfaces.
---
9.1 Defining a Package
package mypack;
---
9.2 Creating and Accessing a Package
Steps:
1. Write package statement.
2. Compile with directory structure.
3. Import using:
import mypack.*;
---
9.3 Understanding CLASSPATH
CLASSPATH is an environment variable that tells JVM where to find classes and packages.
We set:
set classpath=C:\java\mypack;
---
9.4 Importing Packages
import java.util.Scanner;
import java.io.*;
---
10. INTERFACES
---
10.1 Difference Between Class and Interface
Classes Interfaces
Can have implemented methods Only abstract methods (Java 8+ allows default & static)
Supports single inheritance only Supports multiple interface inheritance
Can create object Cannot create objects
Contains variables with any access modifier variables are public static final by default
---
10.2 Defining an Interface
interface Animal {
void sound();
}
---
10.3 Implementing Interface
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
---
10.4 Applying Interfaces
Used for:
Achieving multiple inheritance
Loose coupling
Implementing callback functions
Achieving abstraction
---
10.5 Variables in Interface
Always public static final
Must be initialized.
Example:
interface Test {
int x = 10;
}
---
10.6 Extending Interfaces
interface A { void display(); }
interface B extends A { void show(); }
---
11. Exploring java.io Package
The java.io package provides classes for input and output operations.
Main categories:
1. Streams
Byte Streams
FileInputStream, FileOutputStream
Character Streams
FileReader, FileWriter
Buffered Streams
BufferedReader, BufferedWriter
2. File Handling
File class:
Functions such as:
create
delete
exists
length
list files
get path
3. Console I/O
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.in, System.out, System.err
4. Serialization
ObjectOutputStream
ObjectInputStream Used to save/retrieve objects to/from files.
📘 Unit III – Exception Handling & Multithreading (Detailed Notes)
---
1. EXCEPTION HANDLING
1.1 Concept of Exception Handling
An exception is an abnormal condition or run-time error that disrupts the normal flow of a program.
Exception handling is a mechanism to detect, handle, and recover from these errors without terminating the program abnormally.
Examples of exceptions
Division by zero → ArithmeticException
Array index out of range → ArrayIndexOutOfBoundsException
Null reference → NullPointerException
File not found → FileNotFoundException
---
1.2 Benefits of Exception Handling
1. Improved program reliability
Prevents program crash.
2. Separation of error-handling code from main logic.
3. Propagating errors to calling methods.
4. Grouping of error types using exception hierarchy.
5. Improved debugging and maintainability.
---
1.3 Termination vs Resumptive Models
Termination Model (Java uses this)
Once an exception occurs, control never returns to the point of error.
Program continues after the catch block.
Resumptive Model
Control returns to the point of error after handling.
Java does NOT support resumptive model (older languages like Smalltalk do).
---
1.4 Exception Hierarchy
Throwable
/ \
Exception Error
|
(RuntimeException etc.)
Throwable
Superclass of all exceptions.
Exception
Recoverable conditions (e.g., file not found).
Checked Exceptions:
Compiler checks → must handle using try/catch or throws.
Examples: IOException, SQLException.
Unchecked Exceptions (RuntimeException):
Due to programming errors.
Examples: NullPointerException, ArithmeticException.
Error
Serious problems → cannot be handled.
Examples: OutOfMemoryError, StackOverflowError.
---
1.5 Usage of try, catch, throw, throws, finally
try block
Contains code that may produce an exception.
catch block
Handles specific exceptions.
finally block
Always executes (except System.exit).
Used for closing files, connections.
throw
Used to throw an exception manually.
throws
Declared in method signature when method may throw a checked exception.
---
1.6 Built-in Exceptions
Some common Java exceptions:
ArithmeticException
ArrayIndexOutOfBoundsException
StringIndexOutOfBoundsException
NullPointerException
NumberFormatException
ClassNotFoundException
IOException
InterruptedException
IllegalArgumentException
---
1.7 Creating User-Defined Exceptions
Steps:
1. Extend the Exception class.
2. Provide constructors.
3. Use throw to throw it.
---
2. STRING HANDLING
2.1 String Class
Immutable (cannot be changed once created)
Stored in String Constant Pool
2.2 StringBuffer
Mutable (can be modified)
Thread-safe (synchronized)
Slightly slower
2.3 StringBuilder
Mutable
Not synchronized (faster)
---
3. EXPLORING java.util
Important classes in java.util:
ArrayList
LinkedList
HashMap
HashSet
Hashtable
Stack
Collections class (utility functions like sort, reverse)
Date, Calendar, Random
Scanner (for input)
---
4. MULTITHREADING
4.1 Differences between Multithreading & Multitasking
Multitasking
Running multiple programs at the same time.
Example: Chrome + Word + Music.
Multithreading
Running multiple parts of the same program concurrently.
Example: Game (sound + graphics + user input).
---
4.2 Thread Life Cycle
New → Runnable → Running → Blocked/Waiting → Terminated
1. New
Object created but thread not started.
2. Runnable
Ready to run when CPU is free.
3. Running
Executing code.
4. Blocked/Waiting
Waiting for resources or sleeping.
5. Terminated
Thread ends.
---
4.3 Creating Threads
Method 1: Extending Thread class
Override run() → call start().
Method 2: Implementing Runnable
Create object → pass to Thread.
Preferred method: Runnable (supports multiple inheritance through interfaces).
---
4.4 Thread Priorities
Range 1 to 10
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Used to request thread scheduling order (not guaranteed).
---
4.5 Synchronizing Threads
Need
Avoid conflicts in shared data.
Synchronization types
1. Synchronized method
2. Synchronized block
synchronized(obj) {
// critical section
}
Prevents race conditions.
---
4.6 Inter-Thread Communication
Achieved using:
wait()
notify()
notifyAll()
Used for producer–consumer problems.
---
4.7 Thread Groups
Threads can be grouped.
Helps managing multiple threads together.
---
4.8 Daemon Threads
Background service threads.
Example: Garbage Collector.
Created using setDaemon(true).
---
5. ENUMERATIONS (enum)
Represent a fixed set of constants.
Type-safe.
Example:
enum Color { RED, GREEN, BLUE }
---
6. AUTOBOXING & UNBOXING
Autoboxing
Primitive → Wrapper object
int → Integer
Unboxing
Wrapper → Primitive
Integer → int
Example:
Integer a = 10; // autoboxing
int b = a; // unboxing
---
7. ANNOTATIONS
Used to provide metadata.
Common annotations:
@Override
@Deprecated
@SuppressWarnings
Custom annotation can be created using @interface.
---
8. GENERICS
Allows type-safe classes, methods, and interfaces.
Eliminates casting.
Example:
ArrayList<String> list = new ArrayList<>();
Benefits
Compile-time type safety
Avoids ClassCastException
Reusability
Cleaner code
No comments:
Post a Comment