Module 1
Syllabus:
Introduction to Java Programming-History of Java and its Evolution,Features of
Java (Platform Independence, Object Oriented),Data Types and
Variables,Operators Constants and Literals,Type Casting
Decision Making and Loops :If-else Statements,Switch Statement, Loops (For,
While, Do-While),Break and Continue Statements
Classes and Objects :Array,ArraysString class and String methods, StringBuffer
and StringBuilder, Object-Oriented Programming Concepts, Defining Classes and
Creating Objects, Instance Variables and Methods, Constructors, this Keyword,
super keyword, Types of Classes, Scope Rules, Access Modifier, constants, static
members of a class, garbage collection.
Inheritance: Its types, Superclass and Subclass, Final classes and methods
Polymorphism: Compile-time and Runtime Polymorphism
🌟 Introduction to Java Programming
1️⃣ Introduction to Java Programming
Java is a high-level, object-oriented programming language.
It is platform independent, secure, and robust.
Java is widely used for:
Desktop applications
Web applications
Mobile applications (Android)
Enterprise systems
Embedded systems
2️⃣ History of Java
🔹 Origin of Java
Java was developed in 1991
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Developed by Sun Microsystems
Main developer: James Gosling
The project was initially called the Green Project
🔹 Original Name
The original name of Java was Oak
Named after an oak tree outside James Gosling’s office
The name was changed because Oak was already registered
🔹 Why the Name “Java”?
The development team liked Java coffee
The name Java was short, unique, and easy to remember
🔹 First Release
First official version: Java 1.0
Released in 1995
Java slogan:
“Write Once, Run Anywhere (WORA)”
3️⃣ Why Java Was Developed?
Java was developed to:
Overcome platform dependency
Support network-based applications
Provide security and reliability
Work on embedded systems
4️⃣ Evolution of Java (Java Versions)
Version Year Key Features
Java 1.0 1995 Basic language, JVM
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Version Year Key Features
Java 1.1 1997 JDBC, inner classes
Java 2 (J2SE) 1998 Swing, Collections
Java 5 2004 Generics, annotations
Java 6 2006 Performance improvements
Java 7 2011 try-with-resources
Java 8 2014 Lambda expressions
Java 11 2018 Long-term support (LTS)
Java 17 2021 Enhanced security & speed
Java 21 2023 Latest LTS version
5️⃣ Important Milestones in Java Evolution
🔹 Java Virtual Machine (JVM)
Java code is converted into bytecode
Bytecode runs on JVM
Makes Java platform independent
🔹 Object-Oriented Features
Class and Object
Inheritance
Polymorphism
Encapsulation
Abstraction
🔹 Java and Internet
Used for web applications
Supports server-side programming
Earlier used applets (now obsolete)
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Java in Mobile Development
Java became very popular due to Android development
Used to build mobile applications
6️⃣ Java After Oracle
In 2010, Oracle Corporation acquired Sun Microsystems
Oracle continues to develop and maintain Java
Regular updates, security patches, and new versions are released
🌟 Features of Java
1️⃣ Simple
✔ What does Simple mean?
Java is easy to learn, write, and understand.
✔ Why Java is Simple?
No complex pointers
Automatic memory management
Clear syntax
✔ Simple Example:
class Hello {
public static void main(String[] args) {
[Link]("Hello Java");
}
}
➡ This program prints Hello Java with very simple commands.
2️⃣ Object-Oriented
✔ Meaning:
Java follows Object-Oriented Programming (OOP).
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ OOP Concepts in Java:
Class
Object
Inheritance
Polymorphism
Encapsulation
Abstraction
✔ Simple Example:
class Student {
int id = 1;
String name = "Amit";
}
➡ Student is a class, and its data is inside an object.
3️⃣ Platform Independent
✔ Meaning:
Java program can run on any operating system.
✔ How?
Java code → Bytecode
Bytecode runs on JVM
JVM is available for Windows, Linux, Mac
✔ Simple Example:
Same .class file runs on:
Windows
Linux
Mac
➡ Write Once, Run Anywhere
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
4️⃣ Secure
✔ Meaning:
Java protects programs from viruses and harmful code.
✔ Security Features:
No direct memory access
Bytecode verification
JVM security manager
✔ Simple Example:
Java does not allow pointer access:
// Pointers are not allowed in Java
➡ So memory cannot be misused.
5️⃣ Robust
✔ Meaning:
Java is strong and error-resistant.
✔ Why Java is Robust?
Strong type checking
Exception handling
Automatic garbage collection
✔ Simple Example:
int a = 10;
// int a = "hello"; ❌ not allowed
➡ Java checks errors before running.
6️⃣ Multithreaded
✔ Meaning:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Java can do multiple tasks at the same time.
✔ Real-life Example:
Listening to music
Downloading a file
Browsing internet
➡ All at the same time
✔ Simple Example:
class MyThread extends Thread {
public void run() {
[Link]("Thread running");
}
}
7️⃣ High Performance
✔ Meaning:
Java runs faster than other interpreted languages.
✔ Why?
Uses Just-In-Time (JIT) compiler
Converts bytecode to machine code
✔ Simple Example:
Java executes programs faster than Python (in many cases).
8️⃣ Distributed
✔ Meaning:
Java supports network-based applications.
✔ Uses:
Client-server applications
Web applications
✔ Simple Example:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Java is used in:
Online banking
Web servers
9️⃣ Portable
✔ Meaning:
Java programs can be moved from one system to another.
✔ Why?
Same bytecode
No platform dependency
✔ Simple Example:
A Java program written on Windows can run on Linux without change.
🔟 Dynamic
✔ Meaning:
Java supports dynamic memory allocation and runtime linking.
✔ Why Important?
Classes can be loaded during runtime
Saves memory
✔ Simple Example:
class Test {
}
➡ Class is loaded only when required.
1️⃣1️⃣ Architecture Neutral
✔ Meaning:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Java programs are not dependent on hardware architecture.
✔ How?
Bytecode is the same for all CPUs
✔ Simple Example:
Same Java program runs on:
Intel processor
AMD processor
1️⃣2️⃣ Interpreted
✔ Meaning:
Java code is compiled and then interpreted.
✔ Steps:
1. Java code → Bytecode
2. Bytecode → JVM → Output
✔ Simple Example:
.java → .class → JVM → Output
1️⃣3️⃣ Automatic Garbage Collection
✔ Meaning:
Java automatically deletes unused memory.
✔ Benefit:
No memory leak
Programmer tension-free
✔ Simple Example:
Student s = new Student();
s = null;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
➡ Java frees memory automatically.
✨ Summary (Quick Points)
Java is simple and easy
Object-oriented language
Platform independent
Secure and robust
Supports multithreading
Portable and dynamic
Used for real-world applications
🌟 JVM, JRE, JDK, WORA & JIT
(Simple Explanation + Relationship)
1️⃣ JVM (Java Virtual Machine)
✔ What is JVM?
JVM is a virtual machine (software) that runs Java programs.
👉 JVM does not run .java files
👉 JVM runs only bytecode (.class file)
✔ What does JVM do?
Loads bytecode
Converts bytecode into machine code
Executes the program
Manages memory
Provides security
✔ Simple Flow:
.java → .class → JVM → Output
Without JVM, Java programs cannot run.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
2️⃣ JRE (Java Runtime Environment)
✔ What is JRE?
JRE = JVM + Java Libraries
👉 JRE provides the environment to run Java programs.
✔ What is inside JRE?
JVM
Core Java libraries
Supporting files
✔ Important Point:
JRE can run Java programs
JRE cannot write or compile Java programs
✔ Example:
If your computer has only JRE:
❌ You cannot write Java code
✅ You can run Java applications
3️⃣ JDK (Java Development Kit)
✔ What is JDK?
JDK = JRE + Development Tools
👉 JDK is used to write, compile, and run Java programs.
✔ What is inside JDK?
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
JRE (with JVM)
Java compiler (javac)
Debugger
Development tools
✔ Example:
If your computer has JDK:
✅ You can write Java code
✅ You can compile Java code
✅ You can run Java programs
4️⃣ Relationship between JVM, JRE, and JDK
JDK
└── JRE
└── JVM
👉 JVM is part of JRE
👉 JRE is part of JDK
✔ Real-Life Example:
JVM = Engine of a car
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
JRE = Car (engine + parts)
JDK = Car factory (tools to make the car)
5️⃣ Write Once Run Anywhere (WORA)
✔ What is WORA?
Write Once Run Anywhere means:
Write Java code once
Run it on any operating system
✔ How is WORA possible?
Java compiler converts code into bytecode
Bytecode is platform independent
JVM is available for every OS
✔ Example:
Same Java program runs on:
Windows
Linux
macOS
No change in code required.
6️⃣ JIT (Just-In-Time Compiler)
✔ What is JIT?
JIT is a part of JVM that improves performance.
✔ What does JIT do?
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Converts bytecode into machine code
Compiles frequently used code at runtime
Makes execution faster
✔ Simple Example:
Interpreter: runs code line-by-line (slow)
JIT: runs important code faster
7️⃣ How All Components Work Together
✔ Java Program Execution Steps
1. Programmer writes .java file
2. javac compiler converts it to .class (bytecode)
3. JRE provides runtime environment
4. JVM executes bytecode
5. JIT improves execution speed
6. Output is displayed
8️⃣ One-Line Exam Definitions
JVM: Executes Java bytecode
JRE: Environment to run Java programs
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
JDK: Toolkit to develop Java programs
WORA: Write once, run anywhere
JIT: Improves Java performance
✨ Summary (Exam Ready)
Developers use JDK
Users need JRE
JVM runs the program
JIT makes execution fast
WORA makes Java platform independent
🌟 Data Types and Variables in Java
1️⃣ Variables in Java
✔ What is a Variable?
A variable is a name given to a memory location where data is stored.
👉 Value of a variable can change during program execution.
✔ Why Variables are Needed?
To store data
To perform calculations
To reuse values
✔ Simple Example:
int age = 20;
➡ age is a variable
➡ 20 is the value
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
2️⃣ Rules for Naming Variables
Must start with a letter, _ or $
Cannot start with a number
No spaces allowed
Cannot use Java keywords
Case-sensitive
✔ Valid: total, _sum, marks1
❌ Invalid: 1num, total marks, class
3️⃣ Types of Variables in Java
🔹 Based on Scope
1️⃣ Local Variable
Declared inside a method
Used only inside that method
void show() {
int x = 10;
}
2️⃣ Instance Variable
Declared inside class but outside method
Each object has its own copy
class Student {
int id;
}
3️⃣ Static Variable
Declared using static keyword
Shared by all objects
class Student {
static String college = "ABC";
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
4️⃣ Data Types in Java
✔ What is Data Type?
A data type tells Java:
What type of data is stored
How much memory is needed
5️⃣ Classification of Data Types
Data Types
├── Primitive
└── Non-Primitive (Reference)
6️⃣ Primitive Data Types (8 Types)
Primitive data types store simple values.
🔹 1️⃣ byte
Size: 1 byte
Range: -128 to 127
byte b = 100;
➡ Used to save memory
🔹 2️⃣ short
Size: 2 bytes
short s = 2000;
🔹 3️⃣ int
Size: 4 bytes
Most commonly used
int number = 50;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 4️⃣ long
Size: 8 bytes
long population = 9000000000L;
🔹 5️⃣ float
Size: 4 bytes
Decimal values
Use f at the end
float price = 99.5f;
🔹 6️⃣ double
Size: 8 bytes
More accurate than float
double pi = 3.14159;
🔹 7️⃣ char
Size: 2 bytes
Stores single character
char grade = 'A';
🔹 8️⃣ boolean
Size: 1 bit
Stores true or false
boolean isPass = true;
7️⃣ Primitive Data Types Table
Data Type Size Example
byte 1 byte byte b = 10;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Data Type Size Example
short 2 bytes short s = 100;
int 4 bytes int a = 20;
long 8 bytes long l = 1000L;
float 4 bytes float f = 10.5f;
double 8 bytes double d = 20.5;
char 2 bytes char c = 'A';
boolean 1 bit boolean b = true;
8️⃣ Non-Primitive (Reference) Data Types
Non-primitive data types store references (addresses).
🔹 1️⃣ String
Stores a sequence of characters.
String name = "Java";
🔹 2️⃣ Array
Stores multiple values of same type.
int[] marks = {80, 90, 85};
🔹 3️⃣ Class
User-defined data type.
class Student {
int id;
}
🔹 4️⃣ Interface
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Used to achieve abstraction.
interface Shape {
void draw();
}
9️⃣ Difference Between Primitive and Non-Primitive
Primitive Non-Primitive
Stores value Stores address
Fixed size Variable size
Faster Slower
int, float String, Array
🔟 Variable Initialization
✔ Declaring and Initializing:
int x = 10;
✔ Declaration only:
int y;
y = 20;
1️⃣1️⃣ Default Values of Variables
Variable Type Default Value
int 0
float 0.0
char '\u0000'
boolean false
Reference null
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
📌 Applies only to instance and static variables
1️⃣2️⃣ Type Casting
✔ Implicit Casting:
int a = 10;
double b = a;
✔ Explicit Casting:
double x = 10.5;
int y = (int)x;
🌟 Type Casting in Java
Implicit Casting & Explicit Casting
1️⃣ What is Type Casting?
Type Casting means converting one data type into another data type.
👉 Java allows casting only between compatible data types.
2️⃣ Types of Type Casting in Java
Type Casting
├── Implicit Casting (Widening)
└── Explicit Casting (Narrowing)
3️⃣ Implicit Casting (Widening Casting)
✔ What is Implicit Casting?
Implicit casting means:
Conversion is done automatically by Java
No data loss
Small data type → Bigger data type
👉 Also called Widening Casting
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Order of Implicit Casting
byte → short → int → long → float → double
✔ Simple Example:
int a = 10;
double b = a;
[Link](b);
🔹 Output:
10.0
👉 Java automatically converts int to double.
✔ More Examples:
byte b = 20;
int i = b;
float f = i;
✔ Why No Data Loss?
Because:
Bigger data type can store smaller value easily
✔ Key Points of Implicit Casting:
Done automatically
No casting operator needed
Safe conversion
No data loss
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
4️⃣ Explicit Casting (Narrowing Casting)
✔ What is Explicit Casting?
Explicit casting means:
Conversion is done manually by programmer
Bigger data type → Smaller data type
Possible data loss
👉 Also called Narrowing Casting
✔ Syntax:
datatype variable = (datatype) value;
✔ Simple Example:
double x = 10.5;
int y = (int) x;
[Link](y);
🔹 Output:
10
👉 Decimal part is lost.
✔ More Examples:
long l = 1000;
int i = (int) l;
float f = 20.7f;
int n = (int) f;
✔ Why Data Loss Happens?
Because:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Smaller data type cannot store full value
Decimal part or large value is cut
✔ Key Points of Explicit Casting:
Manual conversion
Casting operator required
Risk of data loss
Used carefully
5️⃣ Implicit vs Explicit Casting (Difference Table)
Implicit Casting Explicit Casting
Automatic Manual
Small → Big Big → Small
No data loss Data loss possible
Safe Risky
int → double double → int
6️⃣ Casting with char (Important for Exam)
✔ char to int (Implicit)
char ch = 'A';
int a = ch;
[Link](a);
🔹 Output:
65
✔ int to char (Explicit)
int x = 66;
char c = (char) x;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link](c);
🔹 Output:
7️⃣ Real-Life Example
🎓 Marks Example:
Implicit:
45 marks → 45.0 marks (no problem)
Explicit:
45.75 marks → 45 marks (decimal lost)
8️⃣ Common Mistakes
❌ Invalid Implicit Casting:
double d = 10.5;
int i = d; // Error
✔ Correct Explicit Casting:
int i = (int) d;
9️⃣ Summary
Type casting converts one data type to another
Implicit casting is automatic and safe
Explicit casting is manual and may lose data
Use explicit casting carefully
🔟 One-Line Definitions
Implicit Casting: Automatic conversion from smaller to larger data type.
Explicit Casting: Manual conversion from larger to smaller data type.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🌟 Operators, Constants and Literals in Java
1️⃣ Operators in Java
✔ What is an Operator?
An operator is a symbol used to perform operations on variables and values.
✔ What is Operand?
The values on which an operator works are called operands.
✔ Example:
int a = 10 + 5;
➡ + is operator
➡ 10 and 5 are operands
2️⃣ Types of Operators in Java
Operators
├── Arithmetic
├── Relational
├── Logical
├── Assignment
├── Unary
├── Bitwise
├── Ternary
3️⃣ Arithmetic Operators
Used to perform mathematical operations.
Operator Meaning Example
+ Addition a+b
- Subtraction a-b
* Multiplication a*b
/ Division a/b
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Operator Meaning Example
% Modulus a%b
✔ Example:
int a = 10, b = 3;
[Link](a + b); // 13
[Link](a % b); // 1
4️⃣ Relational (Comparison) Operators
Used to compare two values.
Result is true or false.
Operator Meaning
== Equal to
!= Not equal
> Greater than
< Less than
>= Greater or equal
<= Less or equal
✔ Example:
int x = 5, y = 10;
[Link](x < y); // true
5️⃣ Logical Operators
Used with boolean values.
Operator Meaning
&& Logical AND
! Logical NOT
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Example:
boolean a = true, b = false;
[Link](a && b); // false
6️⃣ Assignment Operators
Used to assign values.
Operator Example
= a = 10
+= a += 5
-= a -= 3
*= a *= 2
/= a /= 2
✔ Example:
int a = 10;
a += 5; // a = 15
7️⃣ Unary Operators
Works on single operand.
Operator Meaning
+ Unary plus
- Unary minus
++ Increment
-- Decrement
✔ Example:
int x = 5;
x++;
[Link](x); // 6
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
8️⃣ Bitwise Operators
Works on binary values.
Operator Meaning
& AND
^ XOR
~ NOT
<< Left shift
>> Right shift
✔ Example:
int a = 5, b = 3;
[Link](a & b); // 1
9️⃣ Ternary Operator
Used as a short form of if-else.
✔ Syntax:
condition ? value1 : value2;
✔ Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
🔹 Constants in Java
1️⃣ What is a Constant?
A constant is a value that cannot be changed during program execution.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
2️⃣ How to Declare a Constant?
Use the final keyword.
✔ Example:
final int MAX = 100;
❌ MAX = 200; (Error)
3️⃣ Why Use Constants?
Prevent accidental changes
Improve code readability
Used for fixed values
🔹 Literals in Java
1️⃣ What is a Literal?
A literal is a fixed value written directly in the program.
✔ Example:
int x = 10;
➡ 10 is a literal
2️⃣ Types of Literals in Java
Literals
├── Integer
├── Floating-point
├── Character
├── String
├── Boolean
├── Null
3️⃣ Integer Literals
Used to store whole numbers.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
int a = 100;
int b = 0b101; // binary
4️⃣ Floating-Point Literals
Used to store decimal values.
float f = 10.5f;
double d = 20.25;
5️⃣ Character Literals
Single character enclosed in single quotes.
char ch = 'A';
6️⃣ String Literals
Multiple characters enclosed in double quotes.
String name = "Java";
7️⃣ Boolean Literals
Only two values.
boolean flag = true;
8️⃣ Null Literal
Represents no reference.
String s = null;
🔟 Difference Between Constant and Literal
Constant Literal
Fixed value Value written directly
Uses final No keyword
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Constant Literal
Cannot change Just value
🌟 Decision Making and Loops in Java
🔷 PART 1: DECISION MAKING STATEMENTS
Decision making statements are used to take decisions based on conditions.
1️⃣ if Statement
✔ What is if statement?
The if statement executes a block of code only when a condition is true.
✔ Features
Executes code conditionally
Simple and easy to use
Used for single decision
✔ Syntax
if(condition) {
statement;
}
✔ Example Program
int age = 20;
if(age >= 18) {
[Link]("Eligible to vote");
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Output
Eligible to vote
✔ Advantages
Simple logic
Easy to understand
Improves program control
✔ Disadvantages
Cannot handle multiple conditions alone
✔ Real-Life Use
Check eligibility (age, marks)
Login validation
2️⃣ if–else Statement
✔ What is if–else?
Executes one block if condition is true, otherwise executes else block.
✔ Syntax
if(condition) {
statement1;
} else {
statement2;
}
✔ Example Program
int marks = 35;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
if(marks >= 40) {
[Link]("Pass");
} else {
[Link]("Fail");
}
✔ Output
Fail
✔ Advantages
Handles two conditions
Clear decision making
✔ Disadvantages
Not suitable for many conditions
✔ Real-Life Use
Pass/Fail result
Yes/No decisions
3️⃣ else-if Ladder
✔ What is else-if ladder?
Used to check multiple conditions one by one.
✔ Syntax
if(condition1) {
}
else if(condition2) {
}
else {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
}
✔ Example Program
int marks = 85;
if(marks >= 75) {
[Link]("Distinction");
}
else if(marks >= 60) {
[Link]("First Class");
}
else if(marks >= 40) {
[Link]("Pass");
}
else {
[Link]("Fail");
}
✔ Output
Distinction
✔ Advantages
Handles multiple conditions
Better than nested if
✔ Disadvantages
Slower if many conditions
Harder to read if too long
✔ Real-Life Use
Grade system
Salary calculation
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
4️⃣ Nested if–else
✔ What is Nested if?
An if inside another if.
✔ Syntax
if(condition1) {
if(condition2) {
}
}
✔ Example Program
int age = 25;
boolean hasLicense = true;
if(age >= 18) {
if(hasLicense) {
[Link]("Can drive");
}
}
✔ Output
Can drive
✔ Advantages
Handles complex conditions
✔ Disadvantages
Code becomes complex
Difficult to debug
✔ Real-Life Use
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Banking verification
Authentication systems
5️⃣ Switch Statement
✔ What is switch?
Used to select one option from many choices.
✔ Syntax
switch(expression) {
case value1:
break;
case value2:
break;
default:
break;
}
✔ Example Program
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
✔ Output
Wednesday
✔ Advantages
Faster than else-if ladder
Cleaner code
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Disadvantages
Works only with fixed values
Cannot use conditions
✔ Real-Life Use
Menu-driven programs
ATM options
🔷 PART 2: LOOPS IN JAVA
Loops are used to repeat code multiple times.
6️⃣ for Loop
✔ What is for loop?
Used when number of iterations is known.
✔ Syntax
for(initialization; condition; increment) {
statement;
}
✔ Example Program
for(int i = 1; i <= 5; i++) {
[Link](i);
}
✔ Output
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
2
3
4
5
✔ Advantages
Best for fixed loops
Compact syntax
✔ Disadvantages
Not suitable for unknown iterations
✔ Real-Life Use
Printing tables
Array traversal
7️⃣ while Loop
✔ What is while loop?
Executes loop while condition is true.
✔ Syntax
while(condition) {
statement;
}
✔ Example Program
int i = 1;
while(i <= 3) {
[Link](i);
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
i++;
}
✔ Output
1
2
3
✔ Advantages
Suitable when iterations unknown
✔ Disadvantages
Infinite loop risk
✔ Real-Life Use
Reading input until condition met
8️⃣ do–while Loop
✔ What is do–while?
Executes loop at least once.
✔ Syntax
do {
statement;
} while(condition);
✔ Example Program
int i = 1;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
do {
[Link](i);
i++;
} while(i <= 3);
✔ Output
1
2
3
✔ Advantages
Executes at least once
✔ Disadvantages
May execute unnecessarily once
✔ Real-Life Use
Menu-driven programs
🔷 PART 3: BREAK AND CONTINUE
9️⃣ break Statement
✔ What is break?
Terminates the loop immediately.
✔ Example
for(int i = 1; i <= 5; i++) {
if(i == 3) break;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link](i);
}
✔ Output
1
2
✔ Use
Exit loop early
🔟 continue Statement
✔ What is continue?
Skips current iteration and continues loop.
✔ Example
for(int i = 1; i <= 5; i++) {
if(i == 3) continue;
[Link](i);
}
✔ Output
1
2
4
5
✔ Difference
break continue
Stops loop Skips iteration
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🌟 Arrays in Java
1️⃣ What is an Array?
An array is a collection of similar data types stored in continuous memory
locations.
👉 Array is used to store multiple values using a single variable name.
✔ Example (Without Array):
int m1 = 70;
int m2 = 80;
int m3 = 90;
✔ Example (With Array):
int marks[] = {70, 80, 90};
2️⃣ Why Use Array? (Need of Array)
Store multiple values
Reduce number of variables
Easy data handling
Improves program readability
3️⃣ Features of Array
Stores same type of data
Fixed size
Index starts from 0
Fast access using index
Stored in continuous memory
4️⃣ Advantages of Array
Saves memory
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Faster access
Easy sorting and searching
Reduces code length
5️⃣ Disadvantages of Array
Fixed size (cannot grow or shrink)
Stores only similar data types
Memory wastage possible
Insertion and deletion is difficult
6️⃣ Types of Arrays in Java
Arrays
├── One-Dimensional Array
├── Two-Dimensional Array
└── Multi-Dimensional Array
🔷 ONE-DIMENSIONAL ARRAY
7️⃣ Declaration of 1D Array
✔ Syntax:
datatype[] arrayName;
✔ Example:
int[] numbers;
8️⃣ Array Initialization
✔ Method 1:
int[] a = {10, 20, 30};
✔ Method 2:
int[] a = new int[3];
a[0] = 10;
a[1] = 20;
a[2] = 30;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
9️⃣ Accessing Array Elements
[Link](a[0]);
🔟 Example Program (1D Array)
✔ Program:
class ArrayExample {
public static void main(String[] args) {
int[] a = {10, 20, 30, 40};
for(int i = 0; i < [Link]; i++) {
[Link](a[i]);
}
}
}
✔ Output:
10
20
30
40
1️⃣1️⃣ Real-Life Use (1D Array)
Marks of students
Temperature readings
Monthly sales data
🔷 TWO-DIMENSIONAL ARRAY
1️⃣2️⃣ What is 2D Array?
A 2D array is an array of arrays
It stores data in row and column format (matrix form).
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
1️⃣3️⃣ Declaration and Initialization
✔ Syntax:
datatype[][] arrayName;
✔ Example:
int[][] marks = {
{80, 85},
{90, 95}
};
1️⃣4️⃣ Example Program (2D Array)
✔ Program:
class TwoDArray {
public static void main(String[] args) {
int[][] a = {
{1, 2},
{3, 4}
};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
[Link](a[i][j] + " ");
}
[Link]();
}
}
}
✔ Output:
12
34
1️⃣5️⃣ Real-Life Use (2D Array)
Student marks table
Matrix operations
Seating arrangement
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
2️⃣1️⃣ Difference Between Array and Variables
Array Variable
Stores multiple values Stores one value
Fixed size Single value
Same data type Single data
🌟 Arrays Class in Java
([Link])
1️⃣ What is Arrays Class?
The Arrays class is a utility class present in the package:
[Link]
👉 It is used to perform operations on arrays easily, such as:
Sorting
Searching
Comparing
Filling
Converting array to string
📌 It works for both primitive and object arrays.
2️⃣ Why Arrays Class is Needed?
Without Arrays class:
Sorting and searching need manual logic
Code becomes long and complex
With Arrays class:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Short code
Fast execution
Easy to use
3️⃣ Important Features of Arrays Class
Provides static methods
Works on 1D arrays
Supports primitive & object arrays
Improves code readability
Faster than manual coding
4️⃣ How to Use Arrays Class?
✔ Import Statement
import [Link];
5️⃣ Important Methods of Arrays Class
🔹 1️⃣ sort() Method
✔ Purpose:
Sorts array elements in ascending order.
✔ Syntax:
[Link](arrayName);
✔ Example Program:
import [Link];
class SortExample {
public static void main(String[] args) {
int[] a = {40, 10, 30, 20};
[Link](a);
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link]([Link](a));
}
}
✔ Output:
[10, 20, 30, 40]
✔ Real-Life Use:
Sort marks
Sort prices
Ranking systems
🔹 2️⃣ toString() Method
✔ Purpose:
Converts array into readable string format.
✔ Syntax:
[Link](arrayName);
✔ Example:
int[] a = {1, 2, 3};
[Link]([Link](a));
✔ Output:
[1, 2, 3]
✔ Advantage:
Easy printing of array elements.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 3️⃣ binarySearch() Method
✔ Purpose:
Searches an element using binary search.
📌 Array must be sorted before searching.
✔ Syntax:
[Link](arrayName, key);
✔ Example Program:
import [Link];
class SearchExample {
public static void main(String[] args) {
int[] a = {10, 20, 30, 40};
int result = [Link](a, 30);
[Link](result);
}
}
✔ Output:
👉 Index position is returned.
✔ If element not found:
Returns negative value.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 4️⃣ equals() Method
✔ Purpose:
Checks whether two arrays are equal.
✔ Syntax:
[Link](array1, array2);
✔ Example:
import [Link];
class EqualsExample {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
[Link]([Link](a, b));
}
}
✔ Output:
true
🔹 5️⃣ fill() Method
✔ Purpose:
Fills all elements of an array with same value.
✔ Syntax:
[Link](arrayName, value);
✔ Example:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
import [Link];
class FillExample {
public static void main(String[] args) {
int[] a = new int[5];
[Link](a, 7);
[Link]([Link](a));
}
}
✔ Output:
[7, 7, 7, 7, 7]
🔹 6️⃣ copyOf() Method
✔ Purpose:
Creates a new array copy.
✔ Syntax:
[Link](originalArray, newLength);
✔ Example:
import [Link];
class CopyExample {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = [Link](a, 5);
[Link]([Link](b));
}
}
✔ Output:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[1, 2, 3, 0, 0]
🔹 7️⃣ copyOfRange() Method
✔ Purpose:
Copies specific range of array.
✔ Syntax:
[Link](array, from, to);
✔ Example:
int[] a = {10, 20, 30, 40, 50};
int[] b = [Link](a, 1, 4);
[Link]([Link](b));
✔ Output:
[20, 30, 40]
6️⃣ Advantages of Arrays Class
Saves time
Reduces code length
Less errors
Easy array handling
7️⃣ Disadvantages of Arrays Class
Mostly works on 1D arrays
Limited functionality for complex operations
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
8️⃣ Real-Life Applications
Sorting exam marks
Searching records
Comparing datasets
Initializing arrays
🌟 String Class in Java
([Link])
1️⃣ What is String in Java?
A String is a sequence of characters.
In Java, String is a class, not a primitive data type.
String name = "Pradnya";
📌 Strings are used to store:
Names
Messages
Passwords
Text data
2️⃣ Why String is Special in Java?
String is immutable
Stored in String Constant Pool
Comes from [Link] package (no import needed)
3️⃣ How String Objects are Created?
🔹 1️⃣ Using String Literal
String s1 = "Java";
Stored in String Pool
Memory efficient
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 2️⃣ Using new Keyword
String s2 = new String("Java");
Stored in Heap memory
Creates new object
4️⃣ What is String Immutability?
👉 Immutability means cannot be changed.
String s = "Hello";
s = [Link](" World");
✔ Old string remains unchanged
✔ New object is created
📌 This improves security and performance
5️⃣ Important Features of String Class
Immutable
Thread safe
Supports Unicode
Secure
Rich set of methods
6️⃣ Commonly Used String Methods
🔹 1️⃣ length()
Purpose:
Returns number of characters.
String s = "Java";
[Link]([Link]());
Output:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 2️⃣ charAt()
Purpose:
Returns character at given index.
[Link]([Link](1));
Output:
🔹 3️⃣ concat()
Purpose:
Joins two strings.
String s1 = "Hello";
String s2 = "Java";
[Link]([Link](s2));
Output:
HelloJava
🔹 4️⃣ equals()
Purpose:
Compares content.
String a = "Java";
String b = "Java";
[Link]([Link](b));
Output:
true
🔹 5️⃣ equalsIgnoreCase()
[Link]("JAVA".equalsIgnoreCase("java"));
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Output:
true
🔹 6️⃣ compareTo()
Purpose:
Lexicographical comparison.
[Link]("A".compareTo("B"));
Output:
-1
🔹 7️⃣ toUpperCase() / toLowerCase()
[Link]("java".toUpperCase());
Output:
JAVA
🔹 8️⃣ trim()
Purpose:
Removes spaces from start and end.
String s = " Java ";
[Link]([Link]());
Output:
Java
🔹 9️⃣ substring()
Purpose:
Extract part of string.
String s = "Programming";
[Link]([Link](0, 7));
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Output:
Program
🔹 🔟 replace()
[Link]("Java".replace('a', 'o'));
Output:
Jovo
🔹 1️⃣1️⃣ contains()
[Link]("Java Programming".contains("Java"));
Output:
true
🔹 1️⃣2️⃣ split()
String s = "Java is easy";
String[] arr = [Link](" ");
7️⃣ String Constant Pool (SCP)
Special memory area in Heap
Stores string literals
Avoids duplicate objects
Improves performance
8️⃣ Advantages of String Class
Easy text handling
Secure (immutable)
Memory efficient
Rich methods
9️⃣ Disadvantages of String Class
Cannot modify data
Slow for heavy string operations
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
👉 Solution: StringBuffer or StringBuilder
🔟 Real-Life Applications
User input
Database queries
File handling
Web forms
Password validation
1️⃣1️⃣ Difference: String vs StringBuffer vs StringBuilder
Feature String StringBuffer StringBuilder
Mutable ❌ No ✅ Yes ✅ Yes
Thread Safe ✅ Yes ✅ Yes ❌ No
Speed Slow Medium Fast
🌟 StringBuffer in Java
([Link])
1️⃣ What is StringBuffer?
StringBuffer is a predefined class in Java used to create modifiable (mutable)
strings.
👉 Unlike String, the content of StringBuffer can be changed without creating a
new object.
StringBuffer sb = new StringBuffer("Java");
2️⃣ Why StringBuffer is Needed?
String is immutable (cannot change)
Frequent string changes create many objects
StringBuffer allows modification in same object
Useful in multi-threaded programs
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
3️⃣ Important Features of StringBuffer
Mutable (changeable)
Thread-safe (synchronized)
Slower than StringBuilder
Belongs to [Link] package
No need to import package
4️⃣ How StringBuffer Object is Created?
🔹 1️⃣ Empty StringBuffer
StringBuffer sb = new StringBuffer();
🔹 2️⃣ With String
StringBuffer sb = new StringBuffer("Hello");
🔹 3️⃣ With Capacity
StringBuffer sb = new StringBuffer(20);
5️⃣ Capacity in StringBuffer
Default capacity = 16 characters
If string length increases, capacity expands automatically
StringBuffer sb = new StringBuffer();
[Link]([Link]());
Output:
16
6️⃣ Commonly Used StringBuffer Methods
🔹 1️⃣ append()
Purpose:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Adds text at the end.
StringBuffer sb = new StringBuffer("Java");
[Link](" Programming");
[Link](sb);
Output:
Java Programming
🔹 2️⃣ insert()
Purpose:
Insert text at given index.
StringBuffer sb = new StringBuffer("Java");
[Link](4, " Language");
[Link](sb);
Output:
Java Language
🔹 3️⃣ replace()
Purpose:
Replace characters between indexes.
StringBuffer sb = new StringBuffer("Java");
[Link](1, 3, "oo");
[Link](sb);
Output:
Jooa
🔹 4️⃣ delete()
Purpose:
Deletes characters.
StringBuffer sb = new StringBuffer("Java");
[Link](1, 3);
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link](sb);
Output:
Ja
🔹 5️⃣ reverse()
Purpose:
Reverses string.
StringBuffer sb = new StringBuffer("Java");
[Link]();
[Link](sb);
Output:
avaJ
🔹 6️⃣ length()
[Link]([Link]());
🔹 7️⃣ capacity()
[Link]([Link]());
7️⃣ String vs StringBuffer
Feature String StringBuffer
Mutable ❌ No ✅ Yes
Thread Safe ✅ Yes ✅ Yes
Performance Slow Faster
Memory More objects Less objects
8️⃣ StringBuffer vs StringBuilder
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Feature StringBuffer StringBuilder
Thread Safe ✅ Yes ❌ No
Speed Slower Faster
Introduced Java 1.0 Java 1.5
9️⃣ Advantages of StringBuffer
Modifiable string
Thread-safe
Less memory usage
Suitable for concurrent programs
🔟 Disadvantages of StringBuffer
Slower due to synchronization
Not suitable for single-thread apps
1️⃣1️⃣ Real-Life Applications
Multi-threaded applications
Logging systems
String manipulation in servers
Chat applications
🌟 StringBuilder in Java
([Link])
1️⃣ What is StringBuilder?
StringBuilder is a predefined class in Java used to create modifiable (mutable)
strings.
👉 It is similar to StringBuffer, but NOT thread-safe and faster.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
StringBuilder sb = new StringBuilder("Java");
2️⃣ Why StringBuilder is Needed?
String → immutable (slow for changes)
StringBuffer → thread-safe but slow
StringBuilder → fast + mutable
Best for single-threaded applications
3️⃣ Important Features of StringBuilder
Mutable (can change)
Not synchronized
Faster than String & StringBuffer
Belongs to [Link] package
Introduced in Java 1.5
4️⃣ How StringBuilder Object is Created?
🔹 1️⃣ Empty StringBuilder
StringBuilder sb = new StringBuilder();
🔹 2️⃣ With String
StringBuilder sb = new StringBuilder("Hello");
🔹 3️⃣ With Capacity
StringBuilder sb = new StringBuilder(20);
5️⃣ Capacity in StringBuilder
Default capacity = 16
New capacity = (old capacity × 2) + 2
StringBuilder sb = new StringBuilder();
[Link]([Link]());
Output:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
16
6️⃣ Commonly Used StringBuilder Methods
🔹 1️⃣ append()
Purpose:
Adds text at the end.
StringBuilder sb = new StringBuilder("Java");
[Link](" Programming");
[Link](sb);
Output:
Java Programming
🔹 2️⃣ insert()
[Link](4, " Language");
[Link](sb);
Output:
Java Language
🔹 3️⃣ replace()
[Link](1, 3, "oo");
[Link](sb);
Output:
Jooa
🔹 4️⃣ delete()
[Link](1, 3);
[Link](sb);
Output:
Ja
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 5️⃣ reverse()
[Link]();
[Link](sb);
Output:
avaJ
🔹 6️⃣ length()
[Link]([Link]());
🔹 7️⃣ capacity()
[Link]([Link]());
7️⃣ String vs StringBuilder
Feature String StringBuilder
Mutable ❌ No ✅ Yes
Thread Safe ✅ Yes ❌ No
Performance Slow Fast
Memory More Less
8️⃣ StringBuffer vs StringBuilder
Feature StringBuffer StringBuilder
Thread Safe ✅ Yes ❌ No
Speed Slow Fast
Use Case Multi-thread Single-thread
9️⃣ Advantages of StringBuilder
Very fast
Less memory usage
Easy string manipulation
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Best for loops and frequent changes
🔟 Disadvantages of StringBuilder
Not thread-safe
Unsafe in multi-threaded programs
1️⃣1️⃣ Real-Life Applications
String concatenation in loops
Report generation
Data processing
Formatting text
🌟 Object Oriented Programming (OOP) Concepts
1️⃣ What is OOP?
Object Oriented Programming (OOP) is a programming approach where the
program is designed using objects and classes instead of only functions and logic.
👉 Object = real-world entity
👉 Class = blueprint of an object
🔹 Real-Life Example
Class → Student
Objects → Ram, Shyam, Sita
Properties → name, rollNo
Actions → study(), writeExam()
2️⃣ Why OOP is Needed?
Organizes large programs
Improves code reuse
Easy maintenance
Secure data handling
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Represents real-world problems easily
3️⃣ Main OOP Concepts in Java
Java supports 5 main OOP concepts:
1. Class
2. Object
3. Encapsulation
4. Inheritance
5. Polymorphism
6. Abstraction
(Java mainly focuses on first 5; abstraction is also very important)
🔹 1️⃣ Class
✔ Definition:
A class is a blueprint or template that defines:
Data (variables)
Methods (functions)
✔ Syntax:
class Student {
int rollNo;
String name;
void display() {
[Link](rollNo + " " + name);
}
}
✔ Features:
Logical structure
Does not occupy memory
Can create many objects
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 2️⃣ Object
✔ Definition:
An object is an instance of a class.
📌 Object occupies memory.
✔ Syntax:
Student s1 = new Student();
✔ Example Program:
class Student {
int rollNo = 1;
String name = "Amit";
void show() {
[Link](rollNo + " " + name);
}
public static void main(String args[]) {
Student s = new Student();
[Link]();
}
}
✔ Output:
1 Amit
🔹 3️⃣ Encapsulation
✔ Definition:
Encapsulation means binding data and methods together and hiding data from
outside.
👉 Achieved using:
private variables
public methods (getters/setters)
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Real-Life Example:
ATM machine – user cannot access internal process.
✔ Java Example:
class Account {
private int balance = 5000;
public int getBalance() {
return balance;
}
}
✔ Advantages:
Data security
Controlled access
Easy maintenance
✔ Disadvantages:
Slightly complex code
🔹 4️⃣ Inheritance
✔ Definition:
Inheritance means one class acquiring properties of another class.
👉 Parent class → Superclass
👉 Child class → Subclass
✔ Syntax:
class Parent {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
void show() {
[Link]("Parent class");
}
}
class Child extends Parent {
void display() {
[Link]("Child class");
}
}
✔ Example Program:
class Parent {
void msg() {
[Link]("Hello from Parent");
}
}
class Child extends Parent {
public static void main(String args[]) {
Child c = new Child();
[Link]();
}
}
✔ Output:
Hello from Parent
✔ Types of Inheritance in Java:
Single
Multilevel
Hierarchical
(Multiple inheritance not supported using classes; achieved using interfaces)
✔ Advantages:
Code reuse
Reduced redundancy
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Disadvantages:
Tight coupling
Complexity increases
🔹 5️⃣ Polymorphism
✔ Definition:
Polymorphism means many forms.
👉 Same method name, different behavior.
✔ Types:
1. Compile-time (Method Overloading)
2. Runtime (Method Overriding)
✔ Method Overloading Example:
class Add {
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
✔ Method Overriding Example:
class Animal {
void sound() {
[Link]("Animal sound");
}
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
public static void main(String args[]) {
Animal a = new Dog();
[Link]();
}
}
✔ Output:
Dog barks
✔ Advantages:
Flexibility
Code extensibility
🔹 6️⃣ Abstraction
✔ Definition:
Abstraction means hiding implementation details and showing only
functionality.
✔ Achieved Using:
Abstract class
Interface
✔ Abstract Class Example:
abstract class Shape {
abstract void draw();
}
class Circle extends Shape {
void draw() {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link]("Drawing Circle");
}
public static void main(String args[]) {
Shape s = new Circle();
[Link]();
}
}
✔ Output:
Drawing Circle
✔ Advantages:
Reduces complexity
Improves security
4️⃣ Advantages of OOP in Java
Modular code
Code reuse
Easy debugging
High security
Real-world mapping
5️⃣ Disadvantages of OOP
More memory usage
Slower execution
Learning complexity
6️⃣ Real-Life Applications of OOP
Banking systems
Online shopping
Student management systems
Mobile applications
Game development
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
7️⃣ OOP Summary Table
Concept Purpose
Class Blueprint
Object Instance
Encapsulation Data security
Inheritance Code reuse
Polymorphism Multiple behavior
Abstraction Hide details
Below are “Defining Classes and Objects in Java” explained in very simple English, step-by-step,
exam-oriented, with definition, features, syntax, example, full program and output.
(TYBSc IT / Mumbai University friendly 👍)
🌟 Defining Classes and Objects in Java
1️⃣ What is a Class?
🔹 Definition:
A class is a blueprint or template used to create objects.
It defines variables (data members) and methods (functions).
👉 A class does not occupy memory.
🔹 Real-Life Example:
Class → Car
Data → color, speed
Methods → drive(), stop()
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Features of Class:
Blueprint of objects
Logical entity
Can contain variables and methods
Supports data hiding
Reusability
🔹 Syntax of Class:
class ClassName {
// variables
// methods
}
2️⃣ What is an Object?
🔹 Definition:
An object is an instance of a class.
It represents a real-world entity.
👉 An object occupies memory.
🔹 Real-Life Example:
Class → Student
Objects → Ram, Shyam
🔹 Features of Object:
Instance of class
Occupies memory
Accesses class members
Has state and behavior
🔹 Syntax of Object:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
ClassName objectName = new ClassName();
3️⃣ Relationship Between Class and Object
Class Object
Blueprint Real object
Logical Physical
No memory Uses memory
Defines structure Uses structure
4️⃣ Simple Example (Concept)
class Student {
int rollNo;
String name;
}
Student → Class
rollNo, name → Variables
Student s = new Student();
s → Object
5️⃣ Complete Java Program with Class and Object
✔ Program:
class Student {
int rollNo;
String name;
void display() {
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
}
public static void main(String args[]) {
Student s1 = new Student(); // Object creation
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link] = 101;
[Link] = "Amit";
[Link]();
}
}
✔ Output:
Roll No: 101
Name: Amit
6️⃣ Explanation of Program (Step-by-Step)
1. class Student → class definition
2. int rollNo, String name → data members
3. display() → method
4. new Student() → object creation
5. [Link] = 101 → assigning values
6. [Link]() → method call
7️⃣ Advantages of Using Classes and Objects
Real-world representation
Code reusability
Easy maintenance
Data security
Modularity
8️⃣ Disadvantages
More memory usage
Slightly complex syntax for beginners
🌟 Instance Variables and Methods in Java
1️⃣ Instance Variables
🔹 Definition:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
An instance variable is a variable declared inside a class but outside any
method, constructor, or block.
Each object of the class has its own copy of instance variables.
Values of instance variables can differ for each object.
🔹 Features:
Declared inside class but outside methods
Also called non-static variables
Stored in heap memory
Initialized with default values if not explicitly assigned
Data Type Default Value
int 0
float 0.0
char '\u0000'
boolean false
Object null
🔹 Syntax:
class ClassName {
dataType variableName; // instance variable
}
🔹 Example:
class Student {
int rollNo; // instance variable
String name; // instance variable
}
2️⃣ Instance Methods
🔹 Definition:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
An instance method is a method that belongs to an object of a class.
Can access instance variables directly
Must be called using object reference
🔹 Features:
Declared inside class but outside other methods
Can access instance and local variables
Cannot use object without creation
🔹 Syntax:
class ClassName {
returnType methodName() {
// method body
}
}
3️⃣ Example Program: Instance Variables and Methods
class Student {
// Instance variables
int rollNo;
String name;
// Instance method
void display() {
[Link]("Roll No: " + rollNo);
[Link]("Name: " + name);
}
public static void main(String args[]) {
// Creating objects
Student s1 = new Student();
Student s2 = new Student();
// Assigning values
[Link] = 101;
[Link] = "Amit";
[Link] = 102;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link] = "Ravi";
// Calling instance method
[Link]();
[Link]();
}
}
✔ Output:
Roll No: 101
Name: Amit
Roll No: 102
Name: Ravi
4️⃣ Explanation:
1. rollNo and name → instance variables, each object has its own copy
2. display() → instance method, prints variable values
3. [Link]() → calls method for object s1
4. [Link]() → calls method for object s2
5️⃣ Advantages:
Each object has its own data
Can access object-specific behavior
Encapsulation support
6️⃣ Disadvantages:
More memory used if many objects
Object creation is necessary before use
7️⃣ Real-Life Example:
Instance Variable Object Example Instance Method
balance Bank account of Amit deposit(), withdraw()
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Instance Variable Object Example Instance Method
marks Student Ram's marks displayMarks()
color Car object Car1 startCar(), stopCar()
🌟 Constructor in Java
1️⃣ What is a Constructor?
🔹 Definition:
A constructor is a special method of a class that is automatically called when an
object is created.
👉 It is mainly used to initialize (give values to) instance variables.
🔹 Key Points:
Constructor name = Class name
No return type (not even void)
Called automatically using new keyword
2️⃣ Why Constructor is Needed?
To initialize object data
To reduce extra code
To ensure object starts in valid state
To simplify object creation
3️⃣ Features of Constructor
Same name as class
No return type
Automatically invoked
Can be overloaded
Executes only once per object
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
4️⃣ Syntax of Constructor
class ClassName {
ClassName() {
// constructor body
}
}
5️⃣ Types of Constructors in Java
Java mainly has 3 types of constructors:
1. Default Constructor
2. No-Argument Constructor
3. Parameterized Constructor
🔹 1️⃣ Default Constructor
✔ Definition:
A default constructor is provided by the Java compiler if no constructor is
written.
Initializes variables with default values
✔ Example:
class Test {
int x;
public static void main(String args[]) {
Test t = new Test();
[Link](t.x);
}
}
✔ Output:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 2️⃣ No-Argument Constructor
✔ Definition:
A no-argument constructor is written by the programmer and takes no
parameters.
✔ Example Program:
class Student {
int rollNo;
String name;
Student() {
rollNo = 101;
name = "Amit";
}
void display() {
[Link](rollNo + " " + name);
}
public static void main(String args[]) {
Student s = new Student();
[Link]();
}
}
✔ Output:
101 Amit
🔹 3️⃣ Parameterized Constructor
✔ Definition:
A constructor that accepts parameters to initialize values.
✔ Example Program:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
class Student {
int rollNo;
String name;
Student(int r, String n) {
rollNo = r;
name = n;
}
void display() {
[Link](rollNo + " " + name);
}
public static void main(String args[]) {
Student s1 = new Student(101, "Amit");
Student s2 = new Student(102, "Ravi");
[Link]();
[Link]();
}
}
✔ Output:
101 Amit
102 Ravi
6️⃣ Constructor Overloading
🔹 Definition:
Having more than one constructor in a class with different parameters.
✔ Example:
class Demo {
int x;
int y;
Demo() {
x = 0;
y = 0;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
}
Demo(int a, int b) {
x = a;
y = b;
}
void display() {
[Link](x + " " + y);
}
public static void main(String args[]) {
Demo d1 = new Demo();
Demo d2 = new Demo(10, 20);
[Link]();
[Link]();
}
}
✔ Output:
00
10 20
7️⃣ Difference Between Constructor and Method
Constructor Method
Same name as class Any name
No return type Has return type
Called automatically Called manually
Used for initialization Used for operations
8️⃣ Advantages of Constructor
Initializes objects easily
Reduces coding effort
Improves code readability
Ensures valid object state
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
9️⃣ Disadvantages of Constructor
Cannot be inherited
Cannot be overridden
Limited flexibility
🔟 Real-Life Example
Real Life Constructor
Mobile phone setup Initial settings
Bank account opening Initial balance
Student admission Roll no assignment
1️⃣1️⃣ One-Line Exam Definition
A constructor is a special method used to initialize objects in Java.
🌟 this Keyword in Java
1️⃣ What is this Keyword?
🔹 Definition:
this is a reference variable that refers to the current object of the class.
👉 It is used inside instance methods or constructors.
🔹 Simple Meaning:
this = current object
Used to avoid confusion between instance variables and parameters
2️⃣ Why this Keyword is Needed?
To differentiate instance variables from local variables
To call current class methods
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
To call current class constructor
To pass current object as parameter
3️⃣ Uses of this Keyword in Java
Java this keyword is mainly used in 5 ways:
1. Refer instance variable
2. Call current class method
3. Call current class constructor
4. Pass current object as argument
5. Return current object
🔹 1️⃣ Using this to Refer Instance Variable
✔ Problem Without this:
class Student {
int rollNo;
Student(int rollNo) {
rollNo = rollNo; // confusion
}
}
❌ Instance variable not assigned
✔ Correct Using this:
class Student {
int rollNo;
Student(int rollNo) {
[Link] = rollNo;
}
public static void main(String args[]) {
Student s = new Student(101);
[Link]([Link]);
}
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Output:
101
🔹 2️⃣ Using this to Call Current Class Method
class Demo {
void show() {
[Link]("Show method");
}
void display() {
[Link](); // calls current class method
}
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
}
}
✔ Output:
Show method
4️⃣ Features of this Keyword
Refers to current object
Used inside instance context
Avoids naming conflict
Improves readability
Cannot be used in static context
5️⃣ Advantages of this Keyword
Clear distinction between variables
Supports constructor chaining
Cleaner and readable code
Helps in object-oriented design
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
6️⃣ Disadvantages of this Keyword
Confusing for beginners
Cannot be used inside static methods
7️⃣ Real-Life Example
Without this:
Teacher calls student name → confusion
With this:
Teacher calls this student → clear
8️⃣ Difference: this vs super
this super
Refers to current class Refers to parent class
Access current variables Access parent variables
Calls current constructor Calls parent constructor
🌟 super Keyword in Java
1️⃣ What is super Keyword?
🔹 Definition:
super is a reference keyword used to refer to the immediate parent class
object.
👉 It is mainly used in inheritance.
🔹 Simple Meaning:
super = parent class
Used to access parent class variables, methods, and constructors
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
2️⃣ Why super Keyword is Needed?
To access parent class data members
To call parent class methods
To call parent class constructor
To avoid name conflict between parent and child class
3️⃣ Uses of super Keyword in Java
Java super keyword is used in 3 main ways:
1. Refer parent class variable
2. Call parent class method
3. Call parent class constructor
🔹 1️⃣ Using super to Refer Parent Class Variable
✔ Problem Without super:
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
[Link](x); // prints child x
}
}
✔ Correct Using super:
class Parent {
int x = 10;
}
class Child extends Parent {
int x = 20;
void show() {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link](super.x);
}
public static void main(String args[]) {
Child c = new Child();
[Link]();
}
}
✔ Output:
10
🔹 2️⃣ Using super to Call Parent Class Method
class Parent {
void display() {
[Link]("Parent display");
}
}
class Child extends Parent {
void display() {
[Link]("Child display");
}
void show() {
[Link](); // calls parent method
}
public static void main(String args[]) {
Child c = new Child();
[Link]();
}
}
✔ Output:
Parent display
🔹 3️⃣ Using super to Call Parent Class Constructor
👉 Constructor calling parent constructor is called Constructor Chaining.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Example:
class Parent {
Parent() {
[Link]("Parent Constructor");
}
}
class Child extends Parent {
Child() {
super(); // calls parent constructor
[Link]("Child Constructor");
}
public static void main(String args[]) {
new Child();
}
}
✔ Output:
Parent Constructor
Child Constructor
📌 Rule: super() must be first statement in constructor.
4️⃣ Features of super Keyword
Refers to immediate parent class
Used only in inheritance
Cannot be used in static context
Helps in constructor chaining
Improves clarity
5️⃣ Advantages of super Keyword
Avoids name conflict
Reuses parent class code
Supports polymorphism
Makes code readable
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
6️⃣ Disadvantages of super Keyword
Works only with inheritance
Cannot access private members directly
7️⃣ Real-Life Example
Child calling parent guidance
Employee using company rules
Student using college policies
8️⃣ Difference Between this and super
this super
Refers current class Refers parent class
Access current variables Access parent variables
Calls current constructor Calls parent constructor
Used within same class Used in subclass
🌟 Scope Rules in Java
🔹 What is Scope?
✅ Definition:
Scope means where a variable, method, or object can be accessed in a
program.
👉 It decides:
From where a variable can be used
How long a variable exists
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Why Scope Rules Are Important?
Avoids name conflicts
Saves memory
Improves security
Makes program easy to understand
🔹 Types of Scope in Java
Java has 4 main scope rules:
1. Class Scope
2. Instance Scope
3. Static Scope
4. Local Scope
1️⃣ Class Scope
🔹 Definition:
Variables declared inside a class but outside all methods have class scope.
🔹 Features:
Accessible to all methods of the class
Exists as long as object or class exists
🔹 Syntax:
class Demo {
int x = 10; // class scope
}
🔹 Example Program:
class Demo {
int x = 10;
void show() {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link](x);
}
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
}
}
✔ Output:
10
🔹 Real-Life Use:
Student roll number, employee ID
2️⃣ Instance Scope (Instance Variables)
🔹 Definition:
Instance variables are declared inside class and are different for each object.
🔹 Features:
Belong to object
Created when object is created
Destroyed when object is destroyed
🔹 Example:
class Student {
int marks;
public static void main(String args[]) {
Student s1 = new Student();
Student s2 = new Student();
[Link] = 80;
[Link] = 90;
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link]([Link]);
[Link]([Link]);
}
}
✔ Output:
80
90
🔹 Real-Life Use:
Each student’s marks
3️⃣ Static Scope (Static Variables)
🔹 Definition:
Static variables belong to the class, not to objects.
🔹 Features:
Declared using static keyword
Shared among all objects
Single copy in memory
🔹 Syntax:
class Demo {
static int count = 0;
}
🔹 Example:
class Demo {
static int count = 0;
Demo() {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
count++;
}
public static void main(String args[]) {
Demo d1 = new Demo();
Demo d2 = new Demo();
Demo d3 = new Demo();
[Link](count);
}
}
✔ Output:
🔹 Real-Life Use:
Number of users, shared settings
4️⃣ Local Scope (Local Variables)
🔹 Definition:
Local variables are declared inside methods, loops, or blocks.
🔹 Features:
Accessible only inside the block
No default value
Must be initialized before use
🔹 Syntax:
void show() {
int x = 10; // local scope
}
🔹 Example:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
class Demo {
void show() {
int x = 10;
[Link](x);
}
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
}
}
✔ Output:
10
🔹 Real-Life Use:
Temporary calculations
5️⃣ Block Scope
🔹 Definition:
Variables declared inside { } block (if, for, while).
🔹 Example:
class Demo {
public static void main(String args[]) {
if (true) {
int x = 5;
[Link](x);
}
}
}
✔ Output:
❌ x cannot be used outside if block.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
6️⃣ Method Scope
🔹 Definition:
Variables declared inside a method exist only within that method.
🔹 Example:
class Demo {
void display() {
int y = 20;
[Link](y);
}
}
🔁 Variable Priority Rule (Very Important)
When variables have same name:
Priority Order:
Local variable > Instance variable > Static variable
🔹 Example:
class Demo {
int x = 10;
void show() {
int x = 20;
[Link](x);
}
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
}
}
✔ Output:
20
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Using this to Access Instance Variable
class Demo {
int x = 10;
void show() {
int x = 20;
[Link](this.x);
}
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
}
}
✔ Output:
10
📊 Summary Table
Scope Type Where Declared Accessible
Class Inside class Whole class
Instance Inside class Object methods
Static Inside class All objects
Local Inside method That block
Block Inside {} Block only
👍 Advantages of Scope Rules
Prevents errors
Improves readability
Better memory management
Secure data access
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
👎 Disadvantages
Wrong scope causes errors
Variable shadowing confusion
Access Specifier :
🔹 What is an Access Specifier?
✅ Definition:
Access Specifiers are keywords used in Java to control the visibility (scope) of
classes, variables, methods, and constructors.
👉 They decide:
Who can access a member
From where it can be accessed
Note: In Java, Access Specifier and Access Modifier mean the same thing.
🔹 Why Access Specifiers are Needed?
For data security
To support encapsulation
To avoid unauthorized access
To manage large programs easily
🔹 Types of Access Specifiers in Java
Java provides four access specifiers:
1️⃣ public
2️⃣ protected
3️⃣ default (no keyword)
4️⃣ private
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
📊 Access Control Table
Subclass
Access Same Same Other
(Other
Specifier Class Package Classes
Package)
public ✔ ✔ ✔ ✔
protected ✔ ✔ ✔ ❌
default ✔ ✔ ❌ ❌
private ✔ ❌ ❌ ❌
1️⃣ Public Access Specifier
🔹 Definition:
public members can be accessed from anywhere in the program.
🔹 Syntax:
public class Demo {
public int x = 10;
}
🔹 Example Program:
class Demo {
public int x = 10;
public static void main(String args[]) {
Demo d = new Demo();
[Link](d.x);
}
}
✔ Output:
10
🔹 Features:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Maximum visibility
No access restriction
🔹 Real-Life Use:
Library functions, APIs
🔹 Advantages:
Easy access
High reusability
🔹 Disadvantages:
Less data security
2️⃣ Private Access Specifier
🔹 Definition:
private members are accessible only within the same class.
🔹 Syntax:
class Demo {
private int x = 10;
}
🔹 Example Program:
class Demo {
private int x = 10;
void show() {
[Link](x);
}
public static void main(String args[]) {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Demo d = new Demo();
[Link]();
}
}
✔ Output:
10
❌ d.x is not allowed outside the class.
🔹 Features:
Highest security
Supports data hiding
🔹 Real-Life Use:
ATM PIN, Password
🔹 Advantages:
Prevents misuse of data
Improves security
🔹 Disadvantages:
Cannot be accessed outside class
3️⃣ Default Access Specifier
🔹 Definition:
If no access specifier is written, Java uses default access.
🔹 Syntax:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
class Demo {
int x = 10; // default access
}
🔹 Example:
class Demo {
int x = 10;
public static void main(String args[]) {
Demo d = new Demo();
[Link](d.x);
}
}
✔ Output:
10
🔹 Features:
Accessible only within the same package
🔹 Real-Life Use:
Internal package logic
🔹 Advantages:
Controlled package-level access
🔹 Disadvantages:
Not accessible outside package
4️⃣ Protected Access Specifier
🔹 Definition:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
protected members are accessible:
In the same package
In subclasses, even in other packages
🔹 Syntax:
class Demo {
protected int x = 10;
}
🔹 Example Program:
class Parent {
protected int x = 10;
}
class Child extends Parent {
void show() {
[Link](x);
}
public static void main(String args[]) {
Child c = new Child();
[Link]();
}
}
✔ Output:
10
🔹 Features:
Useful in inheritance
Moderate access control
🔹 Real-Life Use:
Bank details shared with child classes
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Advantages:
Supports inheritance
Controlled access
🔹 Disadvantages:
Slightly complex
🚫 Access Specifiers for Classes
Specifier Allowed for Class?
public ✔
default ✔
private ❌
protected ❌
👉 Top-level classes can only be public or default.
� Key Points to Remember
private → only same class
default → same package
protected → package + subclass
public → everywhere
Access Modifier:
Pending
🌟 Constant in Java
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 What is a Constant?
✅ Definition:
A constant is a variable whose value cannot be changed once it is assigned.
👉 In Java, constants are created using the final keyword.
🔹 Why Constants are Needed?
To protect fixed values
To avoid accidental changes
To make code easy to understand
To improve security and readability
🔹 How to Declare a Constant in Java?
🔹 Syntax:
final dataType CONSTANT_NAME = value;
🔹 Example:
final int MAX = 100;
❌ MAX = 200; → Error (value cannot be changed)
🔹 Rules for Constants in Java
1. Must use final keyword
2. Value cannot be modified
3. Usually written in UPPERCASE
4. Must be initialized once
5. Cannot be reassigned
🔹 Types of Constants in Java
1️⃣ Instance Constant
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Declared inside class (non-static)
class Demo {
final int x = 10;
public static void main(String args[]) {
Demo d = new Demo();
[Link](d.x);
}
}
✔ Output:
10
2️⃣ Static Constant (Most Common)
🔹 Declared using static final
class Demo {
static final int MAX = 50;
public static void main(String args[]) {
[Link](MAX);
}
}
✔ Output:
50
3️⃣ Local Constant
🔹 Declared inside method
class Demo {
public static void main(String args[]) {
final int x = 20;
[Link](x);
}
}
✔ Output:
20
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Constant vs Variable (Very Important)
Variable Constant
Value can change Value cannot change
No final keyword Uses final keyword
Flexible Fixed
🔹 Constant with Reference Variable
final int a = 10;
✔ Value cannot change
final int[] arr = {1,2,3};
arr[0] = 9; // allowed
✔ Reference fixed, content change allowed
🔹 Example Program
class Circle {
static final double PI = 3.14;
public static void main(String args[]) {
int r = 5;
double area = PI * r * r;
[Link](area);
}
}
✔ Output:
78.5
🔹 Real-Life Examples of Constants
PI value (3.14)
Maximum marks (100)
Number of days in a week (7)
Speed of light
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
👍 Advantages of Constants
Prevents modification
Improves code clarity
Increases security
Easy maintenance
👎 Disadvantages of Constants
Cannot change value later
Less flexible
🌟 Static Members of a Class in Java
🔹 What are Static Members?
✅ Definition:
Static members are variables, methods, or blocks that belong to the class itself,
not to any object.
👉 Declared using the static keyword.
🔹 Why Static Members are Used?
To share data among all objects
To save memory
When data or method is common for all objects
🔹 Types of Static Members
Java has three static members:
1️⃣ Static Variable
2️⃣ Static Method
3️⃣ Static Block
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
1️⃣ Static Variable
🔹 Definition:
A static variable is a variable that is shared by all objects of a class.
🔹 Features:
Single copy in memory
Belongs to class
Accessed using class name
🔹 Syntax:
class Demo {
static int count = 0;
}
🔹 Example Program:
class Demo {
static int count = 0;
Demo() {
count++;
}
public static void main(String args[]) {
Demo d1 = new Demo();
Demo d2 = new Demo();
Demo d3 = new Demo();
[Link](count);
}
}
✔ Output:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Real-Life Use:
Total number of students, shared settings
2️⃣ Static Method
🔹 Definition:
A static method belongs to the class, not to objects.
🔹 Features:
Can be called without creating object
Can access only static members
Cannot use this keyword
🔹 Syntax:
class Demo {
static void show() {
[Link]("Static method");
}
}
🔹 Example Program:
class Demo {
static void show() {
[Link]("Hello Static");
public static void main(String args[]) {
[Link]();
}
}
✔ Output:
Hello Static
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Real-Life Use:
Utility methods ([Link](), [Link]())
3️⃣ Static Block
🔹 Definition:
A static block is used to initialize static variables.
🔹 Features:
Executes only once
Runs when class is loaded
Used for complex initialization
🔹 Syntax:
static {
// code
}
🔹 Example Program:
class Demo {
static int x;
static {
x = 10;
[Link]("Static block executed");
}
public static void main(String args[]) {
[Link](x);
}
}
✔ Output:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Static block executed
10
🔹 Accessing Static Members
Member Access Method
Static Variable [Link]
Static Method [Link]()
Example:
[Link];
[Link]();
🔹 Static vs Instance Members (Important)
Static Members Instance Members
Belong to class Belong to object
Single copy Multiple copies
Access via class Access via object
Memory efficient More memory
👍 Advantages of Static Members
Saves memory
Easy access
Shared data
👎 Disadvantages of Static Members
Cannot access non-static members directly
Less flexible
Not suitable for object-specific data
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
♻️ Garbage Collection in Java
🔹 What is Garbage Collection?
✅ Definition:
Garbage Collection (GC) is an automatic process in Java that removes unused
objects from memory.
👉 It frees heap memory by destroying objects that are no longer needed.
🔹 Why Garbage Collection is Needed?
To free unused memory
To avoid memory leakage
To improve program performance
Programmer does not need to delete objects manually
🔹 What is Garbage in Java?
🔹 Definition:
An object is called garbage when it is no longer referenced by any variable.
Demo d = new Demo();
d = null; // object becomes garbage
🔹 How Java Garbage Collection Works (Step-by-Step)
1️⃣ Objects are created in Heap memory
2️⃣ JVM checks which objects are not reachable
3️⃣ Unused objects are marked as garbage
4️⃣ Garbage Collector removes them
5️⃣ Memory is freed automatically
🔹 When is an Object Eligible for Garbage Collection?
An object becomes eligible when:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
1️⃣ Null Reference
Demo d = new Demo();
d = null;
2️⃣ Reassigning Reference
Demo d1 = new Demo();
Demo d2 = new Demo();
d1 = d2; // first object becomes garbage
3️⃣ Object Created Inside Method
void show() {
Demo d = new Demo();
} // object destroyed after method ends
4️⃣ Anonymous Object
new Demo();
🔹 Garbage Collector in Java
🔹 Definition:
Garbage Collector is a JVM program that automatically cleans unused objects.
👉 Programmer cannot control it directly.
🔹 Methods Related to Garbage Collection
1️⃣ [Link]()
Requests JVM to run garbage collection.
[Link]();
⚠️ Not guaranteed to run immediately.
2️⃣ finalize() Method
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Called before object is destroyed.
class Demo {
protected void finalize() {
[Link]("Object destroyed");
}
}
⚠️ Deprecated in newer Java versions.
🔹 Example Program
class Demo {
public static void main(String args[]) {
Demo d1 = new Demo();
Demo d2 = new Demo();
d1 = null;
d2 = null;
[Link]();
[Link]("End of program");
}
}
✔ Output (may vary):
End of program
🔹 Types of Garbage Collectors (Short Idea)
Serial GC
Parallel GC
CMS (Concurrent Mark Sweep)
G1 (Garbage First)
👉 JVM chooses automatically.
🔹 Real-Life Example
🗑️ Dustbin Cleaning
Used items → keep
Unused items → throw away
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Same as GC removes unused objects.
👍 Advantages of Garbage Collection
Automatic memory management
Prevents memory leaks
Safer and reliable
Improves productivity
👎 Disadvantages of Garbage Collection
No control over timing
Can affect performance
Not suitable for real-time systems
� Key Points for Exam
GC works only on Heap memory
Objects are removed when no reference exists
Programmer cannot force GC
Java handles memory automatically
📊 Summary Table
Term Meaning
Garbage Unused object
GC Removes unused objects
Heap Object memory area
[Link]() Request GC
finalize() Before destruction
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Inheritance in Java
🔹 What is Inheritance?
✅ Definition:
Inheritance is an OOP concept where one class acquires (inherits) the
properties and methods of another class.
👉 It supports code reusability.
🔹 Why Inheritance is Needed?
Reuse existing code
Reduce duplication
Improve maintainability
Supports IS-A relationship
🔹 Superclass and Subclass
🔹 Superclass (Parent Class):
The class whose properties are inherited.
🔹 Subclass (Child Class):
The class that inherits properties from superclass.
🔹 Syntax:
class Superclass {
// data and methods
}
class Subclass extends Superclass {
// extra data and methods
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Example:
class Animal { // Superclass
void eat() {
[Link]("Eating");
}
}
class Dog extends Animal { // Subclass
void bark() {
[Link]("Barking");
}
public static void main(String args[]) {
Dog d = new Dog();
[Link]();
[Link]();
}
}
✔ Output:
Eating
Barking
🔹 Types of Inheritance in Java
Java supports 5 types (using classes & interfaces):
1️⃣ Single Inheritance
2️⃣ Multilevel Inheritance
3️⃣ Hierarchical Inheritance
4️⃣ Multiple Inheritance (using Interface)
5️⃣ Hybrid Inheritance (using Interface)
1️⃣ Single Inheritance
🔹 Definition:
One subclass inherits from one superclass.
🔹 Structure:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
A→B
🔹 Example:
class A {
void show() {
[Link]("Class A");
}
}
class B extends A {
public static void main(String args[]) {
B obj = new B();
[Link]();
}
}
✔ Output:
Class A
🔹 Real-Life Use:
Person → Student
2️⃣ Multilevel Inheritance
🔹 Definition:
A class inherits from another subclass.
🔹 Structure:
A→B→C
🔹 Example:
class A {
void showA() {
[Link]("Class A");
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
}
}
class B extends A {
void showB() {
[Link]("Class B");
}
}
class C extends B {
public static void main(String args[]) {
C obj = new C();
[Link]();
[Link]();
}
}
✔ Output:
Class A
Class B
🔹 Real-Life Use:
Living Being → Human → Student
3️⃣ Hierarchical Inheritance
🔹 Definition:
Multiple subclasses inherit from one superclass.
🔹 Structure:
A
/\
B C
🔹 Example:
class A {
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
void show() {
[Link]("Class A");
}
}
class B extends A {
void display() {
[Link]("Class B");
}
}
class C extends A {
void print() {
[Link]("Class C");
}
public static void main(String args[]) {
B obj1 = new B();
C obj2 = new C();
[Link]();
[Link]();
}
}
✔ Output:
Class A
Class A
🔹 Real-Life Use:
Vehicle → Car, Bike
4️⃣ Multiple Inheritance (Using Class)
Not possible by class
🔹 Important Rules of Inheritance
Uses extends keyword
One class can extend only one class
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Supports method overriding
Constructors are not inherited
private members are not inherited
👍 Advantages of Inheritance
Code reusability
Easy maintenance
Reduces redundancy
Supports polymorphism
👎 Disadvantages of Inheritance
Tight coupling
Reduced flexibility
Increases complexity
📊 Summary Table
Term Meaning
Inheritance Acquiring properties
Superclass Parent class
Subclass Child class
extends Keyword
implements Interface keyword
🌟 final Method and final Class in Java
🔹 What does final keyword mean?
✅ Definition:
The final keyword is used to restrict modification.
👉 Depending on where it is used:
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
final variable → value cannot change
final method → cannot be overridden
final class → cannot be inherited
🔒 1️⃣ Final Method
🔹 Definition:
A final method is a method that cannot be overridden by a subclass.
🔹 Why Final Method is Used?
To prevent method modification
To maintain original logic
To provide security
🔹 Syntax:
class A {
final void show() {
[Link]("Final method");
}
}
🔹 Example Program:
class A {
final void show() {
[Link]("Class A method");
}
}
class B extends A {
// ❌ Not allowed
// void show() { }
}
✔ Compilation Error if overridden
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Valid Program:
class A {
final void show() {
[Link]("Final method executed");
}
}
class B extends A {
public static void main(String args[]) {
B obj = new B();
[Link]();
}
}
✔ Output:
Final method executed
🔹 Rules of Final Method
Cannot be overridden
Can be inherited
Can be overloaded
Can be called normally
🔹 Real-Life Use:
Security check methods, authentication logic
👍 Advantages of Final Method
Prevents misuse
Ensures fixed behavior
Improves security
👎 Disadvantages of Final Method
Less flexibility
Cannot modify behavior in subclass
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🛑 2️⃣ Final Class
🔹 Definition:
A final class is a class that cannot be inherited.
🔹 Why Final Class is Used?
To prevent inheritance
To avoid misuse
For security reasons
🔹 Syntax:
final class Demo {
}
🔹 Example Program:
final class Demo {
void show() {
[Link]("Final class method");
}
}
class Test {
public static void main(String args[]) {
Demo d = new Demo();
[Link]();
}
}
✔ Output:
Final class method
🔹 Invalid Example:
final class A {
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
// ❌ Not allowed
class B extends A {
}
✔ Compilation Error
🔹 Rules of Final Class
Cannot be inherited
Can contain final or non-final methods
Object creation is allowed
🔹 Real-Life Use:
String, Math, Wrapper classes
👍 Advantages of Final Class
High security
Prevents modification
Easy to maintain
👎 Disadvantages of Final Class
No inheritance
Reduced reusability
📊 Final Method vs Final Class (Very Important)
Feature Final Method Final Class
Prevents overriding ✔ ❌
Prevents inheritance ❌ ✔
Can be inherited ✔ ❌
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
Feature Final Method Final Class
Used for Fix method Fix class
🌟 Polymorphism in Java
🔹 What is Polymorphism?
✅ Definition:
Polymorphism means “many forms”.
👉 In Java, one method or object behaves differently in different situations.
🔹 Why Polymorphism is Needed?
Improves code flexibility
Supports method reuse
Makes program easy to extend
Important OOP concept
🔹 Types of Polymorphism in Java
Java supports two types:
1️⃣ Compile-time Polymorphism
2️⃣ Run-time Polymorphism
� 1️⃣ Compile-Time Polymorphism
🔹 Definition:
Compile-time polymorphism is achieved when method call is resolved at compile
time.
👉 Also called Static Polymorphism.
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 How it is Achieved?
Method Overloading
Operator Overloading (limited in Java)
🔹 Method Overloading
🔹 Definition:
Multiple methods with same name but different parameters.
🔹 Rules:
Same method name
Different number or type of parameters
Return type alone is not enough
🔹 Syntax:
class Demo {
void add(int a, int b) { }
void add(int a, int b, int c) { }
}
🔹 Example Program:
class Demo {
void add(int a, int b) {
[Link](a + b);
}
void add(int a, int b, int c) {
[Link](a + b + c);
}
public static void main(String args[]) {
Demo d = new Demo();
[Link](10, 20);
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
[Link](10, 20, 30);
}
}
✔ Output:
30
60
🔹 Real-Life Example:
Calculator add() method
👍 Advantages:
Fast execution
Less confusion at runtime
👎 Disadvantages:
Less flexibility
🔄 2️⃣ Run-Time Polymorphism
🔹 Definition:
Run-time polymorphism is achieved when method call is resolved at runtime.
👉 Also called Dynamic Polymorphism.
🔹 How it is Achieved?
Method Overriding
Inheritance
Upcasting
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
🔹 Method Overriding
🔹 Definition:
Subclass provides its own implementation of a method already defined in
superclass.
🔹 Rules:
Same method name
Same parameters
IS-A relationship (inheritance)
Cannot override final method
🔹 Syntax:
class A {
void show() { }
}
class B extends A {
void show() { }
}
🔹 Example Program:
class Animal {
void sound() {
[Link]("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
[Link]("Dog barks");
}
public static void main(String args[]) {
Animal a = new Dog(); // upcasting
[Link]();
}
}
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming
✔ Output:
Dog barks
🔹 Real-Life Example:
Vehicle → Car → Bike
👍 Advantages:
High flexibility
Supports dynamic behavior
👎 Disadvantages:
Slightly slower than compile-time
More complex
📊 Compile-Time vs Run-Time Polymorphism (Very Important)
Feature Compile-Time Run-Time
Binding Early Late
Achieved by Overloading Overriding
Inheritance Not required Required
Flexibility Less More
Speed Faster Slower
SYBSC IT - NEP Asst. Prof. Pradnya Nehete Java Programming