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

Unit 1

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Java, including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It also covers the history of Java, its key features, JVM architecture, data types, variables, and their scope and lifetime. Additionally, it discusses Java's advantages, such as platform independence and automatic memory management.
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 views42 pages

Unit 1

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts in Java, including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It also covers the history of Java, its key features, JVM architecture, data types, variables, and their scope and lifetime. Additionally, it discusses Java's advantages, such as platform independence and automatic memory management.
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
You are on page 1/ 42

REVIEW OF OBJECT-ORIENTED PROGRAMMING (OOP) CONCEPTS IN JAVA

1. Class and Object


 Class: A blueprint for creating objects. It defines fields (attributes) and methods
(behaviors).
 Object: An instance of a class that holds actual values.
class Car {
String color;
void drive() {
System.out.println("Car is driving");
}
}
Car myCar = new Car(); // Object creation
2. Encapsulation
 Definition: Binding data (variables) and code (methods) together as a single unit and
restricting access to some components.
 Achieved using: Access modifiers (private, public, protected) and getters/setters.
class Person {
private String name;

public String getName() {


return name;
}

public void setName(String newName) {


name = newName;
}
}
3. Inheritance
 Definition: One class (subclass/child) inherits the fields and methods of another class
(superclass/parent).
 Key benefit: Code reuse.
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog barks");
}
}
4. Polymorphism
 Definition: One interface, many implementations. An object can take many forms.
 Types:
o Compile-time (method overloading)
o Runtime (method overriding)
// Method Overloading
class MathUtils {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
// Method Overriding
class Animal {
void sound() {
System.out.println("Generic sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
5. Abstraction
 Definition: Hiding internal details and showing only essential features.
 Achieved via:
o Abstract classes (can have both abstract and concrete methods)
o Interfaces (Java 8+ allows default and static methods too)
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing Circle");
}
}
HISTORY OF JAVA
Early Development (1991–1995)
 1991: A team at Sun Microsystems, led by James Gosling, started the Green Project
to develop software for consumer electronics like televisions and VCRs.
 Originally, they developed a language called Oak (named after an oak tree outside
Gosling’s office).
 1995: Oak was renamed Java, due to trademark issues with another company using
the Oak name.
Java’s Launch and Rise (1995–1999)
 1995: Java was officially launched by Sun Microsystems.
 Java’s key feature: “Write Once, Run Anywhere” (WORA), meaning compiled Java
code could run on any platform with a Java Virtual Machine (JVM).
 Java gained popularity with the rise of the web, thanks to Java Applets, which
allowed interactive content in browsers.
Enterprise Adoption and Expansion (2000–2009)
 Java became widely used in enterprise applications with the introduction of Java 2
Platform, Enterprise Edition (J2EE).
 Tools like Eclipse, NetBeans, and frameworks like Spring and Hibernate enhanced
Java’s enterprise capabilities.
Oracle Acquisition and Modern Era (2010–Present)
 2010: Oracle Corporation acquired Sun Microsystems, and thus took control of
Java.
 Oracle introduced a new six-month release cycle starting with Java 9 (2017) to
speed up innovation.
 New features include:
o Lambdas (Java 8) – functional programming style
o Modules (Java 9)
o Records, Sealed Classes, Pattern Matching in later versions
Recent Versions
 As of 2024, Java has reached Java 21 (LTS) and is known for its robustness,
scalability, and security.
 It remains a top choice for Android development, enterprise systems, cloud
computing, and big data applications.
JAVA BUZZWORDS
1. Simple
o Designed to be easy to learn and use, especially for programmers familiar with
C/C++.
o Removes complex features like pointers and multiple inheritance.
2. Object-Oriented
o Everything is treated as an object, promoting modular, reusable code.
o Encourages concepts like encapsulation, inheritance, and polymorphism.
3. Secure
o Built-in security features such as bytecode verification, sandboxing, and
runtime security checks.
o Ideal for networked/distributed environments.
4. Platform-Independent
o "Write Once, Run Anywhere" – Java programs run on any device with the
Java Virtual Machine (JVM).
o Source code is compiled into bytecode that the JVM executes.
5. Robust
o Strong memory management, exception handling, and type checking.
o Designed to reduce the likelihood of crashing or unexpected behavior.
6. Multithreaded
o Supports multithreading at the language level, allowing multiple tasks to run
simultaneously.
7. Architecture-Neutral
o Bytecode can run on any machine without modification.
o Not tied to a specific processor or operating system.
8. Interpreted
o Java bytecode is interpreted by the JVM, which provides flexibility and
portability.
9. High Performance
o Though interpreted, the JVM uses Just-In-Time (JIT) compilation for
performance optimization.
10. Distributed
 Built-in support for networking, allowing programs to work across the internet using
RMI, sockets, etc.
11. Dynamic
 Java programs can load classes at runtime and adapt to new environments
dynamically.
JVM ARCHITECTURE IN JAVA
The Java Virtual Machine (JVM) is a crucial component of the Java Runtime
Environment (JRE) that provides a platform-independent way of running Java programs. It is
responsible for executing Java bytecode and converting it into machine code that can be
understood by the underlying operating system. The JVM plays a vital role in achieving
Java's Write Once, Run Anywhere philosophy, as Java programs are compiled into
bytecode, which can run on any device or platform that has a JVM implementation.
Key Components of JVM
The JVM architecture is designed to be platform-independent. It abstracts the
underlying hardware and operating system, providing a uniform execution environment for
Java applications. It consists of several components that work together to load, verify, and
execute Java programs. The JVM architecture can be broken down into the following key
components:
1. Class Loader Subsystem
2. Runtime Data Areas
3. Execution Engine
4. Java Native Interface (JNI)
5. Garbage Collector
JVM Architecture Diagram

1. Class Loader Subsystem


The Class Loader is responsible for loading the compiled .class files (which contain
Java bytecode) into memory. It loads the class files into the JVM from the file system,
network, or other sources, and also manages the process of linking them to the program.
There are three types of class loaders in Java:
 Bootstrap Class Loader: Loads core Java libraries from the Java Runtime
Environment (JRE) such as rt.jar.
 Extension Class Loader: Loads Java classes from the JDK extensions directory.
 System Class Loader: Loads classes from the classpath, typically the classes you
write.
2. Runtime Data Areas
The JVM uses different data areas during the execution of a program. These areas are
used to store information that is used during the execution of Java programs.
a. Method Area
 Stores metadata about the classes, including information about methods, fields, and
method data.
 It is shared among all threads and contains class structures like the bytecode.
 It also stores the constant pool, which holds the constant values used in the program.
b. Heap
 The heap is where all objects and arrays are stored.
 It is the area in memory where dynamic memory allocation occurs.
 The heap is shared by all threads, and it is managed by the Garbage Collector for
memory cleanup.
c. Stack
 Each thread has its own stack.
 The stack stores method invocations, local variables, and partial results.
 Whenever a method is called, a stack frame is created in the stack, and when the
method finishes execution, the frame is popped off the stack.
d. Program Counter (PC) Register
 The PC register keeps track of the current instruction being executed by the thread.
 Every thread has its own PC register, which holds the address of the next instruction
to be executed for that thread.
e. Native Method Stack
 The native method stack is used to support native methods (written in languages like
C or C++) that are used by the Java program.
 The stack keeps track of method calls made to native libraries.
3. Execution Engine
The Execution Engine is the part of the JVM that actually runs the bytecode. It
consists of two main components:
a. Interpreter
 The Interpreter reads bytecode line by line and interprets it, meaning it converts the
bytecode into machine-specific instructions.
 This approach works but is typically slower because it doesn't translate bytecode into
native code ahead of time.
b. Just-In-Time (JIT) Compiler
 The JIT compiler is used to improve the performance of the JVM by compiling
bytecode into native machine code just before execution.
 It works by analyzing the bytecode and compiling it into machine code for the
specific platform, thus speeding up the execution of the program.
 The compiled machine code is cached so that the next time the same code is
encountered, the JVM uses the cached native code, improving performance.
4. Java Native Interface (JNI)
The JNI is an interface that allows Java code to interact with native applications and
libraries written in other languages such as C, C++, or assembly. This is necessary when Java
programs need to use platform-specific features or interact with existing non-Java code.
Example use of JNI:
 Java programs can call a method written in C or C++.
 Java can access hardware-specific features that are not available in standard Java
libraries.
5. Garbage Collector
The Garbage Collector (GC) is responsible for automatic memory management in Java.
It monitors objects that are no longer in use and deallocates memory to ensure efficient
memory usage. The garbage collector runs in the background and removes objects that are no
longer referenced.
 Mark-and-sweep is a typical garbage collection algorithm, which works in two
phases:
 Mark phase: The GC marks all objects that are still in use (i.e., reachable
objects).
 Sweep phase: The GC sweeps through the heap and deletes objects that are
not marked, freeing up memory.
There are several types of garbage collectors, including:
 Serial Garbage Collector: Uses a single thread for garbage collection.
 Parallel Garbage Collector: Uses multiple threads to collect garbage.
 CMS (Concurrent Mark and Sweep) Collector: Aims to minimize application
pause times.
 G1 Garbage Collector: Designed for large heaps with predictable pause time goals.
JVM Execution Flow
1. Java Code Compilation: Java source code (.java files) is compiled by the Java
compiler (javac) into bytecode (.class files).
2. Class Loading: The class loader subsystem loads the .class files into memory.
3. Method Resolution: The JVM looks up the necessary methods and classes and
ensures that they are available.
4. Bytecode Execution: The execution engine interprets or compiles the bytecode into
machine code, depending on whether the JIT compiler is used.
5. Memory Management: The garbage collector ensures that memory is efficiently
managed by clearing unused objects.
Advantages of JVM
1. Platform Independence: Java code is compiled into bytecode, which can run on any
system that has a JVM, making Java a "write once, run anywhere" language.
2. Automatic Memory Management: The garbage collector automatically manages
memory allocation and deallocation, reducing the risk of memory leaks.
3. Security: The JVM provides a secure execution environment by enforcing security
policies and preventing unauthorized access to system resources.
4. Optimized Performance: With the JIT compiler, Java performance is optimized for
the platform it is running on, improving speed and efficiency.
DATA TYPES, VARIABLES, AND THE SCOPE AND LIFETIME OF VARIABLES
IN JAVA
1. Data Types in Java
Java is a statically typed language, meaning every variable must have a declared data type.
a. Primitive Data Types
Java has 8 primitive data types:

Type Size Description Example

byte 1 byte Small integer (-128 to 127) byte b = 100;

short 2 bytes Small integer short s = 1000;

int 4 bytes Default integer type int i = 10000;

long 8 bytes Large integer long l = 100000L;

float 4 bytes Single-precision decimal float f = 10.5f;

double 8 bytes Double-precision decimal double d = 20.5;

char 2 bytes Single 16-bit Unicode char char c = 'A';

boolean 1 bit true or false boolean flag = true;

b. Non-Primitive (Reference) Data Types


 Include Strings, Arrays, Classes, Interfaces, etc.
 Examples:
 String name = "Java";
 int[] numbers = {1, 2, 3};
2. Variables in Java
A variable is a name given to a memory location that stores a value.
Types of Variables:
1. Local Variables
o Declared inside methods, constructors, or blocks.
o Must be initialized before use.
o Scope: Limited to the block where declared.
o Lifetime: Exists while the method/block is executing.
2. Instance Variables
o Declared inside a class but outside any method.
o Each object has its own copy.
o Scope: Accessible by all non-static methods in the class.
o Lifetime: As long as the object exists.
3. Static Variables (Class Variables)
o Declared with the static keyword.
o Shared among all objects of the class.
o Scope: Accessible by all methods (static and non-static).
o Lifetime: Exists as long as the class is loaded in memory.
3. Scope and Lifetime of Variables
Scope
 Defines where a variable can be accessed in code.
 Example:
 public class ScopeExample {
 int instanceVar = 10; // instance scope

 static int staticVar = 20; // class scope


 public void method() {


 int localVar = 30; // local scope
 System.out.println(localVar); // Accessible here
 }
 }
Lifetime
 Duration a variable exists in memory:
o Local: Exists while method runs.
o Instance: Lives as long as the object.
o Static: Lives as long as the class is loaded by JVM.
✅ Example with All Types of Variables
public class VariableExample {
// Static variable
static int staticCounter = 0;
// Instance variable
int instanceCounter = 0;
public void display() {
// Local variable
int localCounter = 0;
localCounter++;
instanceCounter++;
staticCounter++;
System.out.println("Local: " + localCounter);
System.out.println("Instance: " + instanceCounter);
System.out.println("Static: " + staticCounter);
}
public static void main(String[] args) {
VariableExample obj1 = new VariableExample();
VariableExample obj2 = new VariableExample();
obj1.display();
obj2.display();
}
}
Output:
Local: 1
Instance: 1
Static: 1
Local: 1
Instance: 1
Static: 2
Explanation:
 localCounter resets each time display() runs.
 instanceCounter is unique for each object.
 staticCounter is shared, so it keeps incrementing across all instances.
ARRAY IN JAVA
Arrays in Java are data structures that store multiple values of the same data type in
a single variable. They provide a way to group related data together and are especially useful
when dealing with large quantities of data of a uniform type.
1. Basics of Arrays
An array:
 Holds fixed-size elements.
 Is zero-indexed (the first element is at index 0).
 Can be of primitive types (like int, char, double, etc.) or object types (like String,
Integer, etc.).
2. Declaring Arrays
java
CopyEdit
// Declaration
int[] numbers; // preferred
int numbers[]; // also valid
Declaration does not allocate memory. It just tells the compiler you are going to use an array.
3. Creating Arrays (Instantiation)
java
CopyEdit
numbers = new int[5]; // Creates an array that can hold 5 integers
You can also combine declaration and instantiation:
java
CopyEdit
int[] numbers = new int[5];
4. Initializing Arrays
You can assign values using the index:
java
CopyEdit
numbers[0] = 10;
numbers[1] = 20;
Or initialize it directly:
java
CopyEdit
int[] numbers = {10, 20, 30, 40, 50};
5. Accessing Array Elements
java
CopyEdit
System.out.println(numbers[0]); // Output: 10
6. Array Length
java
CopyEdit
System.out.println(numbers.length); // Output: 5
Note: length is a property (not a method, so no parentheses).
7. Looping Through Arrays
For Loop:
java
CopyEdit
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Enhanced For Loop (for-each):
java
CopyEdit
for (int num : numbers) {
System.out.println(num);
}
8. Multidimensional Arrays
java
CopyEdit
int[][] matrix = new int[2][3]; // 2 rows, 3 columns
matrix[0][0] = 1;
Initialization:
java
CopyEdit
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
Accessing:
java
CopyEdit
System.out.println(matrix[1][2]); // Output: 6
9. Arrays of Objects
java
CopyEdit
String[] names = {"Alice", "Bob", "Charlie"};
Each element is a reference to a String object.
10. Limitations of Arrays
 Fixed size after creation.
 No built-in methods for insertion/deletion/sorting (use ArrayList for dynamic needs).
 Manual management of indices can lead to bugs (like
ArrayIndexOutOfBoundsException).
OPERATORS IN JAVA: A DETAILED EXPLANATION
In Java, operators are special symbols used to perform operations on variables and values.
They are used to manipulate data and perform arithmetic, comparison, logical operations, and
more.
Java operators can be categorized into several types:
1. Arithmetic Operators
These operators perform basic arithmetic operations.
Operator Description Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division (returns quotient) a / b
% Modulus (remainder) a%b
Example:
int a = 10, b = 5;
System.out.println(a + b); // Output: 15
System.out.println(a - b); // Output: 5
System.out.println(a * b); // Output: 50
System.out.println(a / b); // Output: 2
System.out.println(a % b); // Output: 0
 Note: Division with integers will truncate the result (i.e., discard any decimal places).
Use float or double for accurate division if needed.
2. Relational (Comparison) Operators
These operators are used to compare two values and return a boolean result (true or false).
Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a>b
< Less than a<b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b
Example:
int a = 10, b = 5;
System.out.println(a == b); // Output: false
System.out.println(a != b); // Output: true
System.out.println(a > b); // Output: true
System.out.println(a < b); // Output: false
System.out.println(a >= b); // Output: true
System.out.println(a <= b); // Output: false
3. Logical Operators
Logical operators are used to combine multiple boolean expressions or conditions.
Operator Description Example
&& Logical AND a && b
` `
! Logical NOT !a
Example:
boolean a = true, b = false;
System.out.println(a && b); // Output: false
System.out.println(a || b); // Output: true
System.out.println(!a); // Output: false
 Note: The && (AND) operator returns true only if both operands are true. The || (OR)
operator returns true if at least one operand is true. The ! (NOT) operator negates the
value of the boolean.
4. Assignment Operators
These operators are used to assign values to variables.
Operator Description Example
= Simple assignment a=b
+= Addition assignment a += b
-= Subtraction assignment a -= b
*= Multiplication assignment a *= b
/= Division assignment a /= b
%= Modulus assignment a %= b
Example:
int a = 5;
a += 3; // Equivalent to a = a + 3; -> a = 8
a -= 2; // Equivalent to a = a - 2; -> a = 6
a *= 4; // Equivalent to a = a * 4; -> a = 24
a /= 6; // Equivalent to a = a / 6; -> a = 4
5. Unary Operators
Unary operators are used to perform operations on a single operand.
Operator Description Example
+ Unary plus (indicates positive value) +a
- Unary minus (negates the value) -a
++ Increment (increase by 1) a++ or ++a
-- Decrement (decrease by 1) a-- or --a
! Logical NOT (negates boolean) !a
Example:
int a = 5;
System.out.println(++a); // Output: 6 (Pre-increment)
System.out.println(a++); // Output: 6 (Post-increment)
System.out.println(--a); // Output: 5 (Pre-decrement)
System.out.println(a--); // Output: 5 (Post-decrement)
6. Bitwise Operators
Bitwise operators perform operations on bits (binary values) and are used for bit-level
manipulation.
Operator Description Example
& Bitwise AND a&b
` ` Bitwise OR
^ Bitwise XOR (exclusive OR) a ^ b
~ Bitwise NOT (inverts bits) ~a
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
Example:
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
System.out.println(a & b); // Output: 1 (0101 & 0011 = 0001)
System.out.println(a | b); // Output: 7 (0101 | 0011 = 0111)
System.out.println(a ^ b); // Output: 6 (0101 ^ 0011 = 0110)
7. Ternary Operator (Conditional Operator)
The ternary operator is a shortcut for if-else statements. It takes three operands.
Operator Description Example
?: Conditional (ternary) operator condition ? expr1 : expr2
Example:
int a = 5, b = 10;
int result = (a > b) ? a : b; // result = b, because a > b is false
System.out.println(result); // Output: 10
8. Instanceof Operator
The instanceof operator is used to check if an object is an instance of a specific class or
subclass.
Operator Description Example
instanceof Checks if an object is an instance of a class obj instanceof ClassName
Example:
String str = "Hello";
System.out.println(str instanceof String); // Output: true
9. Type Cast Operator
Type casting is used to convert one data type to another. Java allows both implicit and
explicit casting.
Implicit Casting (widening):
int a = 10;
double b = a; // No loss of data, so automatically converts
Explicit Casting (narrowing):
double a = 10.5;
int b = (int) a; // Must be done manually, as data might be lost

CONTROL STATEMENTS IN JAVA


Control statements in Java are used to determine the flow of program execution. They
allow you to make decisions (conditional statements), repeat certain actions (loops), and
control the program flow in other ways. Control statements are crucial for implementing
logic, performing actions repeatedly, and handling different scenarios in a program.
Java has the following types of control statements:
1. Decision-making statements (Conditional statements)
2. Looping statements
3. Jump statements
Let's explore each of these control statements in detail.
1. Decision-Making Statements (Conditional Statements)
Decision-making statements allow you to execute certain blocks of code based on
conditions. These are useful when you need to perform different actions based on whether a
condition is true or false.
a. if statement
The if statement is used to execute a block of code if a specific condition is true.
Syntax:
if (condition) {
// Block of code to be executed if the condition is true
}
Example:
public class Main {
public static void main(String[] args) {
int num = 10;
if (num > 5) {
System.out.println("The number is greater than 5");
}
}
}
In this example, since num is greater than 5, the message "The number is greater than
5" is printed.
b. if-else statement
The if-else statement provides an alternative block of code to execute if the condition
is false.
Syntax:
if (condition) {
// Block of code to be executed if the condition is true
} else {
// Block of code to be executed if the condition is false
}
Example:
public class Main {
public static void main(String[] args) {
int num = 3;
if (num > 5) {
System.out.println("The number is greater than 5");
} else {
System.out.println("The number is less than or equal to 5");
}
}
}
Here, since num is not greater than 5, the message "The number is less than or equal to 5"
will be printed.
c. else-if ladder
An else-if ladder allows you to check multiple conditions. This is useful when you
have several possible choices and need to execute different blocks of code depending on
which condition is true.
Syntax:
if (condition1) {
// Block of code for condition1
} else if (condition2) {
// Block of code for condition2
} else {
// Block of code if none of the above conditions are true
}
Example:
public class Main {
public static void main(String[] args) {
int num = 10;

if (num > 10) {


System.out.println("The number is greater than 10");
} else if (num == 10) {
System.out.println("The number is equal to 10");
} else {
System.out.println("The number is less than 10");
}
}
}
In this case, the output will be "The number is equal to 10" because num is 10.
d. switch statement
The switch statement is used when you have multiple conditions based on the value of
a single variable. It is an alternative to using many else-if statements.
Syntax:
switch (expression) {
case value1:
// Block of code to execute if expression equals value1
break;
case value2:
// Block of code to execute if expression equals value2
break;
default:
// Block of code to execute if no cases match
}
 The break statement is used to terminate the switch statement.
 If no break is used, the program continues to execute subsequent cases (fall-through
behavior).
 The default case is optional and executes if none of the conditions match.
Example:
public class Main {
public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Here, the output will be "Wednesday" because day equals 3.
2. Looping Statements
Looping statements allow you to execute a block of code multiple times, based on a
condition.
a. for loop
The for loop is used when you know beforehand how many times you need to execute
a statement or a block of code.
Syntax:
for (initialization; condition; increment/decrement) {
// Block of code to be executed
}
 initialization: Initializes the loop counter.
 condition: Specifies the condition for the loop to continue executing.
 increment/decrement: Modifies the loop counter after each iteration.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}
This loop will print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
b. while loop
The while loop is used when you want to execute a block of code as long as a
specified condition is true.
Syntax:
while (condition) {
// Block of code to be executed
}
Example:
public class Main {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Iteration " + i);
i++;
}
}
}
This loop will also print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
c. do-while loop
The do-while loop is similar to the while loop, except that it guarantees that the block
of code will execute at least once, regardless of whether the condition is true.
Syntax:
do {
// Block of code to be executed
} while (condition);
Example:
public class Main {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration " + i);
i++;
} while (i <= 5);
}
}
This loop will also print:
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Iteration 5
However, unlike the while loop, the do-while loop guarantees the code inside the
block is executed at least once.
3. Jump Statements
Jump statements allow you to control the flow of execution within loops or switch
statements by jumping to another part of the code.

a. break statement
The break statement is used to terminate the current loop or switch statement, and
transfer control to the next statement after the loop or switch block.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exits the loop when i equals 5
}
System.out.println(i);
}
}
}
The output will be:
1
2
3
4
b. continue statement
The continue statement is used to skip the current iteration of a loop and move to the
next iteration.
Example:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips the iteration when i equals 3
}
System.out.println(i);
}
}
}
The output will be:
1
2
4
5
c. return statement
The return statement is used to exit from the current method and optionally return a
value (if the method has a return type other than void).
Example:
public class Main {
public static void main(String[] args) {
System.out.println("Before return statement");
return; // Exits the main method
// The following code will not be executed
System.out.println("After return statement");
}
}
The output will be:
Before return statement
TYPE CONVERSION AND CASTING IN JAVA
In Java, type conversion and casting are used to convert one data type to another. Java
supports both implicit (automatic) and explicit (manual) type conversion.
Let's break these concepts down:
1. Type Conversion in Java
Type conversion refers to changing a variable from one data type to another. There are two
kinds of type conversion in Java:
 Implicit Type Conversion (Widening)
 Explicit Type Conversion (Narrowing)
2. Implicit Type Conversion (Widening)
Widening conversion occurs when a smaller data type is automatically converted to a larger
data type. This type of conversion is done automatically by the Java compiler without any
data loss.
Example:
 From int to long, float to double, char to int, etc.
 The compiler performs widening because no data is lost during the conversion.
Example of Implicit Type Conversion:
int a = 100;
long b = a; // int is automatically converted to long
System.out.println(b); // Output: 100
In the above example, the int variable a is automatically converted into a long type without
explicit casting.
Rules for Implicit Type Conversion:
 Smaller primitive data types (like byte, short, int, char) can be automatically
converted to larger primitive types (like long, float, double).
 Integer types can be converted into floating-point types.
 Char type can be converted to numeric types (e.g., int or long).
3. Explicit Type Conversion (Narrowing)
Narrowing conversion occurs when a larger data type is explicitly converted to a smaller
data type. This type of conversion can result in data loss because the larger value might not
fit into the smaller type's range.
To perform narrowing conversion, you must cast the larger data type to a smaller one using
casting.
Example:
 From long to int, double to float, double to int, etc.
 You need to cast explicitly, and you may lose precision or encounter data truncation.
Example of Explicit Type Conversion:
double a = 9.78;
int b = (int) a; // Explicit casting from double to int
System.out.println(b); // Output: 9 (fractional part is discarded)
In this example, the double value is explicitly cast to int, and the fractional part (.78) is
discarded.
Rules for Explicit Type Conversion:
 Larger primitive data types (like double, long, float) must be cast to smaller types
(like int, short, byte) manually.
 Data loss can occur if the larger type's value exceeds the range of the smaller type.
4. Type Casting Syntax
 Implicit (Widening): This is automatically handled by the compiler. No special
syntax is required.
 Explicit (Narrowing): This requires a cast operator (type) to specify the target type.
Example of Syntax for Explicit Casting:
int a = 10;
byte b = (byte) a; // Casting int to byte (explicit)

CONSTRUCTORS IN JAVA:
In Java, constructors are special methods that are called when an object of a class is created.
Their primary role is to initialize the object's state (i.e., assign values to the instance
variables) when the object is created.
1. What is a Constructor?
A constructor is a method that:
 Has the same name as the class it belongs to.
 Does not have a return type (not even void).
 Is invoked automatically when an object of the class is created.
Constructors are used to set the initial values of the object's instance variables or to perform
any setup steps required before the object is used.
2. Types of Constructors in Java
There are two main types of constructors in Java:
1. Default Constructor (No-Argument Constructor)
2. Parameterized Constructor
3. Default Constructor (No-Argument Constructor)
A default constructor is a constructor that takes no arguments. If you don't explicitly define
any constructors in your class, Java provides a default constructor for you, which does
nothing but create the object.
If you do define a constructor with parameters, the default constructor is not automatically
provided.
Syntax:
class ClassName {
// Default constructor
public ClassName() {
// Initialization code (if any)
}
}
Example:
class Car {
String color;
String model;

// Default constructor
public Car() {
color = "Red";
model = "Toyota";
}
public void display() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Default constructor is called
car1.display();
}
}
Output:
Car Model: Toyota
Car Color: Red
In this example, when the Car object car1 is created using the default constructor, the color
and model fields are initialized to "Red" and "Toyota", respectively.
4. Parameterized Constructor
A parameterized constructor is a constructor that accepts arguments to initialize an object
with specific values at the time of its creation. This allows you to create objects with different
initial states.
Syntax:
class ClassName {
public ClassName(dataType parameter1, dataType parameter2) {
// Initialization code
}
}
Example:
class Car {
String color;
String model;
// Parameterized constructor
public Car(String c, String m) {
color = c;
model = m;
}
public void display() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Blue", "Honda"); // Parameterized constructor is called
car1.display();
Car car2 = new Car("Black", "Ford"); // Another object with different values
car2.display();
}
}
Output:
Car Model: Honda
Car Color: Blue
Car Model: Ford
Car Color: Black
In this example:
 The Car class has a parameterized constructor that takes two arguments (String c,
String m).
 Each object created with the constructor can have its own color and model values set
at the time of object creation.
5. Constructor Overloading
In Java, you can define multiple constructors with different parameter lists within the same
class. This is known as constructor overloading. It allows you to create objects in different
ways (e.g., with or without arguments).
Syntax:
class ClassName {
// Constructor with no parameters
public ClassName() {
// Initialization code
}
// Constructor with one parameter
public ClassName(dataType param1) {
// Initialization code
}
// Constructor with two parameters
public ClassName(dataType param1, dataType param2) {
// Initialization code
}
}
Example:
class Car {
String color;
String model;
// Constructor with no parameters
public Car() {
color = "Red";
model = "Toyota";
}
// Constructor with one parameter
public Car(String c) {
color = c;
model = "Unknown";
}
// Constructor with two parameters
public Car(String c, String m) {
color = c;
model = m;
}
public void display() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
car1.display();
Car car2 = new Car("Blue"); // Calls constructor with one parameter
car2.display();
Car car3 = new Car("Black", "Ford"); // Calls constructor with two parameters
car3.display();
}
}
Output:
Car Model: Toyota
Car Color: Red
Car Model: Unknown
Car Color: Blue
Car Model: Ford
Car Color: Black
In this example:
 The Car class has three constructors: one with no parameters, one with one parameter
(color), and one with two parameters (color and model).
 Based on how many arguments are passed when creating the object, the
corresponding constructor is invoked.
7. Constructor vs Method
Constructors and methods might appear similar, but they have key differences:

Feature Constructor Method

Name Same as the class name Any valid name

Has a return type (e.g., void, int,


Return type None (not even void)
String)

To define behavior or actions for an


Purpose To initialize an object
object

Called automatically when an object is


Invocation Called explicitly on an object
created

Overloading Yes, can have multiple constructors Yes, can have multiple methods

METHODS, STATIC BLOCK, STATIC DATA, AND STATIC METHODS IN JAVA:


In Java, understanding the concepts of methods, static blocks, static data, and static
methods is essential for mastering object-oriented programming. These concepts are
interrelated but serve distinct purposes, especially when dealing with class-level (static) and
instance-level (non-static) behavior.
1. Methods in Java
A method in Java is a block of code that performs a specific task. Methods define the
behavior of an object (or class in the case of static methods) and are invoked to perform
actions. They can be part of a class or an object.
Key Characteristics of Methods:
 Declaration: A method is declared using the following syntax:
 returnType methodName(parameters) {
 // method body
 }
o returnType: The type of value the method returns (e.g., int, String, void if it
doesn't return anything).
o methodName: The name of the method (should follow the naming
conventions).
o parameters: A list of values or references passed to the method (optional).
 Calling a method: A method is invoked by its name, and depending on whether it's
static or non-static, it will be called on the class or an object.
Example of a Simple Method:
class Car {
String model;
String color;
// A method to display the car's information
public void displayInfo() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
car1.model = "Tesla";
car1.color = "Red";

car1.displayInfo(); // Invoking the displayInfo method


}
}
In the example, displayInfo() is a non-static method that works on an instance of the Car
class.
2. Static Block in Java
A static block is a special block of code in Java that is used for static initialization. It is
executed once when the class is loaded into the JVM (Java Virtual Machine), before any
objects of the class are created or methods are called. Static blocks are typically used to
perform one-time initialization of static variables.
Characteristics of Static Blocks:
 A static block is defined with the static keyword.
 It is executed only once when the class is loaded into memory, not every time an
object is created.
 It is used to initialize static data members or perform operations that need to be done
only once, such as establishing connections, loading resources, or complex
initialization that can't be done in a constructor.
Syntax:
static {
// static initialization code
}
Example of a Static Block:
class Example {
static int count;

static {
count = 10; // Static block is executed once when the class is loaded
System.out.println("Static block is executed. Count = " + count);
}
public static void main(String[] args) {
System.out.println("Main method is executed.");
}
}
Output:
Static block is executed. Count = 10
Main method is executed.
 The static block is executed before the main() method.
 The static block is useful for any initialization that needs to be done when the class is
first loaded but before any instances are created.
3. Static Data (Static Variables)
Static data refers to static variables or class variables in Java. These are variables that are
shared among all instances of a class. They belong to the class itself, rather than to any
specific object. As a result, static variables are initialized only once and are shared across all
objects of the class.
Characteristics of Static Variables:
 A static variable is declared using the static keyword.
 It is shared by all objects of the class (i.e., there is only one copy of the static variable
for the entire class, regardless of how many objects are created).
 Static variables can be accessed directly using the class name or through an object.
Syntax:
class ClassName {
static dataType variableName; // Static variable
}
Example of Static Data:
class Counter {
static int count = 0; // Static variable

// Increment the static variable


public static void increment() {
count++;
}
// Display the count
public static void display() {
System.out.println("Count: " + count);
}
}
public class Main {
public static void main(String[] args) {
Counter.increment(); // Static method call
Counter.increment(); // Static method call
Counter.display(); // Output: Count: 2
}
}
Output:
Count: 2
 The static variable count is shared across all instances of Counter (though we are not
creating objects in this case).
 The value of count is incremented each time the increment() method is called,
regardless of the number of instances.
Why Use Static Variables?
 Shared state across instances: Useful when you want to have a common variable
shared among all instances of a class.
 Class-level data: Since the static data is associated with the class, it can be accessed
without needing to create an object of the class.
4. Static Methods in Java
A static method belongs to the class rather than any instance of the class. It can be called
without creating an object of the class. Static methods can directly access static data
members (variables) of the class, but they cannot access instance variables or instance
methods because they are not associated with any specific object.
Characteristics of Static Methods:
 A static method is defined with the static keyword.
 It is invoked using the class name, not the object of the class.
 It can access only static variables and static methods. It cannot access instance
variables or instance methods directly.
 Static methods are useful for performing operations that do not depend on object
states.
Syntax:
class ClassName {
static returnType methodName(parameters) {
// method body
}
}
Example of Static Methods:
class Calculator {
static int add(int a, int b) {
return a + b;
}
static int subtract(int a, int b) {
return a - b;
}
}
public class Main {
public static void main(String[] args) {
int sum = Calculator.add(5, 3); // Calling static method without creating an object
int difference = Calculator.subtract(5, 3); // Calling static method
System.out.println("Sum: " + sum); // Output: Sum: 8
System.out.println("Difference: " + difference); // Output: Difference: 2
}
}
Output:
Sum: 8
Difference: 2
In this example, add() and subtract() are static methods, and we invoke them directly using
the class name Calculator. No objects need to be created.
Why Use Static Methods?
 Utility methods: They are often used for operations that do not require an instance of
the class (like mathematical operations or utility functions).
 Memory Efficiency: Static methods are stored in a common area in memory, and
since they don’t need an object to be invoked, they reduce memory overhead.
5. Difference Between Instance and Static Methods/Variables

Feature Instance Method/Variable Static Method/Variable

Declaration Defined without static keyword Defined with the static keyword

Memory Each object has its own copy of Only one copy exists for the entire class
Allocation instance variables (shared by all objects)

Can be accessed via the class name


Accessing Must be accessed via an object
(without creating an object)
Feature Instance Method/Variable Static Method/Variable

To represent the state and To represent behavior or data that is


Purpose
behavior of individual objects common to all instances of the class

Example Instance-specific behavior, e.g., Class-level behavior, e.g., utility


Usage car.move() functions like Math.pow()

STRING AND STRINGBUFFER CLASSES IN JAVA


In Java, strings are one of the most commonly used data types, but understanding how
String and StringBuffer classes work is essential for writing efficient and optimized code.
The String class and the StringBuffer class both represent sequences of characters, but they
behave quite differently, especially when it comes to mutability and performance.
Let’s dive deeper into the String and StringBuffer classes, highlighting their differences, use
cases, and behavior.
1. The String Class in Java
The String class is one of the most widely used classes in Java and represents a sequence of
characters. However, strings in Java are immutable, which means once a String object is
created, its value cannot be changed.
Key Characteristics of the String Class:
 Immutable: Once a String object is created, it cannot be modified. Any operation that
modifies a string (like concatenation, replace, etc.) will return a new String object.
 Thread-Safe: Because String objects cannot be changed, they are inherently thread-
safe.
 Stored in String Pool: In Java, string literals are stored in a special memory area
called the String Pool (or intern pool), which helps save memory by reusing the
same instance for identical string literals.
Syntax:
String str = "Hello, World!";
Here, the string "Hello, World!" is a string literal and is stored in the string pool.
Common Operations on Strings:
1. Concatenation: Using + operator or concat() method.
2. String str1 = "Hello";
3. String str2 = "World";
4. String result = str1 + " " + str2; // Concatenates two strings
5. String Length: To find the length of the string.
6. int length = str.length(); // Returns the length of the string
7. Substring: Extracting part of the string.
8. String sub = str.substring(0, 5); // Extracts "Hello" from "Hello, World!"
9. Equality: Comparing two strings for equality.
10. boolean isEqual = str1.equals(str2); // Returns true if both strings are equal
11. Indexing: Getting characters by index.
12. char ch = str.charAt(0); // Returns the first character of the string ('H')
Example: String Immutability
public class Main {
public static void main(String[] args) {
String str1 = "Java";
String str2 = str1;
str1 = str1 + " Programming"; // This creates a new string object
System.out.println("str1: " + str1); // "Java Programming"
System.out.println("str2: " + str2); // "Java"
}
}
Output:
str1: Java Programming
str2: Java
 Immutability: When you concatenate to str1, a new string object is created. str2
remains unchanged even though str1 was modified.
2. The StringBuffer Class in Java
The StringBuffer class represents a mutable sequence of characters. Unlike the String class,
the value of a StringBuffer object can be modified without creating a new object. This makes
StringBuffer more efficient than String when performing a lot of string manipulations (such
as appending or modifying the string repeatedly).
Key Characteristics of StringBuffer:
 Mutable: StringBuffer allows you to modify the contents of the string without
creating a new object. All operations that modify the contents (like append, insert, or
delete) change the existing object.
 Not Thread-Safe by Default: Unlike String, which is immutable and inherently
thread-safe, StringBuffer is not thread-safe by default, meaning multiple threads can
alter its value simultaneously without synchronization.
 Efficient for Repeated Modifications: It is more efficient than String when
performing multiple concatenation or modifications because it doesn’t create new
objects each time.
 Resizes Dynamically: StringBuffer internally manages a dynamic array to hold the
characters, which can grow automatically as the string is modified.
Syntax:
StringBuffer buffer = new StringBuffer("Hello");
Common Operations on StringBuffer:
1. Append: Add a string at the end.
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb); // "Java Programming"
2. Insert: Insert a string at a specific position.
sb.insert(4, " Rocks");
System.out.println(sb); // "Java Rocks Programming"
3. Delete: Remove a substring from the StringBuffer.
sb.delete(4, 9); // Removes the substring from index 4 to 9
System.out.println(sb); // "Java Programming"
4. Reverse: Reverse the contents of the StringBuffer.
sb.reverse();
System.out.println(sb); // "gnimmargorP avaJ"
5. Length: Get the length of the StringBuffer.
int length = sb.length(); // Returns the length of the buffer
Example of Using StringBuffer:
public class Main {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
sb.insert(6, "Java "); // Insert "Java " at position 6
System.out.println(sb); // Output: Hello Java World
sb.delete(6, 10); // Remove "Java"
System.out.println(sb); // Output: Hello World
}
}
Output:
Hello Java World
Hello World
StringBuffer vs String:
 Immutability vs Mutability: String objects are immutable, meaning every
modification results in a new object, while StringBuffer objects are mutable, allowing
modifications without creating new objects.
 Performance: When concatenating strings or performing frequent modifications,
StringBuffer is more efficient than String because it avoids creating new objects each
time.
 Thread Safety: String is inherently thread-safe due to its immutability, while
StringBuffer is not thread-safe by default. If thread safety is required, you can use
StringBuilder or synchronize the operations manually.
3. StringBuilder vs StringBuffer
 StringBuffer is thread-safe, meaning its methods are synchronized, making it safe to
use in multithreaded environments. However, this synchronization comes with a
performance cost.
 StringBuilder is very similar to StringBuffer but not synchronized, which means it's
faster than StringBuffer in single-threaded scenarios because it avoids the overhead of
synchronization.
If thread safety is not a concern, StringBuilder is typically the better choice for performance.
Summary of Key Differences

Feature String StringBuffer

Mutability Immutable (cannot be modified) Mutable (can be modified)

Thread Safety Thread-safe Not thread-safe (by default)

Memory Efficiency Less efficient for modifications More efficient for modifications

Performance Slower for frequent modifications Faster for frequent modifications

Usage Ideal for constant strings Ideal for frequent string manipulation
Feature String StringBuffer

Class Type java.lang.String java.lang.StringBuffer

You might also like