Java for Beginners Course Level Coding Cheat Sheet
Java for Beginners Course Level Coding Cheat Sheet
You can expand the hamburger menu in the upper left corner of this window to locate code by video name.
System.out.println("Hello, World!")
A Java
statement used
to print text or
other data to
the standard
output,
typically the
console.
These /* This is a multi-line comment It can be used to explain a block of code or provide detailed information
comments
start with /*
about:blank 1/50
4/14/25, 9:26 AM about:blank
/*
This method calculates the square of a number.
The @param number The number to be squared
documentation @return The square of the input number
comments */
public int square(int number) {
start with /* return number * number;
and ends with }
*/ . These
comments are
used for
generating
documentation
using tools
like Javadoc.
Creating a package
To create a package, use the package keyword at the top of your Java source
file.
The folder structure on your filesystem should match the package declaration. For instance, if your /src
package is com.example.myapp, your source file should be located in the following path example. └── com
└── example
└──>└──>
└──>└── └──>myapp
└──>└── └──>└── MyClass.java
about:blank 2/50
4/14/25, 9:26 AM about:blank
package com.example.library;
public class Library
{
private List <Book> books; // Private attribute to hold books
public Library()
{
books = new ArrayList<>(); // Initialize the list in the constructor
}
In Java, a class is a blueprint for creating objects and }public void addBook(Book book) {
can contain methods (functions) that define behaviors. books.add(book); // Method to add a book to the library
For instance, the second line of this code displays the } <br }
public class library, with methods like
calculatePrice() or applyDiscount().
Creating methods
package com.example.library;
about:blank 3/50
4/14/25, 9:26 AM about:blank
Using imports
import java.util.List;
Use the byte data type when you need to save memory in large
arrays where the memory savings are critical, and the values are
between -128 and 127.
Use the short small integers data type for numbers from −32,768 to
32,767.
about:blank 4/50
4/14/25, 9:26 AM about:blank
Use the int integer data type to store whole numbers larger than
what byte and short can hold. This is the most commonly used
integer type.
Use the long data type when you need to store very large integer
values that exceed the range of int.
Use the float when you need to store decimal numbers but do not
require high precision (for example, up to 7 decimal places).
Use the double data type when you need to store decimal numbers
and require high precision (up to 15 decimal places).
Use the char data type when you need to store a single character
such as a single letter or an initial.
about:blank 5/50
4/14/25, 9:26 AM about:blank
class Car {
String color;
int year;
void displayInfo() {
System.out.println("Color: " + color + ", Year: " + year);
}
}
The reference data type class is like a blueprint for creating
objects. You can see the class identified in the first line of
code.
about:blank 6/50
4/14/25, 9:26 AM about:blank
enum DaysOfWeek {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}
Description Example
about:blank 7/50
4/14/25, 9:26 AM about:blank
Description Example
Relational operators
You use relational operators to compare two values. These operators return a boolean result (true or false).
Description Example
The greater than equal symbols >= compares System.out.println("Is a greater than or equal to b? " + (a >= b)); // true
the values to check for a greater than or equal
to result.
about:blank 8/50
4/14/25, 9:26 AM about:blank
Description Example
Logical operators
You can use logical operators to combine boolean expressions. The following code examples use boolean x = true; and boolean y = false;.
Description Example
The double ampersands && combines two boolean expressions (both must be true).
The double vertical bar symbols || used with boolean values always evaluates both expressions,
even if the first one is true.
The single exclamation point symbol ! operator in Java is the logical NOT operator. This operator
is used to negate a boolean expression, meaning it reverses the truth value.
Description Example
about:blank 9/50
4/14/25, 9:26 AM about:blank
Description Example
a += 5
The plus sign and equal symbols combined += adds and assigns values to variables
a -= 2
The minus sign and equal symbols combined -= subtracts values to variables
a *= 3
The asterisk sign and equal symbols combined *= multipies and assigns values to variables
a /= 2
The forward slash sign and equal symbols combined /= divides and assigns values to variables
a %= 4
The percentage and equal symbols combined %= take the modulus (percentage) and assigns values to the variables
Unary operators
A unary operation is a mathematical or programming operation that uses only one operand or input. Developers use unary operations to
manipulate data and perform calculations. You would use the following assignment operators to assign values to variables.
Description Example
Use the plus symbol to indicate a positive value. int positive = +a;
about:blank 10/50
4/14/25, 9:26 AM about:blank
Description Example
int a = 10;
System.out.println("Unary plus: " + (+a)); // 10
Ternary operators
Ternary operators are a shorthand form of the conditional statement. They can use three operands.
Description Example
int a = 10;
int b = 20;
int max = (a > b) ? a : b; // If a is greater than b, assign a; otherwise assign b
System.out.println("Maximum value is: " + max); // 20
Description Example
int[] numbers;
To declare an array in Java, you use the following syntax: dataType[] arrayName;. The following doce displays the
data type of int and creates an array named numbers.
Initializing an array
After you declare an array, you need to initialize the array to allocate memory for it.
about:blank 11/50
4/14/25, 9:26 AM about:blank
Description Example
These code samples display three methods used to create an array of 5 integers. You can
initialize an array using the new keyword. You can also declare and initialize an array in a single
line. Alternatively, you can create an array and directly assign values using curly braces.
Accessing an array
You can access individual elements in an array by specifying the index inside square brackets.
Description Example
System.out.println(numbers[0]);System.out.println(numbers[0]); // Outputs: 1
about:blank 12/50
4/14/25, 9:26 AM about:blank
Description Example
Description Example
Description Example
You can use a for loop for to iterarate through and array. Here's an example that
prints all elements in the numbers array. The for loop includes this code for (int i
= 0 in the following code snippet.
You can also use the enhanced for loop, known as the "for-each" loop. The enhanced for each for (int number : numbers) {
loop code include this portion, for (int of the following code snippet. System.out.println(number);
}
about:blank 13/50
4/14/25, 9:26 AM about:blank
Description Example
Description Example
int[][] matrix = {
{1,{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Here's how to declare and initialize a 2D array. You will declare the integer
data type and create the matrix array.
System.out.println(matrix[0][1]); // Outputs: 2
Description Example
about:blank 14/50
4/14/25, 9:26 AM about:blank
Description Example
A Java class named Main with a main method. The main method is the
entry point of the program.
if (number > 5) {
System.out.println("The number is greater than 5.");
}
}
}
Closing curly braces to end the main method and class definition.
Explanation: Since number is 10, which is greater than 5, the condition evaluates to true, and the program prints "The number is greater than
5.".
if-else statement
The if-else statement gives an alternative if the condition is false.
about:blank 15/50
4/14/25, 9:26 AM about:blank
Description Example
A Java class named Main with a main method. The main method
is the entry point of the program.
int number = 3;
if (number > 5) {
System.out.println("The number is greater than 5.");
}
else {
System.out.println("The number is not greater than 5.");
}
}
}
Closing curly braces to end the main method and class definition.
about:blank 16/50
4/14/25, 9:26 AM about:blank
else if statement
You can check multiple conditions using else if.
Description Example
A Java class named Main with a main method. The main method is the
entry point of the program.
int number = 5;
if (number > 5) {
System.out.println("The number is greater than 5.");
}
else if (number == 5) {
System.out.println("The number is equal to 5.");
}
The else block executes when none of the above conditions are met, else {
printing "The number is less than 5.". System.out.println("The number is less than 5.");
}
about:blank 17/50
4/14/25, 9:26 AM about:blank
Description Example
}
}
Closing curly braces to end the main method and class definition.
Explanation: Since number is exactly 5, the program prints "The number is equal to 5.".
switch statement
A switch statement checks a single variable against multiple values.
Description Example
A Java class named Main with a main method. The main method is the entry point of the
program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
int day = 3;
A variable day of type int is declared and initialized with the value 3.
The switch statement checks the value of day and compares it against the case labels. switch (day) {
If day is 3, it prints "Wednesday". case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
about:blank 18/50
4/14/25, 9:26 AM about:blank
Description Example
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
}
}
}
Closing curly braces to end the main method and class definition.
Description Example
switch (color) {
case "red":
System.out.println("Color is red.");
break;
about:blank 19/50
4/14/25, 9:26 AM about:blank
Description Example
case "blue":
System.out.println("Color is blue.");
break;
default:
System.out.println("Unknown color.");
}
The default case prints "Unknown color." if color doesn't match "red" or "blue".
Description Example
A Java class named Main with a main method. The main method is the
entry point of the program.
A variable age of type int is declared and initialized with the value 20.
The if statement checks if age is greater than or equal to 18. If true, it if (age >= 18) {
prints "You are an adult.". System.out.println("You are an adult.");
}
about:blank 20/50
4/14/25, 9:26 AM about:blank
Description Example
else {
System.out.println("You are a minor.");
}
The else block executes if age is less than 18, printing "You are a
minor.".
}
}
Closing curly braces to end the main method and class definition.
about:blank 21/50
4/14/25, 9:26 AM about:blank
Description Example
A Java class named ForLoopExample with a main method. The main method is the entry
point of the program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
A for loop is initialized with int i = 1, which starts the counter at 1. The counter
variable i is incremented by i++ after each iteration.
System.out.println(i);
about:blank 22/50
4/14/25, 9:26 AM about:blank
Description Example
while Loop
The while loop is used when the number of iterations is not known in advance. It continues executing as long as the specified condition
remains true.
Description Example
A Java class named WhileLoopExample with a main method. The main method is the
entry point of the program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
int i = 1;
A variable i is initialized to 1.
while (i <= 5) {
System.out.println(i);
i++;
The main method and class are closed with curly braces. }
}
about:blank 23/50
4/14/25, 9:26 AM about:blank
Description Example
do-while Loop
The do-while loop is similar to the while loop but guarantees that the code block executes at least once before checking the condition.
Description Example
A Java class named DoWhileLoopExample with a main method. The main method is the
entry point of the program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
int i = 1;
A variable i is initialized to 1.
do {
The do-while loop starts and executes at least once before checking if i <= 5.
System.out.println(i);
i++;
about:blank 24/50
4/14/25, 9:26 AM about:blank
Description Example
}
}
The main method and class are closed with curly braces.
Nested loops
You can also use loops inside other loops, known as nested loops. This is useful for working with multi-dimensional data structures, like arrays
or matrices.
Description Example
A Java class named NestedLoopsExample with a main method. The main method is the
entry point of the program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
The inner loop controls the columns, also running 10 times for each row. for (int j = 1; j <= 10; j++) {
about:blank 25/50
4/14/25, 9:26 AM about:blank
Description Example
System.out.print(i * j + "\t");
System.out.println();
}
}
The main method and class are closed with curly braces.
break statement
The break statement is used to terminate a loop immediately, regardless of the loop's condition. This can be useful when you want to exit a loop
based on a specific condition that may occur during its execution.
Description Example
A Java class named BreakExample with a main method. The main method is the entry
point of the program.
The main method is declared using public static void main(String[] args). This
method is required for execution in Java programs.
about:blank 26/50
4/14/25, 9:26 AM about:blank
Description Example
The loop iterates through the array, checking if any number is greater than 5.
if (num > 5) {
break;
When a number greater than 5 is found, the loop exits with the break statement.
}
}
The main method and class are closed with curly braces.
continue statement
The continue statement is used to skip the current iteration of a loop and move to the next iteration. It's useful when you want to skip certain
conditions but continue executing the rest of the loop.
Description Example
A Java class named ContinueExample with a main method. The main method is the entry
point of the program.
The main method is declared using public static void main(String[] args). This public static void main(String[] args) {
method is required for execution in Java programs.
about:blank 27/50
4/14/25, 9:26 AM about:blank
Description Example
if (i == 5) {
continue;
System.out.println(i);
}
}
The main method and class are closed with curly braces.
Using string literals: This means writing the string directly inside double quotes.
Description Example
about:blank 28/50
4/14/25, 9:26 AM about:blank
In this example, we created a string called greeting that contains "Hello, World!".
Using the new Keyword: This method involves using the new keyword to create a string object.
Description Example
Although this works, it's more common to use string literals because it's simpler.
String length
To find out how many characters are in a string, you can use the length() method. This method tells you the total number of characters in the
string.
Description Example
Here, we created a string called text and then checked its length. The output tells us that there are 16 characters in "Java Programming".
Accessing characters
If you want to look at individual characters in a string, you can use the charAt() method. This method allows you to get a character at a specific
position in the string.
about:blank 29/50
4/14/25, 9:26 AM about:blank
Description Example
In this example, we accessed the first character of the string "Java". Remember that counting starts at 0, so charAt(0) gives us 'J'.
Concatenating strings
Sometimes you might want to combine two or more strings together. You can do this easily using the + operator or the concat() method.
Description Example
Concatenate first and last names using the + operator. String fullName = firstName + " " + lastName;
about:blank 30/50
4/14/25, 9:26 AM about:blank
Description Example
Here, we combined firstName and lastName using the + operator and added a space between them.
Description Example
String comparison
When you want to check if two strings are the same, use the equals() method. This checks if both strings have identical content.
Description Example
about:blank 31/50
4/14/25, 9:26 AM about:blank
Description Example
In this example, isEqual returns true because both strings are "Hello". However, isNotEqual returns false since "Hello" and "World" are
different.
String immutability
One important thing to know about strings in Java is that they are immutable. This means that once a string is created, it cannot be changed. If
you try to change it, you will actually create a new string instead.
Description Example
about:blank 32/50
4/14/25, 9:26 AM about:blank
Description Example
In this case, we added "World" to original, but instead of changing the original string, we created a new string that combines both parts.
Finding substrings
You may want to get a smaller part of a string. You can do this using the substring() method, which allows you to specify where to start and
where to stop.
Description Example
about:blank 33/50
4/14/25, 9:26 AM about:blank
Description Example
In this example, we started at index 5 and went up to (but did not include) index 16 to extract "Programming".
String methods
Java has many built-in methods for strings that help you manipulate and process them. Here are some useful ones:
Description Example
Create a string.
Description Example
Create a string.
trim(): This method removes any extra spaces at the beginning or end of a string.
about:blank 34/50
4/14/25, 9:26 AM about:blank
Description Example
replace(): If you want to change all instances of one character or substring to another, use this method.
Description Example
Splitting strings
You can break a string into smaller pieces using the split() method. This is useful when you have data separated by commas or spaces.
Description Example
about:blank 35/50
4/14/25, 9:26 AM about:blank
Description Example
apple
banana
cherry
Output:
Joining strings
If you have an array of strings and want to combine them back into one single string, you can use the String.join() method.
Description Example
Join the strings with a separator. String joinedColors = String.join(", ", colors);
about:blank 36/50
4/14/25, 9:26 AM about:blank
Description Example
Description Example
package com.example.myapp;
In this example, com.example.myapp is the name of the package. It's common practice to use a reverse domain name as the package name to
ensure uniqueness.
Description Example
Description Example
about:blank 37/50
4/14/25, 9:26 AM about:blank
Description Example
To use this class in another Java file, you need to import it.
Importing classes
To import a specific class from a package, use the following syntax:
Description Example
import package_name.ClassName;
Description Example
import shapes.*;
This imports all classes in the shapes package, allowing you to use any class without needing to import them individually.
Description Example
Description Example
Description Example
Define a multiply method inside the Calculator class. public class Calculator
The multiply method takes two integers and returns their product. public int multiply(int x, int y) {
about:blank 39/50
4/14/25, 9:26 AM about:blank
Description Example
Define the main method, which is the program's entry point. public static void main(String[] args) {
Create an instance of the Calculator class in the main method. Calculator calc = new Calculator();
Call the multiply method with 4 and 5 and store the result. int product = calc.multiply(4, 5)
Print the result to the screen. System.out.println("The product is: " + product);
Description Example
Define a method with multiple parameters. public void greet(String name, int age) {
System.out.println("Hello " + name + ", you are " + age + " years old.");
}
about:blank 40/50
4/14/25, 9:26 AM about:blank
Description Example
Return values
Functions and methods can return values or perform actions without returning anything.
Description Example
Overloading methods
Java allows defining multiple methods with the same name but different parameters. This is known as method overloading.
Description Example
Define an overloaded method that takes an int. public void show(int number) {
about:blank 41/50
4/14/25, 9:26 AM about:blank
Description Example
about:blank 42/50
4/14/25, 9:26 AM about:blank
Description Example
display.show(10);
display.show("Hello World");
Scope of identifiers
The scope of an identifier refers to the part of the program where the identifier can be accessed.
Description Example
Local Scope: Identifiers are accessible only within the method or block.
Instance Scope: Variables are accessible by all methods in the class. private int x; // x is accessible by all methods
about:blank 43/50
4/14/25, 9:26 AM about:blank
Description Example
Static Scope: Static variables belong to the class and are accessible
throughout the class.
Void methods
A void method does not return a value.
Description Example
Description Example
An Introduction to Exceptions
Basic exception handling
Description Example
about:blank 44/50
4/14/25, 9:26 AM about:blank
Description Example
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} finally {
System.out.println("This block executes regardless of an exception.");
}
}
}
Description Example
Description Example
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code that will always execute
}
One important feature of Java is its exception handling mechanism, which includes the
try, catch, and finally blocks.
about:blank 45/50
4/14/25, 9:26 AM about:blank
Description Example
Description Example
about:blank 46/50
4/14/25, 9:26 AM about:blank
Description Example
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
System.out.println("Error closing connection: " + e.getMessage());
}
}
}
Description Example
about:blank 47/50
4/14/25, 9:26 AM about:blank
Description Example
// Not exiting or terminating the program here
}
// Assuming finally won't execute (this is wrong)
}
// The finally block should be here to ensure it executes.
}
Description Example
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Multiple try-catch
Description Example
about:blank 48/50
4/14/25, 9:26 AM about:blank
Throws keyword
Description Example
Description Example
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CheckedExceptionExample {
public static void main(String[] args) {
try {
File myFile = new File("nonexistentfile.txt");
Scanner myReader = new Scanner(myFile);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
Checked exceptions are exceptions checked at myReader.close();
} catch (FileNotFoundException e) {
compile time. They usually represent recoverable System.out.println("An error occurred: " + e.getMessage());
conditions, such as file not found or network issues. }
}
}
Runtime exceptions
about:blank 49/50
4/14/25, 9:26 AM about:blank
Description Example
Summary
In addition to viewing this resource here, you can select the printer icon located at the top of the screen to print this information or save this
information to a PDF file, based on your computer's capabilities. Also, return to the course itself to access the PDF file within the course for
direct downloading.
Author(s)
Ramanujam Srinivasan
Lavanya Thiruvali Sunderarajan
about:blank 50/50