Core_Java
Core_Java
If you're preparing for interviews or want to strengthen your Core Java knowledge, here are
the most important topics to focus on:
1. Java Basics
Features of Java
Encapsulation
Inheritance
1/5
3. Strings
String Pool, Immutability
Collections Framework:
Comparable vs Comparator
5. Exception Handling
Types of Exceptions (Checked, Unchecked)
Custom Exceptions
2/5
Synchronization (Locks, synchronized keyword)
8. Java 8 Features
Functional Interfaces & Lambda Expressions
Stream API
Method References
Optional Class
JDBC Drivers
Factory Pattern
3/5
Builder Pattern
Observer Pattern
4/5
15. Java Security
Hashing (MD5, SHA)
== vs .equals()
StringBuffer vs StringBuilder
ArrayList vs LinkedList
HashMap vs Hashtable
Fibonacci Series
Palindrome String/Number
Reverse a String
Next Steps?
Let me know if you need in-depth explanations on any of these topics! 😊
5/5
Core Java Best Practices
1. Java Basics
1.1 Introduction to Java
Java is a high-level, object-oriented programming language developed by Sun
Microsystems in 1995 and later acquired by Oracle Corporation. It is platform-independent
and widely used for building enterprise applications, mobile apps, and web applications.
Why Java?
✔ Write Once, Run Anywhere (WORA) – Java applications can run on any platform with a
JVM.
✔ Robust and Secure – Java provides strong memory management and built-in security
features.
✔ Multithreading Support – Java can execute multiple tasks simultaneously.
✔ Rich API & Libraries – Comes with a vast set of prebuilt functions.
2. Features of Java
1️⃣ Platform Independence
Java code is compiled into bytecode, which can run on any OS with a JVM (Java Virtual
Machine).
Example:
java
System.out.println("Java is platform-independent!");
2️⃣ Object-Oriented
Java follows OOP principles: Encapsulation, Inheritance, Polymorphism, and Abstraction.
4️⃣ Multithreading
Java supports multithreading, allowing efficient CPU utilization.
5️⃣ Secure
Java does not use pointers, reducing vulnerabilities.
JDK (Java Development Kit) Includes JRE + development tools (compiler, debugger) to develop
Java programs.
JRE (Java Runtime Contains JVM + libraries required to run Java applications.
Environment)
JVM (Java Virtual Machine) Converts bytecode into machine code for execution on different
platforms.
Execution Flow:
1️⃣ Java Source Code ( ) .java
➡ Compiled by javaccompiler
2️⃣ Bytecode ( file)
.class
➡ Executed by JVM ( java command)
Example:
sh
2/8
java HelloWorld # Run
java
3/8
4.2 Variables in Java
A variable is a name given to a memory location that stores data.
Types of Variables
Type Scope Example
Example:
java
class Example {
int instanceVar = 10; // Instance Variable
static int staticVar = 20; // Static Variable
Types of Operators
Operator Type Example
Arithmetic Operators +, -, *, /, %
4/8
Operator Type Example
Assignment Operators = , += , -= , *= , /=
Unary Operators ++ , --
Ternary Operator ? :
Example:
java
java
java
5/8
double num = 10.5;
int n = (int) num; // Explicit conversion
System.out.println(n); // Output: 10
6. Control Statements
Control statements manage the flow of execution in Java.
int day = 2;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Invalid day");
}
6/8
6.2 Looping Statements
Loops execute a block of code multiple times.
java
int i = 1;
while (i <= 5) {
System.out.println("Number: " + i);
i++;
}
java
int i = 1;
do {
System.out.println("Hello");
i++;
} while (i <= 5);
Conclusion
✔ Java provides strong features like platform independence, security, and OOP principles.
✔ Data types, variables, and operators are fundamental building blocks.
✔ Control statements allow us to manage the program flow efficiently.
7/8
Next Topic: Do you want to explore OOP concepts (Classes, Objects, Inheritance,
Polymorphism)? 🚀
8/8
Core Java Best Practices
Benefits of OOP
✔ Modularity – Code is divided into smaller parts (objects and classes).
✔ Reusability – Inheritance allows using existing code.
✔ Scalability – OOP allows easy modifications and extensions.
✔ Security – Encapsulation hides data and methods.
java
class BankAccount {
private double balance; // Private variable (hidden from outside access)
1/9
}
}
2.2 Inheritance
Inheritance allows a child class to inherit properties and behavior from a parent class
using the extends keyword.
java
class Vehicle {
void move() {
System.out.println("Vehicle is moving...");
}
}
2/9
public class Main {
public static void main(String[] args) {
Car myCar = new Car();
myCar.move(); // Inherited from Vehicle
myCar.speed(); // Defined in Car
}
}
✔ Code reuse – The Car class does not need to redefine the move() method.
✔ Hierarchy – Inheritance forms a relationship between classes.
2.3 Polymorphism
Polymorphism means "many forms", allowing the same method to perform different tasks.
java
class MathOperations {
int add(int a, int b) {
return a + b;
}
3/9
(ii) Method Overriding (Runtime Polymorphism)
Child class provides a new implementation for an inherited method.
java
class Animal {
void sound() {
System.out.println("Animals make sounds");
}
}
2.4 Abstraction
Abstraction hides implementation details and shows only essential features.
4/9
java
java
interface Engine {
void start();
}
5/9
}
}
java
class Example {
int x;
Example(int x) {
this.x = x; // Resolves variable shadowing
}
}
6/9
Used to call parent class methods and constructors.
java
class Parent {
Parent() {
System.out.println("Parent Constructor");
}
}
Example:
java
7/9
3.4 Static vs Non-Static Members
Feature Static Non-Static
Example:
java
class Example {
static int staticVar = 10; // Shared across objects
int instanceVar = 20; // Separate for each object
}
private ✅ ❌ ❌ ❌
default ✅ ✅ ❌ ❌
protected ✅ ✅ ✅ ❌
public ✅ ✅ ✅ ✅
Example:
java
8/9
Conclusion
✔ Java follows four OOP principles: Encapsulation, Inheritance, Polymorphism, and
Abstraction.
✔ Additional OOP concepts like this, super, final, static, and access modifiers improve code
structure.
Next Topic: Do you want to explore Java Collections (List, Set, Map, etc.) or Multithreading
in Java? 🚀
9/9
Core Java Best Practices
1/8
The String Pool is a special memory area inside the Heap where Java stores String
literals.
If a String already exists in the pool, Java returns the same reference instead of creating
a new one.
java
java
2/8
s = s.concat(" Programming"); // Now, `s` points to the new object
System.out.println(s); // Output: Java Programming
}
}
3. String Manipulation
Java provides three classes for String manipulation:
1. String – Immutable
java
3/8
3.2 StringBuilder (Mutable, Fast)
Faster than StringBuffer since it's not synchronized.
java
java
4/8
✔ StringBuffer ensures data consistency in multi-threaded environments.
java
5/8
5. String Comparisons
Java provides three ways to compare Strings:
java
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
java
String s1 = "Java";
String s2 = new String("Java");
6/8
5.3 Using .compareTo() (Lexicographical Comparison)
Used for sorting Strings based on ASCII values.
Returns:
java
Conclusion
✔ Strings in Java are immutable, meaning their value cannot be changed.
✔ Use StringBuilder or StringBuffer for efficient modifications.
✔ Use .equals() for content comparison, not == .
✔ Use .compareTo() for lexicographical comparison.
1. Arrays in Java
An array is a fixed-size, ordered collection of elements of the same data type.
java
// Declaration
int[] arr1; // Recommended
int arr2[]; // Also valid
// Initialization
int[] numbers = {1, 2, 3, 4, 5}; // Using array literal
int[] values = new int[5]; // Creating an array of size 5
// Assigning values
values[0] = 10;
values[1] = 20;
System.out.println(values[1]); // Output: 20
java
System.out.println(matrix[1][2]); // Output: 6
✔ Arrays have fixed size, meaning you cannot dynamically resize them.
1/9
2. Collections Framework
The Java Collections Framework (JCF) provides dynamic and flexible data structures.
java
import java.util.*;
2/9
3.2 LinkedList (Doubly Linked List)
✔ Fast insert/delete, slow read.
java
import java.util.*;
java
import java.util.*;
3/9
4. Set Interface (Unordered, No Duplicates)
4.1 HashSet (No Order, Fast Access)
✔ Uses HashMap internally.
java
import java.util.*;
java
import java.util.*;
4/9
4.3 LinkedHashSet (Insertion Order Maintained)
java
import java.util.*;
java
import java.util.*;
5/9
5.2 TreeMap (Sorted by Key)
✔ Uses Red-Black Tree.
java
import java.util.*;
import java.util.*;
6/9
6. Queue Interface (FIFO - First In First Out)
6.1 PriorityQueue (Elements in Natural Order)
✔ Uses Heap Data Structure.
java
import java.util.*;
java
import java.util.*;
7/9
7. Comparable vs Comparator
✔ Comparable is used for natural ordering ( compareTo() ).
✔ Comparator is used for custom sorting ( compare() ).
java
import java.util.*;
8/9
java
import java.util.*;
class Student {
int id;
String name;
9/9
Core Java Best Practices
java
1/6
Type Description Examples
java
java
2/6
public class FinallyExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Throws ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
} finally {
System.out.println("This will always execute.");
}
}
}
🛡 Output:
pgsql
java
3/6
validateAge(16); // Throws IllegalArgumentException
}
}
java
import java.io.*;
5. Custom Exceptions
4/6
✔ We can define our own exception classes by extending Exception (for checked
exceptions) or RuntimeException (for unchecked exceptions).
java
5/6
✅ Avoid Empty Blocks (handle exceptions properly).
catch
✅ Create Custom Exceptions when necessary.
6/6
Core Java Best Practices
1. What is Multithreading?
Multithreading is a technique where multiple threads (lightweight processes) run
concurrently to achieve parallel execution and improve performance.
java
arduino
Task 1
Task 2
Task 3
java
1/9
class MyThread extends Thread {
public void run() {
System.out.println("Thread running: " + Thread.currentThread().getName());
}
}
mathematica
State Description
2/9
java
java
3/9
}
}
java
4. Synchronization in Java
Problem: When multiple threads access a shared resource, data inconsistency can occur.
java
class Counter {
private int count = 0;
4/9
return count;
}
}
t1.start();
t2.start();
t1.join();
t2.join();
🛡 Output: Final count: 2000 (without synchronization, it may give inconsistent results)
java
import java.util.concurrent.locks.*;
class Counter {
private int count = 0;
private final Lock lock = new ReentrantLock();
5/9
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
5. Deadlock in Java
A deadlock occurs when two threads hold locks on different resources and wait indefinitely
for each other.
class DeadlockExample {
static final Object resource1 = new Object();
static final Object resource2 = new Object();
6/9
synchronized (resource2) {
System.out.println("Thread 2 locked resource 2");
try { Thread.sleep(100); } catch (InterruptedException e) {}
synchronized (resource1) {
System.out.println("Thread 2 locked resource 1");
}
}
});
t1.start();
t2.start();
}
}
java
class SharedResource {
private int data;
private boolean available = false;
7/9
public synchronized void consume() {
while (!available) {
try { wait(); } catch (InterruptedException e) {}
}
System.out.println("Consumed: " + data);
available = false;
notify();
}
}
producer.start();
consumer.start();
}
}
makefile
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
8/9
Summary
Concept Description
Deadlock Occurs when two threads wait indefinitely for each other’s lock.
9/9
Core Java Best Practices
Class Purpose
java
import java.io.File;
import java.io.IOException;
1/8
public class CreateFileExample {
public static void main(String[] args) {
try {
File file = new File("example.txt");
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
🛡 Output:
arduino
3. Writing to a File
3.1 Using FileWriter
FileWriter is used to write character data to a file.
java
import java.io.FileWriter;
import java.io.IOException;
2/8
System.out.println("Successfully written to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
3/8
4. Reading from a File
4.1 Using FileReader
FileReader reads characters from a file.
java
import java.io.FileReader;
import java.io.IOException;
🛡 Output: Hello, Java File Handling! Appending new line using BufferedWriter.
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
4/8
try {
BufferedReader reader = new BufferedReader(new
FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
arduino
5. Deleting a File
You can delete a file using the delete() method of the File class.
java
import java.io.File;
5/8
}
}
java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
6/8
fileOut.close();
System.out.println("Object serialized successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
7/8
Summary
Concept Description
8/8
Core Java Best Practices
@FunctionalInterface
interface MyFunctionalInterface {
void display(); // Single Abstract Method (SAM)
1/8
}
}
🛡 Output:
csharp
Improves performance.
2/8
java
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
🛡 Output:
nginx
Alice
Bob
Charlie
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
3/8
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Alice", "Bob", "Charlie");
System.out.println(filteredNames);
}
}
🛡 Output:
csharp
[Alice]
3. Method References
Method references allow referring to methods by their names instead of writing lambda
expressions.
import java.util.Arrays;
import java.util.List;
4/8
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Alice", "Bob");
interface MyInterface {
default void show() {
System.out.println("Default method in interface.");
}
}
🛡 Output:
sql
5/8
Default method in interface.
interface MathUtil {
static int square(int x) {
return x * x;
}
}
🛡 Output:
scss
Square of 5: 25
📌 Example of Optional
6/8
java
import java.util.Optional;
🛡 Output:
rust
Default Value
Summary
Feature Description
Functional Interfaces & Lambda Allows functional-style programming with concise syntax.
Default & Static Methods Adds functionality to interfaces without breaking old code.
Next Topic: Would you like to explore Java 9 Features or go deeper into
any Java 8 concept? 🚀
7/8
8/8
Core Java Best Practices
java
java
1/5
URL format: jdbc:mysql://hostname:port/databaseName
MySQL: "jdbc:mysql://localhost:3306/mydb"
PostgreSQL: "jdbc:postgresql://localhost:5432/mydb"
Oracle: "jdbc:oracle:thin:@localhost:1521:xe"
Example:
java
java
2/5
Step 5: Close the Connection
Always close the connection to free up resources.
java
con.close();
2. JDBC Drivers
JDBC drivers enable Java applications to interact with different databases.
Type 2: Native-API Driver Uses database-specific native API; requires client installation.
Type 4: Thin Driver (Pure Java) Directly connects to the database; most commonly used.
PostgreSQL: org.postgresql.Driver
Oracle: oracle.jdbc.driver.OracleDriver
java
3/5
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, "John Doe");
pstmt.setString(2, "john@example.com");
con.close();
java
while (rs.next()) {
System.out.println("User: " + rs.getString("name") + ", Email: " +
rs.getString("email"));
}
3.3 Update
java
4/5
3.4 Delete
java
Conclusion
JDBC provides a standard way to interact with databases. Key points:
5/5
Core Java Best Practices
1. Singleton Pattern
Definition
The Singleton Pattern ensures that a class has only one instance and provides a global
access point to it.
Use Cases
Managing database connections.
Logging frameworks.
Configuration settings.
Implementation
java
class Singleton {
private static Singleton instance;
1/8
public class SingletonExample {
public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance();
Singleton obj2 = Singleton.getInstance();
Thread-Safe Singleton
java
class Singleton {
private static Singleton instance;
private Singleton() { }
✅ Advantages:
Saves memory by preventing multiple instances.
Centralized control.
🚫 Disadvantages:
Can be difficult to unit test due to global state.
2. Factory Pattern
Definition
2/8
The Factory Pattern provides an interface for creating objects but lets subclasses decide the
instantiation.
Use Cases
When object creation logic is complex.
When you need to create multiple related objects without exposing the instantiation
logic.
Implementation
java
3/8
// Step 4: Use the Factory
public class FactoryExample {
public static void main(String[] args) {
Shape shape1 = ShapeFactory.getShape("CIRCLE");
shape1.draw(); // Output: Drawing a Circle
✅ Advantages:
Promotes loose coupling.
🚫 Disadvantages:
Additional class overhead.
3. Builder Pattern
Definition
The Builder Pattern simplifies object creation when a class has many optional parameters.
Use Cases
When a class has too many constructor parameters.
Implementation
java
class Car {
private String engine;
private int wheels;
private boolean sunroof;
4/8
private Car(CarBuilder builder) {
this.engine = builder.engine;
this.wheels = builder.wheels;
this.sunroof = builder.sunroof;
}
@Override
public String toString() {
return "Car [engine=" + engine + ", wheels=" + wheels + ", sunroof=" +
sunroof + "]";
}
}
5/8
}
}
✅ Advantages:
Improves readability for large constructors.
Ensures immutability.
🚫 Disadvantages:
Slightly more code than using multiple constructors.
4. Observer Pattern
Definition
The Observer Pattern defines a one-to-many dependency, meaning when one object
changes state, all its dependents (observers) are notified.
Use Cases
Event-driven programming (e.g., GUI applications).
Real-time notifications.
Implementation
java
import java.util.ArrayList;
import java.util.List;
6/8
public void addObserver(Observer observer) {
observers.add(observer);
}
newsAgency.addObserver(subscriber1);
newsAgency.addObserver(subscriber2);
🛡 Output:
sql
7/8
Alice received update: Breaking News: Observer Pattern Implemented!
Bob received update: Breaking News: Observer Pattern Implemented!
✅ Advantages:
Decouples subjects and observers, making systems flexible.
🚫 Disadvantages:
Can cause memory leaks if observers are not removed when no longer needed.
Summary
Pattern Description Use Case
Factory Centralized object creation. When multiple similar objects are created
dynamically.
Builder Simplifies complex object Objects with many optional parameters (Immutable
creation. objects).
Next Topic: Would you like to explore more Design Patterns (e.g.,
Prototype, Adapter, Strategy) or go deeper into one of the above? 🚀
8/8
Core Java Best Practices
class StackExample {
void methodA() {
int x = 10; // Stored in Stack
methodB();
}
void methodB() {
int y = 20; // Stored in Stack
}
1/6
stored in Heap
obj.methodA();
}
}
class HeapExample {
int data; // Instance variable stored in Heap
HeapExample(int data) {
this.data = data;
}
2/6
The Garbage Collector (GC) removes unused objects from the Heap to free up memory.
GC Type Description
Parallel GC Uses multiple threads for GC. Default for JVM before Java 9.
Example:
java
3/6
🔹 Soft Reference (GC removes if memory is low)
Used for caching.
Example:
java
import java.lang.ref.SoftReference;
Example:
java
import java.lang.ref.WeakReference;
Example:
java
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
data = null;
System.gc();
System.out.println(phantomRef.get()); // Always null
}
}
📌 Comparison of References:
Type When is it Collected? Example Use Case
Summary
Stack stores method calls & local variables, while Heap stores objects.
5/6
Would you like more details on GC tuning or JVM memory monitoring tools? 🚀
6/6
Core Java Best Practices
import java.lang.reflect.Method;
import java.lang.reflect.Field;
import java.lang.reflect.Constructor;
class Example {
private String name;
public Example() {}
1/7
// Get Methods
Method[] methods = obj.getDeclaredMethods();
for (Method method : methods) {
System.out.println("Method: " + method.getName());
}
// Get Fields
Field[] fields = obj.getDeclaredFields();
for (Field field : fields) {
System.out.println("Field: " + field.getName());
}
// Get Constructors
Constructor<?>[] constructors = obj.getDeclaredConstructors();
for (Constructor<?> constructor : constructors) {
System.out.println("Constructor: " + constructor.getName());
}
}
}
import java.lang.reflect.Field;
class Student {
private String name = "John";
2/7
field.setAccessible(true);
field.set(student, "Alice");
student.display();
}
}
2. Java Annotations
Annotations provide metadata about classes, methods, or fields.
🔹 @Override Example
java
class Parent {
void display() {
System.out.println("Parent class");
}
}
3/7
void display() { // Ensures this method is actually overriding the parent method
System.out.println("Child class");
}
}
🔹 @FunctionalInterface Example
java
@FunctionalInterface
interface MyFunctionalInterface {
void greet();
}
🔹 @SuppressWarnings Example
java
class OldClass {
@Deprecated
void display() {
System.out.println("This method is deprecated");
}
}
🔹 @Deprecated Example
4/7
java
class OldVersion {
@Deprecated
public void oldMethod() {
System.out.println("This method is outdated.");
}
}
3. Use @Target to specify where it can be used (Class, Method, Field, etc.).
import java.lang.annotation.*;
import java.lang.reflect.*;
5/7
@interface MyAnnotation {
String value();
}
class CustomAnnotationExample {
@MyAnnotation(value = "Hello Annotation")
public void testMethod() {
System.out.println("Method Executed");
}
}
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println("Annotation Value: " + annotation.value());
}
obj.testMethod();
}
}
📌 Explanation:
@Retention(RetentionPolicy.RUNTIME) : Annotation is available at runtime.
Summary
Reflection API allows dynamic class inspection and modification.
6/7
Frameworks like Spring, Hibernate, and JUnit rely heavily on Reflection and
Annotations.
7/7
Core Java Best Practices
📌 Key Points
Requires an instance of the outer class to be instantiated.
class OuterClass {
private String message = "Hello from Outer Class";
// Inner Class
class InnerClass {
void display() {
System.out.println(message); // Accessing outer class private member
}
}
}
1/6
}
}
📌 Explanation:
InnerClass is a non-static member of OuterClass .
📌 Key Points
Can only access static members of the outer class.
class OuterClass {
static String message = "Hello from Outer Class";
2/6
}
}
📌 Explanation:
StaticNestedClass is declared with static , so it does not require an instance of
OuterClass .
📌 Key Points
Defined and instantiated in a single expression.
interface Greeting {
void sayHello();
}
📌 Explanation:
3/6
We created an anonymous inner class that implements the Greeting interface without
a separate class declaration.
📌 Explanation:
We created an anonymous inner class that extends Animal and overrides
makeSound() .
📌 Key Points
Defined inside a method and cannot be accessed outside.
Can access local variables of the method if they are final or effectively final.
4/6
java
class OuterClass {
void outerMethod() {
System.out.println("Inside Outer Method");
class LocalInnerClass {
void localDisplay() {
System.out.println("Inside Local Inner Class");
}
}
📌 Explanation:
LocalInnerClass is defined inside outerMethod() , so it cannot be used outside the
method.
Local inner classes can access variables from the enclosing method if they are final or
effectively final.
Summary
Requires Outer Class Access to Outer Class
Inner Class Type Static? Instance? Members
5/6
Requires Outer Class Access to Outer Class
Inner Class Type Static? Instance? Members
6/6
Core Java Best Practices
Java Networking
Java Networking allows communication between computers using TCP/IP protocols. Java
provides built-in classes in the java.net package to handle networking.
import java.io.*;
import java.net.*;
1/7
InputStreamReader(socket.getInputStream()));
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
📌 Explanation:
ServerSocket listens on port 5000.
2/7
Socket connects the client to the server.
🔸 UDP Server
java
import java.net.*;
🔸 UDP Client
java
import java.net.*;
3/7
byte[] buffer = message.getBytes();
InetAddress address = InetAddress.getByName("localhost");
import java.io.*;
import java.net.*;
4/7
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
📌 Explanation:
URL.openStream() opens a stream to the webpage.
import java.io.*;
import java.net.*;
5/7
e.printStackTrace();
}
}
}
📌 Explanation:
HttpURLConnection is used to send GET requests.
import java.io.*;
import java.net.*;
6/7
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
📌 Explanation:
setRequestMethod("POST") sets the request type.
Summary
Feature Key Classes
7/7
Core Java Best Practices
Java Security
Java provides various security mechanisms to protect data through Hashing, Encryption,
and Decryption techniques. These are essential for securing passwords, sensitive data, and
communication.
java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
return hexString.toString();
1/6
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
📌 Output Example:
yaml
🛑 Weakness: MD5 is vulnerable to hash collisions, where two different inputs produce the
same hash.
java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
2/6
StringBuilder hexString = new StringBuilder();
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
📌 Output Example:
yaml
✅ SHA-256 is widely used for password hashing, digital signatures, and data integrity.
java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
3/6
import javax.crypto.SecretKey;
import java.util.Base64;
// Encrypt Data
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("Encrypted: " + encryptedText);
// Decrypt Data
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedData =
cipher.doFinal(Base64.getDecoder().decode(encryptedText));
System.out.println("Decrypted: " + new String(decryptedData));
}
}
📌 Output Example:
pgsql
Encrypted: s9BbxHTH8T6UYWd/KT8vxQ==
Decrypted: HelloAES
✅ AES is widely used in file encryption, database encryption, and secure communication.
🔹 RSA (Rivest-Shamir-Adleman)
RSA is an asymmetric encryption algorithm, meaning it uses:
4/6
Public Key (for encryption)
java
import java.security.*;
import javax.crypto.Cipher;
import java.util.Base64;
// Encrypt Data
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = cipher.doFinal(data.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedData);
System.out.println("Encrypted: " + encryptedText);
// Decrypt Data
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedData =
cipher.doFinal(Base64.getDecoder().decode(encryptedText));
System.out.println("Decrypted: " + new String(decryptedData));
}
}
📌 Output Example:
makefile
Encrypted: ZmVmM3NydDg...
5/6
Decrypted: HelloRSA
✅ RSA is commonly used in SSL/TLS certificates, digital signatures, and secure email
communication.
Summary
Security Feature Algorithm Use Case
6/6
Core Java Best Practices
I'll provide an in-depth explanation of each Java interview-specific topic, starting with key
differences and then covering common coding questions.
Use Case Used for primitive types and object Used for content comparison in objects
references
Example Code
java
🔹 StringBuffer vs StringBuilder
1/8
Feature StringBuffer StringBuilder
Example Code
java
🔹 ArrayList vs LinkedList
Memory Usage Less (no extra pointers) More (extra pointers for nodes)
Example Code
java
🔹 HashMap vs Hashtable
2/8
Feature HashMap Hashtable
Example Code
java
Usage Keyword for constants, method Cleanup block in Garbage collection hook
overriding prevention try-catch
Example Code
java
// final keyword
final int x = 10;
// finally block
try {
System.out.println("Inside try");
} finally {
System.out.println("Inside finally");
}
// finalize method
3/8
class Test {
protected void finalize() { System.out.println("Object garbage collected"); }
}
java
📌 Output:
0 1 1 2 3 5 8 13 21 34
4/8
public class Palindrome {
public static boolean isPalindrome(String str) {
return str.equals(new StringBuilder(str).reverse().toString());
}
🔹 Sorting Algorithms
🔸 Bubble Sort
java
5/8
}
}
🔸 Quick Sort
java
import java.util.HashSet;
6/8
public class FindDuplicates {
public static void findDuplicates(int[] arr) {
HashSet<Integer> set = new HashSet<>();
for (int num : arr) {
if (!set.add(num)) {
System.out.println("Duplicate found: " + num);
}
}
}
🔹 Reverse a String
java
📌 Output:
makefile
Reversed: olleH
7/8
Would you like more coding challenges or deeper
explanations on any topic?🚀
8/8