K.N.S.
GOVT POLYTECHNIC SAMASTIPUR
: Java Programming
1.1 Java Features and the Java Programming Environment
Java is a high-level, general-purpose, object-oriented programming language designed for
portability, security, and performance. The Java programming environment consists of tools and
runtime components that enable developers to write, compile, and execute Java programs. Key
elements include:
Java Virtual Machine (JVM): Interprets compiled byte code, enabling platform
independence.
Java Runtime Environment (JRE): Includes JVM and libraries for running Java
applications.
Java Development Kit (JDK): Comprehensive toolkit with compiler (javac), debugger,
and other tools for development. As of December 2025, the latest version is JDK 25
(released September 2025), with ongoing feature releases every six months and Long-
Term Support (LTS) versions like JDK 21 and 17.
The environment supports "Write Once, Run Anywhere" (WORA) by compiling source code to
byte code executable on any JVM-equipped platform.
1.2 Object-Oriented Paradigm
Object-Oriented Programming (OOP) organizes software design around objects rather than
functions and logic. Java is fundamentally object-oriented.
Objects & Classes: A class is a blueprint defining properties (fields) and behaviors
(methods). An object is an instance of a class. Example: A Car class with fields like color
and methods like drive(); objects are specific cars (e.g., red Toyota).
Data Abstraction: Hiding complex implementation details and exposing only essential
features. Achieved via abstract classes and interfaces, allowing users to interact with
high-level functionality without knowing internals.
Data Encapsulation: Bundling data and methods within a class, restricting direct access
via access modifiers (private, protected, public). Promotes data security and modularity.
Inheritance: Allows a new class (subclass) to inherit properties and methods from an
existing class (superclass). Supports code reuse (e.g., ElectricCar extends Car).
Polymorphism: Objects of different classes can be treated as objects of a common
superclass. Includes method overriding (runtime) and overloading (compile-time),
enabling flexible behavior.
1.3 Benefits of OOP
OOP offers significant advantages over procedural programming:
Modularity and Reusability: Code organized into classes/objects; inheritance and
polymorphism enable reuse without rewriting.
Easier Maintenance and Scalability: Changes in one class minimally affect others;
systems can grow from small to large.
Better Modeling of Real-World Problems: Objects mirror real entities, improving
intuitiveness.
Data Security: Encapsulation hides internal state, reducing errors and unauthorized
access.
Reduced Redundancy and Improved Productivity: "Don't Repeat Yourself" (DRY)
principle; faster development and fewer bugs.
Collaborative Development: Modular structure suits team-based projects.
1.4 Applications of OOP
OOP is widely used across domains due to its modularity and scalability:
Real-Time Systems: Modeling complex, time-sensitive behaviors (e.g., embedded
systems).
Client-Server Systems: Structuring distributed applications (e.g., web servers).
Hypertext/Hypermedia: Frameworks for dynamic content (e.g., early web apps).
Graphical User Interfaces (GUI): Desktop/mobile apps (e.g., Swing/JavaFX in Java).
Simulation and Modeling: CAD/CAM, AI expert systems.
Enterprise Software: Banking, e-commerce (e.g., scalable databases).
Mobile Development: Android apps (Java/Kotlin).
Games and AI/ML: Object-based entity management.
1.5 Java History
Java originated in 1991 as project "Green" at Sun Microsystems, led by James Gosling (known
as the "Father of Java"), with Patrick Naughton and Mike Sheridan. Initially called Oak (after a
tree outside Gosling's office), it targeted consumer electronics (e.g., set-top boxes) for platform-
independent code.
Renamed Java in 1995 (inspired by Java coffee), it shifted focus to the web. First public release:
JDK 1.0 in 1996. Key milestones:
1998: JDK 1.2 (Java 2), introducing Swing.
2006: Open-sourced under GPL.
2010: Oracle acquired Sun.
2017+: Six-month release cycle; LTS versions (e.g., 8, 11, 17, 21).
Latest: JDK 25 (2025).
Java's "Write Once, Run Anywhere" revolutionized portability.
1.6 Java Features
Java's core features (often summarized by Sun's "buzzwords"):
Simple, Small & Familiar: Clean syntax similar to C/C++, removes complexities like
pointers.
Compiled and Interpreted: Source → bytecode (compiled), then interpreted by JVM.
Platform Independent: Bytecode runs on any JVM-equipped platform.
Portable: No implementation-dependent aspects.
Object-Oriented: Fully supports OOP principles.
Robust & Secure: Automatic garbage collection, exception handling, no pointers,
bytecode verification, security manager.
Distributed: Supports networking (e.g., RMI, sockets).
Multithreaded & Interactive: Built-in threading for concurrent execution.
High Performance: JIT compilation, optimized JVM.
Ease of Development: Vast standard libraries, automatic memory management.
Additional modern strengths: Vast ecosystem, backward compatibility, community support.
1.7 Java vs C
Aspect C Java
Paradigm Procedural Object-Oriented
Memory
Manual (malloc/free) Automatic (garbage collection)
Management
Platform
Platform-specific binaries Platform-independent bytecode
Dependency
Pointers Direct support No explicit pointers
Aspect C Java
Supported (single/multiple via
Inheritance Not supported
interfaces)
Error Handling Limited Strong exception handling
Performance Faster (low-level) Slower overhead but optimized
Prone to errors (e.g., buffer
Safety Safer (bounds checking)
overflows)
C suits system programming; Java excels in applications.
1.8 Java vs C++
Aspect C++ Java
Paradigm Multi-paradigm (OOP + procedural) Pure Object-Oriented
Memory Management Manual (new/delete) Automatic garbage collection
Multiple Inheritance Supported (classes) Only via interfaces
Pointers Full support Hidden/restricted
Compilation Direct to machine code To bytecode (JVM)
Platform Dependent Independent
Operator Overloading Supported Not supported
Garbage Collection Optional/manual Built-in
C++ offers more control/performance; Java prioritizes safety/portability.
1.9 Java Environment
Java Development Kit (JDK): Tools for development (javac, java, javadoc). Current:
JDK 25.
Java Development Tools: IDEs like IntelliJ IDEA, Eclipse, NetBeans; build tools
(Maven, Gradle).
Also includes JRE for runtime.
1.10 Application Programming Interface
Java's vast API (now modular in Java 9+) includes core packages. Early classifications
(outdated; Applets deprecated since JDK 9, removed in future releases; AWT largely superseded
by Swing/JavaFX):
Language Support: [Link] (core classes like String, Object).
Utilities: [Link] (collections, dates).
Input/Output: [Link], [Link] (streams, files).
AWT/Swing: GUI ([Link], [Link]; modern: JavaFX).
Applet Package: Deprecated/obsolete (web applets unsupported).
Networking: [Link] (sockets, URLs).
Modern additions: Concurrency ([Link]), Modules ([Link]).
1.11 Simple Java Program
A basic "Hello World" program structure:
public class HelloWorld { // Class Declaration
public static void main(String[] args) { // Main method (entry point)
[Link]("Hello, World!"); // Output line
}
}
Class Declaration: public class ClassName.
Opening & Closing Braces: Define scope.
Main Line: public static void main(String[] args) – JVM entry point.
Output Line: [Link]() for console output.
Creating Object (if needed): ClassName obj = new ClassName();.
Compile: javac [Link] Run: java HelloWorld
1.12 Java Programming with Multiple Statements
Programs can span multiple classes/files.
Application with Two Classes:
File: [Link]
public class MainClass {
public static void main(String[] args) {
SecondaryClass obj = new SecondaryClass(); // Creating object
[Link](); // Accessing method
}
}
File: [Link]
public class SecondaryClass {
public void display() {
[Link]("Message from secondary class");
}
}
Accessing Class Members: Use dot notation ([Link]()); visibility via modifiers
(public, private).
This promotes modularity and reuse.
1.13 Java Program Structure
A Java program is a collection of classes, typically organized in the following order:
1. Documentation Section: Comments providing program information (author, date).
2. Package Statement: Declares the package name to organize classes (e.g., package myapp;).
3. Import Statement: Imports external packages or classes (e.g., import [Link];).
4. Interface Statements: Defines constants and method declarations (optional).
5. Class Definitions: Defines the main logic and data members.
6. Main Method Class: Contains the public static void main(String[] args) method, which acts as
the program entry point.
Math Function & Comments:
Math Functions: Used for mathematical calculations (e.g., [Link](), [Link]()).
Comments: Ignored by the compiler.
o Single-line: // comment
o Multi-line: /* comment */
o Documentation: /** comment */.
1.14 Java Tokens
Tokens are the smallest individual units of a program that are meaningful to the compiler:
Reserved Keywords: Predefined words with special meanings (e.g., public, class, if, void).
Identifiers: Names given to variables, methods, or classes (e.g., myVariable). Rules: Must start with a
letter, $, or _; cannot start with a digit; case-sensitive.
Literals: Fixed values (constants) in the code
(e.g., 100 (int), 3.14 (double), 'A' (char), "Hello" (String), true (boolean)).
Operators: Symbols for operations (e.g., +, -, *, /, = ).
Separators: Characters that divide code (e.g., (), {}, [], ;, ,, .).
1.15 Compiling the Program - javac
The javac command is the Java compiler that translates human-readable source code (.java files) into
platform-independent Bytecode (.class files).
Command: javac [Link].
1.16 Running the Program - Java Interpreter
The java command is the interpreter (part of JRE) that runs the compiled .class file.
Command: java ClassName (without the .class extension).
1.17 Java Virtual Machine (JVM)
The JVM executes bytecode, enabling Java's "Write Once, Run Anywhere" feature. It includes a Just-In-
Time (JIT) compiler to improve performance.
Bytecode: An intermediate, platform-independent code generated by javac.
1.18 Command Line Arguments
Values passed to a program at runtime via the console, received as a String array in the main method
(String[] args).
Access: args[0], args[1], etc..
Example Run: java ProgramName arg1 arg2.
1.19 Constants & Variables
Variables: Containers for data whose values can change. Must be declared with a data type.
Constants: Variables whose values cannot be modified once initialized, typically defined using
the final keyword.
1.20 Data Types
Primitive Data Types: Basic types directly supported by Java:
o Integer: byte, short, int, long
o Floating Point: float, double
o Character: char
o Boolean: boolean
Non-Primitive Data Types: Referenced types like Classes, Interfaces, and Arrays (e.g., String).
1.21 Operators
Arithmetic: +, -, *, /, % (modulus).
Relational: ==, !=, >, <, >=, <=.
Logical: && (AND), || (OR), ! (NOT).
Increment/Decrement: ++ (pre/post), -- (pre/post).
Conditional (Ternary): condition ? expression1 : expression2.
Bitwise: &, |, ^, ~, <<, >>, >>>.
Assignment: =, +=, -=, *=, /=, %=, etc..
Dot (.): Used to access methods and fields of objects.
1.22 Expressions
Operator Precedence: Determines the order in which operators are evaluated (e.g., * before +).
Associativity: Determines the direction of evaluation when operators have the same precedence (left-to-
right or right-to-left).
1.23 Decision Statements
if: Executes a block if a condition is true.
if-else: Executes one block if true, another if false.
if-else-if ladder: Tests multiple conditions sequentially.
nested if-else: An if-else inside another if-else.
switch: Selects one of many code blocks to execute based on an expression value.
1.24 Loop Statements
While: Checks condition first, then executes the block (pre-test).
Do-while: Executes the block first, then checks the condition (post-test, executes at least once).
For: Combines initialization, condition, and increment/decrement in one line.
For-each (Enhanced For): Iterates through arrays or collections.
1.25 Control Statements (Long Notes)
Control statements manage the flow of program execution based on conditions and loops.
Branching: if, switch.
Looping: for, while, do-while.
Jump Statements:
o break: Exits the current loop or switch case.
o continue: Skips the current iteration of a loop and moves to the next.
o return: Exits from the current method.
Exception Handling: try, catch, finally, throw, throws
1.25 Control Statements: break, continue, and return Statements
These are jump control statements (or loop control/transfer statements) used to alter the normal
sequential flow of execution in a program, particularly inside loops, switches, or functions. They
are common in languages like C, C++, Java, Python, etc.
1. break Statement
Purpose: Terminates the execution of the nearest enclosing loop or switch statement
immediately.
Usage:
o In loops (for, while, do-while): Exits the loop completely.
o In switch: Exits the switch block (prevents fall-through).
Flow: Control jumps to the statement immediately after the loop/switch.
Key Points:
o Only affects the innermost loop in nested loops.
o Useful for early exit when a condition is met (e.g., search found, error detected).
o Can be labeled in some languages (e.g., Java, C++) for breaking outer loops.
Example (in C/Java-like syntax):
for(int i = 1; i <= 10; i++) {
if(i == 5) {
break; // Loop terminates when i=5
}
printf("%d ", i);
}
// Output: 1 2 3 4
In Switch:
switch(choice) {
case 1: printf("One"); break; // Exits switch
case 2: printf("Two"); // Without break, falls through
default: printf("Other");
}
2. continue Statement
Purpose: Skips the remaining code in the current iteration of the loop and jumps to the next
iteration.
Usage: Only inside loops (for, while, do-while).
Flow:
o In for loop: Increments the loop variable and checks condition.
o In while/do-while: Re-evaluates the condition.
Key Points:
o Does not exit the loop entirely (unlike break).
o Useful for skipping invalid/unwanted iterations (e.g., ignore negative numbers, skip even
numbers).
Example:
for(int i = 1; i <= 10; i++) {
if(i % 2 == 0) {
continue; // Skip even numbers
}
printf("%d ", i);
}
// Output: 1 3 5 7 9
Another Example (Sum of positive numbers only):
int num, sum = 0;
while(true) {
scanf("%d", &num);
if(num < 0) continue; // Skip negatives
sum += num;
}
3. return Statement
Purpose: Terminates the execution of the current function/method and transfers control back
to the caller.
Usage: Inside functions/methods.
Variants:
o return; (in void functions): Just exits.
o return value; : Exits and returns a value to the caller.
Flow: Control returns to the calling function; any code after return in the function is
unreachable.
Key Points:
o Can act like break if used inside a loop within a function (exits the entire function).
o Essential for returning results (e.g., from calculations).
o In main(): return 0; indicates successful program termination.
Example:
int add(int a, int b) {
if(a < 0 || b < 0) {
return 0; // Early return if invalid
}
return a + b; // Normal return
}
Using return to exit a loop:
int search(int arr[], int size, int key) {
for(int i = 0; i < size; i++) {
if(arr[i] == key) {
return i; // Found: return index and exit function
}
}
return -1; // Not found
}
Comparison Table
Statement Used In Effect on Loop Effect on Function Skips/ Terminates
Break Loops, switch Terminates the loop entirely No direct effect Terminates
Continue Loops only Skips current iteration No direct effect Skips iteration
Return Functions/methods Can terminate loop + function Terminates function Terminates function
Advantages and Best Practices
Advantages:
o Improve efficiency (early exit/skip unnecessary work).
o Make code cleaner (avoid deep nesting with flags).
Caution:
o Overuse can make code harder to read (spaghetti-like flow).
o Prefer structured alternatives (e.g., better conditions) when possible.
o In nested loops, use labeled break (in Java/C++) for outer loops.
UNIT-2
Unit 2: Derived Syntactical Constructs in Java
2.1 Constructors
Constructors in Java are special methods used to initialize objects. They have the same name as
the class and no return type (not even void). Constructors are invoked automatically when an
object is created using the new keyword.
A constructor in Java is a special member that is called when an object is created. It initializes the new
object’s state. It is used to set default or user-defined values for the object's attributes
A constructor has the same name as the class.
It does not have a return type, not even void.
It can accept parameters to initialize object properties.
Types of Constructors:
Non-parameterized Constructor (Default or No-Arg Constructor): A constructor
with no parameters. If no constructor is explicitly defined in a class, the Java compiler
automatically provides a default no-arg constructor that initializes instance variables to
their default values (e.g., int to 0, boolean to false, objects to null).
A default constructor has no parameters. It’s used to assign default values to an object. If
no constructor is explicitly defined, Java provides a default constructor.
Example:
class Student {
String name;
// Default constructor (provided by compiler if none defined)
Student() {
name = "Unknown"; // Custom initialization possible
}
}
Parameterized Constructor: A constructor that accepts one or more parameters to
initialize object fields with specific values. This allows flexible object creation.
A constructor that accepts parameters to initialize object fields with user-provided
values at the time of object creation.
Useful for custom initialization.
Parameters allow different objects to be initialized with different values.
Example:
class Student {
String name;
int age;
// Parameterized constructor
Student(String n, int a) {
name = n;
age = a;
}
}
// Usage
Student s = new Student("Alice", 20);
Constructors support overloading (multiple constructors with different parameter lists). If any
constructor is defined, the compiler does not add a default one.
2.2 ‘this’ Keyword
The this keyword refers to the current object instance in a class. It is used inside instance
methods or constructors.
Common uses:
To distinguish instance variables from parameters/local variables with the same name
(shadowing).
To invoke another constructor in the same class (constructor chaining: this(args)).
To call instance methods.
To return the current object (return this for method chaining).
Example (disambiguating names):
Java
class Student {
String name;
int age;
Student(String name, int age) {
[Link] = name; // '[Link]' is instance variable
[Link] = age;
}
}
Example (constructor chaining):
Java
class Student {
String name;
int age;
Student() {
this("Unknown", 0); // Calls parameterized constructor
}
Student(String name, int age) {
[Link] = name;
[Link] = age;
}
}
2.3 Command Line Arguments - Varargs (Variable-Length Arguments)
Command Line Arguments: In Java, the main method accepts command-line arguments as a
String array: public static void main(String[] args) args contains the arguments passed when
running the program (e.g., java MyClass arg1 arg2 → args[0] = "arg1").
Varargs: Introduced in Java 5, varargs allow a method to accept a variable number of arguments
of the same type (zero or more). Syntax: type... variable (must be the last parameter).
Internally, varargs is treated as an array.
Example:
Java
class Demo {
static void printNames(String... names) {
[Link]("Number of names: " + [Link]);
for (String name : names) {
[Link](name);
}
}
public static void main(String[] args) {
printNames("Alice", "Bob"); // 2 args
printNames("Charlie"); // 1 arg
printNames(); // 0 args
printNames(args); // Pass command-line args
}
}
Varargs can be used in main as public static void main(String... args), but array form is
conventional.
2.4 Visibility Control (Access Modifiers)
Access modifiers control the visibility of class members (fields, methods, constructors).
Modifier Visibility
Public Accessible from everywhere (any class, any package).
Private Accessible only within the same class.
protected Accessible within the same package and subclasses (even in different packages).
default (no modifier) Accessible only within the same package (package-private).
Example:
Java
class Example {
public int pub = 1;
private int priv = 2;
protected int prot = 3;
int def = 4; // default
}
Best practice: Use the most restrictive modifier possible (e.g., private for fields, expose via
public getters/setters for encapsulation).
2.5 Arrays
Arrays are fixed-size collections of elements of the same type.
Types of Arrays:
Single-dimensional (1D).
Multi-dimensional (e.g., 2D for matrices).
Declaration:
Java
int[] arr; // Preferred
int arr[]; // Alternative (C-style)
int[][] matrix; // 2D array
Creation (allocate memory):
Java
arr = new int[5]; // Size 5, initialized to 0s
matrix = new int[3][4];
Initialization:
At declaration: int[] arr = {1, 2, 3, 4, 5};
After creation: arr[0] = 10;
Example (full process):
Java
int[] numbers = new int[3]; // Declaration + creation
numbers[0] = 10; // Initialization
numbers[1] = 20;
numbers[2] = 30;
int[] nums = {10, 20, 30}; // Shortcut
Arrays have a length property: [Link].
2.6 Strings - String Classes - StringBuffer
String Class: String objects are immutable (cannot be changed after creation). Any
modification creates a new String object. Stored in String pool for efficiency.
Example:
Java
String s1 = "Hello";
String s2 = [Link](" World"); // New object created
[Link](s1); // Still "Hello"
Common methods: length(), char At(), substring(), to UpperCase(), etc.
String Buffer Class: String Buffer is mutable and thread-safe (synchronized methods). Used
for frequent string modifications (e.g., in loops) to avoid performance overhead of immutable
String.
Constructors:
StringBuffer() (capacity 16)
StringBuffer(int capacity)
StringBuffer(String str)
Key methods: append(), insert(), delete(), reverse(), toString().
Example:
Java
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies same object
[Link](5, ","); // "Hello, World"
[Link](5, 6); // "Hello World"
[Link](sb); // "Hello World"
Note: For non-thread-safe scenarios, prefer StringBuilder (faster than StringBuffer).
Comparison:
Feature String StringBuffer
Mutability Immutable Mutable
Thread-safety Yes (immutable) Yes (synchronized)
Performance Slower for modifications Faster for modifications
Feature String StringBuffer
Use case Constant strings Frequent changes (multi-threaded)
UNIT-2
Derived Syntactical Constructs in Java
2.1 Constructors in Java (Detailed Long-Type Notes)
What is a Constructor?
A constructor is a special member method of a class that is automatically called when an object
of that class is created using the new keyword. Its primary purpose is to initialize the newly
created object.
Constructors in Java are special methods used to initialize objects. They have the same name as
the class and no return type (not even void). Constructors are invoked automatically when an
object is created using the new keyword.
A constructor in Java is a special member that is called when an object is created. It initializes the new
object’s state. It is used to set default or user-defined values for the object's attributes
A constructor has the same name as the class.
It does not have a return type, not even void.
It can accept parameters to initialize object properties.
Key Characteristics of Constructors:
Has the same name as the class.
Does not have any return type, not even void.
Can be overloaded (multiple constructors with different parameter lists).
Can be public, protected, private, or default access.
If no constructor is explicitly defined, Java provides a default constructor automatically.
Constructors can call other constructors using this().
Types of Constructors
Java supports mainly three types of constructors based on parameters:
1. Default Constructor (Non-Parameterized)
2. Parameterized Constructor
3. Copy Constructor (not built-in, but can be implemented)
We will focus on the first two as per the topic.
1. Default Constructor (Non-Parameterized Constructor)- Non-parameterized
Constructor (Default or No-Arg Constructor): A constructor with no parameters. If no
constructor is explicitly defined in a class, the Java compiler automatically provides a
default no-arg constructor that initializes instance variables to their default values (e.g.,
int to 0, boolean to false, objects to null).
A default constructor has no parameters. It’s used to assign default values to an object. If
no constructor is explicitly defined, Java provides a default constructor.
A constructor that takes no parameters.
If you do not write any constructor in the class, the Java compiler automatically provides a
default constructor (no-arg constructor) that initializes instance variables to their default values.
If you define any constructor (even parameterized), the compiler will not provide the default
constructor automaticalSyntax:
class ClassName {
// Default constructor
ClassName() {
// Initialization code (optional)
[Link]("Default constructor called");
}
}
Example:
class Student {
int rollNo;
String name;
// Default constructor
Student() {
rollNo = 0;
name = "Unknown";
[Link]("Default constructor executed");
}
void display() {
[Link]("Roll No: " + rollNo + ", Name: " + name);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // Default constructor called
[Link](); // Output: Roll No: 0, Name: Unknown
}
}
When compiler provides default constructor (implicit):
class Employee {
int id;
String name;
// No constructor written → Compiler adds: Employee() { }
}
Important Point: Once you write a parameterized constructor, the default one is not added
automatically. So if you need both, you must write the default constructor explicitly.
2. Parameterized Constructor
A constructor that accepts parameters to initialize object fields with user-provided values at the
time of object creation.
Useful for custom initialization.
Parameters allow different objects to be initialized with different values.
Syntax:
class ClassName {
ClassName(dataType param1, dataType param2, ...) {
// Assign parameters to instance variables
this.instanceVar1 = param1;
this.instanceVar2 = param2;
}
}
Example:
class Student {
int rollNo;
String name;
double marks;
// Parameterized constructor
Student(int r, String n, double m) {
rollNo = r;
name = n;
marks = m;
}
void display() {
[Link]("Roll: " + rollNo + ", Name: " + name + ", Marks: " +
marks);
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(101, "Amit", 85.5); // Parameterized constructor
Student s2 = new Student(102, "Priya", 92.0);
[Link]();
[Link]();
}
}
Output:
Roll: 101, Name: Amit, Marks: 85.5
Roll: 102, Name: Priya, Marks: 92.0
Using this keyword in Parameterized Constructor (Recommended):
class Student {
int rollNo;
String name;
Student(int rollNo, String name) {
[Link] = rollNo; // 'this' differentiates instance var from parameter
[Link] = name;
}
}
Constructor Overloading
Java allows multiple constructors in the same class with different parameter lists (number, type,
or order). This is called constructor overloading.
Example:
class Box {
double width, height, depth;
// Default constructor
Box() {
width = height = depth = 1;
}
// Parameterized: one parameter (cube)
Box(double side) {
width = height = depth = side;
}
// Parameterized: three parameters
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
public class Test {
public static void main(String[] args) {
Box b1 = new Box(); // Default
Box b2 = new Box(5); // Cube
Box b3 = new Box(2, 3, 4); // Cuboid
[Link]("Volume b1: " + [Link]()); // 1
[Link]("Volume b2: " + [Link]()); // 125
[Link]("Volume b3: " + [Link]()); // 24
}
}
Constructor Chaining using this()
One constructor can call another constructor of the same class using this().
Must be the first statement in the constructor.
Useful to avoid code duplication.
Example:
class Student {
int rollNo;
String name;
String course;
Student(int rollNo, String name) {
[Link] = rollNo;
[Link] = name;
[Link] = "General"; // default
}
Student(int rollNo, String name, String course) {
this(rollNo, name); // Calls above constructor
[Link] = course;
}
void display() {
[Link](rollNo + " " + name + " " + course);
}
}
Key Differences: Default vs Parameterized Constructor
Feature Default Constructor Parameterized Constructor
Parameters No parameters One or more parameters
Provided by compiler Yes (if no constructor written) No (must be written explicitly)
Initialization Default values or explicit code Custom values passed at object creation
Use case Basic object creation Specific/initialized object creation
Overloading possible Yes Yes
Feature Default Constructor Parameterized Constructor
Example call new Student() new Student(101, "Ram")
Important Points to Remember
Constructors are not inherited by subclasses.
super() is used to call parent class constructor (implicitly called if no explicit call).
Private constructors are used in Singleton design pattern.
Constructors can throw exceptions.
Static blocks and instance blocks can also help in initialization along with constructors.
2.2 ‘this’ Keyword in Java
The this keyword is a reference variable that refers to the current object of the class inside
which it is used.
Uses of ‘this’ Keyword:
1. To distinguish instance variables from parameters/local variables (when names are same).
2. To invoke current class constructor (constructor chaining).
3. To invoke current class methods (rarely needed, as implicit).
4. To return the current object from a method.
5. To pass the current object as an argument to another method/constructor.
Detailed Explanation with Examples:
1. Differentiating Variables
class Student {
int rollNo;
String name;
Student(int rollNo, String name) {
[Link] = rollNo; // [Link] → instance variable
[Link] = name; // rollNo, name → parameters
}
}
2. Constructor Chaining using this()
class Box {
double width, height, depth;
Box(double w, double h, double d) {
[Link] = w;
[Link] = h;
[Link] = d;
}
Box(double side) {
this(side, side, side); // Calls the three-parameter constructor
}
Box() {
this(1.0); // Calls single-parameter constructor
}
}
3. Returning Current Object
class Counter {
int count = 0;
Counter increment() {
count++;
return this; // Returns current object for method chaining
}
void display() {
[Link]("Count: " + count);
}
}
public class Test {
public static void main(String[] args) {
new Counter().increment().increment().display(); // Output: Count: 2
}
}
4. Passing Current Object as Argument
Java
class Test {
void method(Test obj) {
[Link]("Method called");
}
void caller() {
method(this); // Passing current object
}
}
Key Points:
this cannot be used in static context (static methods/blocks).
this() must be the first statement in constructor.
2.3 Command Line Arguments and Varargs (Variable-Length Arguments)
Command Line Arguments
Arguments passed to the main() method from the command line while running the program.
Declared as: public static void main(String[] args)
args is an array of String containing the arguments.
Example:
Java
public class CmdArgs {
public static void main(String[] args) {
[Link]("No. of arguments: " + [Link]);
for(int i = 0; i < [Link]; i++) {
[Link]("Arg " + (i+1) + ": " + args[i]);
}
}
}
Run command: java CmdArgs Hello 123 Java World Output:
text
No. of arguments: 4
Arg 1: Hello
Arg 2: 123
Arg 3: Java
Arg 4: World
Varargs (Variable-Length Arguments)
Introduced in Java 5.
Allows a method to accept zero or more arguments of the same type.
Syntax: dataType... variableName (ellipses before variable name).
Internally treated as an array.
Rules:
Only one varargs per method.
Varargs must be the last parameter.
Example:
Java
class VarargsDemo {
static void display(String... values) { // Can take 0 or more Strings
[Link]("No. of args: " + [Link]);
for(String s : values) {
[Link](s);
}
}
public static void main(String[] args) {
display(); // 0 args
display("Hello"); // 1 arg
display("Hi", "Java", "World"); // 3 args
}
}
Overloading with Varargs:
Java
static void sum(int... nums) {
int total = 0;
for(int n : nums) total += n;
[Link]("Sum: " + total);
}
Call: sum(1, 2, 3, 4); → Output: Sum: 10
Varargs vs Array: Varargs is more flexible and cleaner than passing array explicitly.
2.4 Visibility Control (Access Modifiers)
Java provides four access modifiers to control visibility of class members (fields, methods,
constructors).
Within Within Subclass (Same Subclass (Different Outside
Modifier
Class Package Package) Package) World
public Yes Yes Yes Yes Yes
protected Yes Yes Yes Yes (via inheritance) No
default (no
Yes Yes Yes No No
modifier)
private Yes No No No No
Detailed Explanation:
1. public: Accessible from everywhere.
2. private: Accessible only within the same class. Used for data hiding.
3. protected: Accessible in same package + subclasses (even in different packages).
4. default (package-private): Accessible only within the same package.
Example:
Java
package pack1;
public class A {
public int pub = 1;
protected int pro = 2;
int def = 3; // default
private int pri = 4;
void show() {
[Link](pub + " " + pro + " " + def + " " + pri); // All
accessible
}
}
Java
package pack2;
import pack1.A;
class B extends A {
void test() {
[Link](pub + " " + pro); // def and pri not accessible
}
}
Java
package pack1;
class C {
void test() {
A obj = new A();
[Link]([Link] + " " + [Link] + " " + [Link]); // pri
not accessible
}
}
2.5 Arrays in Java
An array is a homogeneous collection of fixed-size elements stored in contiguous memory.
Types of Arrays
1. Single-Dimensional (1D) Array
2. Multi-Dimensional (2D, 3D, etc.) Array (array of arrays)
Declaration
Java
dataType[] arrayName; // Preferred
dataType arrayName[]; // C-style (allowed but not recommended)
Example: int[] marks;
Creation (Memory Allocation)
Using new operator:
Java
arrayName = new dataType[size];
Example: marks = new int[5]; // Creates array of 5 integers (default 0)
Declaration + Creation in One Line
Java
int[] arr = new int[10];
Initialization
1. At Declaration:
Java
int[] arr = {10, 20, 30, 40}; // Implicit size = 4
2. After Creation:
Java
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
// ...
3. Using Loop
Multi-Dimensional Array Example:
Java
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
// Initialization
int[][] mat = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Jagged Array (Irregular):
Java
int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[4];
jagged[2] = new int[3];
Key Points:
Array index starts from 0.
Length: [Link]
Arrays are objects → inherit from Object class.
clone() for deep copy (for multi-dim, need manual).
2.6 Strings in Java
String Class
[Link] is immutable (cannot be changed once created).
Stored in String Constant Pool (for literals).
Creation:
Java
String s1 = "Hello"; // Literal → Pool
String s2 = new String("Hello"); // Heap
Common Methods:
length(), charAt(int), substring(int, int), indexOf(), toLowerCase(), toUpperCase(), trim(),
replace(), split(), equals(), compareTo(), etc.
Concatenation: + or concat()
Immutability Example:
Java
String s = "Java";
s = s + " Programming"; // New string object created
StringBuffer Class
Mutable sequence of characters.
Thread-safe (synchronized).
Methods: append(), insert(), delete(), reverse(), capacity()
Example:
StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies same object
[Link](); // "dlroW olleH"
StringBuilder Class (Java 5+)
Mutable, not thread-safe (faster than StringBuffer).
Preferred in single-threaded environments.
Example:
StringBuilder sbd = new StringBuilder("Java");
[Link](" Rocks");
[Link](sbd); // Java Rocks
Comparison Table: String vs StringBuffer vs StringBuilder
Feature String StringBuffer StringBuilder
Mutability Immutable Mutable Mutable
Thread Safety Yes Yes (synchronized) No
Performance Slow (new object) Moderate Fast
Storage String Pool Heap Heap
Use Case Constant text Multi-thread Single-thread
UNIT-3
Inheritance, Interface and Package
3.1 Concept of Inheritance
Inheritance is one of the core pillars of Object-Oriented Programming (OOP) in Java. It is a
mechanism by which one class (called subclass or child class or derived class)
acquires/acquires the properties (fields and methods) of another class (called superclass or
parent class or base class).
Key Purposes of Inheritance:
Code Reusability: Write code once in the superclass and reuse it in multiple subclasses.
Extensibility: Add new features to existing classes without modifying them.
Method Overriding: Achieve runtime polymorphism.
Establish "IS-A" relationship: e.g., Car IS-A Vehicle, Dog IS-A Animal.
Syntax:
Java
class SubClass extends SuperClass {
// SubClass inherits all non-private members of SuperClass
}
Important Points:
Java supports single inheritance for classes (a class can extend only one class).
By default, every class in Java inherits from [Link] class (methods like toString(),
equals(), hashCode()).
Use super keyword to refer to superclass members or call superclass constructor.
Use super() to call superclass constructor (must be first statement in subclass constructor).
Example:
Java
class Vehicle {
int speed;
void start() {
[Link]("Vehicle started");
}
}
class Car extends Vehicle {
int gears;
void accelerate() {
[Link]("Car accelerating");
}
}
public class Test {
public static void main(String[] args) {
Car c = new Car();
[Link] = 100; // Inherited from Vehicle
[Link](); // Inherited method
[Link](); // Own method
}
}
3.2 Types of Inheritance
Java supports the following types of inheritance (based on class hierarchy):
1. Single Inheritance One subclass inherits from one superclass.
Diagram: SuperClass → SubClass
Example:
Java
class Animal { void eat() { ... } }
class Dog extends Animal { void bark() { ... } }
2. Multilevel Inheritance A class inherits from a subclass (chain-like).
Diagram: GrandParent → Parent → Child
Example:
Java
class Animal { void eat() { ... } }
class Mammal extends Animal { void walk() { ... } }
class Dog extends Mammal { void bark() { ... } }
Dog inherits from Mammal, which inherits from Animal.
3. Hierarchical Inheritance Multiple subclasses inherit from one single superclass.
Diagram: SuperClass → SubClass1 → SubClass2 → SubClass3
Example:
Java
class Shape { void draw() { ... } }
class Circle extends Shape { ... }
class Rectangle extends Shape { ... }
class Triangle extends Shape { ... }
4. Multiple Inheritance (Not supported directly in classes) One class inherits from multiple
superclasses.
Why not supported in classes? To avoid the Diamond Problem (ambiguity when two
superclasses have same method).
Diagram: ClassA → ClassC ← ClassB
Java does not allow multiple inheritance through classes, but achieves it through
interfaces (covered later).
5. Hybrid Inheritance Combination of multiple and multilevel/hierarchical. Achieved in
Java using interfaces only.
Summary Table of Supported Types in Java (Classes):
Type Supported in Java Classes? Reason/Example
Single Yes Basic inheritance
Multilevel Yes Chain of inheritance
Hierarchical Yes One parent, many children
Multiple No Diamond problem
Hybrid No (via classes) Achieved using interfaces
3.3 Interface in Java
An interface is a completely abstract blueprint of a class that defines what a class must do
(methods) but not how.
Key Features:
All methods are public abstract by default (until Java 7).
From Java 8: Can have default and static methods with implementation.
From Java 9: Can have private methods.
Variables are public static final by default (constants).
A class implements an interface using implements keyword.
Interfaces support multiple inheritance.
Defining an Interface:
Java
interface Drawable {
int MAX = 100; // public static final
void draw(); // public abstract
default void msg() { // Java 8+
[Link]("Default method");
}
static void info() { // Java 8+
[Link]("Static method in interface");
}
}
Extending Interface: Interfaces can extend other interfaces (multiple inheritance allowed).
Java
interface A { void methodA(); }
interface B { void methodB(); }
interface C extends A, B { void methodC(); }
Implementing Interface:
Java
class Circle implements Drawable {
public void draw() { // Must be public
[Link]("Drawing circle");
}
}
class Test {
public static void main(String[] args) {
Drawable d = new Circle();
[Link]();
[Link](); // Default method
[Link](); // Static method
}
}
Multiple Inheritance via Interfaces:
Java
interface Flyable { void fly(); }
interface Swimmable { void swim(); }
class Duck implements Flyable, Swimmable {
public void fly() { [Link]("Duck flying"); }
public void swim() { [Link]("Duck swimming"); }
}
Interface vs Abstract Class:
Feature Interface Abstract Class
Methods Mostly abstract (default/static allowed) Abstract + concrete
Variables Only constants Instance variables allowed
Multiple Inheritance Yes (class can implement many) No
Constructor No Yes
Access Modifiers Only public Any (public, protected, etc.)
3.4 Method Overloading and Overriding
1. Method Overloading (Compile-time Polymorphism) Multiple methods in the same
class with:
o Same name
o Different parameters (number, type, or order)
Example:
Java
class Calculator {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
int add(int a, int b, int c) { return a + b + c; }
}
2. Method Overriding (Runtime Polymorphism) Subclass provides a specific
implementation of a method that is already defined in its superclass.
o Method name, return type, and parameters must be exactly same.
o Overriding method can have less restrictive access modifier.
o Use @Override annotation (recommended).
Example:
Java
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public class Test {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
[Link](); // Output: Dog barks (runtime decision)
}
}
Overloading vs Overriding
Feature Overloading Overriding
Location Same class Subclass
Method Signature Same name, different parameters Same name + same parameters
Polymorphism Compile-time Runtime
Return Type Can be different Must be same or covariant (Java 5+)
Access Modifier No restriction Cannot be more restrictive
3.5 Package in Java
A package is a grouping mechanism to categorize classes and interfaces, avoid naming conflicts,
and provide access control.
Benefits:
Namespace management
Access protection
Code organization
Types of Packages:
1. Built-in Packages (Pre-defined): [Link], [Link], [Link], [Link], etc.
2. User-defined Packages: Created by programmer.
Naming Convention:
All lowercase
Usually reverse domain name: [Link]
Creating a Package: Add package statement at the top of the file.
Java
package [Link];
public class Account {
// class body
}
Directory Structure: File must be saved in corresponding folder:
com/mycompany/bank/[Link]
Accessing Package Members: Controlled by access modifiers:
public: Accessible from anywhere
protected: Same package + subclasses
Default: Same package only
private: Same class only
Import Statement: To use classes from other packages.
Types of Import:
1. Single-type import:
Java
import [Link];
2. On-demand import (import all):
Java
import [Link].*; // Imports all classes in [Link]
3. Static import (Java 5+):
Java
import static [Link];
import static [Link].*;
// Now use PI directly without [Link]
Example Usage:
Java
package [Link];
import [Link];
import [Link];
public class Demo {
public static void main(String[] args) {
Date d = new Date(); // From [Link]
Account acc = new Account();
}
}
Key Points:
[Link] package is imported automatically.
Fully qualified name can be used without import: [Link] list = new
[Link]();
Packages help in encapsulation and modular design.