0% found this document useful (0 votes)
11 views53 pages

Java Crack

The document covers Java Memory Management, detailing Stack and Heap memory, and the Garbage Collection process. It explains the String Pool, variable types, type conversion, and the basics of classes and objects in Java. Additionally, it discusses the static keyword, method overloading, wrapper classes, and various string and array operations.

Uploaded by

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

Java Crack

The document covers Java Memory Management, detailing Stack and Heap memory, and the Garbage Collection process. It explains the String Pool, variable types, type conversion, and the basics of classes and objects in Java. Additionally, it discusses the static keyword, method overloading, wrapper classes, and various string and array operations.

Uploaded by

venkypotla19
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 53

DAY1

------------------------------------------------------------------------------------------

--
JAVA MEMORY MANAGEMENT
Java Memory Management is the process of allocating and
deallocating memory to objects during program execution, so that the
system runs efficiently and doesn’t run out of memory.

Java handles most of this automatically using the JVM (Java Virtual Machine),
which divides memory into different areas, mainly the Heap and Stack.

🧩 1. Stack Memory

🔹 Description:

 Stack memory stores method calls, local variables, and references to


objects in the heap.

 It follows LIFO (Last In, First Out) order.

 Each thread in Java has its own stack memory.

 Object references (not objects themselves) are stored here.

💾 2. Heap Memory

🔹 Description:

 Heap is used to store objects and class instances.

 It is shared among all threads.


 Objects in the heap are created dynamically using the new keyword.

🔹 Key Points:

 Objects stay in heap until they are no longer referenced.

 Managed automatically by Garbage Collector.

🧹 3. Garbage Collection (GC)

🔹 Description:

 Garbage Collection is the process of automatically deleting unused


(unreferenced) objects from the heap to free up memory.

 The JVM takes care of it, so developers don’t have to manually free
memory (unlike C/C++).

🔹 How It Works:

1. When an object has no active reference, it becomes eligible for garbage


collection.

2. JVM runs the Garbage Collector thread in the background to clean up


such objects.

🔹 Example:

🔹 Important Methods:

 System.gc() → Suggests JVM to run Garbage Collector (not guaranteed).

 finalize() → Called by GC before deleting an object (deprecated in newer


Java versions).

------------------------------------------------------------------------------------------------------------
---------------------------------------

String Pool in Java


The String Pool (also called String Intern Pool) is a special
memory area inside the Heap where Java stores String literals to
save memory and improve performance.
How It Works
When you create strings in two ways:
✅ (a) Using String Literal
String s1 = "Sai";
String s2 = "Sai";
👉 Both s1 and s2 point to the same object in the String Pool.
✅ No new object is created for s2.
❌ (b) Using new Keyword
String s3 = new String("Sai");
String s4 = new String("Sai");
👉 Each new keyword creates a new object in heap, even if the
content is the same.
❌ These are not stored in the String Pool automatically.
intern() Method
If you want to force a string object from heap into the pool, use
the intern() method.
Example:
String s1 = new String("Krishna");
String s2 = s1.intern(); // moves to string pool
String s3 = "Krishna";

System.out.println(s2 == s3); // true


✅ After calling intern(), both refer to the same object in the String
Pool.
------------------------------------------------------------------------------------------
--------------------------------

Variable – it is like a name that stores the data or values to\ be


use
 Local(with in method) , Instance(with in a class), Static(with
in class , call without obj)
 A static variable is a variable that belongs to the class, not
to any specific object.
It means only one copy of that variable exists, shared by all
objects of that class.
_________________________________________________________________________
Type convertion -Converting one type to another
Implicit Casting ( Upcasting)
 Small type to big type
 Bite -> short -> int -> long -> float -> double
int num = 100;
double d = num
Explicit Casting ( Downcasting)
 Big to small
 We need to forcefull convert
Double d = 10.00
Int a = (int) d

Operators
 Arithmetic -> + * / %
 Relational -> > ,< , >= ,<= ,=! ,==
 Logical -> && , || , !
 Bitwise: & | ^ ~ << >> >>> → operate on bits
 Assignment -> = ,=(+_*/%)
 Ternary -> variable = (condition) ? if true : if false

What is a Class in Java?


 A class is a blueprint or template for creating objects.
 It has the data(variable ) and code (methods / functions)
What is an Object in Java?
 An object is an instance of a class.
 When a class is defined, no memory is allocated. Memory is
allocated only when an object is created.
 Think of an object as an actual house built from the
blueprint.
1) java is not 100% OPPS ,Because it supports primitive data
types (8 fixed types) (like byte ,short, int,long , float, double,
char, boolean) which are not objects.
* build in
* fixed storage
* defaulf value 0 , false ..
Non primitive data types
 User define
 Strings , Array, Class and objects , Wapper classes ( Double ,
Character , Integer) , interface
 Storages varies from
 Reference (stores the adders of objects)
 Default value null
------------------------------------------------------------------------------------------
--------------------------------
Public static void main(String[] args )
access modifier of main method is " public " because it is called
by the JVM
"void" is used because main method does not return any to JVM
"static" allows the JVM to call main without creating an object of
the class.
String[] args → For command-line arguments

System.out.println(“ “ );
Println  println is the method of of PrintStream class
Out -> out is the object (public static final) of printStream
(created in side the system class)
System -> this is machi paina vunna class anamata

SWITCH- IT IS USED FOR MUTIPLE INPUT


 IT IS used to execute one block of code from multiple
options
switch (expression) {

case value1:

// code block

break;

case value2:

// code block

break;

...

default:

// code block if no case matches

Int a = 2 ;

Switch (a ) {

Case 1 :

Sys.out.println(“hi”);

Break;
Case 2 :

Sys.out.println(“hi”);

Break;

Default:

Sys.out.println(“hi”);

for-each loop
 Purpose: Iterates over elements of arrays or collections.

 Syntax:

for (datatype var : array) {

// code

 Example:

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

for (int n : nums) {

System.out.println(n);

___________----------------------------------------------------------------------------------------------------------------------
---------------------

 break: Exits the loop immediately.(break down the flow of execution)


if (i == 3) break;
 continue: Skips the current iteration and goes to the next.(just skip
current and contious)
if (i == 3) continue ;

What is Garbage Collection in Java?


process by which the JVM automatically frees up memory by destroying
objects that are no longer used

Static keyword –
What is the purpose of static in Java?
→ To save memory and provide class-level access instead of
object-level access.
 Static is used for memory management
 When a member( variable , method , block or nexted class) are
declare as static , then they are belongs to class rather than
instance of class
 Means we can assess with out creating an object
 Static variables can shared across all the objects in the class
and momeory allocation will be done in one time in class area
 Static method can called with out creating a object ,
Static method can not be used super and this keywords
 Static block – it is used for static initialization of variables ,
runs only once when the class is loaded into memory , executes
before main method
class Demo {
static int value;
static {
value = 100;
System.out.println("Static block executed");
}

static nested classs –


A class inside another class can be declared static and Can be accessed without
creating an object of the outer class.

------------------------------------------------------------------------------------------------------------------------
-------------------------------------------

3)we can overload the main method in java


Yes, we can overload the main method.
But JVM only calls the standard one.( public static void
main(String[] args))
The other overloaded methods must be called or execute
manually.
( public static void main(int a) )
--------------------------------------------------
----------------------------------------------------------------------
4) ATM -> automated teller machine
Wapper classes
Java is not 100% opp , because of primitivte data dypes , in some
cases(collections) we don’t have chance of using primitive data
types , at that time we can use wapper classes (Integer ,
Double ,Character etc )
 AUTO- Boxing : assigning the primitive data to object type or
wapper class
 AUTO-unboxing : retiving the values from object type to
primitive type
INT
 Integer i = 1000;
 System.out.println(Integer.MIN_VALUE); // -2147483648
 System.out.println(Integer.MAX_VALUE); // 2147483647
 System.out.println(Integer.parseInt("123")); // 123
 System.out.println(Integer.toString(500)); // "500"
DOUBLE
 Double d = 45.67;
 System.out.println(Double.MIN_VALUE);
 System.out.println(Double.MAX_VALUE);
 System.out.println(Double.parseDouble("123.45")); // 123.45
 System.out.println(d.doubleValue()); // 45.67
CHARACTER
 Character c = 'A';
 System.out.println(Character.isDigit('5')); // true
 System.out.println(Character.isLetter('A')); // true
 System.out.println(Character.toLowerCase('X'));// 'x'
 System.out.println(Character.toUpperCase('m'));// 'M'
BOOLEAN
 Boolean b = true;
 System.out.println(Boolean.TRUE); // true
 System.out.println(Boolean.FALSE); // false
 System.out.println(Boolean.parseBoolean("true")); // true
 System.out.println(b.booleanValue()); // true

eature == equals()

Compares memory
addresses (reference Compares content/values of
Purpose
equality) for objects, or objects (logical equality).
values for primitives.

Primitives (int, char,


Objects (String, Integer,
Used etc.) and objects (but for
custom objects, etc.) to check
For objects, checks
logical equality.
reference).

Default For objects, checks if For objects, default equals() in


Behavio both references point to Object class behaves like ==,
eature == equals()

but many classes (like String)


r the same object.
override it to compare content.

Return
boolean boolean
Type

Example
java int a = 5, b = 5;
with
System.out.println(a == N/A (use == for primitives)
Primitiv
b); // true
es

java String s1 = new


String("Hello"); String s2
Example java
= new String("Hello");
with System.out.println(s1.equals(s
System.out.println(s1
Objects 2)); // true (same content)
== s2); // false (different
objects in memory)
------------------------------------------------------------------------------------------
----------------------------
ARRAYS An array in Java is a collection of elements of the same
data type, stored in a contiguous memory location.
It is used to store multiple values in a single variable, instead of
declaring separate variables for each value.

Traversal
int[] arr = {10, 20, 30, 40};

for(int i=0; i<arr.length; i++) {

System.out.println(arr[i]);

}
// Output: 10 20 30 40

Insertion / UPDATE

int[] arr = {10, 20, 30, 40};

arr[2] = 99; // Insert at index 2

// Now arr = [10, 20, 99, 40]

Searching

int key = 99, found = -1;

for(int i=0; i<arr.length; i++) {

if(arr[i] == key) {

found = i;

break;

System.out.println("Found at index: " + found);

Arrays Class (Utility Methods)

Sort() –

 Sorts array in ascending order

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

Arrays.sort(arr);

// arr = [1, 2, 5, 8]

equals() – Compares two arrays

int[] a = {1, 2, 3};

int[] b = {1, 2, 3};

System.out.println(Arrays.equals(a, b)); // true

binarySearch() – Finds element in sorted array

int[] arr = {10, 20, 30, 40, 50};

int index = Arrays.binarySearch(arr, 30);

System.out.println("Found at index: " + index); // Output: 2

String
String class:
 Once created, it cannot be changed. (immutable)
 Any modification creates a new String object.
String s1 = "Hello"; // Using literal

String s2 = new String("World"); // Using new keyword

 For that reason , we can use the StringBuffer ,


StringBulider
Operations
Length
String s = "Hello";
System.out.println(s.length()); // Output: 5

charAt(i)
String s = "Hello";
System.out.println(s.charAt(1)); // Output: e

Replace ( ,)
String s = "Hello";
System.out.println(s.replace(I,s)); // Output: hesso

concat()
String s1 = “hello”
String s2 = “ sai “
String s3 = s1.concat(s2);
Sys.out.println(s3);

TRIM()
String s1 = “ sa I “
Sys.out.println(S1.trim()) / //sai
Split()
Sting to array
String s = "apple,banana,orange";
String[ ] fruits = s.split(",");
for(String f : fruits) {
System.out.println(f);
}
✅ Quick tips for interviews:
 length() → Get size of string
 charAt() → Access character by index
 substring() → Get part of string
 concat() → Join strings
 replace() → Replace characters
 trim() → Remove extra spaces
 split() → Break string into array

StringBuffer
 Mutable → Can be changed after creation.
 Thread-safe → Synchronized, safe in multi-threaded
environments.
 slower
Syntax
StringBuffer bs = new StringBuffer(“ hii rama ” );
Operations
Append()
 Bs.append(“devi”);
Insert()
 Bs.insert(4,”sai “); // from index sai
Delect ()
 Bs.delect(3 , 6 ); // del from index 3 to 6
Reverse
 Sb.reverse();
Replace
 Bs.replace(3,6, “sai”);
StringBuilder
 Mutable → Can be changed after creation.
 Not thread-safe
 Faster than StringBuffer.
StringBuilder sb = new StringBuilder("Hi");

sb.append(" Java");

System.out.println(sb); // Output: Hi Java

 Use String when value won’t change


frequently.
 Use StringBuilder when frequent
modifications are needed and speed is
important.
 Use StringBuffer when frequent modifications
and thread-safety are required.
Recursion
Recursion is a programming technique where a method calls itself
to solve a smaller instance of a problem until it reaches a base
case( condition case)
 There are two types
 Base case -> this is the condtion part , stops the infinity
recursions
 Recursive case -> this is where the method calls it self with
a smallest problem

Syntax
returnType methodName(parameters) {

if (base condition) {

// base case logic

return value;

} else {

// recursive case

return methodName(smallerProblem);

Example 1: Factorial of a Number


Factorial of n is n! = n * (n-1) * (n-2) ... * 1
public class RecursionExample {

public static int factorial(int n) {

if (n == 0) { // base case

return 1;

} else { // recursive case

return n * factorial(n - 1);

public static void main(String[] args) {

int num = 5;

System.out.println("Factorial of " + num + " is " + factorial(num));

. Example 2: Fibonacci Series


The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13 …

public class FibonacciExample {

public static int fibonacci(int n) {

if (n == 0) return 0; // base case

if (n == 1) return 1; // base case

return fibonacci(n - 1) + fibonacci(n - 2); // recursive case


}

public static void main(String[] args) {

int n = 7;

for (int i = 0; i < n; i++) {

System.out.print(fibonacci(i) + " ");

. Example 2: Fibonacci Series

public class FibonacciLoop {

public static void main(String[] args) {

int n = 10; // number of terms

int first = 0, second = 1;

System.out.print("Fibonacci Series: " + first + " " + second);

for (int i = 2; i < n; i++) {

int next = first + second;

System.out.print(" " + next);

first = second;

second = next;

Pass by value
1.Java is always pass by value.
2.For primitives, the value itself is copied.
3.For objects, the object reference (address) is
copied, so you can modify the object but not
reassign the reference.

CONSTRUCTOR
What is a Constructor in Java?
 A constructor is a special method used to
initialize objects.
 It has the same name as the class.
 It does not have a return type (not even
void).
 It is called automatically when you create an
object using new.
Types of constructors in Java:
 Default constructor (no arguments).
 Parameterized constructor (with arguments).
 Constructor Overloading (multiple
constructors in one class).
Can be overloaded but not overridde
Why are Constructors Important?
 Without constructors, you would have to
write setter methods each time after
creating an object.
 Constructors make code cleaner and faster to
initialize objects.
Without constructor:
Car c = new Car();
c.setBrand("BMW");
With constructor:
Car c = new Car("BMW");
class Student {

String name;

int age;
// Default Constructor

Student() {

name = "Unknown";

age = 0;

// Parameterized Constructor (1 parameter)

Student(String n) {

name = n;

age = 0;

// Parameterized Constructor (2 parameters)

Student(String n, int a) {

name = n;

age = a;

public class ConstructorOverloadingDemo {

public static void main(String[] args) {

Student s1 = new Student(); // default

Student s2 = new Student("Sai"); // one parameter

Student s3 = new Student("Pradeepthi", 22); // two parameters

System.out.println(s1.name + " " + s1.age);

System.out.println(s2.name + " " + s2.age);

System.out.println(s3.name + " " + s3.age);

-------------------------------------------------------------------
------------------------
5)Object-Oriented Features Java Supports:
Encapsulation
Inheritance
Polymorphism
Abstraction
Class and Object structure

ENCAPSULATION
DEF : means binding the data(variables) and the code (method)
Encapsulation means binding the data (variables/fields) and the
code (methods/functions) that operate on that data into a single
unit (class).
In simple words → it’s like putting variables and methods in a
capsule (class) and restricting direct access to the data from
outside class .
Class cap {

Private String Name;

Private int age ;

Public String getName( ) {

Return name ;

Public void setName(String name) {

this. Name = name ; }

Class Start {

Public static void main(String[] args) {


cap obj = new cap();

String a = Obj.getName();

Obj.setName(“sai”)

Sys.out.pln(a);

----------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------

5)Class: A class is a blueprint that defines the properties and


behaviors of objects.
interface : ardam kaledhu
------------------------------------------------------------------------------------------
--------------------------------
day-2

Inheritance
1)inheritance – 3 types (single , multi level ,hierarchical )
Single Inheritance – One class extends another.
Multilevel Inheritance – Class extends a class that extends
another class.
Hierarchical Inheritance – Multiple classes extend the same
superclass.

❌ Multiple Inheritance with classes is not allowed (to avoid


ambiguity), but possible with interfaces.

2)is it possible multiple inheritance ?? -> no, because of


Ambiguity error
* what is ambiguity error -> ambiguity error occur when
complier gets confused between two or more matching methods
and can't decide which one to use.

3)can we achieve multiple inheritance in java ? -> yes (through


interface)
Class animal {

Void eat() {

Sys.out.pln(“eat”);

}}

Class dog extends animal {

Void bark() {

Sys.out.pln(“bark”);

Class inheritance {

Public stastic void main(String[] args) {

Dog obj = new dog():

Obj.dark():

Obj.eat();

} }
Extends – class to class or interface to interface
Implements – class is inherites from interface ( class – interfeace )
 How can we multiple inher is possible in interface but not in
class ??
Ans :
In classes there is an ambiguity error when there are same named
methods in both classes
In interface , all methods are abstract , there is no body for the
methods ,the inherited class will write the its own code , so no
confusion
If confit is arises because of java 8+ , the class must be override
and resolve it
------------------------------------------------------------------------------------------
--------------------------------
4)SUPER KEYWORD
: is used to call the parent class ‘s members like
(constructor, method, or variable)
: If a subclass has a variable with the same name as
the parent class, super helps to access the parent’s
version.
: If a method is overridden in the child class, we can
still call the parent’s method using super.
: super() is used inside a subclass constructor to
explicitly call the parent class constructor.
 super.variable → accesses parent’s variable.

 super.method() → calls parent’s method.


 super() → calls parent’s constructor.
FINAL KEYWORD: The final keyword in Java is used to restrict
modification
FINAL KEYWORD IS USED FOR –
-- VARIABLES ( CANT CHANGE THE VALUE )
-- METHODS (CANT BE OVEREIDDED)
-- CLASS (IT CANT BE EXTENDS )
-- Final parameters (cannot be changed inside
method.)

THIS : it is reference variable that refers to the current


object of the class.
 resolve ambiguity error between diff scope variables
this.name = name
String name;
Student(String name) {
this.name = name; // this.name → instance variable, name → parameter

----------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------

POLYMOPHISM- one name many forms


 java allows objects or method to behave differently in different
situation

Run-time Polymorphism (Method Overriding)


 Achieved by method overriding (subclass provides its own
version of a parent class method).
 Resolved at runtime (dynamic method dispatch).
 Same method name , same parameters , but diff classes
 Method calling is decided by JVM at RUNTIME based on obj
type not the reference type
Animal a; // reference type is Animal

a = new Dog(); // obj type is dog ..so called dog class’s methods

a.sound(); // Dog barks

a = new Cat(); // obj type is cat ..so called cat class’s methods

a.sound(); // Cat meows

same method works differently depending on which object is calling it. It


happens when a child class overrides a method of the parent class, and
the decision is made while the program is running.

 allows code reuseablity


 make code more flexbile and maintain
 we need inheritance + overriding

Compile-Time Polymorphism (Method Overloading)


 Achieved by method overloading (same method name,
different parameters).
 Resolved at compile time.
Rules for Overloading:
 Methods must have the same name.
 Must differ in number or type of parameters.
Class calculator {

Int add(int a , int b ){

Return a + b; }

Int add(int a , int b , int c ) {


Return a + b+ c ; }

Class main {

Public static void main(String[ ] args) {

Calculator cal = new calculator();

Cal.add( 1 ,2) // calls first mothod

Cal.add(1 ,4 ,5 ) // calls second method

----------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------

DAY-3
ABSTRACTION
 Hiding implementation details and showing only the
essential features.
 Abstraction is about hiding implementation details and
focusing on what an object does
 Abstract is ment by incomplete , child class will fill it
(complete it)
 It is just a blue print for other class
 Abstraction can be achived by abstract class and interface
abstract class :
 Class should be delacared as Abstract
 It have both abstract method ( with out the body) and
normal methods
 Can not be instantiated (cant able to create object for it)
 The child class should complete the abstract methods (write
code here )
abstract class Animal {

abstract void sound(); // abstract method (no body)

void sleep() { // normal method

System.out.println("Sleeping...");

class Dog extends Animal {

void sound() {

System.out.println("Bark");

public class Main {

public static void main(String[] args) {

Animal a = new Dog();

a.sound(); // Output: Bark

a.sleep(); // Output: Sleeping...


}

B) interfaces :
(before Java 8).
* interface is a fully abstract class
* Contains only abstract methods (by default : public and
abstract) and variables (by default :public, static, final)
(From Java 8)
A) interfaces can also have default method using the default
keyword.
interface Vehicle {

void start();

default void stop() { // default method

System.out.println("Vehicle stopped");

B) interface can also have static method using static keyword ,


called by using interface name
interface MathUtils {

static int square(int x) {

return x * x;

public class Main {

public static void main(String[] args) {

System.out.println (MathUtils.square(5)); // Output: 25

*like abstract class , we cant create a object for an interface


INTERFACE IN JAVA : IT IS BLUE PRINT OG CLASSES IN JAVA
1) It has static constant and abs methods
2) It will archive multiple inheritance
3) We can say that interface have abs variables and methods
4) It don’t have the body of the method
5) Methods are public and abstract by default
6) Loose coupling :reducing the dependence between the class
or methods
What is a Package in Java?
 A package is like a folder/directory that groups related classes,
interfaces, and sub-packages together .
 It helps in:
o Organizing code (easier to manage large projects).

o Avoiding name conflicts (same class name can exist in


different packages).
o Reusability of classes.

o Access control (using access modifiers with packages).

Types of Packages
1. Built-in Packages → Already available in Java (e.g., java.util,
java.io, java.sql).

2. User-defined Packages → Created by the programmer for

custom use .
Built in

java.util, java.io, java.sql

User-defined Packages
Step 1: Create a package

package MyPackage; // declare package name

public class MyClass {


public void display() {

System.out.println("Hello from MyClass in MyPackage!");

Step 2: Use it in another file


// File: Test.java

import MyPackage.MyClass; // import user-defined package

public class Test {

public static void main(String[] args) {

MyClass obj = new MyClass();

obj.display();

Compilation:

javac -d . MyPackage/MyClass.java

javac Test.java

java Test

Package Purpose Common Classes

Core language classes (imported by Object, String, Math, Integer,


java.lang
default) System

Scanner, ArrayList, HashMap,


java.util Utilities & Collections
Collections, Date

File, FileReader, FileWriter,


java.io Input/Output operations
BufferedReader

LocalDate, LocalTime,
java.time Modern date/time API (Java 8+)
LocalDateTime, Period

Summary:

 java.lang → Core features (Strings, Math, Wrapper classes).

 java.util → Utilities + Collections.

 java.io → File and stream handling.

 java.time → Modern date/time handling.


COLLECTIONS
 It is the frame work
 The Java Collections Framework is a set of classes and
interfaces that provide a ready-made architecture to store,
manipulate, and process groups of objects efficiently.

Iterable (interface)

Collection (interface)
┌─────────────┬─────────────┬───────────────┐
│ │ │ │
List Set Queue Map (separate
branch)
│ │ │
ArrayList HashSet PriorityQueue
LinkedList LinKHashSet Deque
Vector TreeSet

 ARRAYLIST<>
1) it is the class available in java.util package
2) dynamic memory allocation
3) array is static and arraylist is dynamic (size is not fixed ,
used for ordered elements)
4) syntax : ArrayList<> obj = new ArrayList<>();
5) get() is used to access the certain element from the
list(index starting from 0)
6) remove() is used to remove the certain element from the list
7) clear() to del all
8) size() to know size
9) isEmpty() is used to know that list is empty or not ( it is
Boolean type)
example program
//ArrayList
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList al = new ArrayList<>();
al.add("Swarup");
al.add("Sagar");
al.add(5);
al.remove(1);
System.out.println(al);
System.out.println(al.get(1));
System.out.println(al.size());
al.clear();
System.out.println(al.isEmpty());
}}

 LINKEDLIST
1) It is the class available in java.util package
2) syntax : LinkedList obj = new LinkedList<>();
3) clear()
4) Get()
5) Remove()
6) Size()
7) isEmpty()

Feature ArrayList LinkedList

Underlying
Dynamic array (contiguous memory) Doubly linked list (nodes with pointers)
Structure

Fast for accessing elements by index


Access Time Slow for accessing by index (O(n))
(O(1))

Slow for inserting/deleting in the Fast insertion/deletion in the middle


Insertion/Deletion
middle (O(n)) (O(1))

Memory Usage Less memory (just data) More memory (data + pointers)

When frequent access by index is When frequent insert/delete operations


Best Use Case
needed are needed

finally which is prefered to use ??


✅ Use ArrayList for faster random access.
✅ Use LinkedList for frequent insertions/deletions.

 VECTOR (legacy class )


1) VECTOR is similar to Arraylist
2) it is synchronized ( so that, it is thread safe)
3) allow duplicates and null
4) dynamic memory allocation
5) MAINTAIN INSECTION ORDER
6) what is synchronized ? here all methods are thread safe in multi threading
7) slower than array list ( because of over work like sync)
8) syntax : vector obj = new vector<>();
………………………………………………………………………SETS………………………………………………….

 HashSet
1) It is the class available in java.util package
2) Syntax : Hashset<> obj = new HashSet<>();
Features :
1) Null values accepted (only 1)
2) Not allows duplicate values
3) Not follows insertion order ( why ? because in background it
is using the hash table)
4) ADD() , REMOVE() , SEARCH() FASTER
PROGRAM
//HashSet
public class HashSetDemo {

public static void main(String[] args) {


HashSet<Integer> hs = new HashSet<Integer>();
hs.add(100);
hs.add(100);
hs.add(45);
hs.add(7);
hs.add(null);
hs.add(78);
System.out.println(hs);
}
}

In COLLECTIONS we can add the class objects as the elements


Example :
import java.util.LinkedList;
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList<Student> list = new LinkedList<Student>();
Student std = new Student();
list.add(std):
Student std1 = new Student();
list.add(std1);
System.out.println(list);//[com.swarup.Student@4157f54e,
com.swarup.Student@90f6bfd]
}
}
…………………………………………………………………………………………………
…………..
LINKED HASHSET -> ONLY DIFF FROM HASHSWT IS FOLLOWS
INSERTION ORDER
1) It is the class available in java.util package
2) SYNTAX : LinkedHashSet<> obj = new LinkedHashSet<>();
Features :
1) Don’t allows duplicate values
2) null values (ONLY ONE )
3) Allows Follows insertion order
4) Backed by Hash Table + Linked List

 Combines HashSet (for fast access) and LinkedList (for order)


 Uses a hash table for storage and a linked list to maintain order.

……………………………………………………………………………………………..

TREESET (CLASS)
1) It is the class available in java.util package
2) SYNTAX : TreeSet<Integer> obj = new TreeSet();
Features :
1) INSERTION takes place in a sorted order (A.O)
2) NO DUPLICATE
3) NO NULL VALUE  null pointer exception will be given in a
collection when we try to insert null values
4) No combinations of types are allowed at a time (because it
has to sort the elements so that diff types are not
comparable )
 EXAMPLE
TreeSet<Integer> ts = new TreeSet<>();
ts.add(30);
ts.add(10);
ts.add(20);
System.out.println(ts); // [10, 20, 30]
---------------------------------------
MAP------------------------------------------------------------------------
What is a Map?
 A Map is an object that maps keys to values.
 Each key is unique, but values can be duplicated.
 Unlike Collection (List, Set), Map does not extend Collection
interface.
 Useful for fast lookup based on a key.
 HashMap<Integer, String> map = new HashMap<>();

🔹 Key Features
1. Key-Value Pair → Each element is stored as (key, value).
2. Unique Keys → Duplicates are ignored; new value replaces
old value.
3. Allows nulls → allow one null key and multiple null duplicate
4. Not a Collection → Does not inherit from Collection interface.
5. Implementations → HashMap, LinkedHashMap, TreeMap,
Hashtable (legacy).
METHOD
 Obj.put( key , value)
 Obj.remove(key)
 Obj.get(key)
Types of map

Nul
Null
Implement l Threa
Order Value Notes
ation Ke d-safe
s
y

Unorder Multip
HashMap 1 No Fast lookup
ed le

LinkedHash Insertio Multip Maintains


1 No
Map n order le order

Keys sorted
naturally or
Sorted Multip by
TreeMap No No
(key) le Comparator

------------------------------------------------
queue------------------------------------------------------------------
PriorityQueue
PriorityQueue<Integer> pq = new PriorityQueue<>();
Insertion order : based on priority
it is a min-heap (smallest element has highest priority).
Duplicates are allowed, but null is not allowed.
Operations like add(), offer(), poll(), peek() are available.
Deque in Java
 Deque stands for Double-Ended Queue.
 Queue<Type> q = new LinkedList<>();
 Null alowed
 It allows insertion and removal of elements from both ends
(front and rear).
 Can be used as a Queue (FIFO) or Stack (LIFO).
Operation Method

addFirst() /
Add at front
offerFirst()

addLast() /
Add at rear
offerLast()

Remove from removeFirst() /


front pollFirst()

Remove from removeLast() /


rear pollLast()

Peek front peekFirst()

Peek rear peekLast()

…………………………………………………………………………………

TIP – only tree set will not allows null values among the
SET(interface)
Interface / Ordere
Duplicates? Example
Class d?

ArrayList ✅ Yes ✅ Yes Dynamic array

LinkedList ✅ Yes ✅ Yes Doubly linked list

Vector ✅ Yes ✅ Yes Synchronized list

Stack ✅ Yes ✅ Yes LIFO structure

HashSet ❌ No ❌ No Uses hashing

LinkedHash Maintains
✅ Yes ❌ No
Set insertion order


TreeSet ❌ No Sorted set
Sorted

Keys ❌, Values
HashMap ❌ No Key-value pairs

LinkedHash Keys ❌, Values


✅ Yes Maintains order
Map ✅

✅ Keys ❌, Values
TreeMap Sorted by key
Sorted ✅

…………………………………………………………………
files…………………………………..
Feature Purpose Example Class

Create/delete file or
File Class File
directory

Character Read/write
FileReader, FileWriter
Stream characters

Buffered Efficient BufferedReader,


Stream reading/writing BufferedWriter

Object ObjectOutputStream,
Save/load objects
Stream ObjectInputStream

✅ Key Points:

 Use File to manage files.

 Use FileReader/Writer for character-based operations.

 Use BufferedReader/Writer for line-by-line or large files.


 Use Serialization/Deserialization to store objects.

EXCEPTION
 Def : this is the event OR ptoblem occurs during the
execution of program disrupts the normal flow of program
 There are 2 types of exception --

Checked EXCEPTION (compile time)


 Checked exceptions are exceptions the Java
compiler forces you to handle or declare.
 They are subclasses of Exception but NOT
subclasses of RuntimeException.
 They occurs because of external factors like
network fail ,missing files ,database problem
 Exp : sql exception , IO EXCEPTION

UN-CHECKED EXCEPTION ( runtime )


 Unchecked exceptions are runtime exceptions — subclasses
of RuntimeException. The compiler does not force you to
catch or declare them
 Exp : arithmeatic exception, array index out of bond ,
division by zero exception etc
 They represent programmer errors or violations of method
contracts and invariants
Keywords :
1) Try -> which contains code that might contains the
exception

2) Catch -> catches the exception and handle the exception

3) Finally -> used for closing the resoures , connnections

 It is mostly used for resource cleanup eg : file


closing ,database connection
 this will executes any ways
 it is used for checking or cleaning up purpose (

4) Throw ->use to throw an exception


 It is Used inside a method to actually throw (create and send) an exception object.
 You can throw only one exception at a time.
 Syntax : throw new ExceptionType("message");

5) Throws -> this methos might thrown an exception


 It is used at method declaration part
 Throws means : there might be a error
 We Can throws the multiple exceptions ( separets by
comma)
 Syntax : void methodName() throws exception1 ,
exception2 .. { }
6) ERROR –
 serious problems that usually cannot be fixed by the
program itself
 error occur mostly in the JVM (Java Virtual Machine)
 Errors are usually caused by system failures
(hardware, JVM issues).
 Examples:

 OutOfMemoryError → when JVM runs out of memory


 StackOverflowError → when recursion goes infinite
 VirtualMachineError → JVM internal error

Feature throw throws

Where In method declaration


Inside method/block
used (signature)

Actually throws Declares exceptions that


Purpose
exception may be thrown

Can throw one exception Can declare multiple


Count
at a time exceptions

throw new void myMethod() throws


Syntax
Exception("msg"); IOException

Checked Works with both checked Only for checked exceptions


? & unchecked (compiler needs ii

Feature Exception Error

Problems that occur during Serious issues in


Definition
program execution JVM/system
Feature Exception Error

Programmer mistakes (e.g., System-level issues


Cause divide by zero, null pointer) or (memory crash, JVM
external input (missing file) problems)

Recovera Yes, can be handled with try- Usually No, program


ble? catch often crashes

IOException, OutOfMemoryError,
Examples ArithmeticException, StackOverflowError,
NullPointerException VirtualMachineError

Package java.lang.Exception java.lang.Error

Should No, generally don’t


Yes, always handle exceptions
handle? handle errors

Type Description Example

Checked Checked at compile-


IOException , SQLException
Exception time

Unchecked NullPointerException,
Occurs at runtime
Exception ArithmeticException

Serious problems, not


Error OutOfMemoryError
typically caught

✅ Exception Hierarchy:
Object
└── Throwable
├── Exception
│ ├── IOException
│ └── RuntimeException
│ ├── ArithmeticException
│ ├── NullPointerException
└── Error
├── OutOfMemoryError
Example
//Exception Handling
public class Test {
public static void main(String[] args) {
try {
int [] arr = new int[5];
arr[5]=100; // ArrayIndexOutOfBoundsException
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index 5 is not there");
}
catch(Exception e1){
System.out.println("Arry index out of bounds!");
}
}
}
…………………………………………………………………………………………………
……………………..
NESTED TRY BLOCK:
 A nested try block is a try block inside another try block. It
is used when you want to handle different exceptions at
different levels of your code
 Sytax:
try {
// Outer try block
try {
// Inner try block
} catch (ExceptionType1 e1) {
// Inner catch block
}
} catch (ExceptionType2 e2) {
// Outer catch block
------------------------------------------------------------------------------------------
-------------------------------
public class ThrowThrowsDemo {
static void checkAge(int age) throws ArithmeticException
{
if(age < 18) {
throw new ArithmeticException("Age must be 1 or
above to vote");
}else {
System.out.println("You are eligible to vote");
}
}
public static void main(String[] args) {
checkAge(5);
}
…………………………………………………………………………………………………
………………………………….

THREADING
Threading in Java means executing multiple parts of a
program concurrently.
By default there a one main thread in the program

Thread (c ) implements Runnable(I) -> we


have method run()
| we have method start()

1) What is a Thread?
 This is the smallest unit of execution in the
process
2) Why Use Threads?
 To perform multitasking
 To make your program faster and more responsive
 Especially useful in programs like games, chat apps,
servers, etc.

3) Ways to Create a Thread in Java


You can create a thread in two main ways:
a. By extending the thread class
b. By implements the runnable interface
By extending the thread class
o Create a class that extends Thread.
o Override the run() method – this is where you put
the code that should run in the new thread.
o Create an object of your class.
o Call the start() method – this will internally call
run() in a new thread.

class ABC extends Thread {


public void run() {
System.out.println("hello”);
}
}
public class Test {
public static void main(String[] args) {
ABC obj = new ABC();
t1.start(); // creates new thread, calls
run() in that thread
}
}

By implements the runnable interface


o Create a class that implements the Runnable (I)
o Override the run() method (just like before, this is
the task code).
o Create an object of that class.
o Pass that object to a Thread class constructor.
o Call start() on the Thread object.

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRun = new MyRunnable(); //
Create Runnable object
Thread t1 = new Thread(myRun); // Pass it to
Thread
t1.start(); // Start thread
}
1. start()
thread.start();
➝ Creates a new thread and internally calls run().

2. run()
public void run() {
// task code here
}
➝ Defines the code that will be executed by the thread.
3. sleep(long ms)
Thread.sleep(1000);
➝ Makes the current thread pause execution for given
milliseconds.

4. setName(String name)
thread.setName("Worker-1");
➝ Assigns a custom name to the thread.

5. getName()
String name = thread.getName();
➝ Returns the current name of the thread.

6. setPriority(int p)
thread.setPriority(Thread.MAX_PRIORITY);
➝ Sets priority of a thread (1 = MIN, 5 = NORM, 10 =
MAX).

7. getPriority()
int p = thread.getPriority();
➝ Returns the priority value of the thread.

8. isAlive()
boolean b = thread.isAlive();
➝ Checks if the thread is still running.

9. join()
thread.join();
➝ Makes the current thread wait until the specified
thread finishes execution.

10. currentThread()
Thread t = Thread.currentThread();
➝ Returns a reference to the thread that is currently
running.

1. run() → contains the code/task that the thread will


execute.
2. start() → starts a new thread and calls run()
internally in that new thread.
3. sleep(ms) → pauses the current thread for the given
time in milliseconds.
4. setName("name") → sets a custom name for the
thread.
5. getName() → returns the name of the thread.
6. setPriority(int p) → sets the priority of the thread (1
to 10).
7. getPriority() → returns the priority of the thread.
8. isAlive() → checks whether the thread is still
running or not.
9. join() → makes one thread wait until another thread
finishes execution.
10. currentThread() → returns the reference of the
thread that is currently running.
A thread in Java moves through 5 main states —
New → Runnable → Running → Waiting/Blocked →
Terminated
……………………………………………………………………………………
…………………………….
SQL TO JAVA
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class App


{
public static void main( String[] args )
{
String url = "jdbc:mysql://localhost:3306/admin1";
String username = "root";
String password = "root";

try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con= DriverManager.getConnection(url, username,
password);

Statement stmt = con.createStatement();


String sql = "select * from student";

ResultSet rs = stmt.executeQuery(sql);

while(rs.next()) {
int rollno1 = rs.getInt("rollno");
String fname1 = rs.getString("fname");
int age1 = rs.getInt("age");
int deptid1 = rs.getInt("deptid");

System.out.println("Rollno : "+rollno1+",Name :
"+fname1+",Age : "+age1+",Dept : "+deptid1);

}
rs.close();
stmt.close();
con.close();
}catch (Exception e) {
e.printStackTrace();
}
}
……………………………………………..
……………………………………………………………………………….
CRUD
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class App


{
public static void main( String[] args ) {
Scanner sc = new Scanner(System.in);

String url = "jdbc:mysql://localhost:3306/intel";


String username = "root";
String password = "root";

try (Connection con= DriverManager.getConnection(url, username,


password)){

while(true) {
System.out.println("\n1.Insert Student"); //create
System.out.println("2.View All Students"); //read
System.out.println("3.Update Student"); // update
System.out.println("4.Delete Student"); // delete
System.out.println("5.Exit");
System.out.println("Choose an option");

int choice = sc.nextInt();


sc.nextLine(); //consume newline

switch(choice) {

case 1:
System.out.println("Enter name: ");
String name = sc.nextLine();

System.out.println("Enter age: ");


int age = sc.nextInt();
sc.nextLine();//

System.out.println("Enter email: ");


String email = sc.nextLine();

String insertSQL = "INSERT INTO


Student(name,age,email) values (?,?,?)";
try(PreparedStatement ps =
con.prepareStatement(insertSQL)){
ps.setString(1, name);
ps.setInt(2, age);
ps.setString(3, email);
ps.executeUpdate();
System.out.println("Student inserted successfully");
}
break;
case 2:
String selectSQL = "select * from student";
try (Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(selectSQL)){

while(rs.next()) {
System.out.println("ID : "+rs.getInt("id"));
System.out.println("name :
"+rs.getString("name"));
System.out.println("Age : "+rs.getInt("age"));
System.out.println("Email :
"+rs.getString("email"));
}
}
break;

case 3:
System.out.println("Enter student ID to update: ");
int updateId= sc.nextInt();
sc.nextLine();

System.out.println("Enter ne
w name: ");
String newName = sc.nextLine();

System.out.println("Enter new age: ");


int newAge= sc.nextInt();
sc.nextLine();

System.out.println("Enter new email: ");


String newEmail = sc.nextLine();
String updateSQL = "update student set name = ?, age
= ?, email = ? where id = ? " ;

try (PreparedStatement ps =
con.prepareStatement(updateSQL)){

ps.setString(1, newName);
ps.setInt(2, newAge);
ps.setString(3, newEmail);
ps.setInt(4, updateId);
int rows = ps.executeUpdate();

System.out.println(rows > 0 ? "Student updated.":


"Student not found.");
}
break;

case 4:
System.out.println("Enter student ID to delete: ");
int deleteId= sc.nextInt();
sc.nextLine();

String deleteSQL = "delete from student where id = ?";


try (PreparedStatement ps =
con.prepareStatement(deleteSQL)){

ps.setInt(1, deleteId);
int rows = ps.executeUpdate();
System.out.println(rows > 0 ? "Student deleted.":
"Student not found.");
}
break;
case 5 :
System.out.println("Exiting.....");
return;

default:
System.out.println("Invalid option.");

}
}
}catch(SQLException e) {
e.printStackTrace();
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////

SQL
Structed query language is programming language that stores ,
manipulate and retrieve the data from the database
Data base is a system that’s allows users to store and organise the data
Commands in sql
Feature DELETE TRUNCATE DROP

Completely delete
Remove specific rows Remove all rows
Purpose table (structure +
or all rows from a table from a table
data)

DML (Data DDL (Data


Comman DDL (Data Definition
Manipulation Definition
d Type Language)
Language) Language)

WHERE ✅ Can delete specific ❌ Cannot filter


❌ Not applicable
Clause rows using WHERE rows, deletes all

You might also like