Java Cheat Sheet

Java Cheat Sheet

This document aims to provide a general overview of the Java basics.

General Program Structure

This is just the simple boilerplate of any Java program.
Let's say we have a file called Program.java:

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

Remember, after each operation in Java, it must end with a semicolon (;)

Variables

Variables are a way of string data values in your program. In Java, a variable is defined as such:

type varName = value;
  • type refers to the data type that the variable is
  • varName is the name of the variable, to refer to the variable later on in your program you use this name

There are also rules that govern what you can call your variable:

  • It must begin with a letter.
  • The name cannot be the same as words already used in Java (int, boolean, class, float, etc)

Variable names are case sensitive MyVar and myvar are 2 seperate variables.

Data Types

  • There are 8 primitive data types in Java: byte, char, short, int, long, float, double and boolean.
  • Data types like strings, arrays and classes build on top of these.

For the sake of brevity, we'll be focusing on int, string and arrays (classes will come up later on).

Strings

You can define a string variable like this:

String myStringVar = "Hello world";

Make sure you use double quotation marks!

Special Characters

  • If you want to define a string that contains double quotations marks, you will need to escape them first, otherwise the java compiler will misunderstand you
  • You will also need to escape backslashes you want to include as well, since Java will interpret a backslash as trying to escape the next character.
String illegalCharacterString = "This string contains \"double quotation marks\" and also \"backslashes: \\ \".";

String operations

Concatenation

There are a number of ways to concatenate strings in java. This is a simple way of doing it:

String str1 = "first part";
String str2 = "second part";
String str3 = str1 + str2;
  • You can also use a StringBuilder
  • String builders are an object built into Java
StringBuilder sb = new StringBuilder();

sb.append("This is");
sb.append(" a ");
sb.append(" long string.");

String completeString = sb.toString();
  • You can add a string onto an already existing variable like this:
String str1 = "I am going to finish this ";
str1 += "sentence.";
str1 += "sentence.";
// is shorthand for
str1 = str1 + "sentence.";

lower/upper case conversion

Use the .toUpperCase() and .toLowerCase() methods to convert a string to lower and upper case letters.

Example:

String lowerToUpper = "lower case string";
System.out.println(lowerToUpper.toUpperCase());

Split

  • To split a string by something, use the .split() method:
String spaces = "Split this string by every space";
String[] arrayOfWords = spaces.split(" ");

Integers

Mathematical Operations

Add

int addedNums = 4 + 4;

Subtract

int subtractedNums = 4 - 3;

Division

int test = 3/4
  • Test will be equal to 0 as we are computing integer division.

Exponentials

Before using the Math.pow() function, first make sure you have imported it to begin with.

import java.lang.Math;

Then,

System.out.println(Math.pow(2, 4)); // outputs:  16

Modulus

  • The modulus operator will return the quotient of the division (the remainder)
System.out.println(3 % 4); // outputs:  3

Arrays

We use arrays to store multiple items of a given type.
The general format for defining an array is

type[] arrayOfThing;
  • type can be a class, a boolean or a string.

Main info

If you wanted to have an array of strings, you would define it like this:

String[] arrayOfStrings = { "First String", "Second String", "Third String", "Fourth String" };
  • In Java, indexing starts at 0. This means that if you want to access the first element, you would use arrayOfStrings[0]. Subsequently, if you wanted to access the 3rd element, you would use arrayOfStrings[2].

Booleans

A boolean value can either be true or false.

boolean value = true;

Boolean Expressions

Boolean expressions can be useful to assess equality and compare numbers
The main operators are:

  • Or: |
  • And: &
  • Not: !
  • Equal to: ==,
  • Not equal to: !=
  • Less than: <
  • Less than or equal to: <=
  • Greater than: >
  • Greater than or equal to: >=

We can use these operators like so:

boolean condition1 = 3 > 4; // false
boolean condition2 = 3 >= 3; // true
boolean condition3 = 3 < 4; // true
boolean condition4 = (36 > 12) && (23 < 23); // false

Loops

While Loop

A while loop is used when the number of times to iterate is unknown.
The general syntax for a while loop is:

while (boolean_expression) {
    ...loop code
}

For Loop

For loops are used for a fixed number of iterations, for example, looping through an array.
The general syntax for a for loop is:

for (statement1; statement2; statement3; ){
    ...loop code
}
  • statement1 is only ran once, before the loop runs for the first time.
  • statement2 should be a condition for if the loop should iterate again.
  • statement3 is ran every time the loop iterates.

An example to loop through numbers 0 to 10:

for (int i = 0; i <= 10; i++) {
    System.out.println(i);
}

I/O

Keyboard Input

To read input from the keyboard, use a scanner object.
First, import this by adding this to the beginning of the file.

import java.util.scanner;

Then, declare an instance of the scanner in your class.

class YourProgram{
    // not always the right way to go about declaring a scanner but good enough for now
    public static Scanner kbdInput = new Scanner(System.in);
}

The scanner object has multiple methods that allow us to read in typed input (boolean, int, string etc).

String

System.out.println("number: ");
String name = kbdInput.nextLine();
  • kbdInput.next() also exists, however it is recommended to do your own reading as that will provide a better explanation.

Int

System.out.println("number: ");
String name = kbdInput.nextInt();
  • To learn more options for scanner input, look here.

Output

Throughout this document, you've probably seen the use of System.out.println, however other options also exist.

Standard Print: System.out.print()

System.out.print("Hello");
System.out.print(" World");

Outputs:

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

Outputs:

Hello
World

Formatted Print Statements: System.out.printf()

For more info about advanced use, click here.

  • .printf() allows you to include variables/values inside your print statement without having to create the string prior
  • It looks through the string argument for certain specifiers for different data types, then inserts the provided arguments into the location of the specifiers

Here are a couple of the specifiers

  • %c - char
  • %f - floats (to specify the number of decimal places you want use %.n where n is the number of decimal places)
  • %d - Integers
  • %s - String
  • %% - Use this for any percent sign's your formatted string might contain

Note: System.out.printf() does not include a new line characters, this means that any subsequent

Example:

System.out.printf(
                "Using printf you can format a print statement with floats:  %.2f, integers: %d, chars: %c, and strings: %s. As well as many more!\n",
                3.42342, 502, 'a', "example string");

Outputs:

Using printf you can format a print statement with floats:  3.42, integers: 502, chars: a, and strings: example string. As well as many more!

Reading from a file

  • This is code that will open a file, then output every line.
  • This code also includes a try catch statement, which is used so that the program does not crash if the file you are trying to read does not exist.
try {
    File file = new File('Filename.ext');
    Scanner file_reader = new Scanner(file);
    while (file_reader.hasNextLine()) {
        System.out.println(file_reader.nextLine());
        // here you can do some additional computation on the line string...
    }
    file_reader.close();
} catch (FileNotFoundException e) {
    System.out.println("file not found");
}

Methods

General syntax format for methods

public static returntype functionName(type parameterName, type parameterName, ...){
    return valueOfTheSameReturnType
}

Main Info

  • Methods, also known as functions, allow you to bundle any reused code/distinct sequence of instructions into a reusable code block.
  • In Java, a method must have an output type, and optionally, any number of typed parameters.
  • Methods don't have to return anything, if that is the case for your function the return type would be void

Here's some example code for a method that adds two number together and returns the result

public static int AddNumbers(int num1, int num2) {
    return num1 + num2
}

Classes

General Class Syntax

class ClassName {
    private type fieldName;

    public ClassName(type fieldNameInitialValue){
        this.fieldName = fieldNameInitialValue;
    }

    public type fieldNameGetter(){
        return fieldName;
    }

    public type fieldNameSetter(type NewFieldNameValue){
        this.fieldName = NewFieldNameValue;
    }

    public type otherFunction(type arg){
        ...random shite
    }
}

Main info

  • Classes are a useful tool that allows us to bundle up any methods/data that might relate to a specific entity in a system (e.g: a book in a library database, a student in a school database, etc.)
  • You can define, data fields such as age, height, shoe size extra, and also methods that process the data.

Constructors

  • The constructor is a special method that is used to initialise the class and all of its fields.
  • The Class name and the constructor must have matching names.
  • The Constructor must not have a return type.
  • It can have as many arguments as you want.

Private vs Public

  • If you looked at the general syntax for classes you'll notice that private and public appear in various places throughout the class.
  • A public property of a class will be able to be access from any class that initialises a new object of that class
  • A private property can only be accessed from within the class itself, its good practise to use private property for data fields in the class because otherwise anything outside of the class could change the value.

Getters/Setters

  • Getters and setters are good practise as they allow you to protect any update the value of the class property.

For example:

class Main {
    public static void main(String[] args) {

        SubClass newSub = new SubClass(32);
        System.out.println(newSub.test);

        newSub.test = 234;

        System.out.println(newSub.test);
    }
}

class SubClass {
    public int test;

    public SubClass(int newVal) {
        this.test = newVal;
    }
}

Outputs:

32
234
  • In this example, the value of the test property could be set to any string at any class in the code.
  • However if you use private getters and setters:
class Main {
    public static void main(String[] args) {

        SubClass newSub = new SubClass(32);

        /*
         * All of this now throws an error (because test is now a private property):
         * System.out.println(newSub.test);
         * newSub.test=234;
         * System.out.println(newSub.test);
         */

        System.out.println(newSub.getTest());
        newSub.setTest(234);
        System.out.println(newSub.getTest());
    }
}

class SubClass {
    private int test;

    public SubClass(int newVal) {
        this.test = newVal;
    }

    public int getTest() {
        return this.test;
    }

    public void setTest(int newTestValue) {
        if (newTestValue < 100) {
            this.test = newTestValue;
        }
    }
}

Outputs:

32
32

You can validate any new possible value for the test property.

Printing A Class

  • Usually, if you try and print a class in Java, the output would like something like this:
System.out.println(subClassObject);

This will output:

SubClass@7f416310
  • However, if you define a toString() method in the class, Java will now know how to print it.
class SubClass {
    public int test;

    public SubClass(int newVal) {
        this.test = newVal;
    }

    public String toString() {
        return String.format("%d", this.test);
    }
}

Now, anytime we try and print a instance of the class. It will print the value of test

Linked Lists

  • Here is some example code for a linked list:
class Main {
    public static void main(String[] args) {
        LinkedList myLinkedList = new LinkedList("Test");
        myLinkedList.addHead("Test2");
        myLinkedList.addHead("Test3");
        myLinkedList.printList();
        myLinkedList.removeHead();
        myLinkedList.printList();
    }
}

class LinkedList {
    private ListNode head = null;

    public LinkedList(String payload) {
        this.head = new ListNode(null, payload);
    }

    public void addHead(String payload) {
        this.head = new ListNode(this.head, payload);
    }

    public void removeHead() {
        this.head = this.head.getNext();
    }

    public void printList() {
        ListNode current = this.head;
        while (current != null) {
            System.out.println(current.getPayload());
            current = current.getNext();
        }
    }
}

class ListNode {
    private ListNode next;
    private String payload;

    public ListNode(ListNode head, String payload) {
        this.next = head;
        this.payload = payload;
    }

    public ListNode getNext() {
        return this.next;
    }

    public String getPayload() {
        return this.payload;
    }
}