Java Essentials with Simple Examples:

Here’s a Java cheat sheet that covers essential concepts and syntax. This assumes you have basic knowledge of Java programming.

  1. Basic Structure:

The basic structure of a Java program consists of a class definition and a main method. The class definition is the blueprint of a Java program, containing its properties and methods. The main method is the entry point of the program and is executed by the Java Virtual Machine (JVM) when the program starts.

				
					public class MyClass {
    public static void main(String[] args) {
        // Code here
    }
}

				
			
  1. Variables and Data Types:

Variables are used to store data. In Java, variables have a specific data type. The main data types include int (integer), double (floating-point number), boolean (true or false), char (single character), and String (a sequence of characters). Variables must be declared before use, and they can be assigned a value.

				
					int age = 30;
double salary = 85000.0;
boolean isStudent = false;
char letter = 'A';
String name = "John Doe";
				
			
  1. Arithmetic Operators:

Arithmetic operators perform mathematical operations on operands (variables or literals). Basic arithmetic operators include addition (+), subtraction (-), multiplication (*), division (/), and modulo (%). These operators can be used to perform calculations in Java.

				
					int a = 5;
int b = 2;

int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;

				
			
  1. Comparison and Logical Operators:

Comparison operators are used to compare two values, while logical operators are used to combine two or more conditions. Comparison operators include equality (==), inequality (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=). Logical operators include AND (&&), OR (||), and NOT (!).

				
					int x = 5;
int y = 3;

boolean isEqual = (x == y);
boolean isNotEqual = (x != y);
boolean isGreater = (x > y);
boolean isLess = (x < y);
boolean isGreaterOrEqual = (x >= y);
boolean isLessOrEqual = (x <= y);

boolean andResult = (x > 0) && (y > 0);
boolean orResult = (x < 0) || (y < 0);
boolean notResult = !(x > 0);
				
			
  1. Conditional Statements:

Conditional statements are used to make decisions based on certain conditions. The “if-else” statement is used to execute a block of code if a specified condition is true, and another block of code if the condition is false. The “else if” statement can be used to specify additional conditions.

				
					if (x > y) {
    // Code
} else if (x < y) {
    // Code
} else {
    // Code
}
				
			
  1. Loops:

Loops are used to repeatedly execute a block of code as long as a specified condition is true. Java supports three types of loops: the “for” loop (used to execute a block of code a specific number of times), the “while” loop (used to execute a block of code as long as the condition is true), and the “do-while” loop (used to execute a block of code at least once and then continue executing it as long as the condition is true).

				
					// For loop
for (int i = 0; i < 10; i++) {
    // Code
}

// While loop
int i = 0;
while (i < 10) {
    // Code
    i++;
}

// Do-While loop
int j = 0;
do {
    // Code
    j++;
} while (j < 10);

				
			
  1. Arrays:

Arrays are used to store multiple values of the same data type in a single variable. They have a fixed size, and individual elements can be accessed by their index (position). Arrays can be initialized when declared, and looped through using a for loop or enhanced for loop (also known as a “for-each” loop).

				
					// Declare an array
int[] numbers = new int[5];

// Initialize an array
int[] numbers = {1, 2, 3, 4, 5};

// Access elements
int firstElement = numbers[0];

// Loop through an array
for (int i = 0; i < numbers.length; i++) {
    int element = numbers[i];
}
				
			
  1. Methods:

Methods are reusable blocks of code that can be called with a specific set of input parameters. They can be defined with or without a return type, and with or without input parameters. Methods help organize and modularize code, making it more readable and maintainable.

				
					public static void myMethod() {
    // Code
}

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

// Method call
myMethod();
int result = sum(5, 3);
				
			
  1. Classes and Objects:

A class is a blueprint for creating objects, which are instances of that class. Objects have properties (data members) and methods (functions). A class can have constructors, which are special methods used to initialize an object when it is created. Properties and methods of objects can be accessed using the object’s reference.

				
					public class MyClass {
    String name;
    int age;

    public MyClass(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public void introduce() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }
}

// Creating an object
MyClass obj = new MyClass("John Doe", 30);

// Accessing object properties and methods
System.out.println(obj.name);
obj.introduce();
				
			
  1. Inheritance:

Inheritance is a mechanism in object-oriented programming that allows a class to inherit properties and methods from a parent class (also known as a superclass). The class that inherits from the parent class is called a child class (or subclass). Inheritance promotes reusability and helps create a more organized and modular code structure.

				
					public class ParentClass {
    // Code
}

public class ChildClass extends ParentClass {
    // Code
}
				
			
  1. Interfaces:
				
					interface AnotherInterface {
    void anotherMethod();
}

public class MyClass implements MyInterface, AnotherInterface {
    @Override
    public void myMethod() {
        // Code
    }

    @Override
    public void anotherMethod() {
        // Code
    }
}
				
			
    1. Error Handling:
				
					  // Code that might throw an exception
} catch (Exception e) {
  // Handle the exception
  System.out.println("Error: " + e.getMessage());
} finally {
  // Code that always executes, regardless of an exception
}
				
			
  1. Collections Framework:
				
					import java.util.ArrayList;
import java.util.HashMap;

// ArrayList
ArrayList<String> myList = new ArrayList<>();
myList.add("apple");
myList.add("banana");
myList.remove(0);

// HashMap
HashMap<String, Integer> myMap = new HashMap<>();
myMap.put("apple", 5);
myMap.put("banana", 10);
int value = myMap.get("apple");

				
			
  1. File I/O:
				
					import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

try {
  File myFile = new File("file.txt");
  Scanner reader = new Scanner(myFile);

  while (reader.hasNextLine()) {
    String line = reader.nextLine();
    System.out.println(line);
  }

  reader.close();
} catch (FileNotFoundException e) {
  System.out.println("Error: " + e.getMessage());
}
				
			
  1. Lambda Expressions:
				
					import java.util.ArrayList;
import java.util.Collections;

ArrayList<Integer> myList = new ArrayList<>();
Collections.sort(myList, (a, b) -> a - b);
				
			
  1. Importing Classes and Packages:
				
					import java.util.ArrayList;
import java.time.LocalDate;
				
			
  1. Enumerations:
				
					public enum Days {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Days day = Days.MONDAY;
				
			
  1. Abstract Classes:
				
					public abstract class Animal {
    public abstract void makeSound();
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}
				
			
  1. Polymorphism:
				
					public class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

public class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Woof!");
    }
}

Animal myAnimal = new Dog();
myAnimal.makeSound(); // Output: "Woof!"
				
			
  1. Static Members:
				
					public class MyClass {
    public static int staticVar = 42;
    public int instanceVar = 10;
}

System.out.println(MyClass.staticVar); // Accessing static variable
MyClass obj = new MyClass();
System.out.println(obj.instanceVar); // Accessing instance variable
				
			
  1. Final Keyword:
				
					public final class MyFinalClass {
    // Code
}

public class MyClass {
    public final void myFinalMethod() {
        // Code
    }
}
				
			
  1. Generics:
				
					public class MyGenericClass<T> {
    private T item;

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

    public T getItem() {
        return item;
    }
}

MyGenericClass<String> myObj = new MyGenericClass<>();
myObj.setItem("Hello");
String value = myObj.getItem();
				
			
  1. Threads:
				
					class MyThread extends Thread {
    @Override
    public void run() {
        // Code
    }
}

MyThread myThread = new MyThread();
myThread.start();
				
			
  1. Streams:
				
					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> evenNumbers = numbers.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());

				
			
  1. DateTime API:
				
					import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.ZoneId;

LocalDate currentDate = LocalDate.now();
LocalTime currentTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("UTC"));
				
			
Social Share: