Skip to main content

JAVA Cheat Sheet

 

Category

Concept

Description

Example

Basics

Hello World

Basic program to print "Hello, World!"

java

public class HelloWorld {

 public static void main(String[] args) {

 System.out.println("Hello, World!");

 }

}


Data Types

Primitive types: int, double, char, boolean, etc., and reference types

java

int a = 10;

double b = 5.5;

char c = 'A';

boolean isTrue = true;

String name = "Alice";


Variables

Storage locations with type and name

java

int age = 25;

double salary = 50000.0;

String employee = "John Doe";


Operators

Arithmetic, Relational, Logical, Bitwise, Assignment operators

java

int sum = a + b;

if (a > b && b < c) {

 // ...

}

Control Flow

If-Else

Conditional branching

java

if (score >= 50) {

 System.out.println("Pass");

} else {

 System.out.println("Fail");

}


Switch

Multi-way branch based on variable value

java

switch (choice) {

 case 1:

 System.out.println("One");

 break;

 case 2:

 System.out.println("Two");

 break;

 default:

 System.out.println("Other");

}


Loops

for, while, do-while for iteration

java

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

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

}

// While loop

int j = 0;

while(j < 10) {

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

 j++;

}

Functions (Methods)

Method Declaration

Define reusable code blocks with parameters and return types

java

public int add(int x, int y) {

 return x + y;

}


Recursion

Method calling itself

java

public int factorial(int n) {

 if (n <= 1) return 1;

 else return n * factorial(n - 1);

}

Object-Oriented Programming (OOP)

Classes and Objects

Blueprint for creating objects

java

public class Person {

 String name;

 int age;

 public Person(String name, int age) {

 this.name = name;

 this.age = age;

 }

}

// Creating an object

Person p1 = new Person("Alice", 30);


Inheritance

Mechanism to create a new class from an existing class

java

public class Animal {

 void eat() { System.out.println("Eating"); }

}

public class Dog extends Animal {

 void bark() { System.out.println("Barking"); }

}


Polymorphism

Ability to take many forms (method overriding and overloading)

java

// Method Overloading

public int add(int a, int b) { return a + b; }

public double add(double a, double b) { return a + b; }

// Method Overriding

@Override

public void eat() { System.out.println("Dog eating"); }


Encapsulation

Wrapping data (variables) and methods into a single unit (class)

java

public class Person {

 private String name;

 public String getName() { return name; }

 public void setName(String name) { this.name = name; }

}


Abstraction

Hiding complex implementation details and showing only essential features

java

public abstract class Shape {

 abstract void draw();

}

public class Circle extends Shape {

 void draw() { System.out.println("Drawing Circle"); }

}

Arrays & Collections

Arrays

Fixed-size data structures to store multiple elements of the same type

java

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

String[] names = new String[5];


ArrayList

Resizable-array implementation of the List interface

java

import java.util.ArrayList;

ArrayList<String> list = new ArrayList<>();

list.add("Apple");

list.add("Banana");


HashMap

Hash table based implementation of the Map interface

java

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();

map.put("One", 1);

map.put("Two", 2);

Exception Handling

Try-Catch

Handling exceptions to prevent program crashes

java

try {

 int result = 10 / 0;

} catch (ArithmeticException e) {

 System.out.println("Cannot divide by zero");

}


Finally

Block that always executes after try-catch

java

try {

 // ...

} catch (Exception e) {

 // ...

} finally {

 System.out.println("Cleanup");

}


Throw and Throws

Manually throw exceptions and declare exceptions in method signatures

java

public void validate(int age) throws IllegalArgumentException {

 if(age < 18) {

 throw new IllegalArgumentException("Age must be >= 18");

 }

}

Input/Output (I/O)

File I/O

Reading from and writing to files using FileReader, FileWriter, etc.

java

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

 

// Writing to a file

try (FileWriter fw = new FileWriter("output.txt")) {

 fw.write("Hello, File!");

} catch (IOException e) {

 e.printStackTrace();

}

 

// Reading from a file

try (FileReader fr = new FileReader("output.txt")) {

 int i;

 while((i = fr.read()) != -1) {

 System.out.print((char)i);

 }

} catch (IOException e) {

 e.printStackTrace();

}

Generics

Generic Classes and Methods

Enable types (classes and methods) to operate on objects of various types

java

public class Box<T> {

 private T item;

 public void set(T item) { this.item = item; }

 public T get() { return item; }

}

// Usage

Box<Integer> integerBox = new Box<>();

integerBox.set(10);

Integer num = integerBox.get();

Concurrency

Threads

Creating and managing threads using Thread class or Runnable interface

java

// Extending Thread

public class MyThread extends Thread {

 public void run() {

 System.out.println("Thread running");

 }

}

// Implementing Runnable

public class MyRunnable implements Runnable {

 public void run() {

 System.out.println("Runnable running");

 }

}

// Usage

MyThread t1 = new MyThread();

t1.start();

Thread t2 = new Thread(new MyRunnable());

t2.start();


Synchronization

Controlling access to shared resources to prevent conflicts

java

public class Counter {

 private int count = 0;

 public synchronized void increment() {

 count++;

 }

 public int getCount() { return count; }

}


Executors and Thread Pools

Managing multiple threads efficiently using the Executor framework

java

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

 

ExecutorService executor = Executors.newFixedThreadPool(5);

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

 executor.execute(new MyRunnable());

}

executor.shutdown();

Networking

Sockets

Basic socket programming for network communication

java

import java.io.*;

import java.net.*;

 

// Server

ServerSocket serverSocket = new ServerSocket(8080);

Socket clientSocket = serverSocket.accept();

BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

out.println("Hello Client");

serverSocket.close();

 

// Client

Socket socket = new Socket("localhost", 8080);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String message = in.readLine();

System.out.println(message);

socket.close();

Lambda Expressions

Lambdas

Simplify the implementation of functional interfaces

java

import java.util.Arrays;

import java.util.List;

 

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

names.forEach(name -> System.out.println(name));

Stream API

Streams

Process sequences of elements with functional-style operations

java

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

 

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> squared = numbers.stream()

 .map(n -> n * n)

 .collect(Collectors.toList());

System.out.println(squared); // [1, 4, 9, 16, 25]

Annotations

Custom Annotations

Define custom metadata for classes, methods, etc.

java

import java.lang.annotation.*;

 

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface MyAnnotation {

 String value();

}

 

// Usage

public class Test {

 @MyAnnotation("Example")

 public void myMethod() {

 // ...

 }

}

Reflection

Reflection API

Inspect and manipulate classes, methods, and fields at runtime

java

import java.lang.reflect.*;

 

Class<?> cls = Class.forName("java.util.ArrayList");

Method[] methods = cls.getDeclaredMethods();

for(Method method : methods) {

 System.out.println(method.getName());

}

Generics Advanced

Bounded Type Parameters

Restrict types that can be used as type arguments

java

public <T extends Number> void printNumber(T number) {

 System.out.println(number);

}

Design Patterns

Singleton Pattern

Ensure a class has only one instance and provide a global point of access

java

public class Singleton {

 private static Singleton instance;

 private Singleton() {}

 public static Singleton getInstance() {

 if(instance == null) {

 instance = new Singleton();

 }

 return instance;

 }

}


Factory Pattern

Create objects without specifying the exact class to instantiate

java

public interface Shape { void draw(); }

public class Circle implements Shape { public void draw() { System.out.println("Circle"); } }

public class Square implements Shape { public void draw() { System.out.println("Square"); } }

public class ShapeFactory {

 public Shape getShape(String type) {

 if(type.equalsIgnoreCase("circle")) return new Circle();

 else if(type.equalsIgnoreCase("square")) return new Square();

 return null;

 }

}

Advanced Topics

Generics with Wildcards

Use ?, extends, and super to handle unknown types in generics

java

public void printList(List<?> list) {

 for(Object obj : list) {

 System.out.println(obj);

 }

}

// Upper Bounded

public void processNumbers(List<? extends Number> numbers) { /* ... */ }

// Lower Bounded

public void addNumbers(List<? super Integer> list) { /* ... */ }


Concurrency Utilities

Use high-level concurrency utilities like CountDownLatch, Semaphore, etc.

java

import java.util.concurrent.CountDownLatch;

 

CountDownLatch latch = new CountDownLatch(3);

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

 new Thread(() -> {

 // Task

 latch.countDown();

 }).start();

}

latch.await();

System.out.println("All tasks completed");


Java Memory Model

Understand how Java manages memory, including Heap, Stack, and Garbage Collection

Conceptual understanding; no direct code example

Java 8+ Features

Lambda Expressions

Simplify implementation of functional interfaces

java

List<String> list = Arrays.asList("a", "b", "c");

list.forEach(item -> System.out.println(item));


Streams API

Functional-style operations on streams of elements

java

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

List<Integer> even = numbers.stream()

 .filter(n -> n % 2 == 0)

 .collect(Collectors.toList());

System.out.println(even); // [2, 4]


Optional Class

Handle nullable values without explicit null checks

java

Optional<String> optional = Optional.ofNullable(getName());

optional.ifPresent(name -> System.out.println(name));

// Or with default

String name = optional.orElse("Default");

Best Practices

Code Modularity

Write modular code using classes, methods, and packages

Organize code into packages and classes with single responsibilities


Commenting and Documentation

Use comments and Javadoc to explain code logic and usage

java

/**

 * Adds two integers.

 * @param a First integer

 * @param b Second integer

 * @return Sum of a and b

 */

public int add(int a, int b) {

 return a + b;

}


Exception Handling

Handle exceptions gracefully and avoid swallowing exceptions

Use specific catch blocks and ensure resources are closed using try-with-resources

Debugging

Using IDE Debuggers

Utilize IDE features like breakpoints, watches, and step execution

Depends on the IDE (e.g., IntelliJ IDEA, Eclipse); no direct code example

Performance

Profiling and Optimization

Identify and optimize performance bottlenecks using profiling tools

Use tools like VisualVM, JProfiler; no direct code example

Security

Secure Coding Practices

Follow best practices to write secure Java applications

Input validation, proper exception handling, avoiding SQL injection, etc.; no direct code example

Build Tools

Maven and Gradle

Manage project dependencies and build lifecycle

Example pom.xml for Maven or build.gradle for Gradle; no direct code example

Testing

JUnit Testing

Write and run unit tests using JUnit framework

java

import org.junit.Test;

import static org.junit.Assert.*;

 

public class CalculatorTest {

 @Test

 public void testAdd() {

 Calculator calc = new Calculator();

 assertEquals(5, calc.add(2, 3));

 }

}

Database Connectivity

JDBC

Connect and interact with databases using Java Database Connectivity (JDBC)

java

import java.sql.*;

 

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM users");

while(rs.next()) {

 System.out.println(rs.getString("username"));

}

conn.close();

Advanced I/O

NIO (Non-blocking I/O)

Perform high-performance I/O operations using Java NIO package

java

import java.nio.file.*;

import java.nio.charset.StandardCharsets;

import java.io.IOException;

 

Path path = Paths.get("example.txt");

List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);

Files.write(path, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

Serialization

Serializable Interface

Convert objects to a byte stream for storage or transmission

java

import java.io.Serializable;

 

public class User implements Serializable {

 private static final long serialVersionUID = 1L;

 private String name;

 private int age;

 // Constructors, getters, setters

}

Java Modules

Module System (Java 9+)

Organize code into modules for better encapsulation and dependency management

java

// module-info.java

module com.example.myapp {

 requires java.base;

 exports com.example.myapp.package;

}

Reactive Programming

Reactive Streams

Asynchronous data streams with backpressure support

Use libraries like Reactor or RxJava; no direct code example

Functional Interfaces

Built-in Functional Interfaces

Utilize interfaces like Predicate, Function, Supplier, Consumer

java

import java.util.function.Predicate;

 

Predicate<Integer> isEven = (n) -> n % 2 == 0;

System.out.println(isEven.test(4)); // true

Memory Management

Garbage Collection

Automatic memory management and garbage collection mechanisms

Understand how GC works; no direct code example

Best Practices

Immutable Classes

Design classes whose instances cannot be modified after creation

java

public final class ImmutablePerson {

 private final String name;

 private final int age;

 

 public ImmutablePerson(String name, int age) {

 this.name = name;

 this.age = age;

 }

 

 public String getName() { return name; }

 public int getAge() { return age; }

}


Effective Java Practices

Follow best practices as outlined in "Effective Java" by Joshua Bloch

Examples include favoring composition over inheritance, using interfaces, etc.; no direct code example

Miscellaneous

Annotations

Use built-in and custom annotations to provide metadata

java

@Override

public String toString() {

 return "Example";

}


Varargs

Allow methods to accept variable number of arguments

java

public void printNumbers(int... numbers) {

 for(int num : numbers) {

 System.out.println(num);

 }

}

// Usage

printNumbers(1, 2, 3, 4);


Enums

Define a fixed set of constants

java

public enum Day {

 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

}

// Usage

Day today = Day.MONDAY;

switch(today) {

 case MONDAY:

 System.out.println("Start of the week");

 break;

 // ...

}

Comments

Popular posts from this blog

Gujarati Keyboard layout (terafont-varun), Computer Short cut key, Tally short cut key

Word , Excel , Power Point Shortcut Key in Gujarati

Terafont-Varun (Gujarati Typing) Keyboard Layout by "Sama Soyab"

  For Gujarati Typing : Required : Terafont-Varun Font  After Successfully Installed Terafont Varun Open Any Text Editor or any program. Select Font Terafont-Varun -> Ok For more detail please watch below video. Search Topics : Learn terafont varun, Learn terafont chandan, Learn terafont gujarati to english translation, Learn terafont varun keyboard, Learn terafont converter, Learn terafont varun zip, Learn terafont keyboard, Learn terafont kinnari, Learn terafont akash, Learn terafont aakash, Learn terafont akash ttf, Learn terafont aakash gujarati download, Learn terafont akash keyboard, Learn terafont akash download for windows 10, Learn terafont akash font download, Learn terafont arun, Learn terafont border, Learn terafont chandan keyboard, Learn terafont-chandan font, Learn tera font chandana, Learn convert terafont to shruti, Learn convert terafont varun to shruti, Learn terafont varun chart, Learn terafont download, Learn terafont download for windows 10, Learn tera...