Unit - 1 Java
Unit - 1 Java
Class ek template (pre-defined structure) ya blueprint hoti hai jisse objects banaye jate hain.
Class fields (data) aur methods (procedure ya function) ka collection hoti hai jo us data par kaam karte
hain.
class keyword ka use kisi bhi class ko create karne ke liye kiya jata hai.
A class is template (pre-defined structure) or blueprint from which objects are made.
A class is a collection of fields (data) and methods (procedure or function) that operate
on that data.
“class” keyword is used to create any class.
(A.K.T.U 2023 - 24)
Class Room
{
int length; // instance Variable
int height; // instance Variable
Constructor
Constructor special methods hote hain jo automatically call ho jate hain jab class ka object create hota hai.
Java me constructor ka naam us class ke naam jaisa hi hota hai jisme wo define kiya gaya ho. Constructor ki
syntax me return type include nahi hota, kyunki constructor directly koi value return nahi karta. Lekin constructor
ka implicit return type us class ka type hi hota hai. Constructor me different types ke parameters ho sakte hain.
(A.K.T.U 2023–24)
Jab constructor ko new operator ke through invoke kiya jata hai, to type wahi match hona chahiye jo constructor
definition me specify kiya gaya ho.
Java me objects create hote time khud ko initialize kar sakte hain.
Constructor are special methods that are called automatically when an object of the
class is created.
A java constructor has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type, since constructor directly never
return a value, but the implicit return type of a class’ constructor is the class type itself.
Constructor may include parameter of various type. (A.K.T.U 2023 - 24)
When the constructor is invoked using the new operator, the type must match those
that are specified in the constructor definition.
• Default Constructor:
Agar aap class ke liye koi constructor define nahi karte, to compiler automatically ek
default parameter-less constructor create kar deta hai. Default constructor sirf tabhi
create hota hai jab class me koi constructor define na ho. Agar aap apni class me koi bhi
constructor define kar dete hain, to phir default constructor automatically create nahi
hota.
• Parameterized Constructor:
Jab constructor parameters leta hai aur object create hote time kuch values ke saath
initialize hota hai, to use parameterized constructor kehte hain.
• Copy Constructor:
Jaise naam se pata chalta hai, copy constructor ek naya object create karta hai jo already
existing object ki duplicate copy hota hai.
• Copy Constructor: As the name implies, a copy constructor creates a new instance
or object to be a duplicate of an already existing one
import [Link].*;
class Coding_Club {
// Default Constructor
Coding_Club(){
[Link]("Default constructor");
}
public static void main(String[] args){
Coding_Club obj = new Coding_Club();
}
}
class Coding_Club {
// Parameterized Constructor
Coding_Club(String name, int id)
{
[Link] = name;
[Link] = id;
}
// Method to display object data
void display(){
Method
Java me method code ka ek block hota hai jo ek specific task perform karta hai aur sirf tab run
hota hai jab use call kiya jata hai.
Methods ka use code ko reuse karne, readability improve karne, aur code ko logical aur
manageable sections me organize karne ke liye kiya jata hai.
Java me sabhi functions ko methods kaha jata hai, kyunki unhe hamesha kisi class ke andar hi
define kiya jata hai
A method in Java is a block of code that performs a specific task and only runs when it is
called.
Methods are used to reuse code, improve readability, and organize code into logical,
manageable sections.
In Java, all functions are methods as they must be defined within a class.
Method’s Categories
For Example:-
void show( ) {
}
2. Void return type, with parameters
}
3. Other then void return type, no parameters
int show( ) {
Access Specifiers
Access Specifiers (ya Access Modifiers) keywords hote hain jo classes, interfaces, variables,
methods aur constructors ki accessibility (scope) set karne ke liye use kiye jate hain.
Access Specifiers (also known as access modifiers) are keywords used to set the
accessibility (scope) of classes, interfaces, variables, methods, and constructors.
They are crucial for implementing the principle of encapsulation and controlling which
parts of a program can interact with specific data or functionality.
default (Package-Private)
2. public
3. protected
4. private
1. default (Package-Private)
Agar class, method ya variable ke liye koi access modifier specify nahi kiya jata, to uska default
access hota hai. Iska matlab hai ki wo sirf same package ke andar wali classes ke dwara hi access
kiya ja sakta hai.
Usage:
Ye internal utility classes ya methods ke liye ideal hota hai jo package ke bahar expose karne ke
liye nahi hote.
If no access modifier is specified for a class, method, or variable, it has default access.
This means it is only accessible by other classes within the same package.
Usage:
Ideal for internal utility classes or methods that are not meant to be exposed outside
the package.
2. public
Public modifier ka scope sabse wide hota hai. Jo classes, methods ya variables public declare
kiye jate hain, unhe Java application me kahin se bhi access kiya ja sakta hai.
Usage:
Ye un methods ke liye best hota hai jo class ka main interface ya API provide karte hain, jise
system ke dusre parts ya external applications use kar sakte hain.
The public modifier has the widest scope. Classes, methods, or variables declared
as public are accessible from anywhere in the Java application.
Usage: Best for methods that provide the main interface or API for a class, intended to
be used by other parts of the system or external applications.
3. protected:
Protected modifier private aur public access ke beech balance provide karta hai.
Protected members same package ke andar access kiye ja sakte hain aur subclasses
(child classes) ke dwara bhi access kiye ja sakte hain, chahe subclass kisi dusre
package me hi kyu na ho.
The protected modifier provides a balance between private and public access.
Protected members are accessible within the same package and also by subclasses
(child classes), even if the subclass is in a different package.
4. private
Private modifier sabse zyada restrictive hota hai. Jo members private declare kiye jate hain,
unhe sirf usi class ke andar access kiya ja sakta hai jisme wo declare kiye gaye hain.
Usage:
Ye sensitive data (fields) ke liye commonly use hota hai taaki data integrity maintain rahe. Aksar
ise public getter aur setter methods ke through access aur modify kiya jata hai, jisse controlled
access (encapsulation) milta hai.
The private modifier is the most restrictive. Members declared as private are only
accessible within the same class in which they are declared.
Usage:
Commonly used for sensitive data (fields) to ensure data integrity, often accessed and
modified via public getter and setter methods to provide controlled access
(encapsulation).
Memory sirf ek baar allocate hoti hai jab class load hoti hai.
Static members ko access karne ke liye object create karne ki zarurat nahi hoti, unhe direct class
name se access kiya ja sakta hai. Static methods aur variables directly non-static members ko
access nahi kar sakte.
Static methods override nahi ho sakte, kyunki ye instances ki jagah class se belong karte hain.
The static keyword in Java is used for memory management and belongs to the class
rather than any specific instance. It allows members (variables, methods, blocks, and
nested classes) to be shared among all objects of a class.
1. Static Variables
Static variable ko class variable bhi kaha jata hai. Ye class ke sabhi instances (objects) ke
beech share hota hai aur iska use aise data ko store karne ke liye kiya jata hai jo sabhi
objects ke liye common hona chahiye.
A static variable is also known as a class variable. It is shared among all instances of the
class and is used to store data that should be common for all objects.
class Student {
int rollNo;
String
name;
// static variable
static String Training_Center =
“Coding Club"; Student(int r, String
n){
rollNo = r;
name = n;
}
void display(){
[Link](rollNo + " " + name + " "+ Training_Center);
}
}
Static Methods
Static method class se belong karta hai, kisi specific object se nahi. Isse direct class name ka use
karke call kiya ja sakta hai.
A static method belongs to the class rather than to any object. It can be called directly
using the class name.
Can access only static data directly.
Cannot access instance variables or methods directly.
Cannot use this or super keywords.
Static vs Non-Static
The table below demonstrates the difference between Static and Non-Static
final Keyword in Java
Final keyword ek non-access modifier hai jo modification ko restrict karne ke liye use hota hai.
Ye variables, methods aur classes par apply ho sakta hai.
Ye constants create karne, inheritance ko control karne aur fixed behavior enforce karne me
help karta hai.
The final keyword is a non-access modifier used to restrict modification. It applies to
variables (value cannot change) methods (cannot be overridden) and classes (cannot be
extended). It helps create constants, control inheritance and enforce fixed behavior.
Variable
Method
Class
Initialization rules:
Final variable ko sirf ek hi baar assign karna zaruri hota hai, ya to declaration ke time, ya
constructor ke andar, ya initializer blocks ke andar.
Reference final variables me object ka reference change nahi kiya ja sakta, lekin object ki
internal state change ho sakti hai.
Static final variables constants ko represent karte hain jo class ke sabhi objects ke beech share
hote hain.
Blank final variables wo hote hain jo declare to kiye jate hain lekin initialize nahi hote, aur use
hone se pehle unhe ek baar assign karna zaruri hota hai.
Local final variables jo methods ke andar hote hain, unhe apne block ke andar hi initialize karna
zaruri hota hai.
Agar koi class final declare ki jati hai, to use extend (inherit) nahi kiya ja sakta.
A class declared as final cannot be extended.
final class A {
// fields and methods
}
// Illegal
class B extends A { }
Final classes useful hoti hain jab immutable classes create karni hoti hain, jaise String ya
wrapper classes.
Final classes are useful when creating immutable classes such as String or wrapper
classes
Final Method
Jab kisi method ko final keyword ke saath declare kiya jata hai, to use final method kaha jata
[Link] method ko override nahi kiya ja sakta.
When a method is declared with final keyword, it is called a final method in Java. A final
method cannot be overridden.
class A {
final void m1() {
[Link]("Final method");
}
}
class B extends A {
void m1() { } // compile-time error
}
Java Comments
Java me comments non-executable statements hote hain jo code ko explain karte hain aur
readability improve karte hain. Inhe compiler ignore karta hai aur program execution par koi
effect nahi padta.
In Java, comments are non-executable statements that explain code and improve
readability. They are ignored by the compiler and do not affect program execution.
Enhance code readability and maintainability. Useful for
debugging and documenting logic.
Type of Comments
Java supports three main types of comments:
Single-Line Comments
Multi-Line Comments
Documentation Comments
Single-Line Comments
1. Single-Line Comments
Single-line comments are used to comment on one line of code.
class Coding_Club
{
public static void main(String args[])
{
[Link](“Single line comment below");
// Single line comment here
}
}
Multi-Line Comments
Multi-line comments are used to describe complex code or methods,
as writing multiple single-line comments can be tedious.
class Coding_Club
{
public static void main(String args[])
{
[Link]("Multi Line Comments Below");
/* Comment line 1
Comment line 2
Comment line 3
*/
}
}
3. Documentation Comments
Documentation comments are used to generate external
documentation using Javadoc. They are generally used in
professional projects to describe classes, methods, and parameters.
class Coding_Club
{
public static void main(String args[])
{
[Link](“Documentation Comments Below");
/**
* Comment start
* @param param-name description
* @return description
*/
}
}
Java Data Types
Java ek statically typed programming language hai, jiska matlab hai ki har variable ka data type
compile time par hi pata hota hai.
Compiler type safety enforce karta hai aur invalid assignments ko prevent karta hai.
Data types in Java define the kind of data a variable can hold and the
memory required to store it. They are broadly divided into two
categories:
Primitive data types simple values ko directly memory me store karte hain.
Java me 8 primitive data types hote hain, aur har ek ka fixed size aur range hota hai
Non-primitive data types actual values ki jagah references (memory addresses) ko store karte
hain.
Ye user ke dwara create kiye jate hain aur inme String, Class, Object, Interface aur Array jaise
types include hote hain.
1. String
String characters ka sequence represent karta hai jo double quotes (" ") ke andar likha jata hai.
C/C++ ke unlike, Java me strings objects hote hain aur immutable hote hain (yaani unki value
change nahi hoti).
2. Class
Class ek user-defined blueprint hoti hai jo variables aur methods ko define karti hai.
Ye object ka ek type represent karti hai aur Object-Oriented Programming (OOP) ki foundation
hoti hai.
3. Object
Object class ka ek instance hota hai jo real-world entities ko represent karta hai.
• State (data)
• Behavior (methods)
class Coding_Club {
}
class Main {
4. Interface
Interface abstract methods ka ek contract define karta hai jise implementing classes ko define
karna padta hai.
Ye Java me abstraction aur multiple inheritance achieve karne ka ek tarika provide karta hai.
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
[Link]("Woof");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
[Link]();
}
}
4. Array
Array ek single structure me same type ke multiple elements ko store karta hai.
Java me arrays objects hote hain, dynamically allocate hote hain, aur index 0 se start hota hai.
}
}
Java Operators
Java operators special symbols hote hain jo variables ya values par operations perform karte
hain.
// Addition
int sum = a + b;
// Subtraction
int diff = a - b;
// Multiplication
int mul = a * b;
// Division
int div = a / b;
// Modulus
int mod = a % b; // Modulus
2. Unary Operators
Unary operators sirf ek operand ki zarurat rakhte hain. Inka use value ko increment, decrement,
ya negate karne ke liye kiya jata hai.
Unary Operators need only one operand. They are used to increment,
decrement, or negate a value.
import [Link].*;
// Driver Class
class Coding_Club {
// Integer declared
int a = 10;
int b = 10;
3. Assignment Operator
Assignment operator right-hand side ki value ko left side wale variable ko assign karta hai.
Iski right-to-left associativity hoti hai, isliye right side ki value declared ya constant honi chahiye.
int n = 10;
// n = n + 5
n += 5;
[Link]("After += : " + n);
// n = n * 2
n *= 2;
[Link]("After *= : " + n);
// n = n - 5
n -= 5;
[Link]("After -= : " + n);
// n = n / 2
n /= 2;
[Link]("After /= : " + n);
// n = n % 3
n %= 3;
[Link]("After %= : " + n);
}
}
3. Relational Operators
Relational operators equality, greater than, aur less than jaise relations ko check karne ke liye
use hote hain.
Inka use looping statements aur conditional if-else statements me bahut zyada hota hai.
import [Link].*;
class Coding_Club {
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
Logical Operators are used to perform "logical AND" and "logical OR"
operations, similar to AND gate and OR gate in digital electronics.
They have a short-circuiting effect, meaning the second condition is
not evaluated if the first is false.
import [Link].*;
class Coding_Club {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
6. Ternary operator
Ternary operator if-else statement ka shorthand version hota hai.
Isme teen operands hote hain, isi liye ise Ternary operator kaha jata hai.
7. Bitwise Operators
Bitwise Operators individual bits ko AND, OR, XOR, aur NOT operations ki help se manipulate
karte hain.
Shift Operators bits ko left ya right move karte hain, jisse number effectively powers of two se
multiply ya divide ho jata hai.
import [Link].*;
class Coding_Club
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
• Confusing == with =:
Assignment ke liye = use hota hai, aur equality check ke liye ==. Agar galti se == assignment
ke liye use kar diya jaye to logical errors aa sakte hain.
• The common mistakes that can occur when working with Java
Operators are listed below:
• Confusing == with =: Using == for assignment instead of = for
equality check leads to logical errors.
• Incorrect Use of Floating Point Comparison: Comparing floating
point numbers using == can lead to unexpected results due to
precision issues.
• Integer Division Confusion: Dividing two integers will result in
integer division (truncating the result).
• Overusing + for String Concatenation in Loops: Using + for
concatenating strings in loops leads to performance issues
because it creates new string objects on each iteration.
Control flow
Control flow statements programming languages ka ek important part hote hain jo developers ko
yeh control karne dete hain ki program me instructions kis order me execute honge.
Simple words me, control flow statements program ke flow ko control karte hain.
Control flow statements are fundamental components of
programming languages that allow developers to control the order in
which instructions are executed in a program. They enable execution
of a block of code multiple times, execute a block of code based on
conditions, terminate or skip the execution of certain lines of code,
etc.
1. If Statement in Programming:
2. if-else Statement in Programming:
3. if-else-if Statement in Programming:
4. Ternary Operator or Conditional Operator in Programming:
5. Switch Statement in Programming:
1. If Statement in Programming:
If statement ka use tab hota hai jab specified condition true ho, tab ek block of code execute kiya jata hai.
The if statement is used to execute a block of code if a specified condition is true. import
[Link].*;
class Coding_Club {
public static void main(String[] args)
{
int a = 5;
if (a == 5) {
[Link]("a is equal to 5");
}
}
}
The if-else statement is used to execute one block of code if a specified condition is true,
and another block of code if the condition is false.
import [Link].*;
class Coding_Club {
public static void main(String[] args)
{
int a = 10;
if (a == 5) {
[Link]("a is equal to 5");
}
else {
[Link]("a is not equal to 5");
}
}
}
Agar pehli condition true ho to uska block of code execute hota hai, agar dusri condition true ho
to doosra block execute hota hai, aur agar koi bhi condition true na ho to default block of code
execute ho jata hai.
The if-else-if statement is used to execute one block of code if a specified condition is
true, another block of code if another condition is true, and a default block of code if
node of the conditions are true.
import [Link].*;
class Coding_Club {
public static void main(String[] args)
{
int a = 15;
if (a == 5) {
[Link]("a is equal to 5");
}
else if (a == 10) {
[Link]("a is equal to 10");
}
else {
[Link]("a is not equal to 5 or 10");
}
}
}
class Coding_Club {
public static void main(String[] args)
{
int a = 10;
[Link](a == 5 ? "a is equal to 5"
: "a is not equal to 5");
}
}
In language like C, C++, and Java, a switch statement is used to execute one block of code
from multiple options based on the value of an expression.
int a = 15;
switch (a) {
case 5:
[Link]("a is equal to 5");
break;
case 10:
[Link]("a is equal to 10");
break;
default:
[Link]("a is not equal to 5 or 10");
}
Yeh tasks ke liye bahut important hote hain jaise list ke elements par iterate karna, file se data
read karna, ya kisi instructions ko specific number of times execute karna.
The for loop is used to iterate over a sequence (e.g., a list, tuple, string, or range) and
execute a block of code for each item in the sequence.
The while loop is used to repeatedly execute a block of code as long as a specified
condition is true.
/*package whatever //do not write package name here */
import [Link].*;
class Coding_Club {
public static void main(String[] args)
{
int count = 0;
while (count < 5) {
[Link](count);
count++;
}
}
}
import [Link].*;
class Coding_Club {
public static void main(String[] args)
{
int count = 0;
do {
[Link](count);
count++;
} while (count < 5);
}
}
Example: Ek for loop ko doosre for loop ke andar use karke two-dimensional iteration create kiya
ja sakta hai. 😊
Loops can be nested within one another to perform more complex iterations. For
Example, a for loop can be nested inside another for loop to create a two-dimensional
iteration.
import [Link].*;
class Coding_Club {
public static void main (String[] args) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
[Link]("i=" + i + " j=" + j);
}
}
}
}
Yeh programmer ko allow karte hain ki certain conditions ya requirements ke basis par program
control ko code ke different parts me transfer kiya ja sake
Jab yeh loop ke andar milta hai, to yeh loop ki execution ko terminate kar deta hai aur control ko
loop ke turant baad wale statement par transfer kar deta hai. 😊
import [Link].*;
class Coding_Club {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i % 2 == 1)
continue;
[Link](i + " ");
}
}
}
Arrays in Java
• Array same data type ke elements ka collection hota hai jo contiguous memory locations
me store hote hain. Isse multiple values ko ek single name ke under store kiya ja sakta hai
aur index ki help se access kiya jata hai.
• Java arrays me primitive types (jaise int, char, boolean, etc.) aur objects (jaise String,
Integer, etc.) dono store kiye ja sakte hain.
• Jab primitive types ke arrays use hote hain to elements contiguous memory locations me
store hote hain.
• Lekin non-primitive types me actual objects nahi, balki unke references contiguous
locations me store hote hain.
// Primitive array
int[] arr = {10, 20, 30, 40};
int n = [Link];
[Link]("Primitive Array -> ");
for (int i = 0; i < n; i++)
[Link](arr[i] + " ");
[Link]();
Non-primitive array me String objects store hote hain aur ise bhi same tarike se print kiya jata
hai, uski length property ka use karke. 😊
The primitive array stores integer values and is traversed using loop.
The non-primitive array stores String object and is printed in the same
way using its length property.
Declaring an Array
Java me array declare karne ke liye pehle data type likha jata hai, phir array ka name,
aur uske baad empty square brackets [ ] lagaye jate hain. 😊
Actual memory allocation new keyword ki help se hoti hai, jisme array ka size specify kiya jata
hai. 😊
new keyword se create kiye gaye array ke elements automatically initialize ho jate hain:
Jab array ka size aur uske variables pehle se known hote hain, tab array literals ka use kiya ja
sakta hai. 😊
In a situation where the size of the array and variables of the array
are already known, array literals can be used.
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of
Java.
Kisi element ko access karne ke liye array ka name likhkar uske saath square brackets [ ] me
index dena padta hai. 😊
Elements of an array can be accessed by their position, called the
index. In Java, array indexing starts from 0 (not 1). To access an
element, provide the index inside square brackets [] along with the
array name.
class Coding_Club {
public static void main(String[] args) {
Isme array element ko access karke usse ek new value assign kar di jati hai. 😊
class Coding_Club {
public static void main(String[] args) {
Java me arrays ko easily traverse kiya ja sakta hai loop ki help se, jisme loop variable 0 se start
hota hai aur [Link] - 1 tak chalta hai. 😊
class Coding_Club {
public static void main(String[] args){
Array ka size find karne ke liye Java ek built-in property length provide karta hai. 😊
The size of an array refers to the number of elements it can hold. To
find the size of array java provides a built-in property called length.
class Coding_Club {
public static void main(String[] args) {
Har character 16 bits me store hota hai, yani UTF-16 encoding ka use hota hai.
Java strings ko handle karne ke liye ek strong aur flexible API provide karta hai, jisse
concatenation, comparison aur manipulation jaise operations easily kiye ja sakte hain. 😊
// Main Function
public static void main(String args[])
{
// creating Java string using a new keyword
String str = new String(“ITM");
[Link](str);
}
}
❖ There are two ways to create a string in Java:
Example:
String str = “ITM”;
2. Using new keyword (Heap Memory)
String s = new String("Welcome");
Aise case me JVM normal (non-pool) heap memory me ek naya String object create karti hai, aur
literal "Welcome" ko String Constant Pool me store kar diya jata hai.
Diye gaye example me sirf ek object create hoga. Sabse pehle JVM String Constant Pool me
"Welcome" value wala koi string object search karti hai.
Agar waha nahi milta, to naya string object create kar diya jata hai. 😊
Agar String Constant Pool me us value ka string nahi milta, to JVM ek naya object create kar deti
hai.
Uske baad jab "Welcome" value wala string pool me mil jata hai, to JVM naya object create nahi
karti, balki usi existing instance ka reference return kar deti hai. 😊
In such a case, JVM will create a new string object in normal (non-
pool) heap memory and the literal "Welcome" will be placed in the
string constant pool. The variable s will refer to the object in the heap
(non-pool)
In the given example only one object will be created. Firstly JVM will
not find any string object with the value "Welcome" in the string
constant pool, so it will create a new object. After that it will find the
string with the value "Welcome" in the pool, it will not create a new
object but will return the reference to the same instance.
Example:
String str = new String (“ITM”);
❖ Classes that implement CharSequence include:
1. String
2. StringBuffer
3. StringBuilder
4. StringTokenizer
1. String
Java me String ek immutable class hoti hai, iska matlab hai ki jab ek String object create ho jata
hai, to uski value change nahi ki ja sakti.
Agar string ko modify karna ho, to ek naya String object create hota hai, aur original string
unchanged rehti hai. 😊
Syntax:
String str = “ITM”; // Method 1
String str = new String String(“geeks”); // Method 2
2. StringBuffer
StringBuffer Java me String ki peer class hai. Yeh mutable hoti hai, yani iski value change ki ja
sakti hai.
Yeh thread-safe class bhi hai, isliye ise multi-threaded environment me use kiya jata hai, jahan
multiple threads ek hi StringBuffer object ko use karte hain.
Kyuki yeh thread-safe hoti hai, isme extra overhead hota hai. Isliye mainly multithreaded
programs me hi use ki jati hai. 😊
Iska use sirf ek hi thread ke andar kiya jata hai, isliye koi extra overhead nahi hota.
Isi wajah se StringBuilder mainly single-threaded programs me use kiya jata hai. 😊
StringTokenizer object internally string ke andar ek current position maintain karta hai, jise
tokenize kiya jana hota hai.
Kuch operations is current position ko aage move kar dete hain, yani jo characters process ho
chuke hote hain unke baad position shift ho jati hai.
Token return karne ke liye us string ka substring liya jata hai jisse StringTokenizer object create
kiya gaya tha. 😊
Jab ek string object create ho jata hai, to uska data ya state change nahi kiya ja sakta, balki
change karne par ek naya string object create ho jata hai. 😊
class Coding_Club
{
public static void main(String[] args)
{
String s = "Sachin";
Lekin agar hum explicitly usse reference variable ko assign kar den, to s "Sachin Tendulkar"
object ko refer karne lagega.
Here, Sachin is not changed but a new object is created with “Sachin
Tendulkar”. That is why a string is known as immutable.
As we can see in the given figure that two objects are created but s
reference variable still refers to "Sachin" and not to "Sachin
Tendulkar". But if we explicitly assign it to the reference variable, it
will refer to the "Sachin Tendulkar" object.
Classes and Objects in Java
Java me classes aur objects Object-Oriented Programming (OOP) ki foundation hote hain. Yeh
real-world entities ko model karne aur code ko structured way me organize karne me help karte
hain.
Class:
Class ek blueprint hoti hai jiska use objects create karne ke liye kiya jata hai, jisme common
properties aur behavior hote hain.
Object:
Object class ka ek instance hota hai. Yeh class template se create hui ek specific entity ko
represent karta hai
Java Class
Class ek blueprint hoti hai jo objects ke liye data aur behavior define karti hai. Yeh related fields
aur methods ko ek single unit me group karti hai. Memory tabhi allocate hoti hai jab object
create hota hai.
• Objects create karne ke liye template ki tarah kaam karti hai, jisme shared structure hota
hai.
• Fields ke liye memory tab tak occupy nahi hoti jab tak object (instantiation) create na ho.
• Isme fields, methods, constructors, nested classes aur interfaces ho sakte hain.
class Student {
int id;
String n;
public Student(int id, String n) {
[Link] = id;
this.n = n;
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student(10, "Alice");
[Link]([Link]);
[Link](s1.n);
}
}
Java Objects
Object ek class ka instance hota hai jo uske data aur operations ko access karne ke liye create
kiya jata hai. Har object apna alag state hold karta hai.
State:
Fields me store hui values ko state kaha jata hai.
Behavior:
Methods ke through define kiye gaye actions ko behavior kehte hain.
Identity:
Yeh ek object ko dusre object se alag (distinguish) karta hai.
Class ke sabhi instances same structure aur behavior share karte hain, lekin unke state values
alag-alag store ho sakte hain.
Agar koi constructor define nahi kiya gaya ho, to Java automatically ek default no-argument
constructor provide karti hai, jo parent constructor ko call karta hai.
Note: Every class has at least one constructor. If none is defined Java
provides a default no-argument constructor that calls the parent
constructor.
• Instantly create aur use ho jata hai, isse short-lived tasks me memory save hoti hai.
Example:
new Dog("Max", "Labrador", 3, "Black").getName();
Inheritance in Java
Inheritance Java me OOP ka ek important concept hai jo ek class ko dusri class se properties aur
behaviors inherit karne ki permission deta hai.
Isse existing class se new class create ki ja sakti hai, jisse code reusability aur better organization
milta hai.
• Subclass parent class ke fields aur methods ko bina dobara likhe reuse kar sakti hai.
• Subclass apne naye fields aur methods add bhi kar sakti hai ya existing methods ko modify
karke functionality ko extend kar sakti hai.
• // Parent class
• class Animal {
• void sound() {
• [Link]("Animal makes a sound");
• }
• }
• // Child class
• class Dog extends Animal {
• void sound() {
• [Link]("Dog barks");
• }
• }
• // Child class
• class Cat extends Animal {
• void sound() {
• [Link]("Cat meows");
• }
• }
• // Child class
• class Cow extends Animal {
• void sound() {
• [Link]("Cow moos");
• }
• }
• // Main class
• public class Coding_Club {
• public static void main(String[] args) {
• Animal a;
• a = new Dog();
• [Link]();
• a = new Cat();
• [Link]();
• a = new Cow();
• [Link]();
• }
• }
Animal ek base (parent) class hai, aur Dog, Cat, aur Cow derived classes hain jo Animal class ko
extend karti hain.
Animal is the base class and Dog, Cat, and Cow are derived classes that
extend the Animal class.
1. Single Inheritance
Isme sub-class ek single parent class ki properties aur behavior inherit karti hai.
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as
the derived class also acts as the base class for other classes.
•
• class Vehicle {
• Vehicle() {
• [Link]("This is a Vehicle");
• }
• }
• class FourWheeler extends Vehicle {
• FourWheeler() {
• [Link]("4 Wheeler Vehicles");
• }
• }
• class Car extends FourWheeler {
• Car() {
• [Link]("This 4 Wheeler Vehicle is a Car");
• }
• }
• public class Main {
• public static void main(String[] args) {
• Car obj = new Car(); // Triggers all constructors in order
• }
• }
[Link] Inheritance
Hierarchical inheritance me ek single base class se ek se zyada subclasses inherit karte hain.
Example: Cars aur Buses dono Vehicle class se inherit karte hain
In hierarchical inheritance, more than one subclass is inherited from a single base
class. i.e. more than one derived class is created from a single base class. For example,
cars and buses both are vehicle
• class Vehicle {
• Vehicle() {
• [Link]("This is a Vehicle");
• }
• }
• Car() {
• }
• }
• Bus() {
• }
• }
• }
• }
In Multiple inheritances, one class can have more than one superclass and inherit
features from all parent classes.
Note: that Java does not support multiple inheritances with classes. In Java, we can
achieve multiple inheritances only through Interfaces.
•
• interface LandVehicle {
• default void landInfo() {
• [Link]("This is a LandVehicle");
• }
• }
• interface WaterVehicle {
• default void waterInfo() {
• [Link]("This is a WaterVehicle");
• }
• }
• // Subclass implementing both interfaces
• class AmphibiousVehicle implements LandVehicle,
WaterVehicle {
• AmphibiousVehicle() {
• [Link]("This is an AmphibiousVehicle");
• }
• }
• public class Test {
• public static void main(String[] args) {
• AmphibiousVehicle obj = new AmphibiousVehicle();
• [Link]();
• [Link]();
• }
• }
4. Hybrid Inheritance
Hybrid inheritance ek mix hota hai do ya usse zyada inheritance types ka.
Java me agar multiple inheritance involve karni ho, to hybrid inheritance sirf Interfaces ke
through implement ki ja sakti hai.
Polymorphism ka matlab hai "many forms", jo Greek words poly (many) aur morph (forms) se
aaya hai. Matlab ek entity ke multiple forms ho sakte hain.
Multiple Behaviors:
Ek hi method alag objects ke liye alag tarike se behave kar sakti hai.
Method Overriding:
Child class apne parent class ke method ko redefine kar sakti hai.
Method Overloading:
Hum ek hi naam ke multiple methods define kar sakte hain, bas parameters different hone
chahiye.
Runtime Decision:
Runtime me Java decide karta hai ki kaunsa method call karna hai, based on object ka actual
class.
Har role person ke alag behavior ko define karta hai, jo object ke basis par change hota hai jo
method ko call kar raha hai.
Yeh tab hota hai jab same class me multiple methods ka naam same ho, lekin parameters alag-
alag ho.
Method Overloading:
Method overloading ka matlab hai ek hi naam ke multiple methods define karna, bas unke
parameter lists different honi chahiye.
Method call compile time par resolve hota hai, arguments ke basis par jo pass kiye gaye hote
hain.
Method Overloading
Method overloading means defining multiple methods
with the same name but different parameter lists. The
method call is resolved at compile time based on the
arguments passed.
Multiply method ko alag-alag parameter types ke saath overload kiya gaya hai.
Compiler compile time par hi decide kar leta hai ki kaunsa method call karna hai, based on pass
kiye gaye arguments
Runtime Polymorphism
Runtime Polymorphism Java me dynamic method dispatch ke naam se bhi jana jata hai.
Yeh tab hota hai jab method call runtime par resolve hota hai, aur isse method overriding ke
through achieve kiya jata hai.
Method Overriding:
Method overriding tab hota hai jab subclass apni implementation provide karti hai parent class
ke method ki, jiska naam, parameters, aur return type same hona chahiye
Method Overriding
Method overriding occurs when a subclass provides its own
implementation of a method already defined in its superclass.
The method must have the same name, parameters, and
return type.
Note:
Runtime me jo method execute hota hai, wo reference type par nahi, balki actual object type par
depend karta hai.
Note: At runtime, the method that gets executed depends on
the actual object type, not the reference type.
• // Class 1
• // Helper class
• class Parent {
• // Method of parent class
• void Print() {
• [Link]("parent class");
• }
• }
• // Class 2
• // Helper class
• class subclass1 extends Parent {
• // Method
• void Print() {
• [Link]("subclass1");
• }
• }
• // Class 3
• // Helper class
• class subclass2 extends Parent {
• // Method
• void Print() {
• [Link]("subclass2");
• }
• }
• // Class 4
• // Main class
• class Main {
• // Main driver method
• public static void main(String[] args) {
• // Creating object of class 1
• Parent a;
• // Now we will be calling print methods
• // inside main() method
• a = new subclass1();
• [Link]();
• a = new subclass2();
• [Link]();
• }
• }
Example:
Ye program Java me method overriding demonstrate karta hai, jahan Print() method
subclasses (subclass1 aur subclass2) me redefine kiya gaya hai, taki specific
implementations provide ki ja sake.
Explanation:
Jab child class ka object create hota hai, to child class ka method call hota hai.
Kyuki parent class ka method child class me override ho chuka hai, child class ka method zyada
priority rakhta hai.
Example: This program demonstrates method overriding in Java, where the Print()
method is redefined in the subclasses (subclass1 and subclass2) to provide specific
implementations.
Explanation: In the above example, when an object of a child class is created, then the
method inside the child class is called. This is because the method in the parent class is
overridden by the child class. This method has more priority than the parent method
inside the child class. So, the body inside the child class is executed.
Advantages of Polymorphism
Polymorphism ke advantages:
• Code Reusability: Ek hi method ya class alag-alag object types ke saath kaam kar sakti hai.
• Flexibility: Alag-alag objects ko common superclass type ke roop me treat kiya ja sakta hai.
• Abstraction: Hum general types (abstract classes ya interfaces) ke saath kaam kar sakte
hain, concrete classes ke bajaye.
• Dynamic Behavior: Method calls runtime par resolve hote hain, actual object type ke basis
par
Polymorphism ke advantages:
• Code Reusability: The same method or class works with different object types.
• Flexibility: Different objects can be treated as a common superclass type.
• Abstraction: Enables working with general types (abstract classes or interfaces)
instead of concrete classes.
• Dynamic Behavior: Method calls are resolved at runtime based on the actual object
type.
Disadvantages of Polymorphism
Polymorphism ke disadvantages:
• Understanding difficulty: Isse object ka behavior samajhna thoda difficult ho sakta hai.
• Performance issues: Kyuki polymorphic behavior runtime par decide hota hai, isme extra
computations lag sakti hain, jo performance ko affect kar sakti hai
Polymorphism ke disadvantages:
Object-Oriented Programming (OOP) me yeh code ko organized aur secure rakhne me help karta
hai.
• Class implementation hide kar sakti hai aur sirf required functionalities dusre classes ke
liye expose karti hai.
• Agar class ke data aur methods private banaye jayein, to implementation future me
change ki ja sakti hai bina existing code ko affect kiye.
Benefits:
• Data integrity maintain hoti hai, kyunki variables me assign hone wale values ko validate
aur control kiya ja sakta hai.
Encapsulation means combining data and the functions that work on that data into a
single unit, like a class. In Object-Oriented Programming, it helps keep things organized
and secure.
A class can hide the implementation part and discloses only the functionalities required
by other classes. By making class data and methods private, representations or
implementations can later be changed without impacting the codes that uses this class.
It helps in better maintainability, readability and usability. It also helps maintain data
integrity by allowing validation and control over the values assigned to variables.
How Encapsulation is Achieved in Java
Java me Encapsulation achieve karne ke liye:
• Public getter aur setter methods provide ki jati hain, jisse data access aur modify kiya ja
sake.
Key Rules:
• Data ko private declare karo: Isse class ka data hide ho jata hai aur outside se directly
access nahi kiya ja sakta
• Getters aur Setters ka use karo: Variables ko private rakho aur controlled access ke liye
public getter aur setter methods provide karo. Zarurat pade to validation bhi include kar
sakte ho.
• Proper access modifiers apply karo: Data ko hide karne ke liye private use karo aur access
provide karne wale methods ke liye public.
[Link] = name;
}
}
public class Coding_Club {
public static void main(String[] args){
Yeh encapsulation mechanism Programmer object ke internal state ko protect karta hai aur
name attribute ko access aur modify karne me better control aur flexibility provide karta hai.
Explanation
In the above example, we use the encapsulation and use getter
(getName) and setter (setName) method which are used to show and
modify the private data. This encapsulation mechanism protects the internal
state of the Programmer object and allows for better control and flexibility in
how the name attribute is accessed and modified.
Advantages of Encapsulation
Encapsulation ke advantages:
• Data Hiding: Encapsulation class variables ka direct access restrict karta hai, jisse sensitive
data unauthorized access se protect hota hai.
• Enhanced Security: Encapsulation data validation aur control allow karta hai, jisse invalid
ya harmful values set nahi ho sakti.
• Code Reusability: Encapsulated classes different programs me reuse ki ja sakti hain bina
internal logic expose kiye.
• Better Modularity: Encapsulation data aur methods ko ek class me organize karke modular
aur structured code promote karta hai.
• Increased Code Complexity: Har variable ke liye getter aur setter methods likhne se code
lamba aur thoda complex ho jata hai.
• Performance Overhead: Data ko direct access ke bajaye methods ke through access karne
se thoda performance cost aa sakta hai, especially performance-critical applications me.
• Less Flexibility in Some Cases: Agar class members ka access over-restrict kar diya jaye, to
dusre classes ke liye class ko efficiently extend ya use karna limited ho sakta hai.
Abstraction in Java
Abstraction Java me internal implementation details ko hide karne aur sirf essential
functionality show karne ka process hai.
Yeh focus karta hai ki object kya karta hai, kaise karta hai nahi.
• Abstraction complex details hide karta hai aur sirf important features show karta hai.
• Functionality ko abstract karne se, implementation me changes hone par bhi wo code jo
abstraction par depend karta hai, unaffected rehta hai
Abstraction in Java is the process of hiding internal
implementation details and showing only essential
functionality to the user. It focuses on what an object does
rather than how it does it.
Abstraction hides the complex details and shows only essential
features.
Abstract classes may have methods without implementation
and must be implemented by subclasses.
By abstracting functionality, changes in the implementation do
not affect the code that depends on the abstraction.
Yeh TV ke saath interaction simplify karta hai aur complex technology ko hide karta hai.
Hume yeh samajhne ki zarurat nahi ki TV internally kaise kaam karta hai; hume bas button press
karna hai channel change karne ya volume adjust karne ke liye.
abstract class TV {
abstract void turnOn();
abstract void turnOff();
}
// Concrete class implementing the abstract methods
class TVRemote extends TV{
@Override
void turnOn(){
Example (Shape):
• Base type Shape me common properties jaise color aur size hoti hain.
• Specific shapes—Circle, Square, Triangle—Shape se inherit karte hain aur apne unique
properties ya behaviors rakh sakte hain.
Illustration:
• Har shape ka area calculate karne ka method alag hota hai, jo shared features aur
individual differences dono dikhata hai.
Is tarah abstract class common features provide karti hai, aur subclasses ko specific
implementation dene ka option deti hai.
return color;
}
}
class Circle extends Shape{
double radius;
public Circle(String color, double radius){
// calling Shape constructor
super(color);
[Link]("Circle constructor called");
[Link] = radius;
}
@Override double area(){
Interface
Interface ek class ka blueprint hota hai jo Java me 100% abstraction achieve karne ke liye use
hota hai.
• Method bodies nahi hoti (except default aur static methods Java 8 ke baad se).
Implementation:
Interface ko implement karne ke liye class ke saath implements keyword ka use kiya jata hai.
private double r;
// Constructor for Circle
public Circle(double r){
this.r = r;
}
// Implementing the abstract method
// from the Shape interface
public double calculateArea()
{
return [Link] * r * r;
}
}
// Implement the interface in a
// class named Rectangle
class Rectangle implements Shape{
[Link] = length;
[Link] = width;
}
// Implementing the abstract
// method from the Shape interface
public double calculateArea() {
return length * width;
}
}
Advantages of Abstraction
Abstraction ke benefits:
• Increased Security: Sirf necessary details user ko show ki jaati hain, jisse security improve
hoti hai.
• Harder Debugging & Understanding: System ko samajhna aur debug karna difficult ho jata
hai, especially unfamiliar users ke liye.
Abstraction ke disadvantages:
• Not Implementing Abstract Methods: Hamesha ensure karo ki abstract methods concrete
subclass me implement hon.
• Overusing Abstraction: Har cheez ko abstract mat banao jab zarurat na ho. Abstraction ka
use sirf design ko enhance karne ke liye karo.
The common mistakes that can occur and we should avoid when
working with Abstraction in Java are listed below:
• Not Implementing Abstract Methods: Always make sure that the
abstract methods are implemented in the concrete subclass.
• Overusing Abstraction: Avoid making everything abstract when
it’s not required. Use abstraction only when it enhances the
design.
• Inconsistent Method Signatures in Subclasses: When you
override abstract methods, please make sure the method
signature matches exactly, any mistake can cause errors.
Java Packages
Package Java me ek mechanism hai jo related classes, interfaces, aur sub-packages ko ek single
unit me group karta hai.
Packages ke benefits:
• Avoid name conflicts: Do classes ke same name ke hone par bhi different packages me
exist kar sakti hain.
• Access protection: Public, protected, aur default access modifiers ke through access
control provide karte hain
• Reusability: Packaged code ko import karke kahi bhi use kiya ja sakta hai.
Built-in Packages
Built-in Packages me bohot saari classes hoti hain jo Java API ka part hoti hain.
• [Link] – Language support classes (jaise primitive data types, math operations). Ye
package automatically import ho jata hai.
• [Link] – Utility classes provide karta hai jaise Linked Lists, Dictionaries, aur date &
time operations.
Example:
[Link] ka use built-in package se hota hai.
Built-in Packages
1. Built-in Packages
2. Built-in Packages comprise a large number of classes that are part of the
Java API. Some of the commonly used built-in packages are:
3. [Link]: Contains language support classes(e.g, classes that define primitive
data types, math operations). This package is automatically imported.
4. [Link]: Contains classes for supporting input/output operations.
5. [Link]: Contains utility classes that implement data structures such as Linked
Lists and Dictionaries, as well as support for date and time operations.
6. [Link]: Contains classes for creating Applets.
7. [Link]: Contains classes for implementing the components for graphical user
interfaces (like buttons, menus, etc).
8. Example: Using [Link] (Built-in Package)
import [Link]; // built-in package
public class Coding_Club {
2. User-defined Packages
User-defined Packages wo packages hote hain jo user khud define karta hai.
User-defined Packages are the packages that are defined by the user.
package [Link];
public class Helper {
public static void show() {
[Link]("Hello from Helper!");
}
}
import [Link];
public class Test {
public static void main(String[] args) {
[Link]();
}
}
Accessing Classes Inside a Package
public Coding_Club() {
[Link](l);
}
public static void main(String[] args) {
new Coding_Club();
}
}
Access Modifiers and Packages
Haan, packages Java ke access levels ko directly influence karte hain.
• Default (no modifier): Same package ke andar accessible, package ke bahar nahi.
• Protected: Same package ke andar aur subclasses (even different packages) me accessible.
Isliye packages ka structure access control aur data encapsulation me important role play karta
hai.
• Java Compiler aur JVM is CLASSPATH ka use karke required files locate karte hain.
• Agar CLASSPATH set nahi hai, to Java Compiler required files find nahi kar payega aur
error throw karega.
The CLASSPATH is an environment variable that tells the Java compiler [Link] where to
look for class files to import or [Link] where to find class to interpret.
CLASSPATH describes the location where all the required files are available which are used
in the application. Java Compiler and JVM (Java Virtual Machine) use CLASSPATH to locate
the required files. If the CLASSPATH is not set, Java Compiler will not be able to find the
required files and hence will throw the following error.
Error : Could not find or load main class <Class name> (e.g. Coding_Club)
The above error is resolved when CLASSPATH is set.
// If the following code is run when the CLASSPATH is not
// set, it will throw the above error.
// If it is set, we get the desired result
import [Link].*;
class Coding Club {
public static void main(String[] args)
{
// prints GeeksForGeeks to the console
[Link]("GeekForGeeks!");
}
}
b. Agar nahi milta, to New par click karo aur Variable name me CLASSPATH enter karo.
5. Variable value me directories ya jar files ke file paths ka list enter karo:
Example:
.;C:\java\lib\[Link];C:\java\classes
• Yahan first dot (.) current directory ko represent karta hai, jo zaruri hai.
Is tarah Java compiler aur JVM ko pata chal jata hai ki required classes aur resources kahan se
load karni hain
• JAR file format multiple files ko ek single archive file me bundle karne ke liye use hota hai.
• Typically, JAR me class files aur auxiliary resources hote hain, jo applets aur applications
ke liye use hote hain.
Options:
Details:
• Command compressed JAR file generate karta hai aur current directory me place karta hai.
• Saath hi default manifest file bhi JAR archive ke liye generate hoti hai.
Example:
The Java Archive (JAR) file format enables you to bundle multiple files
into a single archive file. Typically a JAR file contains the class files and
auxiliary resources associated with applets and applications.
The basic format of the command for creating a JAR file is :
jar cf jar-file input-file(s)
The options and arguments used in this command are :
The c option indicates that you want to create a JAR file.
The f option indicate that you want the output to go to a file.
The command will generate a compressed JAR file and place it in the
current directory.
The command will also generate a default manifest file for the JAR
archive.
D:\RAT\jar cf [Link] p1/*.class
Package Naming Convention in Java
Rules for Java Package Names:
Rules:
• Written in lowercase letters
• Usually based on reverse domain name
Words separated by dots ( . )
• Avoid underscores and uppercase letters
Constant UPPER_CASE PI