Core Java Cheat Sheet
1. Basic Syntax
java
// Hello World Program
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
2. Data Types
java
int age = 25;
double price = 10.5;
char grade = 'A';
boolean isJavaFun = true;
String name = "Praveen";
3. Operators
java
int sum = 10 + 5; // Addition
int diff = 10 - 5; // Subtraction
int product = 10 * 5; // Multiplication
int quotient = 10 / 5; // Division
int remainder = 10 % 5; // Modulus
4. Conditional Statements
java
if (age > 18) {
System.out.println("Adult");
} else {
System.out.println("Minor");
}
5. Loops
java
// For Loop
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// While Loop
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
}
// Do-While Loop
int j = 1;
do {
System.out.println(j);
j++;
} while (j <= 5);
6. Arrays
java
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers[0]); // Prints 1
7. Methods
java
public class Main {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(5, 10)); // Prints 15
}
}
8. Object-Oriented Programming
java
class Person {
String name;
Person(String name) {
this.name = name;
}
void display() {
System.out.println("Name: " + name);
}
}
public class Main {
public static void main(String[] args) {
Person p = new Person("Praveen");
p.display();
}
}
9. Exception Handling
java
try {
int num = 10 / 0; // This will cause an exception
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero");
} finally {
System.out.println("Execution Completed");
}
10. Multithreading
java
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
This is just a starting point, but I can refine it based on what areas you'd like
to focus on more! Let me know if you want specific details on any topic. 🚀
exception handling explain in detail with exmaple
Exception Handling in Java
Exception handling is a mechanism in Java to deal with runtime errors or unwanted
scenarios that might disrupt program execution. It ensures the program doesn't
crash unexpectedly and allows graceful recovery from errors.
1. What is an Exception?
An exception is an event that occurs during the execution of a program and disrupts
its normal flow. Examples include:
ArithmeticException (e.g., division by zero)
NullPointerException (trying to access an object that is null)
ArrayIndexOutOfBoundsException (accessing an index outside array bounds)
2. Exception Handling Keywords
Java provides four main keywords to handle exceptions:
try: Defines a block of code where an exception might occur.
catch: Handles the exception if one occurs.
finally: A block that always executes after try-catch, useful for cleanup
operations.
throw: Used to explicitly throw an exception.
throws: Declares exceptions that a method might throw.
Example 1: Basic Exception Handling
java
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
Output:
Error: Cannot divide by zero!
Program continues...
👉 The program doesn’t crash because we handled the exception.
Example 2: Handling Multiple Exceptions
java
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // Array index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid array index!");
} catch (Exception e) { // Catch any other exception
System.out.println("General error occurred.");
}
}
}
Output:
Error: Invalid array index!
👉 The first catch block matches, so the general Exception e block doesn’t execute.
Example 3: Using finally Block
java
public class FinallyExample {
public static void main(String[] args) {
try {
int num = Integer.parseInt("ABC"); // Throws NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format!");
} finally {
System.out.println("This will always execute.");
}
}
}
Output:
Error: Invalid number format!
This will always execute.
👉 The finally block runs regardless of an exception occurring.
Example 4: Throwing Exceptions Manually
java
public class CustomExceptionExample {
public static void main(String[] args) {
int age = 15;
if (age < 18) {
throw new IllegalArgumentException("You must be 18 or older.");
}
System.out.println("Access granted!");
}
}
Output:
Exception in thread "main" java.lang.IllegalArgumentException: You must be 18 or
older.
👉 throw lets us create custom error conditions.
Example 5: Using throws in Methods
java
public class ThrowsExample {
static void checkAge(int age) throws IllegalArgumentException {
if (age < 18) {
throw new IllegalArgumentException("You must be 18 or older.");
}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
Error: You must be 18 or older.
👉 throws declares that a method might throw an exception.
Best Practices for Exception Handling
✔ Use specific exceptions instead of a general Exception class. ✔ Log exceptions
properly instead of just printing messages. ✔ Never catch and ignore exceptions—
handle them gracefully. ✔ Use finally for resource cleanup like closing database
connections. ✔ Follow a structured approach to handling errors in large
applications.
Since you're deeply invested in Java debugging, mastering exception handling will
help you create reliable, fault-tolerant applications! Let me know if you'd like
advanced topics like custom exceptions or logging mechanisms 🚀.
jdbc in detail
Java Database Connectivity (JDBC) - Detailed Explanation
JDBC (Java Database Connectivity) is an API that enables Java applications to
interact with relational databases. It allows querying and updating data using SQL.
1. JDBC Architecture Overview
JDBC consists of the following components:
Driver Manager – Loads database drivers and establishes connections.
Driver – A specific implementation for different databases (e.g., MySQL,
PostgreSQL).
Connection – Represents a connection to the database.
Statement – Used to execute SQL queries.
ResultSet – Stores the result of SELECT queries.
SQLException – Handles database-related exceptions.
2. JDBC Setup
Add JDBC Driver Dependency
For MySQL, include the JDBC driver in your project:
Maven Dependency (MySQL)
xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
Manually Download JDBC Driver Download the MySQL JDBC driver here.
3. Establishing a Database Connection
java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase"; // Database URL
String user = "root"; // Database username
String password = "password"; // Database password
try (Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connected to the database!");
} catch (SQLException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Uses try-with-resources to close the connection automatically. ✔ Handles
SQLException properly.
4. Executing SQL Queries
a) Creating a Table
java
import java.sql.Connection;
import java.sql.Statement;
public class CreateTable {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
String sql = "CREATE TABLE employees (id INT PRIMARY KEY, name
VARCHAR(50), salary DOUBLE)";
stmt.executeUpdate(sql);
System.out.println("Table created successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
b) Inserting Data
java
import java.sql.Connection;
import java.sql.Statement;
public class InsertData {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
String sql = "INSERT INTO employees VALUES (1, 'John Doe', 50000)";
stmt.executeUpdate(sql);
System.out.println("Data inserted successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
5. Retrieving Data with ResultSet
java
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class FetchData {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM employees")) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double salary = rs.getDouble("salary");
System.out.println(id + " | " + name + " | " + salary);
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
6. Using PreparedStatement (Avoid SQL Injection)
java
import java.sql.Connection;
import java.sql.PreparedStatement;
public class InsertPreparedStatement {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "root";
String password = "password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "INSERT INTO employees (id, name, salary) VALUES
(?, ?, ?)";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, 2);
pstmt.setString(2, "Alice");
pstmt.setDouble(3, 60000);
pstmt.executeUpdate();
System.out.println("Data inserted successfully using
PreparedStatement!");
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
7. Updating and Deleting Records
Updating Records
java
String sql = "UPDATE employees SET salary = ? WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setDouble(1, 70000);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
}
Deleting Records
java
String sql = "DELETE FROM employees WHERE id = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
pstmt.setInt(1, 2);
pstmt.executeUpdate();
}
8. Best Practices for JDBC
✔ Use PreparedStatement to avoid SQL injection. ✔ Always close database connections
using try-with-resources. ✔ Use connection pooling for better performance (via
HikariCP or Apache DBCP). ✔ Log errors properly instead of just printing them. ✔
Avoid hardcoded database credentials—use environment variables or configuration
files.
Next Steps
Since you're invested in Java and Spring Boot, learning Spring Data JPA would be a
great next step—it simplifies database interactions significantly! Let me know if
you'd like a guide on that 🚀.
explain file handling in detal
File Handling in Java - Detailed Explanation
File handling in Java allows us to perform operations like reading, writing,
deleting, and manipulating files efficiently. Java provides built-in classes under
the java.io and java.nio packages for file handling.
1. File Handling Classes in Java
Java provides several classes for working with files:
File – Represents file or directory paths.
FileWriter & FileReader – Used for writing and reading character data.
BufferedWriter & BufferedReader – Efficiently handle character streams.
PrintWriter – Writes formatted data into files.
FileInputStream & FileOutputStream – Handle binary data (e.g., images, PDFs).
ObjectInputStream & ObjectOutputStream – Used for reading/writing serialized
objects.
2. Creating a File
java
import java.io.File;
import java.io.IOException;
public class CreateFileExample {
public static void main(String[] args) {
File file = new File("example.txt"); // File object
try {
if (file.createNewFile()) {
System.out.println("File created successfully!");
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Uses createNewFile() method to create a file. ✔ Handles errors using IOException.
3. Writing to a File
Using FileWriter
java
import java.io.FileWriter;
import java.io.IOException;
public class WriteFileExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("example.txt")) {
writer.write("Hello, Praveen! This is a Java file handling example.");
System.out.println("Data written successfully!");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Uses FileWriter to write text into a file. ✔ Uses try-with-resources to ensure
proper file closure.
4. Reading a File
Using FileReader
java
import java.io.FileReader;
import java.io.IOException;
public class ReadFileExample {
public static void main(String[] args) {
try (FileReader reader = new FileReader("example.txt")) {
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Reads text data character by character. ✔ Handles exceptions properly.
Using BufferedReader for Efficient Reading
java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReadExample {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new
FileReader("example.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Reads line by line, improving performance for larger files.
5. Appending Data to a File
java
import java.io.FileWriter;
import java.io.IOException;
public class AppendFileExample {
public static void main(String[] args) {
try (FileWriter writer = new FileWriter("example.txt", true)) { // `true`
enables append mode
writer.write("\nAdding new content to the file.");
System.out.println("Data appended successfully!");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Opens the file in append mode using FileWriter("example.txt", true).
6. Deleting a File
java
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted successfully!");
} else {
System.out.println("File not found.");
}
}
}
✔ Uses delete() method to remove files.
7. Handling Binary Data (Images, PDFs)
Writing Binary Data
java
import java.io.FileOutputStream;
import java.io.IOException;
public class BinaryWriteExample {
public static void main(String[] args) {
byte[] data = {65, 66, 67}; // ASCII values for 'A', 'B', 'C'
try (FileOutputStream fos = new FileOutputStream("binary.dat")) {
fos.write(data);
System.out.println("Binary data written successfully!");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Reading Binary Data
java
import java.io.FileInputStream;
import java.io.IOException;
public class BinaryReadExample {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("binary.dat")) {
int byteData;
while ((byteData = fis.read()) != -1) {
System.out.print((char) byteData);
}
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Works for binary formats like images, PDFs, and serialized objects.
8. Serialization & Deserialization (Saving Objects to Files)
Writing an Object to a File
java
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializeExample {
public static void main(String[] args) {
Person person = new Person("Praveen", 25);
try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("person.dat"))) {
oos.writeObject(person);
System.out.println("Object serialized successfully!");
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Reading an Object from a File
java
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializeExample {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("person.dat"))) {
Person person = (Person) ois.readObject();
System.out.println("Name: " + person.name + ", Age: " + person.age);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
✔ Uses Serializable interface. ✔ Enables storing Java objects in files.
9. Best Practices for File Handling
✔ Use BufferedReader & BufferedWriter for efficiency. ✔ Always close file streams
using try-with-resources. ✔ Handle IOException properly instead of ignoring errors.
✔ Use serialization for saving object states. ✔ Ensure files exist before
reading/writing to avoid exceptions.
Next Steps
Since you have deep expertise in Java, exploring Java NIO (New I/O) APIs could be
beneficial for handling files more efficiently in high-performance applications.
Let me know if you'd like details on that 🚀.