Core Java Cheat Sheet— A Quick Refresher

Natasha Ferguson
15 min readNov 8, 2022

--

In this post, I summarize the most commonly used Java language features and APIs. This is meant to be a quick run through for experienced developers that are going back to Java or picking up Java as their 2nd, 3rd language who understand the core concepts of programming.

Java is a popular programming language, created in 1995. It is owned by Oracle, and more than 3 billion devices run Java. Java is statically typed (you need to define the data type before variable name). It is used for Android apps, desktop applications, web applications, web servers and application servers, games, database connection and more.

Java Main Class Syntax

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

1. Printing

Use the println() method to print a line of text to the screen

There is also a print() method, which is similar to println(). The only difference is that it does not insert a new line at the end of the output.

2. Comments

Single-line comments start with two forward slashes (//). Any text between // and the end of the line is ignored by Java (will not be executed).

Multi-line comments start with /* and ends with */.

3. Variables

String — stores text, such as “Hello”. String values are surrounded by double quotes.

int — stores integers (whole numbers), without decimals, such as 123 or -123

float — stores floating point numbers, with decimals, such as 19.99 or -19.99

char — stores single characters, such as ‘a’ or ‘B’. Char values are surrounded by single quotes

boolean — stores values with two states: true or false

To create a variable, you specify the type and assign it a value:

type variableName = value;

Where type is one of Java’s types (such as int or String), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable. To create a variable that should store text, look at the following example:

String name = "Kira";

You can also declare a variable without assigning the value, and assign the value later:

int myNum;myNum = 15;

Here’s how to declare variables of other types:

int myNum = 5;float myFloatNum = 5.99f;char myLetter = 'D';boolean myBool = true;String myText = "Hello";

To declare more than one variable of the same type, you can use a comma-separated list:

int x = 5, y = 6, z = 50;

You can also assign the same value to multiple variables in one line:

int x, y, z;x = y = z = 50;

4. Data Types

There are 8 primitive data types in Java:

Non-Primitive Data Types

· Non-primitive data types are called reference types because they refer to objects.

· Primitive types are predefined (already defined) in Java.

· Non-primitive types are created by the programmer and is not defined by Java (except for String). Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.

· A primitive type starts with a lowercase letter, while non-primitive types starts with an uppercase letter.

· Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

5. Casting/converting

Type casting is when you assign a value of one primitive data type to another type.

Widening casting (converting a smaller type to a larger type size) is done automatically when passing a smaller size type to a larger size type:

int myInt = 3;double myDouble = myInt; // Automatic casting: int to double

Narrowing casting (converting a larger type to a smaller size type) must be done manually by placing the type in parentheses in front of the value:

double myDouble = 7.78d;int myInt = (int) myDouble; // Manual casting: double to int

6. String

The String data type is used to store a sequence of characters (text). A String in Java is actually a non-primitive data type, because it refers to an object. The String object has methods that are used to perform certain operations on strings.

Create a variable of type String and assign it a value:

String greeting = "Hello";

The + operator can be used between strings to concatenate them. You can also use the concat() method.

The backslash (\) escape character turns special characters into string characters.

The String class has a set of built-in methods that you can use on strings.

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

indexOf() Returns the position of the first found occurrence of specified characters in a string

length() Returns the length of a specified string

split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

toLowerCase() Converts a string to lower case letters

toUpperCase() Converts a string to upper case letters

For a complete reference of String methods, go to https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

7. Numbers

Primitive number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals. Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.

Floating point types represents numbers with a fractional part, containing one or more decimals. There are two types: float and double.

byte myNum1 = 10;
short myNum2 = 5000;
int myNum3 = 100000;
long myNum4 = 15000000000L;
float myNum5 = 5.75f;
double myNum6 = 19.99d;

A floating point number can also be a scientific number with an “e” to indicate the power of 10:

float f1 = 35e3f;
double d1 = 12E4d;

8. Operations

We use the + operator to add together two values. It can also be used to add together a variable and a value, or a variable and another variable.

Arithmetic operators:

Assignment operators:

we use the assignment operator (=) to assign the value 10 to a variable called x. The addition assignment operator (+=) adds a value to a variable.

int x = 10;int y = 15;y += 5;

Comparison Operators:

Logical Operators:

9. Math class

The Java Math class has many methods that allows you to perform mathematical tasks on numbers.

Math.max(x,y) method can be used to find the highest value of x and y.

Math.min(a,b) method can be used to find the lowest value of a and b.

Math.sqrt(z) method returns the square root of z.

Math.abs(p) method returns the absolute (positive) value of p.

Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive).

Math.max(1, 10);Math.min(30, 10);Math.sqrt(64);Math.abs(-4.5);int randomNum = (int)(Math.random() * 101);  // 0 to 100

Complete Math Reference: https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html

10. User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation.

In our example, we will use the nextInt() method, which is used to read an int value from the user:

import java.util.Scanner;public class Salary {  public static void main(String [] args) {    int wage;    Scanner scnr = new Scanner(System.in);    wage = scnr.nextInt();    System.out.print("Salary is ");    System.out.println(wage * 40 * 50);  }}

Scanner — Input Types

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

11. Array

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

Array declarations and accessing elements

To declare an array, define the variable type with square brackets:

e.g. int[] yearsArr = new int[4];

The array declaration uses [ ] symbols after the data type to indicate that the variable is an array reference.

We declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

You can access an array element by referring to the index number. Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

String[] fruits = {"apple", "kiwi", "mango", "orange"};System.out.println(fruits[0]);

To change the value of a specific element, refer to the index number:

fruits[0] = "banana";

Multidimensional Arrays

A multidimensional array is an array of arrays. To create a two-dimensional array, add each array within its own set of curly braces. myNumbers is an array with two arrays as its elements.

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. This example accesses the third element (2) in the second array (1) of myNumbers:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };int x = myNumbers[1][2];System.out.println(x); // Outputs 7

12. Dynamic arrays — ArrayList class

An array is a fixed size, homogeneous data structure. The limitation of arrays is that they’re fixed in size. It means that we must specify the number of elements while declaring the array. The ArrayList class is a resizable array, which can be found in the java.util package.

The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified (if you want to add or remove elements to/from an array, you have to create a new one). While elements can be added and removed from an ArrayList whenever you want. The syntax is also slightly different:

import java.util.ArrayList; // import the ArrayList classArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object

Basic Operations on ArrayList

The ArrayList class has many useful methods. For example, to add elements to the ArrayList, use the add() method:

import java.util.ArrayList;public class Main {  public static void main(String[] args) {    ArrayList<String> cars = new ArrayList<String>();    cars.add("Volvo");    cars.add("BMW");    cars.add("Ford");    cars.add("Mazda");    System.out.println(cars); }}

To access an element in the ArrayList, use the get() method and refer to the index number:

cars.get(0);

To modify an element, use the set() method and refer to the index number:

cars.set(0, "Opel");

To remove an element, use the remove() method and refer to the index number:

cars.remove(0);

Besides these basic methods, here are some more ArrayList methods that are commonly used:

size() Returns the length of the arraylist.

sort() Sort the arraylist elements.

clone() Creates a new arraylist with the same element, size, and capacity.

contains() Searches the arraylist for the specified element and returns a boolean result.

ensureCapacity() Specifies the total element the arraylist can contain.

isEmpty() Checks if the arraylist is empty.

indexOf() Searches a specified element in an arraylist and returns the index of the element.

13. Array methods

static int binarySearch(int[] a, int key)

Searches the specified array of ints for the specified value using the binary search algorithm. The array must be sorted before making this call.If it is not sorted, the results are undefined.

static int binarySearch(int[] a, int fromIndex, int toIndex, int key)

Searches between the range specified in the specified array for the given value using the binary search algorithm and returns the value.

static void sort(int[] a)

Sorts the specified array into ascending order. This is a serial sorting method and works well with small to large arrays.

static void parallelSort(int[] a)

Sorts the specified array into ascending order. This works well with array with very large number of elements.

copyOf(T[] original, int newLength)

Returns a new array which is a copy of the array specified and padded with 0s to obtain the specified length. newLength is the number of array elements to be copied.

copyOfRange(T[] original, int from, int to)

Returns a new array containing the specified range from the original array, truncated or padded with nulls to obtain the required length.

static compare(int[] arr1, int[] arr2)

This method compares two arrays passed as parameters lexicographically, which basically means that the sorting will happen in alphabetical order.

static String toString(<T>[] arr)

This method returns a String representation of the contents of arr. Individual elements in string representation will be separated by comma operator.

More Array class methods can be found at https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

14. Methods/Functions

A method must be declared within a class. It is defined with the name of the method, followed by parentheses.

public class Main {  static void myMethod() {    // code to be executed  }}

static means that the method belongs to the Main class and not an object of the Main class.

void means that this method does not have a return value.

To call a method in Java, write the method’s name followed by two parentheses () and a semicolon ;

Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma.

The void keyword, used in the examples above, indicates that the method should not return a value. If you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead of void, and use the return keyword inside the method:

public class Main {  static int myMethod(int x, int y) {    return x + y;  }  public static void main(String[] args) {    System.out.println(myMethod(5, 3));  }}// Outputs 8

15. If-elseif-else branches and switch statements

Use the if statement to specify a block of Java code to be executed if a condition is true.

Use the else if statement to specify a new condition if the first condition is false.

Use the else statement to specify a block of code to be executed if the condition is false.

import java.util.Scanner;public class EvenOdd {  public static void main (String[] args) {    Scanner scnr = new Scanner(System.in);    int userNum;    int divRemainder;
System.out.print("Enter a number: "); userNum = scnr.nextInt(); divRemainder = userNum % 2; if (divRemainder == 0) { System.out.println(userNum + " is even."); } else { System.out.println(userNum + " is odd."); } }}

Multi-branch if-else statement

if (expression1) {// Statements that execute when expression1 is true// (first branch)}else if (expression2) {// Statements that execute when expression1 is false and expression2 is true// (second branch)}else {// Statements that execute when expression1 is false and expression2 is false// (third branch)}

Multi-branch if-else example:

import java.util.Scanner;public class MultIfElseAnniv {  public static void main(String[] args) {    Scanner scnr = new Scanner(System.in);    int numYears;
System.out.print("Enter number years married: "); numYears = scnr.nextInt(); if (numYears == 1) { System.out.println("Your first year -- great!"); } else if (numYears == 10) { System.out.println("A whole decade -- impressive."); } else if (numYears == 25) { System.out.println("Your silver anniversary -- enjoy."); } else if (numYears == 50) { System.out.println("Your golden anniversary -- amazing."); } else { System.out.println("Nothing special."); } }
}

Short Hand If…Else

There is also a short-hand if else, which is known as the ternary operator because it consists of three operands.

It can be used to replace multiple lines of code with a single line, and is most often used to replace simple if else statements:

Syntax

variable = (condition) ? expressionTrue : expressionFalse;

int age = 20;boolean isEighteenOrOver = age == 20 ? true : false;System.out.println("Age over or equal to 18: " + isEighteenOrOver);

Switch Statements

Instead of writing many if..else statements, you can use the switch statement. The switch statement selects one of many code blocks to be executed:

switch (expression) {  case constantExpr1:    // Statements    break;  case constantExpr2:    // Statements    break;  ...  default: // If no other case matches    // Statements    break;}

When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it’s time for a break. There is no need for more testing.

int day = 4;switch (day) {  case 6:    System.out.println("Today is Saturday");    break;  case 7:    System.out.println("Today is Sunday");    break;  default:    System.out.println("Looking forward to the Weekend");}// Outputs "Looking forward to the Weekend"

16. For / while / do while loops

while (expression) { // Loop expression  // Loop body: Executes if expression evaluated to true  // After body, execution jumps back to the "while"}// Statements that execute after the expression evaluates to falseint i = 0;while (i < 5) {  System.out.println(i);  i++;}

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Do not forget to increase the variable used in the condition, otherwise the loop will never end!

int i = 0;do {  System.out.println(i);  i++;}while (i < 5);

For Loop

When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:

for (initialExpression; conditionExpression; updateExpression) {  // Loop body}// Statements after the loopfor (int i = 0; i < 5; i++) {  System.out.println(i);}

Loop Over an Array

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};for (int i = 0; i < cars.length; i++) {  System.out.println(cars[i]);}

Loop Over a Two-Dimensional Array

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };for (int i = 0; i < myNumbers.length; ++i) {  for(int j = 0; j < myNumbers[i].length; ++j) {    System.out.println(myNumbers[i][j]);  }}

17. Exception catching — try catch block

When an error occurs, Java will throw an exception (throw an error). The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

try {

// Block of code to try

}

catch(Exception e) {

// Block of code to handle errors

}

18. Class

Java is an object-oriented programming language. Everything in Java is associated with classes and objects, along with its attributes and methods. The class construct defines a new type that can group data and methods to form an object. More on object-oriented programming concepts here.

To create a class, use the keyword class. Methods (functions) and attributes (fields/variables) are declared within a class, and that they are used to perform certain actions.

// Info about a restaurant
public
class Restaurant {
// Internal fields
...

// Sets the restaurant's name
public void setName(String restaurantName) {
...
}
// Sets the rating (1-5, with 5 best)
public void setRating(int userRating) {
...
}
// Prints name and rating on one line
public void print() {
...
}
}

To create one or more objects of Restaurtant, specify the class name, followed by the object name, and use the keyword new. The “new” operator allocates a new object in the heap, runs a constructor to initialize it, and returns a pointer to it.

Restaurant favLunchPlace = new Restaurant();Restaurant favDinnerPlace = new Restaurant();

To call a method, write the method’s name followed by two parentheses () and a semicolon;

favLunchPlace.setName(“Central Deli”);
favLunchPlace.setRating(4);
favDinnerPlace.setName(“Friends Cafe”);
favDinnerPlace.setRating(5);
System.out.println(“My favorite restaurants: “);
favLunchPlace.print();
favDinnerPlace.print();

You will often see Java programs that have either static or public attributes and methods.

Access Modifiers:

For classes, public declared items can be accessed everywhere (by any other class).

For attributes, methods and constructors:

Public modifier: the code is accessible for all classes

Private modifier: the code is only accessible within the declared class

Non-Access Modifiers:

Abstract modifier with classes: The class cannot be used to create objects. To access an abstract class, it must be inherited from another class.

For attributes and methods, you can use the one of the following:

Final modifier: Attributes and methods cannot be overridden/modified

Static modifier: Attributes and methods belongs to the class, rather than an object. A static method means that it can be accessed without creating an object of the class, unlike public.

Constructor

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes. A constructor that can be called without any arguments is called a default constructor.

Constructors are similar to methods, but they cannot be called at will. Instead, they are run automatically by the JVM when a new object is created.

public class Restaurant {  private String name;  private int rating;  public Restaurant() {  // Default constructor    name = "NoName";    // Default name: NoName indicates name was not  set    rating = -1;        // Default rating: -1 indicates rating was not set  }  public void setName(String restaurantName) {    name = restaurantName;  }  public void setRating(int userRating) {    rating = userRating;  }  public void print() {    System.out.println(name + " -- " + rating);  }}

Learn about essential object-oriented concepts such as Encapsulation, Inheritance, Polymorphism and Abstraction here.

Sources:

Java documentation

GeeksForGeeks

JavaTpoint

W3Schools

Programiz

--

--