Contents:
•What is Full Stack Development?
•JAVA FULL STACK DEVELOPMENT?
•Architecture Diagram
•Software's/Installations
•Basic Java Application
Full Stack Development:
Full Stack Development means developing both the front-end (client side) and back-end (server side)
along with managing the database and sometimes the deployment (hosting and maintenance).
Java Full Stack Development:
Java Full Stack Development in Web Design means developing both the front-end (client side) and back-end (server side)
parts of a website or web application,
along with managing the database and sometimes the deployment (hosting and maintenance).
1. Website
A website is a collection of static or informational web pages that mainly provide content to read or view.
It is mostly one-way interaction — the user reads or sees the content but doesn’t do much else.
🔹 Purpose: To display information
🔹 Example: News sites, portfolios, blogs, company websites
2. Web Application:
A web application is an interactive program that runs in a web browser. Users can perform tasks, input data, and get real-
time results.
It’s a two-way interaction between user and server.
🔹 Purpose: To perform specific functions or tasks
🔹 Example: Online banking, shopping sites, email services
Feature Website Web Application
Purpose Informational Interactive / Functional
User Interaction Very limited High (forms, login, etc.)
Backend / Database Not always needed Always needed
Examples Blog, News site Gmail, Amazon
Technology HTML, CSS, JS Frontend + Backend (Java, [Link], etc.)
Dynamic Content Mostly static Dynamic (changes per user)
Architecture Diagram: Java FSD
Architecture Diagram: Mobile App Development
Software's/Installations
1. Java
2. Eclipse IDE
3. MySQL (Database Server)
Java:
Link to download: (Download MSI)
With Login:
[Link]
With out login:
[Link]
Note: Download MSI file and install it. After installation we need to setup Environment Variables in System Settings
using the following steps:
[Link] My Computer/This PC Properties
[Link] Advanced System Settings
[Link] on Environment Variables
[Link] System Variables select path and click on edit
[Link] New and Add the Java installation path till bin folder and Click ok
[Link] Setup is done and go to the command prompt and type java –version, it has to show the java version successfully
as below:
Eclipse IDE:
Download link:
[Link]
pers
After download, Extract it into a folder
Note: When we open Eclipse, Iit will integrate Java installed automatically
MySql Database Server:
Download link:
MySQL :: Download MySQL Community Server
Contents:
•Class and Objects
•Variables
•Data types
•Operators
•Control Statements
•OOP concepts
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
•Exception Handling
•Garbage Collector
•Collections
•Iterators, Generics
•Lamba, Streams and Date/Time API
Class:
A class is like a blueprint or template for creating objects. It defines attributes (data)
and methods (functions/behaviors) that the objects created from the class will have.
•Think of a class as a plan for a house.
•It does not occupy memory by itself.
•It defines what an object will contain and what it can do.
Example:
// Class definition
class House {
// Properties (attributes)
String color;
int rooms;
double area;
// Behaviors (methods)
void openDoor() {
[Link]("The door of the " + color + " house is opened.");
}
void lockDoor() {
[Link]("The door of the " + color + " house is locked.");
}
}
Object:
An object is an instance of a class. It is created based on the blueprint provided by the class.
Objects occupy memory and can use the attributes and methods defined in the class.
•Think of an object as a real house built from the blueprint.
•Each object can have different values for its attributes.
Example:
// Main Class definition
public class Main {
public static void main(String[] args) {
// Creating objects (instances of class)
House h1 = new House();
[Link] = "Blue";
[Link] = 3;
[Link] = 1200.5;
House h2 = new House();
[Link] = “Red";
[Link] = 4;
[Link] = 1500.0;
// Accessing methods using objects
[Link]();
[Link]();
}
}
Data types
Java language has a rich implementation of data types. Data types specify size and
the type of values that can be stored in an identifier.
In java, data types are classified into two categories :
Primitive Data type
Non-Primitive Data type
PRIMITIVE DATATYPE
Integer data types
byte (1 byte)
short (2 bytes) -32768 to 32767
int(4 bytes)
• All numeric data types are signed
long (8 bytes)
• The size of data type remains the same on all
Floating Type platforms (standardized)
float (4 bytes) • char data type in Java is 2 bytes because it
Ex. float price = 25.67f; uses UNICODE character set.
double (8 bytes) • Unicode is a industry standard designed to
Ex. double salary = 2345.6556; uniquely encode characters used in different
human languages.
Textual • The other character sets are ASCII and
char (2 bytes) 65536
Ex. char operator = ‘+’ ; EBCDIC character sets
Logical
boolean(1 bit (true/false)
Ex. boolean flag = true;
1.
Datatype can be primitive type or reference type
Data Types and Values To specify
a
hexadecim
Ranges for primitive data types are as follows:- al (base
16)
number,
put a
leading
‘0x’ in
front of it.
To specify an octal (base number, put a leading ‘0’ in front of i
Wrapper Classes: A Wrapper Class in Java is a class that converts (wraps) a primitive data type into an object.
In Java, there are two kinds of data types:
Primitive types → like int, char, boolean, etc.
Non-Primitive types/Objects → instances of classes (like String, Integer, ArrayList, etc.)
Many parts of Java (such as Collections, Generics, and APIs) only work with objects, not primitives.
Primitive Wrapper
Type Class Size Default Value Range (Approximate) Example
byte Byte 1 byte 0 –128 to 127 byte b = 10;
short Short 2 bytes 0 –32,768 to 32,767 short s = 1000;
int Integer 4 bytes 0 –2,147,483,648 to 2,147,483,647 int i = 50000;
–9,223,372,036,854,775,808 to
long Long 8 bytes 0L 9,223,372,036,854,775,807 long l = 100000L;
float Float 4 bytes 0.0f ±3.4e−038 to ±3.4e+038 float f = 3.14f;
double Double 8 bytes 0.0d ±1.7e−308 to ±1.7e+308 double d = 99.99;
char Character 2 bytes '\u0000' 0 to 65,535 (Unicode values) char c = 'A';
1 bit (JVM-
boolean Boolean dependent) FALSE true or false boolean flag = true;
Note: All wrapper classes are present in a package [Link]
Example:
Why Its Important:
int a = 10; // Primitive type
Integer b = 10; // Non-primitive (Wrapper class) [Link] and Generics
[Link]([Link]().getName()); // Output: [Link] [Link] Object Methods
Difference Primitive and Non-Primitive(Wrapper Class): [Link] null Values
[Link] Conversions and Utilities
Feature int Integer
Non-primitive
Type Primitive
(Wrapper class)
Defined as Keyword Class ([Link])
Heap (object
Memory Stack
reference)
Default Value 0null
Has Methods ❌ No ✅ Yes
Can be used in
❌ No ✅ Yes
Collections
Can be null ❌ No ✅ Yes
[Link] and Generics: Autoboxing and Unboxing:
ArrayList<int> list = new ArrayList<>(); // ❌ Not allowed Java does it automatically through:
ArrayList<Integer> list = new ArrayList<>(); // ✅ Works Autoboxing → converts primitive → wrapper
[Link](10); // int → Integer (autoboxing)
Unboxing → converts wrapper → primitive
2. Using Object Methods:
int num = 10; int a = 5;
// [Link](); ❌ Not allowed Integer b = a; // autoboxing
Integer obj = 10; int c = b; // unboxing
[Link]([Link]()); // ✅ Converts to "10"
3. Handling Null Values:
Integer age = null; // ✅ allowed
int age2 = null; // ❌ not allowed
4. Type Conversion and Utilities:
int num = [Link]("123"); // String → int
String s = [Link](456); // int → String
Non-Primitive types In Java:
Type Description Example
Class Blueprint for creating objects. Can contain variables and class Student { String name; int age; }
methods.
Object Instance of a class. Represents actual data in memory. Student s1 = new Student();
String Sequence of characters. It is a class in [Link]. String name = "Java";
Array Collection of elements of the same type. int[] numbers = {1,2,3};
Interface A collection of abstract methods that a class can interface Animal { void sound(); }
implement.
Enum (Enumeration) Represents a fixed set of constants. enum Color { RED, GREEN, BLUE }
Wrapper Classes Classes that wrap primitive types as objects. Integer, Double, Character, Boolean
Keywords in Java
const and goto are no more used. true ,false and null are called as literal values.
Identifiers in Java
All Java components require names. Name used for classes, methods,
interfaces and variables are called Identifier. Identifier must follow
some rules. Here are the rules:
All identifiers must start with either a letter( a to z or A to Z ) or
currency character($) or an underscore.
After the first character, an identifier can have any combination of
characters.
Identifiers in Java are case sensitive, foo and Foo are two different
identifiers.
A Java keyword cannot be used as an identifier
Variable
A variable is a name of place holder that can hold single value at a
time.
Declaration of a variable:
Datatype variableName [=value];
Java Programming language defines mainly three kind of variables.
Instance variables
Static Variables
Local Variables
variable name should not start with numbers and special symbols except underscore.
Instance variables
Instance variables are variables that are declare inside a
class but used outside any method , constructor or block.
Instance variable are also variable of object commonly
known as field or property.
class Student
Ex..
{
String name;
int age;
}
Here name and age are instance variable of Student class
Static variables
Static are class variables declared with static keyword. Static variables
are initialized only once. Static variables are also used in declaring
constant along with final keyword.
Ex..
class Student
{
String name;
int age;
static int
instituteCode=1101;
}
Here instituteCode is a static variable. Each object of Student class will share instituteCode property.
Local variables
Local variables are declared in constructor or blocks or methods.
Local variables are initialized when method or constructor block start
and will be destroyed once its end. Local variable reside in stack.
Access modifiers are not used for local variable.
Ex..
float getDiscount(int price)
{
float discount;
discount=price*(20/100);
return discount;
}
Here discount is a local variable.
Operator: Operators are symbols that perform operations on variables and values.
Category Operators Description
Arithmetic Perform mathematical operations (addition, subtraction,
+-*/%
Operators multiplication, division, remainder)
Operate on a single operand (increment, decrement, unary
Unary Operators ++ -- + - ! ~
plus/minus, logical NOT, bitwise complement)
Assignment
= += -= *= /= %= &= ` = ^= <<= >>= >>>=`
Operators
Relational
== != > < >= <= Compare two values; return true or false
Operators
Logical Operators && `
Bitwise Operators &` ^ ~ << >> >>>`
Ternary Operator ?: Conditional operator — shorthand for if-else
instanceof instanceof
Tests whether an object is an instance of a given class or
Operator subclass
Type Cast
(type) Converts one data type to another (e.g., (int), (float))
Operator
Addition of two numbers:
public class AddTwoNumbers {
Basic Java Program: public static void main(String[] args) {
// This is a simple Java program // Directly assign values
int num1 = 10;
class Greet { int num2 = 20;
public static void main(String[] args) {
[Link](“Welcome to Java FSD!"); // Add the two numbers
} int sum = num1 + num2;
}
// Display the result
[Link]("The sum of " + num1 + "
and " + num2 + " is: " + sum);
}
}
Scanner Class: The Scanner class in Java is part of the [Link] package and is used to read input from various sources, such
as the keyboard, files, or strings. It is most commonly used to take input from the user via the console.
Addition of two numbers:
import [Link]; // Import the Scanner class to take
input
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]); // Create
Scanner object
// Add the two numbers
// Ask user for first number
[Link]("Enter first number: "); int sum = num1 + num2;
int num1 = [Link]();
// Display the result
// Ask user for second number [Link]("The sum of " + num1 + " and " + num2 + " is: " + sum);
[Link]("Enter second number: ");
int num2 = [Link](); [Link](); // Close the scanner
}
}
Various Output Methods:
class Main {
public static void main(String[] args) {
// Integer sum
int a = 3, b = 4, c;
c = a + b;
[Link]("The sum of " + a + " and " + b + " is: " + c);
[Link]("Sum of two numbers %d and %d is %d\n", a, b, c);
// Float sum
float a1 = 3, b1 = 4, c1;
c1 = a1 + b1;
String result = [Link]("Sum of two numbers %.2f and %.2f is %.2f", a1, b1, c1);
[Link](result);
}
}
import [Link];
public class GreetUser {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]); // Create Scanner object
[Link]("Enter your name: ");
String name = [Link](); // Read a string
[Link]("Enter your age: ");
int age = [Link](); // Read an integer
[Link]("Hello " + name + ", you are " + age + " years old.");
[Link](); // Close the scanner
}
}
Control Statements:
Control statements are used to control the flow of execution of a program
i.e., they decide which statements are executed, how many times, and under what conditions.
They are mainly divided into three types:
1. Decision-making statements/ Conditional Statements
Used to make choices based on conditions.
Statement Description Example
Executes a block if a condition is
if true if(a > b){ [Link](a); }
Executes one block if true, another
if–else if false if(a > b){...} else {...}
if–else if–else Checks multiple conditions if(a>0){...} else if(a<0){...} else {...}
Compares a value with multiple
switch cases java switch(day){case 1:...; break; default:...;}
Control Statements: (Contd..)
2. Looping statements (Iteration statements)
Used to execute a block repeatedly.
Statement Description Example
Executes a block a fixed number of
for for(int i=1;i<=5;i++){...}
times
while Repeats while condition is true while(i<=5){...}
Executes at least once, then checks
do–while do{...}while(i<=5);
condition
Control Statements: (Contd..)
3. Jump (Branching) statements
Used to transfer control from one part of code to another.
Statement Description Example
break Exits from loop or switch if(x==5) break;
continue Skips current iteration if(x==3) continue;
return Exits from a method return value;
Examples: Break:
If-else:
public class Main {
public class Main {
public static void main(String[] args) {
public static void main(String[] args) {
int number = -5; int i = 1;
if (number > 0) {
[Link](number + " is positive."); while (i <= 10) {
} else if (number < 0) { [Link](i);
[Link](number + " is negative.");
} else { if (i == 5) {
[Link]("The number is zero."); [Link]("Reached 5, stopping the loop.");
} break; // Exit the loop
} }
}
While: i++;
public class Main { }
public static void main(String[] args) { }
int i = 1; // Initialization }
while (i <= 5) { // Condition
[Link](i);
i++; // Increment
}
}
}
Inner Class:
An inner class is a class defined within another class.
Java allows you to nest classes inside other classes, and these are called inner classes.
They are used to logically group classes that are only used in one place,
increase encapsulation, and can access all members (even private ones) of the outer class.
Types of Inner Classes:
[Link]-static (regular) inner class
[Link] nested class
[Link] inner class (defined inside a method)
[Link] inner class (no name, often used for one-time use like event handling)
1. Non-static (regular) inner class:
Example:
public class OuterClass {
private String outerMessage = "Hello from Outer class!";
// Inner class
class InnerClass {
void display() {
// Inner class can access private members of the outer class
[Link](outerMessage);
}
}
public static void main(String[] args) {
// Create an instance of OuterClass
OuterClass outer = new OuterClass();
// Create an instance of InnerClass using the outer object
[Link] inner = [Link] InnerClass();
// Call method of inner class
[Link]();
}
}
2. Static Nested Class:
[Link] with the static keyword inside another class.
[Link] only access static members of the outer class.
[Link] not need an instance of the outer class to be created.
Example:
public class OuterClass {
static String staticMessage = "Hello from static nested class!";
String Name;
// Static nested class
static class StaticNestedClass {
void display() {
[Link](staticMessage); // Can access static members
}
}
public static void main(String[] args) {
// Create instance of static nested class directly
[Link] nested = new [Link]();
[Link]();
[Link];// Error
}
}
3. Local Inner Class (inside a method):
[Link] inside a method or a block.
[Link] access final or effectively final variables from the enclosing method.
[Link] is limited to the block/method where it's declared.
Example:
public class OuterClass {
void outerMethod() {
String msg = "Hello from local inner class!";
// Local inner class inside method
class LocalInnerClass {
void display() {
[Link](msg); // Accessing outer method's variable
}
}
// Creating object and calling method
LocalInnerClass local = new LocalInnerClass();
[Link]();
}
public static void main(String[] args) {
OuterClass outer = new OuterClass();
[Link]();
}
}
4. Anonymous Inner Class:
1.A class without a name, used to override methods or implement interfaces on the fly.
[Link] used when you only need to use the class once (e.g., event handling, threading, etc.)
Example:
interface Animal {
void makeSound();
}
public class Main {
public static void main(String[] args) {
// Anonymous inner class implementing Animal interface
Animal dog = new Animal() {
@Override
public void makeSound() {
[Link]("Dog barks");
}
};
[Link]();
}
}
Inheritance:
Inheritance is an OOP (Object-Oriented Programming) concept in Java where a class (child/subclass)
inherits properties and behaviors (fields and methods) from another class (parent/superclass).
Parent/super class/base class
Child/sub class/derived class
[Link] in code reusability
[Link] method overriding
[Link] hierarchical relationships
Syntax:
class Parent {
// Parent class members
}
class Child extends Parent {
// Child class members
}
Note:
Parent = Superclass/Base class
Child = Subclass/Derived class
Types of Inheritance:
Java supports different types of inheritance,
but with some restrictions (Java does not support multiple inheritance using classes to avoid ambiguity).
Type Description Example
Single Inheritance Child inherits from one parent Dog extends Animal
Multilevel Inheritance Chain of inheritance Puppy → Dog → Animal
Hierarchical Inheritance Multiple children from one parent Dog extends Animal, Cat extends Animal
Multiple Inheritance
A class implements multiple interfaces class C implements A, B
(through interface)
Hybrid Inheritance Combination of multiple types (using classes + interfaces) class C extends B implements A
Single Inheritance:
One class inherits from another.
Example:
class Developer {
void writeCode() {
[Link]("Developer writes code");
}
}
class ProjectLead extends Developer {
void reviewCode() {
[Link]("Project Lead reviews code");
}
}
class Main {
public static void main(String[] args) {
ProjectLead lead = new ProjectLead();
[Link](); // inherited from Developer
[Link](); // own method
}
}
Multilevel Inheritance: Project Manager->Project Lead->Developer
A class inherits from a derived class
Example:
class Developer { class Main {
void writeCode() { public static void main(String[] args) {
[Link]("Developer writes code"); ProjectManager pm = new ProjectManager();
} [Link](); // from Developer
} [Link](); // from ProjectLead
[Link](); // from ProjectManager
class ProjectLead extends Developer { }
void manageTeam() { }
[Link]("Project Lead manages a small team");
}
}
class ProjectManager extends ProjectLead {
void planProject() {
[Link]("Project Manager plans the project");
}
}
Hierarchical Inheritance:
Multiple classes inherit from one parent class.
Example:
class Main {
class Developer {
public static void main(String[] args) {
void writeCode() {
Tester t = new Tester();
[Link]("Developer writes code");
Designer d = new Designer();
}
}
[Link]();
[Link]();
class Tester extends Developer {
[Link]();
void testCode() {
[Link]();
[Link]("Tester tests the code");
}
}
}
}
class Designer extends Developer {
void designUI() {
[Link]("Designer creates UI/UX design");
}
}
Multiple Inheritance (Not Supported with Classes):
Java doesn’t allow multiple inheritance with classes — but supports it using interfaces.
Example:
class Main {
interface Developer {
public static void main(String[] args) {
void writeCode();
TechLead lead = new TechLead();
}
[Link]();
[Link]();
interface Manager {
}
void writeCode();
}
void planProject();
}
class TechLead implements Developer, Manager {
public void writeCode() {
[Link]("Tech Lead writes optimized code");
}
public void planProject() {
[Link]("Tech Lead plans sprint tasks");
}
}
Interface: It is class which consists of only Abstract methods that are public by default.
Abstract Method: A Method which has only Declaration but no Definition, It has to inherited to another class to define it.
Hybrid Inheritance:
Combination of more than one type (using interfaces).
Example:
class Main {
interface Employee {
public static void main(String[] args) {
void attendMeeting();
ProjectLead lead = new ProjectLead();
}
[Link]();
[Link]();
class Developer {
}
void writeCode() {
}
[Link]("Developer writes code");
}
}
class ProjectLead extends Developer implements Employee {
public void attendMeeting() {
[Link]("Project Lead attends client meeting");
}
}
Polymorphism:
Polymorphism in Java is one of the core concepts of object-oriented programming (OOP). It allows one interface to be used
for a general class of actions.
The most common use of polymorphism is when a parent class reference is used to refer to a child class object.
// Method with 3 int parameters
There are two types of polymorphism in Java: public int add(int a, int b, int c) {
[Link]-Time Polymorphism (Static Binding / Method Overloading) return a + b + c;
[Link]-Time Polymorphism (Dynamic Binding / Method Overriding)
}
1. Compile Time Polymorphism: // Method with 2 double parameters
This type of polymorphism is resolved during compilation. public double add(double a, double b) {
It happens when multiple methods in the same class return a + b;
have the same name but different parameters. }
Example: public static void main(String[] args) {
public class MathOperations { MathOperations m = new MathOperations();
[Link]([Link](5, 10)); // Calls method with 2 ints
// Method with 2 int parameters [Link]([Link](5, 10, 15)); // Calls method with 3 ints
public int add(int a, int b) { [Link]([Link](5.5, 4.5)); // Calls method with 2 doubles
return a + b; }
} }
2. Runtime Polymorphism:
[Link] type of polymorphism is resolved at runtime.
[Link] occurs when a subclass provides a specific implementation of a method already defined in its superclass.
Example:
class Animal { public class TestPolymorphism {
void sound() { public static void main(String[] args) {
[Link]("Animal makes a sound"); Dog a1 = new Dog(); // Upcasting
} Cat a2 = new Cat();
}
class Dog extends Animal { [Link](); // Calls Dog's sound() -> "Dog barks"
@Override [Link](); // Calls Cat's sound() -> "Cat meows"
void sound() { }
[Link]("Dog barks"); }
}
}
class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
Super class reference with sub class objects:
[Link] is a core concept in Java polymorphism — using a superclass reference to refer to a subclass object.
[Link] allows for dynamic method dispatch, enabling runtime polymorphism.
Example1 :
class Animal { public class Main {
void makeSound() { public static void main(String[] args) {
[Link]("Animal makes a sound"); Animal myAnimal = new Dog(); // Superclass reference, subclass object
}
} [Link](); // Calls Dog's overridden method
class Dog extends Animal { // [Link](); // ❌ Error: fetch() is not defined in Animal
@Override }
void makeSound() { }
[Link]("Dog barks");
}
void fetch() {
[Link]("Dog fetches the ball");
}
}
Example 2:
This example in more detail about what is dynamic method dispatch, enabling runtime polymorphism.
interface Animal { import [Link];
public class TestPolymorphism {
void sound();
public static void main(String[] args) {
} Animal a;
class Dog implements Animal { Scanner scanner = new Scanner([Link]); // Create Scanner object
[Link]("Enter 1:Dog,2:Cat,3:Exit");
public void sound() { int op = [Link]();
[Link]("Dog barks"); if(op ==1)
} {
} a = new Dog();
[Link]();
class Cat implements Animal {
}
public void sound() { else if(op==2)
[Link]("Cat meows"); {
} a = new Cat();
} [Link]();
}
else{
[Link]("Exiting...!");
}
}
}
Abstraction:
Abstraction is one of the four pillars of Object-Oriented Programming (OOP).
In Java, abstraction means hiding the internal implementation details and showing only the essential features to the user.
Like, Think of it like using a TV remote — you can press buttons to change the channel or volume,
but you don’t know (or need to know) how the remote works internally.
Abstraction is achieved in Java using: // Subclass (inherits from Animal)
class Dog extends Animal {
[Link] classes
// Implementation of abstract method
[Link]
@Override
Note: It helps reduce complexity and increase code reusability. void makeSound() {
[Link]("Dog barks");
Example: }
// Abstract class }
abstract class Animal {
// Abstract method (no body) public class Main {
abstract void makeSound(); public static void main(String[] args) {
Animal myDog = new Dog(); // Superclass reference to subclass object
// Regular method [Link](); // Outputs: Dog barks
void sleep() { [Link](); // Outputs: Sleeping...
[Link]("Sleeping..."); }
} }
}
Encapsulation:
Encapsulation is the concept of wrapping data (variables)
and code (methods) together as a single unit.
Note: It is used to protect the internal state of an object from unintended or unauthorized access.
In Java, encapsulation is achieved by:
[Link] fields as private.
[Link] public getter and setter methods to access and update those fields.
Benefits of Encapsulation:
[Link] security (you control who can access what).
[Link] internal implementation (only expose what’s necessary).
[Link] code more flexible and maintainable.
[Link] data validation before allowing changes.
class BankAccount {
Encapsulation Example : // Step 1: Private fields (data hiding)
// Deposit method
public void deposit(double amount) {
private String accountHolder;
if (amount > 0) {
public class Main { private double balance;
balance += amount;
public static void main(String[] args) {
[Link]("Deposited Rs." +
BankAccount account = new BankAccount(); // Step 2: Getter for account holder
amount + " successfully.");
public String getAccountHolder() {
} else {
// Using setters to set account details return accountHolder;
[Link]("Deposit amount
[Link]("Vijay"); }
must be positive.");
[Link](5000);
}
// Step 3: Setter for account holder
}
// Using getters to get account details public void setAccountHolder(String
[Link]("Account Holder: " + accountHolderName) {
// Withdraw method
[Link]()); accountHolder=accountHolderName;
public void withdraw(double amount) {
[Link]("Current Balance: Rs." + }
if (amount > 0 && amount <= balance) {
[Link]());
balance -= amount;
// Getter for balance
[Link]("Withdrawn Rs." +
// Trying to deposit and withdraw money public double getBalance() {
amount + " successfully.");
[Link](2000); // Valid deposit return balance;
} else if (amount > balance) {
[Link](1000); // Valid withdrawal }
[Link]("Insufficient
balance!");
// Trying invalid transactions // Setter for balance with validation
} else {
[Link](-500); // Invalid deposit public void setBalance(double
[Link]("Invalid withdrawal
[Link](10000); // Invalid withdrawal accountHolderBalance) {
amount.");
(insufficient balance) if (balance >= 0) {
}
} balance = accountHolderBalance;
}
} } else {
}
[Link]("Balance cannot be
negative.");
}
}
Access Modifiers:
Access modifiers are keywords that control which parts of your program can access a class, method, or variable.
They are essential for encapsulation, security, and modular design.
Access Same Class Same Package Subclass Other Classes
Modifier (Different
Package)
public ✅ ✅ ✅ ✅
Protected ✅ ✅ ✅ ❌
(default) ✅ ✅ ❌ ❌
Private ✅ ❌ ❌ ❌
Exception Handling:
Exception Handling in Java is a mechanism to handle runtime errors (exceptions) so that the normal flow of the program is not interrupted.
It allows you to detect, handle, and recover from errors gracefully instead of crashing the program.
Java provides five main keywords to implement Exception Handling:
•try Example:
•catch
•throw
public class TryCatchExample {
•throws
•finally public static void main(String[] args) {
try {
int num = 10 / 0; // This will cause ArithmeticException
Syntax:
} catch (ArithmeticException e) {
try { [Link]("Error: Division by zero is not
// Code that may throw an exception allowed!");
} catch (ExceptionType e) { }
// Code to handle the exception [Link]("Program continues...");
} }
}
//Throw example:
import [Link];
public class ThrowExample {
public static void main(String[] args) {
Scanner s=new Scanner([Link]);
int age = [Link]();
if (age < 18) {
throw new ArithmeticException("Access denied - You must be 18 or older.");
}
[Link]("Access granted - You are old enough!");
}
}
//Throws example:
import [Link].*;
public class ThrowsExample {
static void readFile() throws IOException {
FileReader file = new FileReader("[Link]");
[Link]();
[Link]();
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]("File not found or cannot be read.");
}
}
}
//Finally example:
import [Link];
public class FinallyExample {
public static void main(String[] args) {
Scanner s=new Scanner([Link]);
try {
int a=[Link]();
int b=[Link]();
int num = a/b;
[Link]("Division of two numbers is"+num);
} catch (ArithmeticException e) {
[Link]("Exception caught: " + [Link]());
} finally {
[Link]("This block always executes (e.g., close file, release
resources).");
}
}
}
The Collection that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data
such as
[Link]
[Link]
[Link]
[Link]/Updation
[Link]
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
[Link] provides readymade architecture.
[Link] represents a set of classes and interfaces.
[Link] is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
[Link] and its implementations, i.e., classes
Java Collection means a single unit of objects.
Java Collection framework provides
[Link] (Set, List, Queue, Deque)
[Link] (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Hierarchy of Collection Framework
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
No. Method Description
1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean addAll(Collection<? extends E> c) It is used to insert the specified collection elements in the invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the collection.
4 public boolean removeAll(Collection<?> c) It is used to delete all the elements of the specified collection from the invoking collection.
5 default boolean removeIf(Predicate<? super E> filter) It is used to delete all the elements of the collection that satisfy the specified predicate.
6 public boolean retainAll(Collection<?> c) It is used to delete all the elements of invoking collection except the specified collection.
7 public int size() It returns the total number of elements in the collection.
8 public void clear() It removes the total number of elements from the collection.
9 public boolean contains(Object element) It is used to search an element.
10 public boolean containsAll(Collection<?> c) It is used to search the specified collection in the collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime type of the returned array is that of the specified array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the collection as its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements in the collection.
18 public boolean equals(Object element) It matches two collections.
19 public int hashCode() It returns the hash code number of the collection.
Iterator interface
Methods of Iterator interface
There are only three methods in the Iterator interface. They
are:
No. Method Description
1 public boolean hasNext() It returns true if the iterator has more elements
otherwise it returns false.
2 public Object next() It returns the element and moves the cursor
pointer to the next element.
3 public void remove() It removes the last elements returned by the
iterator. It is less used.
List Interface:
List interface is the child interface of Collection interface. It inhibits a list type data structure in
which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();
ArrayList
The ArrayList class implements the List interface.
It uses a dynamic array to store the duplicate element of different data types.
The ArrayList class maintains the insertion order and is non-synchronized.
The elements stored in the ArrayList class can be randomly accessed.
Consider the following example.
import [Link].*;
class TestJavaCollection {
public static void main(String[] args) {
// Creating ArrayList
ArrayList<String> list = new ArrayList<String>();
// Adding elements to ArrayList
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
// Traversing list through Iterator
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to store the elements.
It can store the duplicate elements. It maintains the insertion order and is not synchronized.
In LinkedList, the manipulation is fast because no shifting is required.
Consider the following example.
import [Link].*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Vector
Vector uses a dynamic array to store the data elements.
It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of Collection framework
Consider the following example.
import [Link].*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Vijay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e., Stack.
The stack contains all of the methods of Vector class and also provides
its methods like boolean push(), boolean peek(), boolean push(object o),
which defines its properties.
Consider the following example.
import [Link].*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
[Link]("Vijay");
[Link]("Ajay");
[Link]("Amit");
[Link]("Ashish");
[Link]("Garima");
[Link]();
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that is used to hold the elements
which are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
Queue interface can be instantiated as:
•Queue<String> q1 = new PriorityQueue();
•Queue<String> q2 = new ArrayDeque();
There are various classes that implement the Queue interface, some of them are given below:
[Link]
[Link]
…
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities.
PriorityQueue doesn't allow null values to be stored in the queue.
PriorityQueue stores elements in natural (alphabetical) order
Consider the following example:
import [Link].*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Amit Sharma");
[Link]("Vijay Raj");
[Link]("JaiShankar");
[Link]("Raj");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]("iterating the queue elements:");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
[Link]();
[Link]();
[Link]("after removing two elements:");
Iterator<String> itr2=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects which are to be processed by their priorities.
PriorityQueue doesn't allow null values to be stored in the queue.
PriorityQueue stores elements in natural (alphabetical) order
Consider the following example:
import [Link].*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
[Link]("Amit Sharma");
[Link]("Vijay Raj");
[Link]("JaiShankar");
[Link]("Raj");
[Link]("head:"+[Link]());
[Link]("head:"+[Link]());
[Link]("iterating the queue elements:");
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
[Link]();
[Link]();
[Link]("after removing two elements:");
Iterator<String> itr2=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
ArrayQueue
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike queue, we can add or delete the elements from
both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Consider the following example:
import [Link].*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
[Link]("Gautam");
[Link]("Karan");
[Link]("Ajay");
//Traversing elements
for (String str : deque) {
[Link](str);
}
}
}
Set Interface:
[Link] Interface in Java is present in [Link] package. It extends the Collection interface.
[Link] represents the unordered set of elements which doesn't allow us to store the duplicate items.
[Link] can store at most one null value in Set.
[Link] is implemented by HashSet, LinkedHashSet, and TreeSet.
Set can be instantiated as:
•Set<data-type> s1 = new HashSet<data-type>();
•Set<data-type> s2 = new LinkedHashSet<data-type>();
•Set<data-type> s3 = new TreeSet<data-type>();
HashSet
[Link] class implements Set Interface.
[Link] represents the collection that uses a hash table for storage.
[Link] is used to store the elements in the HashSet.
[Link] contains unique items
Consider the following example:
import [Link].*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
LinkedHashSet
[Link] class represents the LinkedList implementation of Set Interface.
[Link] extends the HashSet class and implements Set interface.
[Link] HashSet, It also contains unique elements.
[Link] maintains the insertion order and permits null elements.
Consider the following example:
import [Link].*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
SortedSet Interface
[Link] is the alternate of Set interface that provides a total ordering on its elements. The elements of the SortedSet are arranged
in the increasing (ascending) order. The SortedSet provides the additional methods that inhibit the natural ordering of the elements.
[Link] SortedSet can be instantiated as:
[Link]<data-type> set = new TreeSet();
TreeSet
[Link] TreeSet class implements the Set interface that uses a tree for storage. Like HashSet, TreeSet also contains unique elements.
However, the access and retrieval time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Consider the following example:
import [Link].*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}