Java Crack
Java Crack
------------------------------------------------------------------------------------------
--
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:
💾 2. Heap Memory
🔹 Description:
🔹 Key Points:
🔹 Description:
The JVM takes care of it, so developers don’t have to manually free
memory (unlike C/C++).
🔹 How It Works:
🔹 Example:
🔹 Important Methods:
------------------------------------------------------------------------------------------------------------
---------------------------------------
Operators
Arithmetic -> + * / %
Relational -> > ,< , >= ,<= ,=! ,==
Logical -> && , || , !
Bitwise: & | ^ ~ << >> >>> → operate on bits
Assignment -> = ,=(+_*/%)
Ternary -> variable = (condition) ? if true : if false
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
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
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:
// code
Example:
System.out.println(n);
___________----------------------------------------------------------------------------------------------------------------------
---------------------
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");
}
------------------------------------------------------------------------------------------------------------------------
-------------------------------------------
eature == equals()
Compares memory
addresses (reference Compares content/values of
Purpose
equality) for objects, or objects (logical equality).
values for primitives.
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
Traversal
int[] arr = {10, 20, 30, 40};
System.out.println(arr[i]);
}
// Output: 10 20 30 40
Insertion / UPDATE
Searching
if(arr[i] == key) {
found = i;
break;
Sort() –
Arrays.sort(arr);
// arr = [1, 2, 5, 8]
String
String class:
Once created, it cannot be changed. (immutable)
Any modification creates a new String object.
String s1 = "Hello"; // Using literal
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");
Syntax
returnType methodName(parameters) {
if (base condition) {
return value;
} else {
// recursive case
return methodName(smallerProblem);
if (n == 0) { // base case
return 1;
int num = 5;
int n = 7;
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;
Student(String n) {
name = n;
age = 0;
Student(String n, int a) {
name = n;
age = a;
-------------------------------------------------------------------
------------------------
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 {
Return name ;
Class Start {
String a = Obj.getName();
Obj.setName(“sai”)
Sys.out.pln(a);
----------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------
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.
Void eat() {
Sys.out.pln(“eat”);
}}
Void bark() {
Sys.out.pln(“bark”);
Class inheritance {
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.
----------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------
a = new Dog(); // obj type is dog ..so called dog class’s methods
a = new Cat(); // obj type is cat ..so called cat class’s methods
Return a + b; }
Class main {
----------------------------------------------------------------------------------------------------------------------------------------
-----------------------------------------------
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 {
System.out.println("Sleeping...");
void sound() {
System.out.println("Bark");
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();
System.out.println("Vehicle stopped");
return x * x;
Types of Packages
1. Built-in Packages → Already available in Java (e.g., java.util,
java.io, java.sql).
custom use .
Built in
User-defined Packages
Step 1: Create a package
obj.display();
Compilation:
javac -d . MyPackage/MyClass.java
javac Test.java
java Test
LocalDate, LocalTime,
java.time Modern date/time API (Java 8+)
LocalDateTime, Period
Summary:
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()
Underlying
Dynamic array (contiguous memory) Doubly linked list (nodes with pointers)
Structure
Memory Usage Less memory (just data) More memory (data + pointers)
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 {
……………………………………………………………………………………………..
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
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()
…………………………………………………………………………………
TIP – only tree set will not allows null values among the
SET(interface)
Interface / Ordere
Duplicates? Example
Class d?
LinkedHash Maintains
✅ Yes ❌ No
Set insertion order
✅
TreeSet ❌ No Sorted set
Sorted
Keys ❌, Values
HashMap ❌ No Key-value pairs
✅
✅ 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
Object ObjectOutputStream,
Save/load objects
Stream ObjectInputStream
✅ Key Points:
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 --
IOException, OutOfMemoryError,
Examples ArithmeticException, StackOverflowError,
NullPointerException VirtualMachineError
Unchecked NullPointerException,
Occurs at runtime
Exception ArithmeticException
✅ 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
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.
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.
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con= DriverManager.getConnection(url, username,
password);
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;
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");
switch(choice) {
case 1:
System.out.println("Enter name: ");
String name = sc.nextLine();
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();
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();
case 4:
System.out.println("Enter student ID to delete: ");
int deleteId= sc.nextInt();
sc.nextLine();
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)