Java Cheat Sheet

  • linkedin
  • facebook
  • twitter
  • mail

Java is so vast that even experienced programmers will find it difficult to remember everything. Use this cheat sheet to get a detailed picture of Java concepts like variables, data types, loops, operators, classes, objects, and more.

Java Cheat Sheet

In terms of concepts, Java is vast, so even experienced programmers will find it difficult to remember everything.

Fortunately, this cheat sheet gives you a detailed picture of Java concepts like variables, data types, loops, operators, classes, objects, error handling, and more.

You can use this Java cheat sheet as a reference to quickly look up Java syntax and refresh your memory.


Java Introduction

Java is a popular programming language for building various applications, including mobile and web applications, games, and scientific applications.

Java's syntax is verbose but readable. A basic Java program is structured inside the main method of a class.

Hello World Program in Java

Here's a simple Java code to print Hello World to the screen:

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello, World!");
  }
}

Output:

Hello, World!

To execute Java code like the one above, you can use an Online Java Compiler. Or you can install a Java IDE on your system and execute Java code locally.


Java Print Output

In Java, we can use the System.out.println() function to print output.

1. To print output in Java

public class Output1 {
  public static void main(String[] args) {
    // print text
    System.out.println("Hello, how are you?");

    // print numbers
    System.out.println(43);
  }
}

Output:

Hello, how are you?
43

2. Multiple arguments using + (string concatenation)

public class Output2 {
  public static void main(String[] args) {
    System.out.println("Hi Guys," + " Do you like high-fives?");
  }
}

Output:

Hi Guys, Do you like high-fives?

3. Printing on multiple lines with \n

public class Output3 {
  public static void main(String[] args) {
    System.out.println("Hi Guys,\nDo you like high-fives?");
  }
}

Output:

Hi Guys,
Do you like high-fives?

4. Printing the result of an expression

public class Output4 {
  public static void main(String[] args) {
    System.out.println(20 / 5);
  }
}

Output:

4

Data Types

Java has several primitive data types. Here are three basic ones you can use:

1. Integer (int): represents positive or negative whole numbers, such as 12, -6, 0, and 100.

public class DataTypeInt {
  public static void main(String[] args) {
    System.out.println(-6);
  }
}

Output:

-6

2. Floating point (float): represents real numbers, such as 3.14, -32.6, and 0.0.

public class DataTypeFloat {
  public static void main(String[] args) {
    float value = 12.4f;
    System.out.println(value);
  }
}

Output:

12.4

3. String (String): represents a sequence of characters, such as "Hello World" or "How are you?".

public class DataTypeString {
  public static void main(String[] args) {
    String message = "How are you?";
    System.out.println(message);
  }
}

Output:

How are you?

Variables

A variable is a named location in memory that stores a value. In Java, variables are used to store data. For example, in age = 5, age is the variable with a value of 5.

In Java, we need to determine the data type of a variable before we can declare it.

public class VariableDemo {
  public static void main(String[] args) {
    // declare a variable with an integer value
    int age = 25;

    // declare a variable with a float value
    float salary = 52978.84f;

    // declare a variable with a string value
    String name = "Smith";

    System.out.println(age);
    System.out.println(salary);
    System.out.println(name);
  }
}

Here are certain rules we need to follow while naming variables in Java:

  • Variable names in Java must begin with a letter, dollar sign ($), or underscore (_).
  • Subsequent characters can be letters, digits, dollar signs, or underscores.
  • Variable names are case-sensitive, so myVariable and myvariable are considered two different variables.
  • We cannot use reserved keywords like int and void as variable names.

There are also certain naming conventions in Java to name variables. These conventions aren't strict rules, but they make your code more readable:

  • Use descriptive variable names that reflect the purpose of a variable.
  • camelCase is commonly used for naming a variable, where the first word is lowercase and the following words are capitalized. For example, primeNumber.
  • snake_case, where words are separated by underscores (for example, prime_number), is less common in Java but still understandable.

Here's a table that shows a few legal and illegal variable names in Java:

Legal Variable Names Illegal Variable Names
firstname 1stname
user_id user-id
_temp (none – _temp is valid)
MAX_AGE (Max_Age is valid but breaks typical conventions)

Input

Java provides various methods for input and output through the java.util package. We need to import this package to take input from users.

import java.util.Scanner;

Here, Scanner is a class in the java.util package that can take numeric or string input from the user.

Example of using the Scanner class to read input from the console:

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner name = new Scanner(System.in);
    System.out.println("Enter username:");

    String userName = name.nextLine();
    System.out.println("Username is: " + userName);
  }
}

Comments

In Java, any text after // on a line is considered a single-line comment.

Java will not execute comments, but they help you explain your code.

public class Comments {
  public static void main(String[] args) {
    int marks = 80;  // initialize a variable
    char grade = 'A'; // initialize a second variable

    System.out.println(marks + grade);
  }
}

Output:

145

Operators

Java has three main types of operators to operate on variables:

  • Arithmetic operators: addition, subtraction, multiplication, division, remainder.
  • Comparison operators: compare two values and return a boolean result.
  • Logical operators: combine or invert boolean expressions.

Arithmetic Operators

Java supports the following arithmetic operators:

+ (addition)

class Add {
  public static void main(String[] args) {
    int a = 32;
    int b = 18;
    System.out.println(a + b);
  }
}

Output:

50

- (subtraction)

class Sub {
  public static void main(String[] args) {
    int a = 32;
    int b = 18;
    System.out.println(a - b);
  }
}

Output:

14

* (multiplication)

class Mul {
  public static void main(String[] args) {
    int a = 30;
    int b = 20;
    System.out.println(a * b);
  }
}

Output:

600

/ (division)

class Div {
  public static void main(String[] args) {
    int a = 30;
    int b = 2;
    System.out.println(a / b);
  }
}

Output:

15

% (remainder)

class Rem {
  public static void main(String[] args) {
    int a = 13;
    int b = 2;
    System.out.println(a % b);
  }
}

Output:

1

Operator Precedence

Operator precedence decides which operator is evaluated first.

In Java, *, /, and % have higher precedence than + and -. Parentheses can be used to override the default order.

class OpPre {
  public static void main(String[] args) {
    int result = 5 * 6 + 10 / 5;
    System.out.println(result);
  }
}

Output:

32

Here, 10 / 5 is executed first, then 5 * 6, and finally the results are added.


Assignment Operators

Java supports the following assignment operators:

class AssignmentDemo {
  public static void main(String[] args) {
    int number = 12;   // =

    number += 8;       // number = number + 8
    number -= 4;       // number = number - 4
    number *= 2;       // number = number * 2
    number /= 4;       // number = number / 4
    number %= 3;       // number = number % 3

    System.out.println(number);
  }
}

Comparison Operators

Java supports the following comparison operators:

class ComparisonDemo {
  public static void main(String[] args) {
    int a = 20;
    int b = 30;

    System.out.println(a == b);  // false
    System.out.println(a != b);  // true
    System.out.println(a < b);   // true
    System.out.println(a <= b);  // true
    System.out.println(a > b);   // false
    System.out.println(a >= b);  // false
  }
}

Logical Operators

Java supports the following logical operators:

  • && (logical AND)
  • || (logical OR)
  • ! (logical NOT)
class LogicalDemo {
  public static void main(String[] args) {
    int a = 30;
    int b = 20;
    int c = 10;

    boolean r1 = (a > b) && (a > c);  // true
    boolean r2 = (a > b) && (a < c);  // false
    boolean r3 = (a < b) || (a < c);  // false
    boolean r4 = (a > b) || (a < c);  // true
    boolean r5 = !(a < b);            // true
    boolean r6 = !(a > b);            // false

    System.out.println(r1);
    System.out.println(r2);
    System.out.println(r3);
    System.out.println(r4);
    System.out.println(r5);
    System.out.println(r6);
  }
}

Java Conditional Statements

Conditional statements are used to control the flow of a program.

  • if
  • if-else
  • switch

if Statement

class IfExample {
  public static void main(String[] args) {
    int x = 10;
    if (x > 5) {
      System.out.println("x is greater than 5");
    }
  }
}

Output:

x is greater than 5

if-else Statement

class IfElseExample {
  public static void main(String[] args) {
    int x = 10;
    if (x > 5) {
      System.out.println("x is greater than 5");
    } else {
      System.out.println("x is not greater than 5");
    }
  }
}

Switch Statement

The switch statement in Java is a control flow statement that allows you to execute a block of code among many alternatives.

switch (expression) {
  case value1:
    // execute code if expression == value1
    break;
  case value2:
    // execute code if expression == value2
    break;
  ...
  default:
    // execute code if the expression doesn't match any values
}

Example:

class SwitchExample {
  public static void main(String[] args) {
    int month = 3;
    switch (month) {
      case 1:
        System.out.println("January");
        break;
      case 2:
        System.out.println("February");
        break;
      case 3:
        System.out.println("March");
        break;
      default:
        System.out.println("Invalid month");
    }
  }
}

Output:

March

Loops

In Java, we can use the following loops:

  • for loop: executes a block of code a certain number of times.
  • while loop: executes a block of code while a condition is true.

for Loop

Syntax:

for (initialization; condition; iteration) {
  // code to be executed
}

Example:

class ForLoopExample {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      System.out.println(i);
    }
  }
}

Output:

0
1
2
3
4
5
6
7
8
9

while Loop

Syntax:

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

Example:

class WhileLoopExample {
  public static void main(String[] args) {
    int x = 0;
    while (x < 10) {
      System.out.println(x);
      x++;
    }
  }
}

Output:

0
1
2
3
4
5
6
7
8
9

Functions (Methods)

In Java, a function is called a method. A method is a block of code that performs a specific task and optionally returns a value.

Declaring a Method

Syntax

return_type method_name(parameter_list) {
  // method body
}

Example

class MathUtils {
  static int add(int x, int y) {
    return x + y;
  }
}

Calling a Method

class MethodCallExample {
  static int add(int x, int y) {
    return x + y;
  }

  public static void main(String[] args) {
    int sum = add(2, 3); // sum is now 5
    System.out.println(sum);
  }
}

Method Overloading

In Java, it is possible to have multiple methods with the same name as long as they have a different parameter list. This is called method overloading.

class OverloadExample {
  static int add(int x, int y) {
    return x + y;
  }

  static double add(double x, double y) {
    return x + y;
  }
}

“Default Arguments” in Java

Java does not support default argument values like some other languages. Instead, you typically use method overloading to simulate default values.

class DefaultArgExample {
  static int add(int x, int y) {
    return x + y;
  }

  static int add(int x, int y, int z) {
    return x + y + z;
  }

  public static void main(String[] args) {
    System.out.println(add(2, 3));       // uses 2-arg version
    System.out.println(add(2, 3, 0));    // explicitly passes 0 as "default"
  }
}

Classes and Objects

Object-Oriented Programming (OOP) is a programming paradigm where we organize our code into objects and classes.

A class defines the attributes and behavior of its objects.

Classes

General syntax:

class ClassName {
  // fields (attributes)
  // methods
}

Objects

An object is an instance of a class.

To create an object in Java, you use the new operator:

ClassName objectName = new ClassName();

Example

class Student {
  int id;
  String name;

  public static void main(String[] args) {
    Student s1 = new Student();  // an object of class Student
    System.out.println(s1.id);   // default: 0
    System.out.println(s1.name); // default: null
  }
}

Exception Handling

Try-Catch Blocks

To handle exceptions in Java, you can use a try-catch block.

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

Example

class TryCatchExample {
  public static void main(String[] args) {
    try {
      int result = 10 / 0;
      System.out.println(result);
    } catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero!");
    }
  }
}

Finally Block

You can use a finally block to specify code that will always execute, whether or not an exception is thrown.

try {
  // code that may throw an exception
} catch (ExceptionType e) {
  // code to handle the exception
} finally {
  // code that will always be executed
}

Example

class TryCatchFinallyExample {
  public static void main(String[] args) {
    try {
      int result = 10 / 0;
      System.out.println(result);
    } catch (ArithmeticException e) {
      System.out.println("Cannot divide by zero!");
    } finally {
      System.out.println("This message will always be printed.");
    }
  }
}

Throwing an Exception

In Java, you can throw an exception using the throw keyword.

if (someObject == null) {
  throw new NullPointerException("someObject is null");
}

Java Arrays

An array in Java is a collection of elements of the same data type.

Declaring and Initializing Arrays

int[] numbers;                // declares an array variable
numbers = new int[5];         // creates an array of size 5

int[] numbers2 = {1, 2, 3, 4, 5};  // initialize an array with values

Accessing Array Elements

Array indices start at 0.

// Get the first element in the array
int firstElement = numbers2[0];

// Get the second element in the array
int secondElement = numbers2[1];

// Get the last element in the array
int lastElement = numbers2[numbers2.length - 1];

Modifying Array Elements

numbers2[0] = 10;
numbers2[1] = 20;
numbers2[numbers2.length - 1] = 100;

Iterating Through an Array

for (int i = 0; i < numbers2.length; i++) {
  System.out.println(numbers2[i]);
}

Full Example

class ArraysExample {
  public static void main(String[] args) {
    int[] numbers = {1, 2, 3, 4, 5};

    System.out.println("The first element in the array is " + numbers[0]);
    System.out.println("The second element in the array is " + numbers[1]);
    System.out.println("The last element in the array is " + numbers[numbers.length - 1]);

    System.out.println("\nHere are the array elements:");
    for (int i = 0; i < numbers.length; i++) {
      System.out.println(numbers[i]);
    }

    numbers[0] = 10;
    numbers[1] = 20;

    System.out.println("\nThe new array elements are:");
    for (int i = 0; i < numbers.length; i++) {
      System.out.println(numbers[i]);
    }
  }
}

The code above defines a class named ArraysExample with a main method that declares an array of integers 1, 2, 3, 4, 5. It prints the first, second, and last elements, then iterates through the array, then modifies the first and second elements and prints the array again.