Ultimate Java Cheatsheet 2023

Hello and welcome to our ultimate Java cheatsheet! Whether you're a beginner just starting out with the language or an experienced developer looking for a quick reference, this cheatsheet has something for you. We've compiled a comprehensive list of the most important concepts and features in Java, along with examples and explanations to help you get up to speed quickly. From classes and objects to streams and modules, this cheat sheet covers it all. So grab a cup of coffee and get ready to dive into the world of Java!



Basic Syntax

Comments

// This is a single-line comment

/*
This is a multi-line comment.
*/

Variables

In Java, you must declare variables before using them. The basic syntax for declaring a variable is:

<type> <name>;

For example:

int age;
double salary;
String name;
boolean isEmployed;

You can also assign a value to a variable when you declare it:

int age = 35;
double salary = 75000.00;
String name = "John Smith";
boolean isEmployed = true;

Data Types

Java has a wide range of built-in data types, including:

  • int: a 32-bit signed integer
  • long: a 64-bit signed integer
  • float: a 32-bit floating-point number
  • double: a 64-bit floating-point number
  • char: a 16-bit Unicode character
  • boolean: a true/false value
  • byte: a 8-bit signed integer
  • short: a 16-bit signed integer

Operators

Java has the following operators:

  • Arithmetic operators: +, -, *, /, % (modulus)
  • Comparison operators: == (equal to), != (not equal to), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)
  • Logical operators: && (and), || (or), ! (not)
  • Assignment operators: =, +=, -=, *=, /=, %=

Control Structures

Java has the following control structures:

If-Else Statement

if (condition) {
  // code to be executed if condition is true
} else {
  // code to be executed if condition is false
}

For Loop

for (int i = 0; i < 10; i++) {
  // code to be executed
}

While Loop

while (condition) {
  // code to be executed
}

Do-While Loop

do {
  // code to be executed
} while (condition);

Switch Statement

switch (expression) {
  case value1:
    // code to be executed if expression equals value1
    break;
  case value2:
    // code to be executed if expression equals value2
    break;
  default:
    // code to be executed if expression does not match any case
}

Arrays

An array is a collection of variables of the same data type. To declare an array in Java, use the following syntax:

<type>[] <name> = new <type>[size];

For Example:

int[] numbers = new int[5];
String[] names = new String[3];

You can also use the following syntax to declare an array:

<type>[] <name> = {<elements>};

For Example:

int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"John", "Jane", "Bob"};

Accessing Array Elements

To access an element of an array, you can use the following syntax:

<name>[index]

For Example:

int first = numbers[0];
String second = names[1];

Modifying Array Elements

To modify an element of an array, you can use the following syntax:

<name>[index] = <value>;

For Example:

numbers[2] = 10;
names[0] = "Mike";

Array Length

To get the length of an array, you can use the length field:

int size = numbers.length;

Iterating Over Arrays

To iterate over an array, you can use a loop, such as a for loop:

for (int i = 0; i < numbers.length; i++) {
  int element = numbers[i];
  // code to process element
}

You can also use the for-each loop:

for (int element : numbers) {
  // code to process element
}

Classes and Objects

A class is a blueprint for creating objects. It defines the data and behavior of a type. To create a class in Java, use the following syntax:

public class <name> {
  // class body
}

To create an object from a class, use the new keyword:

Person person = new Person();

Methods

A method is a block of code that performs a specific task. To define a method in Java, use the following syntax:

<access modifier> <return type> <name>(<parameters>) {
  // method body
}

For Example:

public void printHello() {
  System.out.println("Hello!");
}

Constructors

A constructor is a special type of method that is called when an object is created. To define a constructor in Java, use the following syntax:

<name>(<parameters>) {
  // constructor body
}

For Example:

public Person(String name) {
  this.name = name;
}

Inheritance

Inheritance is a way to create a new class that is a modified version of an existing class. The new class is called the subclass, and the existing class is the superclass. To create a subclass in Java, use the extends keyword:

public class Subclass extends Superclass {
  // subclass body
}

Interfaces

An interface is a set of related methods with empty bodies. It is used to specify the behavior of a class. To create an interface in Java, use the interface keyword:

public interface MyInterface {
  // interface methods
}

To implement an interface in a class, use the implements keyword:

public class MyClass implements MyInterface {
  // class body
}

Packages

A package is a namespace that organizes a set of related classes. To create a package in Java, use the package keyword followed by the package name:

package com.example;

To import a class from a package, use the import keyword followed by the fully qualified class name:

import com.example.MyClass;

Exceptions

An exception is an abnormal condition that occurs during the execution of a program. Java has a built-in exception handling mechanism to handle exceptions. To handle an exception, you can use a try-catch block:

try {
  // code that may throw an exception
} catch (<exception type> e) {
  // code to handle the exception
}

You can also throw an exception manually using the throw keyword:

if (age < 0) {
  throw new IllegalArgumentException("Age cannot be negative");
}

Input and Output

To read input from the console, you can use the Scanner class:

Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();

To write output to the console, you can use the System.out.println() method:

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

Files

To read and write files in Java, you can use the File and FileWriter classes:

File file = new File("filename.txt");
FileWriter writer = new FileWriter(file);
writer.write("Hello, World!");
writer.close();

To read from a file, you can use the FileReader class:

File file = new File("filename.txt");
FileReader reader = new FileReader(file);
int character;
while ((character = reader.read()) != -1) {
  System.out.print((char) character);
}
reader.close();

Multithreading

Multithreading is the ability of a central processing unit (CPU) (or a single core in a multi-core processor) to provide multiple threads of execution concurrently, supported by the operating system. To create a thread in Java, you can extend the Thread class or implement the Runnable interface:

public class MyThread extends Thread {
  @Override
  public void run() {
    // code to be executed by the thread
  }
}
public class MyRunnable implements Runnable {
  @Override
  public void run() {
    // code to be executed by the thread
  }
}

To start a thread, call the start() method:

Thread thread = new MyThread();
thread.start();
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();

Collections

Java has a built-in framework for working with collections called java.util. Some of the most commonly used classes in this framework are:

  • ArrayList: a resizable array
  • LinkedList: a doubly-linked list
  • HashSet: a set implemented using a hash table
  • TreeSet: a set implemented using a tree
  • HashMap: a map implemented using a hash table
  • TreeMap: a map implemented using a tree

Generics

Generics allow you to create classes, interfaces, and methods that can work with multiple data types. To use generics, you can use the <T> notation:

public class MyClass<T> {
  private T value;

  public MyClass(T value) {
    this.value = value;
  }

  public T getValue() {
    return value;
  }
}

You can also specify multiple data types using the <T, U> notation:

public class MyClass<T, U> {
  private T firstValue;
  private U secondValue;
  public MyClass(T firstValue, U secondValue) {
    this.firstValue = firstValue;
    this.secondValue = secondValue;
  }

  public T getFirstValue() {
    return firstValue;
  }

  public U getSecondValue() {
    return secondValue;
  }
}

Annotation

Annotations are a way to provide metadata about a program. They can be used for a variety of purposes, such as code generation, runtime processing, and code optimization. To create an annotation in Java, use the @interface keyword:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
  int value() default 0;
}

To use an annotation, you can use the @ symbol followed by the annotation name:

@MyAnnotation(value = 10)
public void myMethod() {
  // method body
}

Lambda Expressions

Lambda expressions are a way to create anonymous functions in Java. They allow you to create simple functions without the need to define a new class. To create a lambda expression in Java, use the following syntax:

(<parameters>) -> {
  // code to be executed
}

For Example:

(int x, int y) -> x + y

Streams

Streams are a way to process data in a declarative way. They allow you to perform operations on a sequence of elements, such as filtering, mapping, and reducing. To create a stream in Java, you can use the stream() method of a collection:

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

You can then perform operations on the stream using methods such as filter(), map(), and reduce():

Stream<Integer> evenNumbers = stream.filter(x -> x % 2 == 0);
Stream<String> strings = evenNumbers.map(x -> "Number: " + x);
int sum = evenNumbers.reduce(0, (x, y) -> x + y);

Optional

Optional is a container object used to represent the absence of a value. It can be used as an alternative to null to prevent NullPointerExceptions. To create an Optional object in Java, you can use the of() or ofNullable() methods:

Optional<String> optional = Optional.of("value");
Optional<String> optional = Optional.ofNullable(null);

You can then use methods such as isPresent(), get(), and orElse() to work with the value:

if (optional.isPresent()) {
  String value = optional.get();
}

String value = optional.orElse("default");

Modules

Modules are a way to structure and package code in Java 9 and later. To create a module in Java, you can use the `module-info.

To create a module in Java, you can use the module-info.java file:

module com.example {
  requires java.base;
  exports com.example.api;
  provides com.example.api.Service with com.example.impl.ServiceImpl;
}

To use a module in your code, you can use the requires keyword to import other modules, the exports keyword to make packages available to other modules, and the provides keyword to specify implementations for a service.

Reactive Streams

Reactive Streams is a Java library for building reactive systems. It allows you to build asynchronous, non-blocking, and event-driven applications. To use Reactive Streams in Java, you can use the Publisher, Subscriber, Subscription, and Processor interfaces:

Publisher<String> publisher = new Publisher<String>() {
  @Override
  public void subscribe(Subscriber<? super String> subscriber) {
    // code to publish data to the subscriber
  }
};

Subscriber<String> subscriber = new Subscriber<String>() {
  @Override
  public void onSubscribe(Subscription subscription) {
    // code to handle subscription
  }

  @Override
  public void onNext(String data) {
    // code to handle incoming data
  }

  @Override
  public void onError(Throwable error) {
    // code to handle error
  }

  @Override
  public void onComplete() {
    // code to handle completion
  }
};

publisher.subscribe(subscriber);


I hope this Java cheatsheet was helpful!

AJ Blogs

Hello everyone, My name Arth and I like to write about what I learn. Follow My Website - https://sites.google.com/view/aj-blogs/home

Post a Comment

Previous Post Next Post
Best Programming Books

Facebook

AJ Facebook
Checkout Our Facebook Page
AJ Blogs
Checkout Our Instagram Page