0% found this document useful (0 votes)
0 views59 pages

Java Core

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its platform independence and versatility in application development. It features three main editions: Java SE for core applications, Java EE for enterprise applications, and Java ME for embedded systems. Key components of Java include the JVM for executing bytecode, various data types, and a range of operators for performing operations.

Uploaded by

madhavjosshi55
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)
0 views59 pages

Java Core

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its platform independence and versatility in application development. It features three main editions: Java SE for core applications, Java EE for enterprise applications, and Java ME for embedded systems. Key components of Java include the JVM for executing bytecode, various data types, and a range of operators for performing operations.

Uploaded by

madhavjosshi55
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

# INTRODUCTION TO JAVA

1. What is Java?
Java is a high-level, object-oriented, platform-independent programming language
developed by Sun Microsystems in 1995.

Key Points:
· Java is used to develop desktop, web, mobile, and enterprise applications
· Java programs can run on any operating system that has a JVM
· Motto of Java:
“Write Once, Run Anywhere (WORA)”

Uses of Java:
· Web applications (Banking, E-commerce)
· Mobile apps (Android)
· Desktop applications
· Enterprise systems
· Cloud & Big Data applications

2. History of Java
· 1991 – Java project started by James Gosling at Sun Microsystems
· Original name: Oak (named after an oak tree)
· Later renamed to Java
· 1995 – Java officially released
· 2010 – Oracle Corporation acquired Sun Microsystems
· Currently maintained by Oracle

Java Versions (Few Important):


· Java 1.0 – First version
· Java 5 – Generics, Enhanced for loop
· Java 8 – Lambda expressions, Stream API
· Java 11 – Long Term Support (LTS)
· Java 17 – Latest LTS version

3. Features of Java
Feature Description
Simple Easy to learn syntax
Object-Oriented Uses classes & objects
Platform
Runs on any OS
Independent
No pointers, bytecode
Secure
verification
Robust Strong memory management
Multithreaded Multiple tasks at same time
Portable Same program works everywhere
High Performance Uses JIT compiler
Distributed Supports network programming

4. Java Editions
Java is divided into three main editions:

1. Java SE
2. Java EE (Jakarta EE)
3. Java ME

5. Java SE (Standard Edition)


Java SE is the core Java platform.

Used for:
· Desktop applications
· Console applications
· Foundation for other Java editions

Includes:
· Core Java concepts
· OOPs
· Exception handling
· Multithreading
· Collections
· File handling

📌 Example: Calculator, Text Editor

6. Java EE (Jakarta EE)


Java EE is used for large-scale enterprise applications.
Used for:
· Web applications
· Enterprise-level systems

Technologies:
· Servlets
· JSP
· EJB
· JPA
· Web Services

📌 Example: Banking systems, Airline reservation systems

🔹 Note:
Java EE is now called Jakarta EE

7. Java ME (Micro Edition)


Java ME is designed for small and embedded devices.

Used for:
· Mobile phones (old)
· Embedded systems
· IoT devices

Features:
· Limited memory usage
· Lightweight APIs

📌 Example: Feature phones, set-top boxes

8. Java vs C / C++
Feature Java C / C++
Platform Independent Yes No
Object Oriented Fully Partial
Pointer Support No Yes
Memory Automatic
Manual
Management (GC)
Security High Less
Multithreading Built-in Not built-in
Compilation Bytecode Machine
code

9. JVM, JRE, JDK (Architecture)


JVM (Java Virtual Machine)
· Converts bytecode into machine code
· Makes Java platform independent
· Runs .class files

JRE (Java Runtime Environment)


· Provides environment to run Java programs
· Contains JVM + Libraries

JDK (Java Development Kit)


· Used to develop Java programs
· Contains JRE + Compiler + Tools

Relationship:
JDK → JRE → JVM

10. Java Program Execution Flow


Steps:
1. Write Java program (.java)
2. Compile using javac
3. Bytecode file (.class) created
4. JVM loads the bytecode
5. Bytecode verifier checks security
6. JIT compiler converts bytecode to machine code
7. Program executes

Diagram (Textual):
.java → Compiler → .class → JVM → Machine Code → Output

Summary
· Java is a powerful, secure, and platform-independent language
· JVM is the backbone of Java
· Java SE is for core learning
· Java EE is for enterprise applications
· Java ME is for embedded systems
# JAVA BASICS :-
1. First Java Program
Program: Hello World
class HelloWorld {

public static void main(String[] args) {

[Link]("Hello, World!");

Explanation:
· class HelloWorld → Defines a class
· public → Accessible from anywhere
· static → No object needed to run
· void → No return value
· main() → Entry point of Java program
· String[] args → Command-line arguments
· [Link]() → Prints output

📌 Output:
Hello, World!

2. Java Syntax
Java syntax refers to the rules and structure used to write Java programs.

Basic Syntax Rules:


· Java is case-sensitive
· Class name should start with capital letter
· Method names start with lowercase
· Every statement ends with semicolon (;)
· Code blocks are enclosed in { }

Example:
int a = 10;

[Link](a);
3. Structure of Java Program
A Java program is divided into logical sections.

General Structure:
// Package statement (optional)

package mypackage;

// Import statement (optional)

import [Link];

// Class declaration

class MyClass {

// Main method

public static void main(String[] args) {

// Statements

[Link]("Java Program Structure");

Parts Explanation:
1. Package Statement
2. Import Statement
3. Class Declaration
4. Main Method
5. Statements

4. Java Tokens
Tokens are the smallest units of a Java program.

Types of Java Tokens:


1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
5. Keywords
Keywords are reserved words with predefined meaning in Java.

Examples of Java Keywords:


class, public, static, void, int,

if, else, for, while, return,

new, this, super

📌 Note:

· Keywords cannot be used as variable names

6. Identifiers
Identifiers are names given to:

· Variables
· Methods
· Classes
· Objects

Rules for Identifiers:


· Must start with letter, _ or $
· Cannot start with a digit
· Cannot use keywords
· No spaces allowed
· Case-sensitive

Valid Identifiers:
number

_total

$amount

StudentName

Invalid Identifiers:
2num // starts with digit

class // keyword

total marks // space not allowed


7. Literals
Literals are constant values used in a program.

Types of Literals:
Type Example
Integer 10, 100
Floating- 10.5,
point 3.14
Character 'A', '9'
String "Java"
true,
Boolean
false
Null null

Example:
int a = 10;

char ch = 'A';

String name = "Java";

boolean status = true;

8. Comments in Java
Comments are used to explain code and are ignored by the compiler.

A) Single-Line Comment
Used for one-line explanation.
// This is a single-line comment

int x = 5;

B) Multi-Line Comment
Used for multiple lines.
/*

This is a

multi-line

comment

*/ int y = 10;
C) Documentation Comments
Used to generate API documentation using javadoc.
/**

* This class demonstrates Java comments

* @author Aryan

* @version 1.0

*/

class CommentDemo {

public static void main(String[] args) {

[Link]("Documentation Comment");

📌 Symbols Used:

· /** ... */

Comparison of Comments
Comment
Symbol
Type
Single-line //
Multi-line /* */
Documentation /** */

# DATA TYPES & VARIABLES:-


1. Variables in Java
A variable is a container used to store data values in a Java program.

1. Variables in Java
A variable is a container used to store data values in a Java program.

Syntax:
dataType variableName = value;
Example:
int age = 20;

String name = "Java";

2. Types of Variables in Java


Java variables are classified based on scope and lifetime.

A) Local Variable
· Declared inside a method or block
· Cannot be accessed outside the method
· Must be initialized before use
class Test {

public static void main(String[] args) {

int x = 10; // local variable

[Link](x);

📌 Scope: Within the method only

B) Instance Variable
· Declared inside a class but outside methods
· Belongs to an object
· Each object gets its own copy
class Student {

int rollNo; // instance variable

void display() {

[Link](rollNo);
}

📌 Scope: Entire class (through object)

C) Static Variable
· Declared using static keyword
· Shared among all objects
· Memory allocated once
class Counter {

static int count = 0; // static variable

Counter() {

count++;

[Link](count);

public static void main(String[] args) {

new Counter();

new Counter();

new Counter();

📌 Output:
1

3
3. Data Types in Java
Data types specify what type of data a variable can store.

Classification:
1. Primitive Data Types
2. Non-Primitive Data Types

4. Primitive Data Types


Java has 8 primitive data types.

A) Integer Types
Data
Size Range
Type
byte 1 byte -128 to 127
2 -32,768 to
short
bytes 32,767
4
int -2³¹ to 2³¹-1
bytes
8
long Very large
bytes
byte b = 10;

short s = 100;

int i = 1000;

long l = 100000L;

B) Floating-Point Types
Data
Size Precision
Type
4
float 6-7 digits
bytes
8 15-16
double
bytes digits
float f = 10.5f;

double d = 99.99;

📌 Note: f is mandatory for float.

C) Character Type
· Stores single character
· Uses Unicode
char ch = 'A';

D) Boolean Type
· Stores true or false
boolean isJavaEasy = true;

5. Non-Primitive Data Types


· Store references
· Can store multiple values
· User-defined or built-in classes

Examples:
· String
· Array
· Class
· Interface
· Object
String name = "Java";

int[] marks = {80, 90, 85};

6. Type Casting
Type casting means converting one data type into another.

A) Widening (Implicit Casting)


· Smaller → Larger data type
· Done automatically
· No data loss
int a = 10;

double b = a; // widening

[Link](b);

📌 Output: 10.0

B) Narrowing (Explicit Casting)


· Larger → Smaller data type
· Must be done manually
· Data loss possible
double x = 10.5;

int y = (int) x; // narrowing

[Link](y);

📌 Output: 10

7. Type Conversion
Type conversion happens when:

· Assigning one type to another


· Using expressions
· User input (Scanner)
int a = 10;

double b = a + 2.5;

📌 Result: b = 12.5

8. var Keyword (Java 10+)


· Introduced in Java 10
· Used for local variable type inference
· Compiler automatically detects data type

Example:
var num = 10;

var name = "Java";

var price = 99.99;

📌 Important Rules:

· Only for local variables


· Must be initialized
· Cannot be used as class variable or method parameter

❌ Invalid:
var x; // error
Comparison Table: Variables
Variable
Scope Memory
Type
Local Method Stack
Instance Object Heap
Method
Static Class
Area

# OPERATORS:-
1. Arithmetic Operators
Used to perform mathematical calculations.

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
%
Modulus
(remainder)

Example Program:
class ArithmeticDemo {

public static void main(String[] args) {

int a = 10, b = 3;

[Link](a + b); // 13

[Link](a - b); // 7

[Link](a * b); // 30

[Link](a / b); // 3

[Link](a % b); // 1

2. Unary Operators
Operate on single operand.
Operator Meaning
+ Unary plus
- Unary minus
++ Increment
-- Decrement
!
Logical
NOT

Example:
class UnaryDemo {

public static void main(String[] args) {

int x = 5;

[Link](++x); // 6 (pre-increment)

[Link](x++); // 6 (post-increment)

[Link](--x); // 6

[Link](x--); // 6

3. Relational Operators
Used to compare two values and return true or false.

Operator Meaning
== Equal to
!= Not equal
> Greater than
< Less than
>=
Greater than or
equal
<= Less than or equal

Example:
class RelationalDemo {

public static void main(String[] args) {

int a = 10, b = 20;

[Link](a > b); // false


[Link](a < b); // true

[Link](a == b); // false

[Link](a != b); // true

4. Logical Operators
Used with boolean values.

Operator Meaning
&&
Logical
AND
`
!
Logical
NOT

Example:
class LogicalDemo {

public static void main(String[] args) {

int a = 10, b = 20;

[Link](a < b && b > 15); // true

[Link](a > b || b > 15); // true

[Link](!(a > b)); // true

5. Bitwise Operators
Perform operations at bit level.

Operator Meaning
&
Bitwise
AND
` `
^ XOR
~ Complement
Example:
class BitwiseDemo {

public static void main(String[] args) {

int a = 5; // 0101

int b = 3; // 0011

[Link](a & b); // 1

[Link](a | b); // 7

[Link](a ^ b); // 6

6. Shift Operators
Used to shift bits left or right.

Operator Meaning
<< Left shift
>> Right shift
>>>
Unsigned right
shift

Example:
class ShiftDemo {

public static void main(String[] args) {

int a = 8;

[Link](a << 2); // 32

[Link](a >> 2); // 2

7. Assignment Operators
Used to assign values.

Operator Meaning
= Assignment
+= Add and assign
-= Subtract and assign
*=
Multiply and
assign
/= Divide and assign
%=
Modulus and
assign

Example:
class AssignmentDemo {

public static void main(String[] args) {

int a = 10;

a += 5; // 15

a -= 3; // 12

a *= 2; // 24

a /= 4; // 6

[Link](a);

8. Ternary Operator
Used as short form of if-else.

Syntax:
condition ? value1 : value2;

Example:
class TernaryDemo {

public static void main(String[] args) {

int a = 10, b = 20;

int max = (a > b) ? a : b;

[Link](max);

}
📌 Output: 20

9. Operator Precedence
Determines order of execution.

Precedence Order (High → Low):


1. ()
2. ++ -- !
3. * / %
4. + -
5. << >> >>>
6. < > <= >=
7. == !=
8. &
9. ^
10. |
11. &&
12. ||
13. ?:
14. = += -=

Example:
class PrecedenceDemo {

public static void main(String[] args) {

int result = 10 + 5 * 2;

[Link](result);

# CONTROL STATEMENTS:-
Control statements are used to control the flow of execution of a Java program.

1. Types of Control Statements


1. Decision Making Statements
2. Looping Statements
3. Jump Statements
A. DECISION MAKING STATEMENTS
Used to make decisions based on conditions.

1. if Statement
Executes a block of code only if the condition is true.

Syntax:
if (condition) {

// statements

Example:
class IfDemo {

public static void main(String[] args) {

int age = 18;

if (age >= 18) {

[Link]("Eligible to vote");

2. if-else Statement
Executes one block if condition is true, otherwise another block.

Syntax:
if (condition) {

// true block

} else {

// false block

Example:
class IfElseDemo {
public static void main(String[] args) {

int number = 5;

if (number % 2 == 0) {

[Link]("Even number");

} else {

[Link]("Odd number");

3. if-else-if Ladder
Used to test multiple conditions.

Syntax:
if (condition1) {

// block

} else if (condition2) {

// block

} else {

// default block

Example:
class IfElseIfDemo {

public static void main(String[] args) {

int marks = 75;

if (marks >= 90) {

[Link]("Grade A");

} else if (marks >= 60) {

[Link]("Grade B");

} else {
[Link]("Grade C");

4. Nested if Statement
An if inside another if.

Example:
class NestedIfDemo {

public static void main(String[] args) {

int age = 20;

boolean hasID = true;

if (age >= 18) {

if (hasID) {

[Link]("Entry allowed");

5. switch Statement (Java 12+ Enhanced Switch)


Used to execute one block from multiple choices.

A) Traditional switch
class SwitchDemo {

public static void main(String[] args) {

int day = 3;

switch (day) {

case 1:

[Link]("Monday");

break;
case 2:

[Link]("Tuesday");

break;

case 3:

[Link]("Wednesday");

break;

default:

[Link]("Invalid day");

B) Enhanced switch (Java 12+)


· No break needed
· Cleaner syntax
· Supports -> and yield
class EnhancedSwitchDemo {

public static void main(String[] args) {

int day = 2;

String result = switch (day) {

case 1 -> "Monday";

case 2 -> "Tuesday";

case 3 -> "Wednesday";

default -> "Invalid day";

};

[Link](result);

}
B. LOOPING STATEMENTS
Used to repeat a block of code.

6. while Loop
Executes code while condition is true.

Syntax:
while (condition) {

// statements

Example:
class WhileDemo {

public static void main(String[] args) {

int i = 1;

while (i <= 5) {

[Link](i);

i++;

7. do-while Loop
Executes code at least once, then checks condition.

Syntax:
do {

// statements

} while (condition);

Example:
class DoWhileDemo {
public static void main(String[] args) {

int i = 1;

do {

[Link](i);

i++;

} while (i <= 5);

8. for Loop
Used when number of iterations is known.

Syntax:
for (initialization; condition; increment) {

// statements

Example:
class ForDemo {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

[Link](i);

9. for-each Loop
Used to traverse arrays and collections.

Syntax:
for (datatype variable : array) {

// statements

}
Example:
class ForEachDemo {

public static void main(String[] args) {

int[] nums = {10, 20, 30};

for (int n : nums) {

[Link](n);

C. JUMP STATEMENTS
Used to transfer control.

10. break Statement


Terminates loop or switch.
class BreakDemo {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

if (i == 3) {

break;

[Link](i);

📌 Output: 1 2

11. continue Statement


Skips current iteration.
class ContinueDemo {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

if (i == 3) {

continue;

[Link](i);

📌 Output: 1 2 4 5

12. return Statement


Returns value and exits method.
class ReturnDemo {

static int add(int a, int b) {

return a + b;

public static void main(String[] args) {

[Link](add(10, 20));

Comparison Table (Loops)


Entry/Exit
Loop
Control
while Entry-controlled
do-
Exit-controlled
while
for Entry-controlled
for-each Collection-based
#OBJECT- ORIENTED PROGRAMMING:-
OOP is a programming approach based on objects that contain data and methods.

Main OOP Principles


1. Encapsulation
2. Inheritance
3. Polymorphism
4. Abstraction

1. Class & Object


Class
A class is a blueprint or template for creating objects.
class Student {

int roll;

String name;

void display() {

[Link](roll + " " + name);

Object
An object is an instance of a class.
class Test {

public static void main(String[] args) {

Student s1 = new Student();

[Link] = 1;

[Link] = "Aryan";

[Link]();

}
2. Constructors
A constructor is a special method:

· Same name as class


· No return type
· Automatically called when object is created

A) Default Constructor
class Demo {

Demo() {

[Link]("Default Constructor");

public static void main(String[] args) {

new Demo();

B) Parameterized Constructor
class Student {

int roll;

String name;

Student(int r, String n) {

roll = r;

name = n;

void display() {

[Link](roll + " " + name);

C) Constructor Overloading
Multiple constructors with different parameters.
class Sample {

Sample() {

[Link]("No argument");

Sample(int x) {

[Link](x);

3. this Keyword
this refers to the current object.

Uses:
· Differentiate instance and local variables
· Call another constructor
class Student {

int roll;

Student(int roll) {

[Link] = roll;

4. static Keyword
Belongs to class, not object.

Used for:
· Static variables
· Static methods
· Static blocks
class Counter {

static int count = 0;

Counter() {
count++;

[Link](count);

5. Inheritance
Inheritance allows a class to acquire properties of another class.

Syntax:
class A {

int x = 10;

class B extends A {

void show() {

[Link](x);

📌 Types: Single, Multilevel, Hierarchical


(Java does NOT support multiple inheritance using classes)

6. Method Overloading
Same method name, different parameters.
class MathOp {

int add(int a, int b) {

return a + b;

int add(int a, int b, int c) {

return a + b + c;

}
7. Method Overriding
Child class provides its own implementation of parent method.
class Parent {

void show() {

[Link]("Parent");

class Child extends Parent {

void show() {

[Link]("Child");

8. Polymorphism
One name, many forms

Types:
· Compile-time → Method Overloading
· Run-time → Method Overriding
Parent p = new Child();

[Link](); // Child

9. Abstraction
Hiding internal implementation and showing essential features only.

A) Abstract Class
· Declared using abstract
· Can have abstract and non-abstract methods
abstract class Shape {

abstract void draw();

class Circle extends Shape {


void draw() {

[Link]("Drawing Circle");

B) Interface
· Supports 100% abstraction
· Uses implements
interface Animal {

void sound();

class Dog implements Animal {

public void sound() {

[Link]("Bark");

10. Encapsulation
Wrapping data and methods together using private variables and public methods.
class Account {

private int balance;

public void setBalance(int b) {

balance = b;

public int getBalance() {

return balance;

11. Access Modifiers


Modifier Scope
public Everywhere
private Within class
Same package +
protected
subclass
default Same package

12. final Keyword


Uses:
· final variable → constant
· final method → cannot override
· final class → cannot inherit
final int MAX = 100;

13. Object Class


Object is the superclass of all classes.

Common Methods:
· toString()
· equals()
· hashCode()
· getClass()

class Demo {

public static void main(String[] args) {

Demo d = new Demo();

[Link]([Link]());

14. instanceof Operator


Used to test object type.
class Test {

public static void main(String[] args) {

String s = "Java";

[Link](s instanceof String); // true


}

# STRINGS :-
A String in Java represents a sequence of characters.

📌 Important:
Strings in Java are objects, not primitive data types.

1. String Class
· Located in [Link] package
· Automatically imported
· String objects are immutable (cannot be changed)
String s = "Java";

2. String Creation
A) Using String Literal
String s1 = "Java";

String s2 = "Java";

· Stored in String Constant Pool (SCP)


· Memory efficient
· Same value → same memory

B) Using new Keyword


String s3 = new String("Java");

· Creates a new object in heap


· SCP not used directly

Memory Comparison
Method Memory
Literal SCP
new Heap
3. String Methods
Commonly Used String Methods
Method Description
length() Returns string length
toUpperCase()
Converts to
uppercase
toLowerCase()
Converts to
lowercase
charAt() Returns character
substring() Extracts substring
contains() Checks content
replace() Replaces characters
trim() Removes spaces
split() Splits string
indexOf() Returns index

Example Program:
class StringMethodsDemo {

public static void main(String[] args) {

String s = " Java Programming ";

[Link]([Link]());

[Link]([Link]());

[Link]([Link]());

[Link]([Link](2));

[Link]([Link](1, 5));

4. String Comparison
A) Using == Operator
· Compares reference (memory address)
· Not content
String a = "Java";

String b = "Java";
[Link](a == b); // true

B) Using equals() Method


· Compares content
String a = new String("Java");

String b = new String("Java");

[Link]([Link](b)); // true

C) compareTo() Method
· Lexicographical comparison
· Returns:
o 0 → equal
o <0 → smaller
o >0 → greater

[Link]("A".compareTo("B"));

5. StringBuffer
· Mutable
· Thread-safe
· Slower than StringBuilder
class StringBufferDemo {

public static void main(String[] args) {

StringBuffer sb = new StringBuffer("Java");

[Link](" Programming");

[Link](sb);

6. StringBuilder
· Mutable
· Not thread-safe
· Faster than StringBuffer
class StringBuilderDemo {

public static void main(String[] args) {


StringBuilder sb = new StringBuilder("Java");

[Link](" Language");

[Link](sb);

7. Mutable vs Immutable Strings


Immutable
· Cannot be changed after creation
· New object created for modification
String s = "Java";

s = [Link](" World");

Mutable
· Can be changed without creating new object
StringBuilder sb = new StringBuilder("Java");

[Link](" World");

Comparison Table
Feature String StringBuffer StringBuilder
Mutable ❌ No ✅ Yes ✅ Yes
Thread-Safe ❌ No ✅ Yes ❌ No
Performance Slow Medium Fast
Memory SCP/Heap Heap Heap

# ARRAYS:-
An array is a collection of similar data types stored in contiguous memory locations.

📌 Important:

· Array size is fixed


· Index starts from 0
· Arrays are objects in Java
1. One-Dimensional Arrays
A one-dimensional array stores data in a single row.

Declaration
int[] a;

Allocation
a = new int[5];

Initialization
a[0] = 10;

a[1] = 20;

Complete Example
class OneDArrayDemo {

public static void main(String[] args) {

int[] marks = {70, 80, 90};

[Link](marks[0]);

[Link](marks[1]);

[Link](marks[2]);

2. Multi-Dimensional Arrays
A multi-dimensional array stores data in rows and columns.

2-D Array Declaration


int[][] matrix = new int[2][3];

Initialization
int[][] a = {

{1, 2, 3},

{4, 5, 6}

};
Example Program
class TwoDArrayDemo {

public static void main(String[] args) {

int[][] a = {

{1, 2, 3},

{4, 5, 6}

};

for (int i = 0; i < [Link]; i++) {

for (int j = 0; j < a[i].length; j++) {

[Link](a[i][j] + " ");

[Link]();

3. Array Initialization
Types of Initialization
A) At Declaration
int[] a = {10, 20, 30};

B) Using new Keyword


int[] a = new int[]{10, 20, 30};

C) Dynamic Initialization
int[] a = new int[3];

a[0] = 5;

a[1] = 10;

a[2] = 15;
4. Array Traversing
Traversing means accessing each element of an array.

A) Using for Loop


for (int i = 0; i < [Link]; i++) {

[Link](a[i]);

B) Using for-each Loop


for (int x : a) {

[Link](x);

📌 Note:
for-each loop is read-only.

5. Anonymous Arrays
An anonymous array is an array without a name.

Example
class AnonymousArrayDemo {

static void printArray(int[] a) {

for (int i : a) {

[Link](i);

public static void main(String[] args) {

printArray(new int[]{10, 20, 30});

📌 Use Case:
Used when array is required only once.
6. Array vs ArrayList
Array
· Fixed size
· Can store primitives and objects
· Faster
· Length is fixed

ArrayList
· Dynamic size
· Stores only objects
· Slower than array
· Part of Collections Framework

Comparison Table
Feature Array ArrayList
Size Fixed Dynamic
Primitive + Object
Data Types
Object only
Performance Faster Slower
Memory Less More
Methods Limited Many

Example: ArrayList
import [Link];

class ArrayListDemo {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

[Link](10);

[Link](20);

[Link](30);

[Link](list);

}
# EXCEPTION HANDLING
Exception Handling is a mechanism to handle runtime errors and maintain normal program
flow.

1. Types of Errors in Java


Java errors are classified into three types:

A) Compile-Time Errors
· Occur during compilation
· Syntax errors
int a = 10 // missing semicolon

B) Runtime Errors
· Occur during execution
· Handled using exceptions
int a = 10 / 0; // ArithmeticException

C) Logical Errors
· Program runs but gives wrong output
· Difficult to detect
// Wrong formula used

2. Exceptions
An exception is an abnormal condition that occurs at runtime and disrupts program execution.

Common Built-in Exceptions


· ArithmeticException
· NullPointerException
· ArrayIndexOutOfBoundsException
· NumberFormatException
· IOException
3. Checked vs Unchecked Exceptions
Checked Exceptions
· Checked at compile time
· Must be handled using try-catch or throws

Examples:

· IOException
· SQLException
· FileNotFoundException

Unchecked Exceptions
· Checked at runtime
· Subclasses of RuntimeException

Examples:

· ArithmeticException
· NullPointerException
· ArrayIndexOutOfBoundsException

Comparison Table
Feature Checked Unchecked
Checked
Compile time Runtime
at
Handling Mandatory Optional
[Link] /
Package [Link]
[Link]
Example IOException ArithmeticException

4. try-catch Block
Used to handle exceptions.

Syntax
try {

// risky code

} catch (Exception e) {

// handling code

}
Example
class TryCatchDemo {

public static void main(String[] args) {

try {

int a = 10 / 0;

} catch (ArithmeticException e) {

[Link]("Cannot divide by zero");

5. Multiple catch Blocks


Used to handle different exceptions separately.
class MultipleCatchDemo {

public static void main(String[] args) {

try {

int[] a = new int[5];

a[10] = 50;

} catch (ArithmeticException e) {

[Link]("Arithmetic error");

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Array index error");

} catch (Exception e) {

[Link]("General exception");

📌 Note:
· Child exception must come before parent exception

6. finally Block
· Always executes whether exception occurs or not
· Used for resource cleanup
class FinallyDemo {

public static void main(String[] args) {

try {

int x = 10 / 2;

} catch (Exception e) {

[Link]("Error");

} finally {

[Link]("Finally block executed");

7. throw Keyword
Used to explicitly throw an exception.
class ThrowDemo {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Not eligible");

[Link]("Eligible");

public static void main(String[] args) {

checkAge(16);

}
8. throws Keyword
Used to declare exceptions in method signature.
class ThrowsDemo {

static void display() throws InterruptedException {

[Link](1000);

public static void main(String[] args) throws InterruptedException {

display();

📌 Difference:

· throw → throws an exception


· throws → declares an exception

9. Custom Exceptions
User-defined exceptions created by extending Exception class.

Example
class InvalidAgeException extends Exception {

InvalidAgeException(String msg) {

super(msg);

class CustomExceptionDemo {

static void vote(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age below 18");

[Link]("Voting allowed");
}

public static void main(String[] args) {

try {

vote(16);

} catch (InvalidAgeException e) {

[Link]([Link]());

10. Exception Propagation


Passing exception from one method to another.

Example
class PropagationDemo {

static void m1() {

int a = 10 / 0;

static void m2() {

m1();

static void m3() {

try {

m2();

} catch (ArithmeticException e) {

[Link]("Exception handled in m3");

public static void main(String[] args) {


m3();

# JAVA PACKAGES
A package in Java is a namespace that groups related classes and interfaces into a single unit.

1. What is a Package?
Definition
A package is a folder that contains related classes, interfaces, and sub-packages.

Why Packages are Used


· Organizes large projects
· Avoids name conflicts
· Provides access control
· Improves reusability
· Easy maintenance

📌 Real-life Example:
Like folders in a computer (Documents, Pictures, Videos)

2. Built-in Packages
Java provides many predefined packages.

Common Built-in Packages


Package Purpose
[Link]
Core classes (String, Math,
Object)
[Link] Utilities (Scanner, ArrayList)
[Link] Input/Output
[Link] Database
[Link] Networking
[Link] Date & Time
📌 Note:
[Link] is automatically imported.
Example (Built-in Package)
import [Link];

class BuiltInPackageDemo {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter name:");

String name = [Link]();

[Link]("Hello " + name);

3. User-Defined Packages
Programmer can create own packages.

Creating a Package
package mypack;

public class Hello {

public void show() {

[Link]("Hello from mypack");

📌 Compile:
javac -d . [Link]

Using User-Defined Package


import [Link];

class Test {

public static void main(String[] args) {

Hello h = new Hello();

[Link]();

}
}

4. Accessing Packages
Packages can be accessed in three ways:

A) Fully Qualified Name


[Link] sc = new [Link]([Link]);

✔ No import needed
❌ Long syntax

B) Import Specific Class


import [Link];

✔ Most commonly used

C) Import Entire Package


import [Link].*;

✔ Short syntax
❌ May include unused classes

5. import Keyword
The import keyword is used to access classes from other packages.

Syntax
import [Link];

or
import packageName.*;

Example
import [Link];

class ImportDemo {

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

[Link](10);

[Link](20);
[Link](list);

Access Control with Packages


Access modifiers control visibility across packages.

Same Same Other


Modifier Subclass
Class Package Package
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ❌
default ✔ ✔ ❌ ❌
private ✔ ❌ ❌ ❌

# MULTITHREADING IN JAVA
Multithreading is a feature that allows multiple threads to run concurrently within a single
program to improve performance and responsiveness.

1. What is a Thread?
A thread is a lightweight sub-process and the smallest unit of execution in a Java program.

📌 Key Points

· Threads share the same memory


· Faster than processes
· Java supports multithreading using Thread class and Runnable interface

2. Thread Life Cycle


A thread passes through different states during execution.

States
1. New – Thread created
2. Runnable – Ready to run
3. Running – Executing
4. Waiting / Blocked – Temporarily inactive
5. Terminated (Dead) – Execution finished
Text Diagram
New → Runnable → Running → Dead

↘ Waiting / Blocked ↗

3. Creating Threads in Java


Java provides two ways to create threads:

A) By Extending Thread Class


Steps
1. Extend Thread
2. Override run()
3. Call start()

Example
class MyThread extends Thread {

public void run() {

[Link]("Thread is running");

public static void main(String[] args) {

MyThread t = new MyThread();

[Link]();

B) By Implementing Runnable Interface


Steps
1. Implement Runnable
2. Override run()
3. Pass object to Thread

Example
class MyRunnable implements Runnable {

public void run() {


[Link]("Runnable thread running");

public static void main(String[] args) {

Thread t = new Thread(new MyRunnable());

[Link]();

📌 Recommended: Runnable (supports multiple inheritance)

4. Thread Class vs Runnable Interface


Thread Runnable
Feature
Class Interface
Inheritance Single only Multiple possible
Flexibility Less More
Memory More Less
Preferred ❌ ✅

5. Thread Methods
Common Thread Methods
Method Description
start() Starts thread
run() Thread logic
sleep(ms) Pauses thread
join()
Waits for
thread
getName() Thread name
setPriority() Sets priority
isAlive() Checks status

Example
class ThreadMethodDemo extends Thread {

public void run() {

[Link]("Thread running");

public static void main(String[] args) {


ThreadMethodDemo t = new ThreadMethodDemo();

[Link]();

[Link]([Link]());

6. Synchronization
Synchronization prevents data inconsistency when multiple threads access shared resources.

Types
· Synchronized method
· Synchronized block

Synchronized Method Example


class Table {

synchronized void print(int n) {

for (int i = 1; i <= 5; i++) {

[Link](n * i);

Synchronized Block Example


synchronized(this) {

// critical section

📌 Purpose: Thread safety

7. Inter-Thread Communication
Used when threads need to communicate with each other.

Methods
· wait()
· notify()
· notifyAll()

Example
class Customer {

int amount = 10000;

synchronized void withdraw(int amt) {

if (amount < amt) {

try { wait(); } catch (Exception e) {}

amount -= amt;

[Link]("Withdraw successful");

synchronized void deposit(int amt) {

amount += amt;

notify();

8. Deadlock
A deadlock occurs when two or more threads wait forever for each other’s resources.

Causes
· Nested synchronization
· Circular dependency

Example (Conceptual)
Thread A → Resource 1 → waits for Resource 2

Thread B → Resource 2 → waits for Resource 1

📌 Prevention

· Avoid nested locks


· Lock ordering
· Use timeouts
9. Daemon Threads
Daemon threads run in the background and support user threads.

Examples
· Garbage Collector
· Finalizer

Example
class DaemonDemo extends Thread {

public void run() {

[Link]("Daemon thread");

public static void main(String[] args) {

DaemonDemo t = new DaemonDemo();

[Link](true);

[Link]();

📌 JVM exits when all user threads finish.

10. Thread Pool


A thread pool manages a group of reusable threads.

Advantages
· Better performance
· Reduced overhead
· Controlled resource usage

Example (Executor Framework)


import [Link];

import [Link];

class ThreadPoolDemo {

public static void main(String[] args) {


ExecutorService es = [Link](3);

[Link](() -> [Link]("Task 1"));

[Link](() -> [Link]("Task 2"));

[Link](() -> [Link]("Task 3"));

[Link]();

11. Concurrency Utilities ([Link])


Java provides advanced concurrency support.

Important Classes & Interfaces


Utility Purpose
Thread pool
ExecutorService
management
Callable Returns result
Future Holds result
CountDownLatch Thread coordination
Semaphore Resource control
ReentrantLock Advanced locking

Callable Example
import [Link].*;

class CallableDemo {

public static void main(String[] args) throws Exception {

ExecutorService es = [Link]();

Callable<Integer> task = () -> 10 + 20;

Future<Integer> result = [Link](task);

[Link]([Link]());

[Link]();

You might also like