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
-
Java uses
camelCase
for most variables and methods -
Java uses
PascalCase
for class and interface names -
For constants, use all
UPPER_CASE_SNAKE_CASE
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 String
s 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 public
, private
, 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()
Print Statements
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
-
int:
int
s store whole number values between-2147483648
and2147483647
. -
double:
double
s store decimal number values between4.9E-324
and1.7976931348623157E+308
: -
boolean:
boolean
s storetrue
orfalse
values: -
char:
char
s store single character values: -
String:
String greetings = "Greetings, earthlings!";
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!");
}
-
A
public
method can be accessed by any part of a program, including other classes. -
A
static
method can be called throughout a program without creating an object of the class. -
A
void
method does not return a value.
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
-
.length()
: The.length()
method returns the length, or total number of characters, of theString
it’s called on: -
.concat()
: The.concat()
method concatenates oneString
to the end of anotherString
. Concatenation is the operation of joining two strings together: -
.equals()
:With objects likeString
s, we can’t use the primitive equality, instead we use.equals()
-
.indexOf()
: If we want to know the index of the first occurrence of a character in a string, we can use the.indexOf()
method on a string. Remember that the indices in Java start with0
: -
.charAt()
: The.charAt()
method returns the character located at theString
‘s specified index: -
.substring()
-
.toUpperCase()
/.toLowerCase()
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
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;
}
}