0% found this document useful (0 votes)
2 views151 pages

Unit - 1 Java

The document explains the concept of classes and objects in Java, detailing how classes serve as templates for creating objects and how constructors initialize these objects. It also covers various types of constructors, methods, access specifiers, and the use of the static and final keywords in Java. Additionally, it discusses the importance of comments in code for improving readability and maintainability.

Uploaded by

gadaranapandit76
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views151 pages

Unit - 1 Java

The document explains the concept of classes and objects in Java, detailing how classes serve as templates for creating objects and how constructors initialize these objects. It also covers various types of constructors, methods, access specifiers, and the use of the static and final keywords in Java. Additionally, it discusses the importance of comments in code for improving readability and maintainability.

Uploaded by

gadaranapandit76
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is class in 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)

How to define a Class in Java.

Class Room
{
int length; // instance Variable
int height; // instance Variable

void area( ) // method

int area = length * height;


}

/* Here are three members in the class.


* Two data member and one method.
*/
What is Object in java.
Object is an instance of class.
To better understand what is the difference between class and object.

Please refer the following table.


(A.K.T.U 2023 - 24)

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.

Ye automatic initialization constructor ke use se hota hai.

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.

Java allows object to initialize themselves when they are created.


This automatic initialization is performed through the use of a constructor.
Type of Constructor

Constructor ke kai types hote hain.

• 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.

There are many type of Constructor

• Default Constructor: if you don’t define a constructor for a class, a default


parameter less constructor is automatically created by the complier. Default
constructor is created only if there are no constructor. If you define any
constructor for your class, no default constructor is automatically created.

• Parameterized Constructor: When a constructor takes parameter and is called


when an object and is initialized with some values at the time of creation.

• 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 {

// data members of the class


String name;
int id;

// Parameterized Constructor
Coding_Club(String name, int id)
{
[Link] = name;
[Link] = id;
}
// Method to display object data
void display(){

[Link]("Name : " + name


+ " and Id : " + id);
}

// main() method — placed inside the same class for


// universal compatibility
public static void main(String[] args){

// This will invoke the parameterized constructor


Coding_Club obj = new Coding_Club("Sweta", 68);
[Link]();
}
}

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

1. Void return type, no parameters

For Example:-

void show( ) {
}
2. Void return type, with parameters

void show(int a, int b ) {

}
3. Other then void return type, no parameters

int show( ) {

return (any integer value)


}

4. Other then void return type, with parameters

int show(int a, int b) {

return (any integer value)


}

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.

Ye encapsulation ke principle ko implement karne aur program ke kaun-kaun se parts kisi


specific data ya functionality ke saath interact kar sakte hain, usko control karne me important
role play karte 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.

Type of Access Specifiers

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).

Cannot be applied to: Classes or interfaces.


static Keyword in Java
Java me static keyword memory management ke liye use hota hai aur ye kisi specific object ki
jagah class se belong karta hai. Ye allow karta hai ki variables, methods, blocks aur nested
classes sabhi objects ke beech share ho saken.

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.

Memory is allocated only once when the class is loaded.


No object creation is needed to access static members; use the class name directly.
Static methods and variables can’t access non-static members directly.
Static methods can’t be overridden because they belong to the class, not instances.

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.

Ye sirf static data ko directly access kar sakta hai.

Ye instance variables ya methods ko directly access nahi kar sakta.


Aur this ya super keywords ka use bhi nahi kar sakta.

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.

• Final variable: iski value change nahi ki ja sakti.

• Final method: ise override nahi kiya ja sakta.

• Final class: ise extend nahi kiya ja sakta.

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.

The following are different contexts where the final is used:

Variable
Method

Class

Characteristics of final keyword in Java


Final variables me jo value assign ki jati hai wo initialization ke baad dobara change nahi ki ja
sakti.

Final methods ko subclasses ke dwara override nahi kiya ja sakta.


Final classes ko extend nahi kiya ja sakta.

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.

Final variables hold a value that cannot be reassigned after initialization.


Final methods cannot be overridden by subclasses. Final classes
cannot be extended.
Initialization rules require that a final variable must be assigned exactly once either at
declaration or inside constructors or initializer blocks.
Reference final variables cannot change which object they point to though the internal
state of the object can change.
Static final variables represent constants shared across all objects. Blank final variables
are declared without initialization and must be assigned once before use.
Local final variables inside methods must be initialized within their block

public class Demo {

public static void main(String[] args) {


final double PI = 3.14159;
[Link]("Value of PI: " + PI);
}
}
Final class

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.

Ye code ki readability aur maintainability ko improve karte hain.


Aur debugging aur logic ko document karne ke liye useful hote hain.

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.

// Java program to show single line comments

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.

Java is a statically typed programming language, which means the


data type of every variable is known at compile time. The compiler
enforces type safety and prevents invalid assignments such as:

int x = “Coding_Club”; // Compile-time error


Java me data types define karte hain ki koi variable kis type ka data hold kar sakta hai aur us
data ko store karne ke liye kitni memory required hogi.

Ye mainly do categories me divide hote hain.

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.

Non-Primitive (Reference) Data Types:


Non-primitive ya reference data types objects ke memory references ko store karte hain.

Primitive Data Types: Store simple values directly in memory.


Non-Primitive (Reference) Data Types: Store memory references to
objects.
Primitive Data Types
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

Primitive data types store simple values directly in memory. Java


provides eight primitive data types, each with a fixed size and range
1. boolean Data Type
Ye do logical values me se ek ko represent karta hai: true ya false.
Iska use conditions aur control statements me commonly kiya jata hai .
Represents one of two logical values: true or false. It is commonly
used in conditions and control statements.
boolean flag = false;

2. byte Data Type


Ye 8-bit signed integer hota hai jo large numeric arrays me memory save karne ke liye
use kiya jata hai.
An 8-bit signed integer used to save memory in large numeric arrays.
byte b = 5;

3. short Data Type


Ye 16-bit signed integer hota hai jo tab use kiya jata hai jab memory limited ho aur
values moderate size ki hon.
A 16-bit signed integer often used when memory is limited and values
are moderate in size.
short s = 10;

4. int Data Type


Ye 32-bit signed integer hota hai aur sabse commonly use hone wala numeric data type
hai.
A 32-bit signed integer and the most commonly used numeric data
type.
int i = 15;

5. long Data Type


Ye 64-bit signed integer hota hai jo tab use kiya jata hai jab large values ke liye int
sufficient nahi hota.
A 64-bit signed integer used when int is not sufficient for large values.
Long l = 12;

6. float Data Type


Ye 32-bit single-precision floating-point data type hota hai jo fractional (decimal) values
ke liye use kiya jata hai.
A 32-bit single-precision floating-point type used for fractional values.
float f = 25.0.5f; or float f = 25.0.5F;

7. double Data Type


Ye 64-bit double-precision floating-point data type hota hai aur decimal numbers ke
liye default data type hota hai.
A 64-bit double-precision floating-point type and the default for
decimal numbers.
Double d = 36.032d; or Double d = 36.032D;

8. char Data Type


Ye 16-bit Unicode character data type hota hai jo single symbol ya letter ko store karne
ke liye use kiya jata hai
A 16-bit Unicode character used to store single symbols or letters.
Char c = ‘@’; or char c = ‘a’;

Non-Primitive (Reference) Data Types

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.

Non-primitive data types store references (memory addresses) rather


than actual values. They are created by users and include types like
String, Class, Object, Interface, and Array.

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).

String represents a sequence of characters enclosed in double quotes.


Unlike C/C++, Java strings are objects and are immutable.
String str = "Hello";

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.

A class is a user-defined blueprint that defines variables and methods.


It represents a type of object and forms the foundation of Object-
Oriented Programming.
class Coding_Club {

3. Object
Object class ka ek instance hota hai jo real-world entities ko represent karta hai.

Iske teen main parts hote hain:

• State (data)

• Behavior (methods)

• Identity (unique reference).

An Object is an instance of a class representing real-world entities. It


has state (data), behavior (methods), and identity (unique reference).

class Coding_Club {
}
class Main {

public static void main() {

Coding_Club obj = new Coding_Club();


}
}

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.

An interface defines a contract of abstract methods that implementing


classes must define. It provides a way to achieve abstraction and
multiple inheritance in Java.

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.

An array stores multiple elements of the same type in a single


structure. Java arrays are objects, dynamically allocated, and indexed
from 0.

public class Coding_Club {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5};


String[] names = {“Ram", “Shayam", “Mohan"};

[Link]("First number: " + numbers[0]);


[Link]("Second name: " + names[1]);

}
}
Java Operators

Java operators special symbols hote hain jo variables ya values par operations perform karte
hain.

Ye operators programming me important hote hain, kyunki ye data ko efficiently manipulate


karne me help karte hain.

Java operators are special symbols that perform operations on


variables or values. These operators are essential in programming as
they allow you to manipulate data efficiently.
1. Arithmetic Operators
Arithmetic operators primitive aur non-primitive data types par simple arithmetic operations
perform karne ke liye use hote hain.
Arithmetic Operators are used to perform simple arithmetic
operations on primitive and non-primitive data types.

public class Coding_Club {


public static void main(String[] args) {
int a = 10, b = 3;

// 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

[Link]("Sum: " + sum);


[Link]("Difference: " + diff);
[Link]("Multiplication: " + mul);
[Link]("Division: " + div);
[Link]("Modulus: " + mod);
}
}

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 {

public static void main(String[] args){

// Integer declared
int a = 10;
int b = 10;

// Using unary operators


[Link]("Postincrement : " + (a++));
[Link]("Preincrement : " + (++a));

[Link]("Postdecrement : " + (b--));


[Link]("Predecrement : " + (--b));
}

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.

The assignment operator assigns a value from the right-hand side to a


variable on the left. Since it has right-to-left associativity, the right-
hand value must be declared or constant.

public class Coding_Club {


public static void main(String[] args){

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.

Comparison ke baad ye boolean result (true ya false) return karte hain.

Inka use looping statements aur conditional if-else statements me bahut zyada hota hai.

Relational Operators are used to check for relations like equality,


greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements.

import [Link].*;
class Coding_Club {

public static void main(String[] args){

// Comparison operators
int a = 10;
int b = 3;
int c = 5;

[Link]("a > b: " + (a > b));


[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
[Link]("a == c: " + (a == c));
[Link]("a != c: " + (a != c));
}
}
4. Logical Operators
Logical operators logical AND aur logical OR operations perform karne ke liye use hote hain,
bilkul digital electronics ke AND gate aur OR gate ki tarah.
Inme short-circuiting effect hota hai, yani agar first condition false ho to second condition
evaluate nahi hoti.

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;

[Link]("x && y: " + (x && y));


[Link]("x || y: " + (x || y));
[Link]("!x: " + (!x));
}
}

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.

The Ternary Operator is a shorthand version of the if-else statement.


It has three operands and hence the name Ternary. The general
format is,

public class Coding_Club {

public static void main(String[] args){

int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result = ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
[Link]("Max of three numbers = "+ result);
}
}

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.

These operators perform operations at the bit level.


Bitwise Operators manipulate individual bits using AND, OR, XOR, and
NOT.
Shift Operators move bits to the left or right, effectively multiplying or
dividing by powers of two.

import [Link].*;

class Coding_Club
{
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;

[Link]("d & e : " + (d & e));


[Link]("d | e : " + (d | e));
[Link]("d ^ e : " + (d ^ e));
[Link]("~d : " + (~d));
[Link]("d << 2 : " + (d << 2));
[Link]("e >> 1 : " + (e >> 1));
[Link]("e >>> 1 : " + (e >>> 1));
}
}
8. instanceof Operator
Iska use yeh test karne ke liye kiya jata hai ki koi object kisi class, subclass, ya interface ka
instance hai ya nahi.
The instanceof operator is used for type checking. It can be used to
test if an object is an instance of a class, a subclass, or an interface.
The general format

public class Coding_Club {

public static void main(String[] args){

String str = "Hello";


[Link](str instanceof String);

Object obj = new Integer(10);


[Link](obj instanceof Integer);
[Link](obj instanceof String);
}
}

Common Mistakes to Avoid


• Java Operators ke saath kaam karte waqt kuch common mistakes ho sakti hain, jo neeche
di gayi hain:

• 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.

• Incorrect Use of Floating Point Comparison:


Floating point numbers ko == se compare karna kabhi-kabhi unexpected results de sakta
hai, kyunki precision issues hote hain.

• Integer Division Confusion:


Agar do integers ko divide kiya jata hai to result integer division hota hai, jisme decimal
part truncate (remove) ho jata hai.

• Overusing + for String Concatenation in Loops:


Loops me strings ko + se baar-baar concatenate karne se performance issue ho sakta hai,
kyunki har iteration me naya string object create hota hai.

• 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.

Inki help se:

• Koi block of code multiple times execute karaya ja sakta hai.

• Conditions ke basis par code execute kar sakte hain.

• Kuch lines of code ko terminate ya skip bhi kiya ja sakta hai.

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.

Conditional Statements in Programming:


Conditional statements programming me use hote hain specified conditions ke basis par certain
blocks of code execute karne ke liye.

Yeh programs me decision-making ke liye bahut important hote hain.

Neeche conditional statements ke kuch common types diye gaye hain:

Conditional statements in programming are used to execute certain blocks of code


based on specified conditions. They are fundamental to decision-making in programs. Here
are some common types of conditional statements:

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");
}
}
}

2. if-else Statement in Programming:


if-else statement ka use tab hota hai jab specified condition true ho to ek block of code
execute hota hai, aur agar condition false ho to doosra block of code execute hota hai.

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");
}
}
}

3. if-else-if Statement in Programming:


if-else-if statement ka use tab hota hai jab multiple conditions check karni hoti hain.

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");
}
}
}

4. Ternary Operator or Conditional Operator in Programming:


Kuch programming languages me ternary operator ka use kisi condition ke basis par
variable ko value assign karne ke liye kiya jata hai. 😊

In some programming languages, a ternary operator is used to assign a value to a variable


based on a condition.
import [Link].*;

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");
}
}

[Link] Statement in Programming:


Languages jaise C, C++, aur Java me switch statement ka use ek expression ki value ke
basis par multiple options me se ek block of code execute karne ke liye kiya jata hai. 😊

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");
}

Looping Statements in Programming:


Looping statements, jinko iteration ya repetition statements bhi kaha jata hai, programming me
ek block of code ko baar-baar execute karne ke liye use kiye jate hain.

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.

Neeche looping statements ke kuch common types diye gaye hain: 😊

Looping statements, also known as iteration or repetition statements, are used in


programming to repeatedly execute a block of code. They are essential for performing
tasks such as iterating over elements in a list, reading data from a file, or executing a set of
instructions a specific number of times. Here are some common types of looping
statements:

1. For Loop in Programming:


2. While Loop in Programming:

3. Do-while Loop in Programming:

5. Nested Loops in Programming:


1. For Loop in Programming:
For loop ka use ek sequence (jaise list, tuple, string, ya range) par iterate karne ke liye hota hai,
aur sequence ke har item ke liye ek block of code execute kiya jata hai. 😊

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.

public class Main {


public static void main(String[] args)
{
for (int i = 0; i < 5; i++) {
[Link](i);
}
}
}

2. While Loop in Programming:


While loop ka use ek block of code ko baar-baar execute karne ke liye hota hai, jab tak
specified condition true rehti hai. 😊

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++;
}
}
}

3. Do-while Loop in Programming:


Kuch programming languages jaise C aur Java me do-while loop ka use ek block of code ko kam
se kam ek baar execute karne ke liye hota hai, aur uske baad jab tak specified condition true
rahe tab tak code repeatedly execute hota rehta hai. 😊
In some programming languages, such as C and java, a do-while loop is used to execute a
block of code at least once, and then repeatedly execute the block 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;
do {
[Link](count);
count++;
} while (count < 5);
}
}

4. Nested Loops in Programming:


Loops ko ek dusre ke andar bhi use kiya ja sakta hai, jise nested loops kaha jata hai, jisse
complex iterations perform kiye ja sakte hain.

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);
}
}
}
}

Jump Statements in Programming:


Jump statements programming me program ke flow of control ko change karne ke liye use hote
hain.

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

Jump statements in programming are used to change the flow of


control within a program. They allow the programmer to transfer
program control to different parts of the code based on certain
conditions or requirements. Here are common types of jump
statements:
1. Break Statement in Programming:
Break statement mainly loops se jaldi exit hone ke liye use hota hai.

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. 😊

The break statement is primarily used to exit from loops prematurely.


When encountered inside a loop, it terminates the loop’s execution
and transfers control to the statement immediately following the
loop.
import [Link].*;
class Coding_Club {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 5)
break;
[Link](i + " ");
}
}
}
2. Continue Statement in Programming:
Continue statement ka use loop ki current iteration ko skip karne ke liye hota hai
aur direct next iteration par move kar jata hai. 😊
The continue statement is used to skip the current iteration of a loop
and proceed to the next iteration.

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.

• Array ka first element index 0 par hota hai. 😊

• An array is a collection of elements of the same data type


stored in contiguous memory locations. It allows multiple
values to be stored under a single name and accessed using an
index.
• Java arrays can hold both primitive types (like int, char,
boolean, etc.) and objects (like String, Integer, etc.)
• When we use arrays of primitive types, the elements are stored
in contiguous locations. For non primitive types, references to
items are stored at contiguous locations.
• The first element of the array is at index 0.
After creating an array, its size is fixed; we can not change it.
public class Coding_Club {

public static void main(String[] args){

// 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 (String objects)


String[] names = {"Lakshit", "Rahul", "Pankaj"};

[Link]("Non-Primitive Array -> ");


for (int i = 0; i < [Link]; i++)
[Link](names[i] + " ");
}
}
Explanation:
Primitive array me integer values store hoti hain aur ise loop ki help se traverse kiya jata hai.

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. 😊

In Java, an array is declared by specifying the data type, followed by


the array name, and empty square brackets [ ].
data Type [] arrayName;
or
Data Type arrayName[];
Initialization an Array
Jab array declare kiya jata hai, tab sirf ek reference create hota hai.

Actual memory allocation new keyword ki help se hoti hai, jisme array ka size specify kiya jata
hai. 😊

When an array is declared, only a reference is created. Memory is


allocated using the new keyword by specifying the array size.

Int arr[] = new int[size];


Array declaration generally static hota hai, lekin agar size define na ho, to array dynamically sized
ho sakta hai.

Java me arrays ke liye memory hamesha heap me allocate hoti hai.

new keyword se create kiye gaye array ke elements automatically initialize ho jate hain:

• 0 (numeric types ke liye)

• false (boolean ke liye)

• null (reference types ke liye) 😊


• Array Declaration is generally static, but if the size in not
defined, the Array is Dynamically sized.
• Memory for arrays is always allocated on the heap in Java.
• The elements in the array allocated by new will automatically
be initialized to zero (for numeric types), false (for boolean) or
null (for reference types).

Initialization using Array Literal

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.

// Declaring array literal


int [] arr = {1,2,3,4,5};

Is array ki length hi created array ki length ko determine karti hai.

Java ke latest versions me new int[] likhne ki zarurat nahi hoti. 😊

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.

Operations on Array Elements


1. Access Array Elements
Array ke elements ko unki position se access kiya jata hai, jise index kaha jata hai.

Java me array indexing 0 se start hoti hai (1 se nahi).

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) {

int[] arr = {2, 4, 8, 12, 16};

// Accessing fourth element


[Link](arr[3] + " ");

// Accessing first element


[Link](arr[0]);
}
}
2. Update Array Elements
Array me kisi specific index par element ko update karne ke liye, assignment operator = ka use
kiya jata hai.

Isme array element ko access karke usse ek new value assign kar di jati hai. 😊

To update an element at a specific index in an array, use the


assignment operator = while accessing the array element and assign a
new value.

class Coding_Club {
public static void main(String[] args) {

int[] arr = {2, 4, 8, 12, 16};

// Updating first element


arr[0] = 90;
[Link](arr[0]);
}
}
3. Traverse Array
Traversing an array ka matlab hai array ke har element ko ek-ek karke access karna.

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. 😊

Traversing an array means accessing each element one by one. In Java,


arrays can be easily traversed using a loop where the loop variable
runs from 0 to [Link] - 1.

class Coding_Club {
public static void main(String[] args){

int[] arr = {2, 4, 8, 12, 16};

// Traversing and printing array


for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + " ");
}
}
}
4. Size of Array
Array ka size us number of elements ko refer karta hai jo array hold kar sakta hai.

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) {

int[] arr = {2, 4, 8, 12, 16};


[Link]("Size of array: " + [Link]);
}
}
Java Strings
Java me String ek object type hota hai jo double quotes (" ") ke andar characters ki sequence
store karta hai.

Har character 16 bits me store hota hai, yani UTF-16 encoding ka use hota hai.

String ka behaviour characters ke array jaisa 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. 😊

In Java, a String is the type of object that can store a sequence of


characters enclosed by double quotes and every character is stored in
16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an
array of characters. Java provides a robust and flexible API for
handling strings, allowing for various operations such as
concatenation, comparison and manipulation.
Example
String name = “Coding_Coding”;
String num = “1234”;
public class Coding_Club {

// 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:

1. String literal (Static Memory)

2. 2. Using new keyword (Heap Memory)


1. String literal (Static Memory)
Java ko more memory efficient banane ke liye aisa kiya jata hai, kyunki agar string pehle
se String Constant Pool me exist karti hai to naya object create nahi hota. 😊

To make Java more memory efficient (because no new objects are


created if it exists already in the string constant pool).

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.

Variable s heap (non-pool) me bane object ko refer karta 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. 😊

String is an immutable class in Java, which means that once a String


object is created, its value cannot be changed. If you want to modify a
string a new String object is created and the original remains
unchanged.

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. 😊

StringBuffer is a peer class of String, it is mutable in nature and it is


thread safe class , we can use it when we have multi threaded
environment and shared object of string buffer i.e, used by mutiple
thread. As it is thread safe so there is extra overhead, so it is mainly
used for multithreaded program.

StringBuffer sb = new StringBuffer(“ITM”);


3. StringBuilder
StringBuilder Java me String aur StringBuffer ka alternative hai. Yeh mutable sequence of
characters create karta hai, aur thread-safe nahi hota.

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. 😊

StringBuilder in Java represents an alternative to String and


StringBuffer Class, as it creates a mutable sequence of characters and
it is not thread safe. It is used only within the thread , so there is no
extra overhead , so it is mainly used for single threaded program

StringBuider sb = new StringBuilder(“Coding”);


[Link](“ Club”)
4. StringTokenizer
Java me StringTokenizer class ka use string ko tokens me break (split) karne ke liye kiya jata hai.
String Tokenizer class in Java is used to break a string into tokens.

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. 😊

A StringTokenizer object internally maintains a current position within


the string to be tokenized. Some operations advance this current
position past the characters processed. A token is returned by taking a
substring of the string that was used to create the StringTokenizer
object.
StringTokenizer st = new StringTokenizer(“Coding Club”);
Immutable String in Java

Java me String objects immutable hote hain.

Immutable ka simple matlab hai unmodifiable ya unchangeable.

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. 😊

In Java, string objects are immutable. Immutable simply means


unmodifiable or unchangeable. Once a string object is created its data
or state can't be changed but a new string object is created.
import [Link].*;

class Coding_Club
{
public static void main(String[] args)
{
String s = "Sachin";

// concat() method appends the string at the end


[Link](" Tendulkar");

// This will print Sachin because strings are immutable objects


[Link](s);
}
}
Yaha “Sachin” change nahi hota, balki “Sachin Tendulkar” ke naam se ek naya object create ho
jata hai. Isi wajah se String ko immutable kaha jata hai.
Jaise figure me dikhaya gaya hai, do objects create hote hain, lekin reference variable s abhi bhi
"Sachin" ko hi refer karta hai, "Sachin Tendulkar" ko nahi.

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

In Java, classes and objects form the foundation of Object-Oriented


Programming (OOP). They help model real-world entities and organize
code in a structured way.
A class is a blueprint used to create objects that share common
properties and behavior.
An object is an instance of a class. It represents a specific entity
created from the class template.
For Example, Dog is a class, Tommy is an object of that class.

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.

A class is a blueprint that defines data and behavior for objects. It


groups related fields and methods in a single unit. Memory for its
members is allocated only when an object is created.
• Acts as a template to create objects with shared structure.
• Does not occupy memory for fields until instantiation.
• Can contain fields, methods, constructors, nested classes and
interfaces.

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.

An object is an instance of a class created to access its data and


operations. Each object holds its own state.
• State: Values stored in fields.
• Behavior: Actions defined through methods.
• Identity: Distinguishes one object from another.
Object Instantiation
Object create karne ki process ko instantiation kaha jata hai.

Class ke sabhi instances same structure aur behavior share karte hain, lekin unke state values
alag-alag store ho sakte hain.

Creating an object is known as instantiation. All instances of a class


share structure and behavior while storing different state values.
Dog tuffy;
tuffy = new Dog(“Tuffy”,”Papillon”,5,”White’);

• public class Dog {


• String name;
• String breed;
• int age;
• String color;
• public Dog(String name, String breed, int age, String color) {
• [Link] = name;
• [Link] = breed;
• [Link] = age;
• [Link] = color;
• }
• public String getName() { return name; }
• public String getBreed() { return breed; }
• public int getAge() { return age; }
• public String getColor() { return color; }
• @Override
• public String toString() {
• return "Name is: " + name
• • + "\nBreed age and color are: "
• • + breed + " " + age + " " + color;
• }
• public static void main(String[] args) {
• Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
• [Link](tuffy);
• }
• }
• Explanation: This creates a Dog object named tuffy using the Dog
constructor inside main(), which initializes name, breed, age, and
color. When [Link](tuffy) is executed, the overridden
toString() method is called to display the object’s data.
Note: Har class me kam se kam ek constructor hota hai.

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.

Initialize Object by using Method/Function


• public class Coding_Club {
• static String name;
• static float price;
• static void set(String n, float p) {
• name = n;
• price = p;
• }
• static void get() {
• [Link]("Software name is: " + name);
• [Link]("Software price is: " + price);
• }
• public static void main(String[] args) {
• Coding_Club.set("Visual Studio", 0.0f);
• Coding_Club.get();
• }
• }

Ways to Create Object in Java


1. Using new Keyword
new Keyword is most direct way to create an object.
// creating object of class Test
Test t = new Test();
2. Using clone() method
3. class Coding_Club implements Cloneable {
4. String name = "GeeksForGeeks";
5. @Override
6. protected Object clone() throws
7. CloneNotSupportedException {
8. return [Link]();
9. }
10. public static void main(String[] args) {
11. try {
12. Coding_Club c = new Coding_Club();
13. Coding_Club cc = (Coding_Club) [Link]();
14. [Link]([Link]);
15. } catch (Exception e) {
16. [Link]();
17. }
18. }
19. }
20.
Anonymous Objects
Anonymous objects wo objects hote hain jo bina reference variable ke create kiye jate hain aur
one-time operations ke liye turant use ho jate hain.

• No reference variable: Isliye object ko reuse nahi kiya ja sakta.

• Instantly create aur use ho jata hai, isse short-lived tasks me memory save hoti hai.

• Event handling me common hai (jaise button clicks).

Example:
new Dog("Max", "Labrador", 3, "Black").getName();

Anonymous objects are created without a reference and used


immediately for one-time operations.
• No reference variable: Cannot reuse the object.
• Created & used instantly, saves memory for short-lived tasks.
• Common in event handling (e.g., button clicks).
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.

Inheritance in Java is a core OOP concept that allows a class to acquire


properties and behaviors from another class. It helps in creating a new
class from an existing class, promoting code reusability and better
organization.
A subclass can reuse the fields and methods of the parent class
without rewriting the code
A subclass can add its own fields and methods or modify existing ones
to extend functionality.

• // 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.

Types of Inheritance in Java


Below are the different types of inheritance which are supported by Java.

1. Single Inheritance

Single inheritance me ek sub-class sirf ek hi super class se derive hoti hai.

Isme sub-class ek single parent class ki properties aur behavior inherit karti hai.

Kabhi-kabhi ise simple inheritance bhi kaha jata hai.


In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.
• //Super class
• class Vehicle {
• Vehicle() {
• [Link]("This is a Vehicle");
• }
• }
• // Subclass
• class Car extends Vehicle {
• Car() {
• [Link]("This Vehicle is Car");
• }
• }
• public class Test {
• public static void main(String[] args) {
• // Creating object of subclass invokes base class constructor
• Car obj = new Car();
• }
• }
2. Multilevel Inheritance
Multilevel inheritance me ek derived class base class se inherit karti hai, aur yei
derived class khud doosri classes ke liye base class ka kaam bhi 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.

Yani, ek hi base class se multiple derived classes create ki jati 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");

• }

• }

• class Car extends Vehicle {

• Car() {

• [Link]("This Vehicle is Car");

• }

• }

• class Bus extends Vehicle {

• Bus() {

• [Link]("This Vehicle is Bus");

• }
• }

• public class Test {

• public static void main(String[] args) {

• Car obj1 = new Car();

• Bus obj2 = new Bus();

• }

• }

3. Multiple Inheritance (Through Interfaces)


Multiple inheritance me ek class ke paas ek se zyada superclasses ho sakte hain aur wo sabhi
parent classes ke features inherit kar sakti hai.

Note: Java classes ke saath multiple inheritance support nahi karta.


Java me multiple inheritance sirf Interfaces ke through achieve kiya ja sakta hai.

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.

It is a mix of two or more of the above types of


inheritance. In Java, we can achieve hybrid inheritance
only through Interfaces if we want to involve multiple
inheritance to implement Hybrid inheritance.
Polymorphism in Java
Polymorphism Java me OOP ka ek core concept hai jo objects ko unke specific class type ke basis
par alag behavior dene ki permission deta 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.

Polymorphism in Java is one of the core concepts in object-oriented


programming (OOP) that allows objects to behave differently based on
their specific class type. The word polymorphism means having many
forms, and it comes from the Greek words poly (many) and morph
(forms). This means one entity can take many forms.

Multiple Behaviors: The same method can behave differently depending


on the object that calls this method.

Method Overriding: A child class can redefine a method of its parent


class.

Method Overloading: We can define multiple methods with the same


name but different parameters.
Runtime Decision: At runtime, Java determines which method to call
depending on the object's actual class.

Real-Life Illustration of Polymorphism


Socho ek person jo life me different roles play karta hai, jaise father, husband, aur employee.

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.

Consider a person who plays different roles in life, like a father,


a husband, and an employee. Each of these roles defines
different behaviors of the person depending on the object
calling it.

• // Base class Person


• class Person {

• // Method that displays the
• // role of a person
• void role() {
• [Link]("I am a person.");
• }
• }
• // Derived class Father that
• // overrides the role method
• class Father extends Person {

• // Overridden method to show
• // the role of a father
• @Override
• void role() {
• [Link]("I am a father.");
• }
• }
• public class Main {
• public static void main(String[] args) {

• // Creating a reference of type Person
• // but initializing it with Father class object
• Person p = new Father();

• // Calling the role method. It calls the
• // overridden version in Father class
• [Link]();
• }
• }

Types of Polymorphism in Java

In Java Polymorphism is mainly divided into two types:


Compile-Time Polymorphism
Compile-Time Polymorphism Java me static polymorphism ke naam se bhi jana jata hai, aur ise
method overloading ke through achieve kiya jata 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.

Compile-Time Polymorphism in Java is also known as


static polymorphism and also known as method
overloading. This happens when multiple methods in the
same class have the same name but different parameters.

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.

Method overloading by changing the number of


arguments
• class Helper {
• // Method with 2 integer parameters
• static int Multiply(int a, int b)
• {
• // Returns product of integer numbers
• return a * b;
• }
• // Method 2
• // With same name but with 2 double parameters
• static double Multiply(double a, double b)
• {
• // Returns product of double numbers
• return a * b;
• }
• }
• // Class 2
• // Main class
• class Geeks
• {
• // Main driver method
• public static void main(String[] args) {

• // Calling method by passing
• // input as in arguments
• [Link]([Link](2, 4));
• [Link]([Link](5.5, 6.3));
• }
• }
Explanation:

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

Explanation: The Multiply method is overloaded with


different parameter types. The compiler picks the correct
method during compile time based on the 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

Runtime Polymorphism in Java is also known as dynamic


method dispatch. It occurs when a method call is resolved at
runtime, and it is achieved using method overriding.

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.

Isliye child class ke method ka body execute hota 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:

• It can make more difficult to understand the behavior of an object.


• This may cause performance issues, as polymorphic behavior may require additional
computations at runtime.
Encapsulation in Java
Encapsulation ka matlab hai data aur us data par kaam karne wale functions ko ek single unit
me combine karna, jaise class.

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:

• Better maintainability, readability aur usability.

• 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:

• Private data members use kiye jate hain.

• 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.

Encapsulation in Java is achieved using:


• Private data members
• Public getter and setter methods
Key Rules:
• Declare data as private: Hide the class data so it cannot be
accessed directly from outside the class.
• Use getters and setters: Keep variables private and
provide public getter and setter methods for controlled
access and safe modification, often with validation.
• Apply proper access modifiers: Use private for data hiding
and public for methods that provide access.
class Programmer {
private String name;
// Getter method used to get the data
public String getName() { return name; }
// Setter method is used to set or modify the data
public void setName(String name) {

[Link] = name;
}
}
public class Coding_Club {
public static void main(String[] args){

Programmer p = new Programmer();


[Link](“ITM");
[Link]("Name=> " + [Link]());
}
}
Explanation:
Upar wale example me encapsulation use ki gayi hai aur getter (getName) aur setter (setName)
methods ka use kiya gaya hai, jo private data ko access aur modify karne ke liye hain.

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.

• Improved Maintainability: Internal implementation me changes easily kiye ja sakte hain


bina external code ko affect kiye.

• 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.

The advantages of encapsulation are listed below:


• Data Hiding: Encapsulation restricts direct access to class
variables, protecting sensitive data from unauthorized
access.
• Improved Maintainability: Changes to internal
implementation can be made without affecting external
code that uses the class.
• Enhanced Security: Encapsulation allows validation and
control over data, preventing invalid or harmful values
from being set.
• Code Reusability: Encapsulated classes can be reused in
different programs without exposing internal logic.
• Better Modularity: Encapsulation promotes organized,
modular code by keeping data and methods together
within a class.
Disadvantages of Encapsulation
Encapsulation ke disadvantages:

• 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.

The disadvantages of encapsulation are listed below:


• Increased Code Complexity: Writing getter and setter
methods for every variable can make the code longer and
slightly more complex.
• Performance Overhead: Accessing data through methods
instead of directly can introduce a minor performance
cost, especially in performance-critical applications.
• Less Flexibility in Some Cases: Over-restricting access to
class members may limit the ability of other classes to
extend or use the class efficiently.
Data Hiding vs Encapsulation

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.

• Abstract classes me methods without implementation ho sakte hain, jo subclasses dwara


implement karna zaruri hota 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.

How to Achieve Abstraction in Java?


Java me abstraction implement karne ke do tarike hote hain:

• Abstract Classes (Partial Abstraction)

• Interface (100% Abstraction)

Java provides two ways to implement abstraction, which are


listed below:
• Abstract Classes (Partial Abstraction)
• Interface (100% Abstraction)

Real-Life Example of Abstraction


Television remote control abstraction ka best example hai.

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.

The television remote control is the best example of abstraction. It


simplifies the interaction with a TV by hiding all the complex
technology. We don't need to understand how the TV internally
works; we just need to press the button to change the channel or
adjust the volume.

abstract class TV {
abstract void turnOn();
abstract void turnOff();
}
// Concrete class implementing the abstract methods
class TVRemote extends TV{
@Override
void turnOn(){

[Link]("TV is turned ON.");


}
@Override
void turnOff(){

[Link]("TV is turned OFF.");


}
}
// Main class to demonstrate abstraction
public class Coding_Club {

public static void main(String[] args){

TV remote = new TVRemote();


[Link]();
[Link]();
}
}
Explanation:
• TV is abstract class defining turnOn() and turnOff()
methods.
• TVRemote class implements the abstract methods with
specific logic.
• Coding_Club class(Main class) uses TV remote = new
TVRemote(); to interact without knowing the internal
implementation.
Abstract class
Abstract Class ek aisi class hoti hai jo instantiate nahi ki ja sakti aur jisme abstract methods
(methods without body) ke saath-saath concrete methods (methods with implementation) bhi ho
sakte hain.

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:

• Kuch shapes flip kiye ja sakte hain.

• Har shape ka area calculate karne ka method alag hota hai, jo shared features aur
individual differences dono dikhata hai.

An abstract class is a class that cannot be instantiated and


may contain abstract methods (methods without body) as
well as concrete methods (with implementation).
In shape example, a base type Shape has common properties
like color and size. Specific shapes—Circle, Square, Triangle—
inherit from Shape and may have unique properties or
behaviors.
For instance, some shapes can be flipped, and each shape
calculates its area differently, illustrating both shared features
and individual differences.
Partial Abstraction
Example:

Ye program partial abstraction demonstrate karta hai.

• Abstract class Shape define ki gayi hai.

• Isme ek abstract method area() hai (jo subclasses implement karenge).

• Ek concrete method getColor() bhi hai.

• Aur constructor bhi defined hai.

Is tarah abstract class common features provide karti hai, aur subclasses ko specific
implementation dene ka option deti hai.

Example: This program demonstrates partial abstraction by


defining an abstract class Shape that includes an abstract
method area(), a concrete method getColor(), and a
constructor.

abstract class Shape{


String color;
// these are abstract methods
abstract double area();
public abstract String toString();
// abstract class can have the constructor
public Shape(String color){

[Link]("Shape constructor called");


[Link] = color;
}
// this is a concrete method
public String getColor(){

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(){

return [Link] * [Link](radius, 2);


}
@Override public String toString(){

return "Circle color is " + [Link]() + "and area is : " + area();


}
}
class Rectangle extends Shape{
double length;
double width;
public Rectangle(String color, double length,
double width)
{
// calling Shape constructor
super(color);
[Link]("Rectangle constructor called");
[Link] = length;
[Link] = width;
}
@Override double area() { return length * width; }
@Override public String toString()
{
return "Rectangle color is " + [Link]()
+ "and area is : " + area();
}
}
• public class Test {
• public static void main(String[] args)
• {
• Shape s1 = new Circle("Red", 2.2);
• Shape s2 = new Rectangle("Yellow", 2, 4);
• [Link]([Link]());
• [Link]([Link]());
• }
• }

Interface
Interface ek class ka blueprint hota hai jo Java me 100% abstraction achieve karne ke liye use
hota hai.

• Isme abstract methods aur constants ho sakte hain.

• 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.

Interfaces is a blueprint of a class used to achieve 100% abstraction


in Java. It can contain abstract methods and constants but no
method bodies (except default and static methods from Java 8
onward).
Implementation: To implement an interface we use the
keyword “implements” with class.
// Define an interface named Shape
interface Shape{

// Abstract method for calculating the area


double calculateArea();
}
// Implement the interface
// in a class named Circle
class Circle implements Shape{

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{

private double length;


private double width;
// Constructor for Rectangle
public Rectangle(double length, double width){

[Link] = length;
[Link] = width;
}
// Implementing the abstract
// method from the Shape interface
public double calculateArea() {
return length * width;
}
}

public class Main {


public static void main(String[] args) {
// Reference type is the interface (Shape)
Shape cir = new Circle(5.0);
Shape rect = new Rectangle(4.0, 6.0);
// Dynamic method dispatch — decides which method to call at runtime
[Link]("Area of Circle: " + [Link]());
[Link]("Area of Rectangle: " + [Link]());
}
}

Advantages of Abstraction
Abstraction ke benefits:

• Simplifies Understanding: Complex systems ko samajhna easy hota hai, kyunki


implementation details hide ki jaati hain.

• Separation of Concerns: System ke different parts alag-alag rakhe ja sakte hain.

• Efficient Code Maintenance: Code ko efficiently maintain kiya ja sakta hai.

• Increased Security: Sirf necessary details user ko show ki jaati hain, jisse security improve
hoti hai.

Abstraction makes complex systems easier to understand by hiding the implementation


details.
Abstraction keeps different part of the system separated.
Abstraction maintains code more efficiently.
Abstraction increases the security by only showing the necessary details to the user.
Disadvantages of Abstraction
Abstraction ke disadvantages:
• Unnecessary Complexity: Agar overuse ho jaye, to code unnecessarily complex ho sakta
hai.

• Reduced Flexibility: Implementation me flexibility kam ho sakti hai.

• Harder Debugging & Understanding: System ko samajhna aur debug karna difficult ho jata
hai, especially unfamiliar users ke liye.

• Performance Overhead: Abstraction layers ke wajah se performance affect ho sakti hai.

Abstraction ke disadvantages:

• It can add unnecessary complexity if overused.


May reduce flexibility in implementation.
• Makes debugging and understanding the system harder for
unfamiliar users.
• Overhead from abstraction layers can affect performance.

Common Mistakes to Avoid


Common mistakes to avoid in Abstraction (Java):

• 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.

• Inconsistent Method Signatures in Subclasses: Jab abstract methods override karo, to


method signature exactly match honi chahiye, warna errors aa sakte hain.

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:

• Organize large applications: Code ko modular aur maintainable banate hain.

• 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.

• Encouraging Modular Programming: Code ko modular aur organized banata hai

A package in Java is a mechanism to group related classes, interfaces,


and sub-packages into a single unit. Packages help organize large
applications, avoid naming conflicts, provide access protection, and
make code modular and maintainable.
• Avoiding name conflicts (two classes with the same name can
exist in different packages)
• Providing access control using public, protected, and default
access
• Reusability: packaged code can be imported and used anywhere
• Encouraging modular programming

Built-in Packages

Built-in Packages me bohot saari classes hoti hain jo Java API ka part hoti hain.

Commonly used built-in packages:

• [Link] – Language support classes (jaise primitive data types, math operations). Ye
package automatically import ho jata hai.

• [Link] – Input/output operations ke liye classes provide karta hai.

• [Link] – Utility classes provide karta hai jaise Linked Lists, Dictionaries, aur date &
time operations.

• [Link] – Applets create karne ke liye classes.

• [Link] – GUI components ke liye classes (jaise buttons, menus, etc).

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 {

public static void main(String[] args) {

// using Random class


Random rand = new Random();
// generates a number between 0–99
int number = [Link](100);
[Link]("Random number: " + number);
}
}

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!");
}
}

To use it in another class:

import [Link];
public class Test {
public static void main(String[] args) {
[Link]();
}
}
Accessing Classes Inside a Package

In Java, we can import classes from a package using either of


the following methods:

1 Import a Single Class


import [Link];
This imports only the Vector class from the [Link] package.
2. Import all classes from a package:
import [Link].*;
This imports all classes and interfaces from the [Link]
package but does not include sub-packages.

Example: Import the Vector class


import [Link];
public class Coding_Club {

public Coding_Club() {

// [Link] is imported, We are able to access it


directly in our code.
Vector v = new Vector();
[Link] l = new [Link]();
[Link](3);
[Link](5);
[Link](7);

[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.

• Private: Sirf same class ke andar accessible.

• Default (no modifier): Same package ke andar accessible, package ke bahar nahi.

• Protected: Same package ke andar aur subclasses (even different packages) me accessible.

• Public: Kahaan se bhi accessible, chahe package alag ho.

Isliye packages ka structure access control aur data encapsulation me important role play karta
hai.

• Packages directly influence Java access levels:


CLASSPATH Setting for Package
CLASSPATH ek environment variable hai jo Java compiler ([Link]) aur Java interpreter
([Link]) ko batata hai ki class files kahan se import ya find karni hain.

• CLASSPATH me application ke liye required files ka location define hota 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!");
}
}

How to Set Classpath in Java?


Class path Environment Variable set karne ka tarika (Windows):

1. Right-click karo My Computer par aur Properties select karo.

2. Advanced system settings select karo.

3. Environment Variables par click karo — yahan do variable lists dikhengi.

4. User variables list me CLASSPATH variable dhundo:

a. Agar mil jaye, to Edit par click karo.

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:

a. Current directory ko dot (.) se represent kiya jata hai.

b. Agar multiple items hain, to semicolon (;) se separate karo.

Example:

.;C:\java\lib\[Link];C:\java\classes

• Yahan first dot (.) current directory ko represent karta hai, jo zaruri hai.

• Baaki paths additional directories ya jar files ko specify karte hain.

Is tarah Java compiler aur JVM ko pata chal jata hai ki required classes aur resources kahan se
load karni hain

Setting classpath enviorment variable :


Right click on My Computer
Select properties.
Select advance system settings.
Click the Environment Variables and you will see two lists of variables.
Look in the user variables list for a variable named CLASSPATH. If you
find it, click Edit. If you don’t find it, click New and enter CLASSPATH in
the Variable name field.
The Variable value field is a list of file paths of directories or jar files. The
first thing in this list should be the current directory, which is
represented in windows as a single period (DOT). If there’s more than
one thing in this list, separate items with a semicolon.
For example, my CLASSPATH variable starts with these three items
(there are a couple more, but this should be enough to give you the
idea). The only part you need is the first “dot”.
JAR Files
Java Archive (JAR) File:

• 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.

Basic Command for Creating a JAR File:

jar cf jar-file input-file(s)

Options:

• c → JAR file create karne ke liye.

• f → Output ek file me dene ke liye.

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:

D:\RAT> jar cf [Link] p1/*.class

• Yahan [Link] output JAR file hai.


• p1/*.class me saare class files bundle honge.

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:

• Lowercase letters me likho.

• Usually reverse domain name convention follow karo.

• Words ko dots (.) se separate karo.

• Underscores aur uppercase letters avoid karo.

Rules:
• Written in lowercase letters
• Usually based on reverse domain name
Words separated by dots ( . )
• Avoid underscores and uppercase letters

Import Naming Convention


Rules :
• Package – lowercase
• Class – First letter Capital (PascalCase)
import [Link]
For Example :
import [Link];
static import Naming Convention
Static import is used to import static members (variables/methods) of
a class.
Rules :
Package – lowercase
Class – PascalCase
Static Member – camelCase (for methods) or Upper_Case (for
constants)
Syntax
import static [Link]
Import Static Method
Without static import:
[Link](16);
With static import:
import static [Link];
sqrt(16);

import static [Link];


[Link](PI);

Import All Static Members

import static [Link].*;

Naming Summary Table

Element Naming Style Example

Package lowercase [Link]

Class PascalCase Scanner


Method camelCase nextInt()

Variable camelCase totalMarks

Constant UPPER_CASE PI

Important Points for Exams


Package names → always lowercase
Class names → first letter capital
Static members → camelCase (methods), UPPER_CASE (constants)
Use static import only when necessary (for readability)

You might also like