Java Programming Language Cheatsheet

Process

Java code gets written in a .java file. When we run our program, the code gets compiled into bytecode which is a machine language that the JVM can understand. Bytecode gets sent to the JVM where it is analyzed and then executed as instructions. The JVM terminates once it executes the final instruction!

Java Style Guide

Naming Conventions

Brackets and Parenthesis

You can omit brackets for single line conditionals and loops but it's best practice to use them

Indentations and Spacing

All indentations should be two spaces, and you should indent each time you have a new block

You should use a space before and after keywords or operators (eg: x = 3)

Compiling from the Command Line

use javac filename.java to compile the file. If there are any bugs they will be flagged at this point and the .class file will not be created

Running Your Program

Use java filename (note, do not include the extension)

Main Method Parameters

Each Java class must have a main method, and every main method contains the parameters String[] args, but what does that mean?

args is an array of Strings that is passed to the program when it’s run.

For example, we can create a HelloWorld class to use elements from args:


public class HelloWorld {

  public static void main(String[] args) {

    System.out.println("Hello world, my name is " + args[0] + "!");

  }

}

Java Class Structure

Classes

Java classes can be publicprivate, or protected

They’re declared using one of those keywords, followed by class and the name of the class. The curly braces, { and }, mark the scope of the class. Everything inside the curly braces is part of the class.

Methods

Every Java program must have a method called main()

There are two common ways of printing in Java: System.out.print() and System.out.println().


System.out.print("I'm first!");

System.out.println("I'm second!");

System.out.print("I'm third!");

Comments

Inline comments are created with two forward slashes //comment


/* This is a multi-line code block that comments anything inside slash and asterisk

*/

Variables and Types

To declare a variable use dataType variableName = value; (you can declare a variable without assigning a value)

Data Types

Conditionals


if (expression) {

  // Code to run if expression is true

} else if (expression) {

  // Code to run if previous expression is false and current condition is true

} else if (expression) {

  // Code to run if previous expression is false and current condition is true

} else {

  // Code to run if all previous expressions are false

}

Loops

While


while (num < 20) {

  num = num + 1;

}

Do-While


do {

System.out.println("2 is equal to 4!");

} while (2 == 4);

// Prints: 2 is equal to 4!

For


for (int i = 0; i <= 10; i++) {

  System.out.println(i);

}

For Each

for-each loops, which are also referred to as enhanced loops, allow us to directly loop through each item in a list of items (like an array or ArrayList) and perform some action with each item.


for (String s : myArray) {

  // Do something

}

Methods


public static void exampleMethod() {

  System.out.println("Hello Method!");

}

Parameters

In order to pass information into a method, we need to add parameters to our method declaration. Parameters are placed inside the parentheses of the declaration and must state the data type as well as the parameter name.


public static void exampleMethod(String greeting, String name) {

  System.out.println(greeting + " " + name);

}

Common String Methods

Arrays


// Array of ints:

int[] lottoNumbers = {12, 29, 4, 38, 3};

// Array of Strings:

String[] clothingItems = {"Huipil", "Beanie", "Kimono", "Sari"};

Classes and constructors


  

public class Car {

  

  public static void main(String[] args) {

  

  }

  

}

  

Access Modifiers

Pasted image 20230103194759.png

Constructors

The constructor, Car(), shares the same name as the class:


  

public class Car {

  

  // Constructor method:

  

  public Car() {

  

    // Instructions for creating a Car instance

  

  }  

  

  public static void main(String[] args) {

  

  }

  

}

  

Defining State with Parameters

To create dynamic objects, parameters can be added to the class constructor. Instance variables can then be assigned the parameter values:


  

class Cat {

  

  // Instance fields:

  

  String noise;

  

  int numLives = 9;

  

  // Constructor takes in one String parameter

  

  public Cat(String animalNoise){

  

    // Assign instance variable to parameter value:

  

    noise = animalNoise;

  

  }

  

  public static void main(String[] args) {

  

    // Send argument to constructor when creating an object:

  

    Cat firstCat = new Cat("mew");

  

    // Send argument to constructor when creating another object:

  

    Cat secondCat = new Cat( "mow");

  

    System.out.println(firstCat.noise); // Prints: mew

  

    System.out.println(secondCat.noise); // Prints: mow

  

  }

  

}

  

This

To use the this keyword, prepend this followed by . to the instance variable:


  

class Cat {

  

  String noise;

  

  int numLives = 9;

  

  // Parameter has same name as the instance variable

  

  public Cat(String noise){

  

    // Assign instance variable to parameter value:

  

    this.noise = noise;

  

  }

  

}