Java Core
Java Core
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
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
Used for:
· Desktop applications
· Console applications
· Foundation for other Java editions
Includes:
· Core Java concepts
· OOPs
· Exception handling
· Multithreading
· Collections
· File handling
Technologies:
· Servlets
· JSP
· EJB
· JPA
· Web Services
🔹 Note:
Java EE is now called Jakarta EE
Used for:
· Mobile phones (old)
· Embedded systems
· IoT devices
Features:
· Limited memory usage
· Lightweight APIs
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
Relationship:
JDK → JRE → JVM
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 {
[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.
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 [Link];
// Class declaration
class MyClass {
// Main method
// Statements
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.
📌 Note:
6. Identifiers
Identifiers are names given to:
· Variables
· Methods
· Classes
· Objects
Valid Identifiers:
number
_total
$amount
StudentName
Invalid Identifiers:
2num // starts with digit
class // keyword
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';
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.
/**
* @author Aryan
* @version 1.0
*/
class CommentDemo {
[Link]("Documentation Comment");
📌 Symbols Used:
· /** ... */
Comparison of Comments
Comment
Symbol
Type
Single-line //
Multi-line /* */
Documentation /** */
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;
A) Local Variable
· Declared inside a method or block
· Cannot be accessed outside the method
· Must be initialized before use
class Test {
[Link](x);
B) Instance Variable
· Declared inside a class but outside methods
· Belongs to an object
· Each object gets its own copy
class Student {
void display() {
[Link](rollNo);
}
C) Static Variable
· Declared using static keyword
· Shared among all objects
· Memory allocated once
class Counter {
Counter() {
count++;
[Link](count);
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
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;
C) Character Type
· Stores single character
· Uses Unicode
char ch = 'A';
D) Boolean Type
· Stores true or false
boolean isJavaEasy = true;
Examples:
· String
· Array
· Class
· Interface
· Object
String name = "Java";
6. Type Casting
Type casting means converting one data type into another.
double b = a; // widening
[Link](b);
📌 Output: 10.0
[Link](y);
📌 Output: 10
7. Type Conversion
Type conversion happens when:
double b = a + 2.5;
📌 Result: b = 12.5
Example:
var num = 10;
📌 Important Rules:
❌ 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 {
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 {
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 {
4. Logical Operators
Used with boolean values.
Operator Meaning
&&
Logical
AND
`
!
Logical
NOT
Example:
class LogicalDemo {
5. Bitwise Operators
Perform operations at bit level.
Operator Meaning
&
Bitwise
AND
` `
^ XOR
~ Complement
Example:
class BitwiseDemo {
int a = 5; // 0101
int b = 3; // 0011
[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 {
int a = 8;
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 {
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 {
[Link](max);
}
📌 Output: 20
9. Operator Precedence
Determines order of execution.
Example:
class PrecedenceDemo {
int result = 10 + 5 * 2;
[Link](result);
# CONTROL STATEMENTS:-
Control statements are used to control the flow of execution of a Java program.
1. if Statement
Executes a block of code only if the condition is true.
Syntax:
if (condition) {
// statements
Example:
class IfDemo {
[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 {
[Link]("Grade A");
[Link]("Grade B");
} else {
[Link]("Grade C");
4. Nested if Statement
An if inside another if.
Example:
class NestedIfDemo {
if (hasID) {
[Link]("Entry allowed");
A) Traditional switch
class SwitchDemo {
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
default:
[Link]("Invalid day");
int day = 2;
};
[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 {
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++;
8. for Loop
Used when number of iterations is known.
Syntax:
for (initialization; condition; increment) {
// statements
Example:
class ForDemo {
[Link](i);
9. for-each Loop
Used to traverse arrays and collections.
Syntax:
for (datatype variable : array) {
// statements
}
Example:
class ForEachDemo {
[Link](n);
C. JUMP STATEMENTS
Used to transfer control.
if (i == 3) {
break;
[Link](i);
📌 Output: 1 2
if (i == 3) {
continue;
[Link](i);
📌 Output: 1 2 4 5
return a + b;
[Link](add(10, 20));
int roll;
String name;
void display() {
Object
An object is an instance of a class.
class Test {
[Link] = 1;
[Link] = "Aryan";
[Link]();
}
2. Constructors
A constructor is a special method:
A) Default Constructor
class Demo {
Demo() {
[Link]("Default Constructor");
new Demo();
B) Parameterized Constructor
class Student {
int roll;
String name;
Student(int r, String n) {
roll = r;
name = n;
void display() {
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 {
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);
6. Method Overloading
Same method name, different parameters.
class MathOp {
return a + b;
return a + b + c;
}
7. Method Overriding
Child class provides its own implementation of parent method.
class Parent {
void show() {
[Link]("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 {
[Link]("Drawing Circle");
B) Interface
· Supports 100% abstraction
· Uses implements
interface Animal {
void sound();
[Link]("Bark");
10. Encapsulation
Wrapping data and methods together using private variables and public methods.
class Account {
balance = b;
return balance;
Common Methods:
· toString()
· equals()
· hashCode()
· getClass()
class Demo {
[Link]([Link]());
String s = "Java";
# 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";
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 {
[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
[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 {
[Link](" Programming");
[Link](sb);
6. StringBuilder
· Mutable
· Not thread-safe
· Faster than StringBuffer
class StringBuilderDemo {
[Link](" Language");
[Link](sb);
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:
Declaration
int[] a;
Allocation
a = new int[5];
Initialization
a[0] = 10;
a[1] = 20;
Complete Example
class OneDArrayDemo {
[Link](marks[0]);
[Link](marks[1]);
[Link](marks[2]);
2. Multi-Dimensional Arrays
A multi-dimensional array stores data in rows and columns.
Initialization
int[][] a = {
{1, 2, 3},
{4, 5, 6}
};
Example Program
class TwoDArrayDemo {
int[][] a = {
{1, 2, 3},
{4, 5, 6}
};
[Link]();
3. Array Initialization
Types of Initialization
A) At Declaration
int[] a = {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.
[Link](a[i]);
[Link](x);
📌 Note:
for-each loop is read-only.
5. Anonymous Arrays
An anonymous array is an array without a name.
Example
class AnonymousArrayDemo {
for (int i : a) {
[Link](i);
📌 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 {
[Link](10);
[Link](20);
[Link](30);
[Link](list);
}
# EXCEPTION HANDLING
Exception Handling is a mechanism to handle runtime errors and maintain normal program
flow.
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.
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 {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
try {
a[10] = 50;
} catch (ArithmeticException e) {
[Link]("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
} 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 {
try {
int x = 10 / 2;
} catch (Exception e) {
[Link]("Error");
} finally {
7. throw Keyword
Used to explicitly throw an exception.
class ThrowDemo {
[Link]("Eligible");
checkAge(16);
}
8. throws Keyword
Used to declare exceptions in method signature.
class ThrowsDemo {
[Link](1000);
display();
📌 Difference:
9. Custom Exceptions
User-defined exceptions created by extending Exception class.
Example
class InvalidAgeException extends Exception {
InvalidAgeException(String msg) {
super(msg);
class CustomExceptionDemo {
[Link]("Voting allowed");
}
try {
vote(16);
} catch (InvalidAgeException e) {
[Link]([Link]());
Example
class PropagationDemo {
int a = 10 / 0;
m1();
try {
m2();
} catch (ArithmeticException e) {
# 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.
📌 Real-life Example:
Like folders in a computer (Documents, Pictures, Videos)
2. Built-in Packages
Java provides many predefined packages.
class BuiltInPackageDemo {
[Link]("Enter name:");
3. User-Defined Packages
Programmer can create own packages.
Creating a Package
package mypack;
📌 Compile:
javac -d . [Link]
class Test {
[Link]();
}
}
4. Accessing Packages
Packages can be accessed in three ways:
✔ No import needed
❌ Long syntax
✔ 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 {
[Link](10);
[Link](20);
[Link](list);
# 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
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 ↗
Example
class MyThread extends Thread {
[Link]("Thread is running");
[Link]();
Example
class MyRunnable implements Runnable {
[Link]();
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 {
[Link]("Thread running");
[Link]();
[Link]([Link]());
6. Synchronization
Synchronization prevents data inconsistency when multiple threads access shared resources.
Types
· Synchronized method
· Synchronized block
[Link](n * i);
// critical section
7. Inter-Thread Communication
Used when threads need to communicate with each other.
Methods
· wait()
· notify()
· notifyAll()
Example
class Customer {
amount -= amt;
[Link]("Withdraw successful");
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
📌 Prevention
Examples
· Garbage Collector
· Finalizer
Example
class DaemonDemo extends Thread {
[Link]("Daemon thread");
[Link](true);
[Link]();
Advantages
· Better performance
· Reduced overhead
· Controlled resource usage
import [Link];
class ThreadPoolDemo {
[Link]();
Callable Example
import [Link].*;
class CallableDemo {
ExecutorService es = [Link]();
[Link]([Link]());
[Link]();