In terms of concepts, Java is vast, so even experienced programmers will find it difficult to remember everything.
Fortunately, this cheat sheet gives you a detailed picture of Java concepts like variables, data types, loops, operators, classes, objects, error handling, and more.
You can use this Java cheat sheet as a reference to quickly look up Java syntax and refresh your memory.
Java Introduction
Java is a popular programming language for building various applications, including mobile and web applications, games, and scientific applications.
Java's syntax is lengthy but readable. A basic Java program is structured inside the main method of a class.
Hello World Program in Java
Here's a simple Java code to print "Hello World" to the screen:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
To execute Java code like the one above, you can use our Online Java Compiler. Or you can install a Java IDE on your system and execute Java code locally.
Java Print Output
In java, we can use the System.out.println()
function to print output.
1. To print output in Java, you can use the print()
function.
// print text
public class Output {
public static void main(String[] args) {
System.out.println("Hello, How are you!");
}
}
// Output: Hello, how are you?
// print numbers
public class Output {
public static void main(String[] args) {
System.out.println(43);
}
}
// Output: 43
2. You can pass multiple arguments to the System.out.println()
function, separated by the + operator.
public class Output {
public static void main(String[] args) {
System.out.println("Hi Guys," +" Do you like high-fives?");
}
}
// Output: Hi Guys, Do you like high-fives?
Here, arguments are printed on the same line.
3. To print text on multiple lines, you can use the newline character \n
.
public class Output {
public static void main(String[] args) {
System.out.println("Hi Guys,\n" +"Do you like high-fives?");
}
}
// Output:
// Hi Guys,
// Do you like high-fives?
4. To print the result of an expression, you can pass the expression as an argument to print()
.
public class Output {
public static void main(String[] args) {
System.out.println(20/5);
}
}
// Output: 4
Data Types
Java has three main primitive data types you can use:
1. Integer (int): represents positive or negative whole numbers, such as 12, -6, 0, and 100.
public class datatype{
public static void main(String[] args) {
System.out.println(-6);
}
}
//Output: -6
2. Floating point (float): represents real numbers, such as 3.14, -32.6, and 0.0.
public class datatype{
public static void main(String[] args) {
System.out.println(12.4);
}
}
//Output: 12.4
3. String (str): represents a sequence of characters, such as 'Hello World'
or "How are you?"
.
public class datatype{
public static void main(String[] args) {
System.out.println("How are you?");
}
}
//Output: How are you?
Variables
A variable is a named location in memory that stores a value. In Java, variables are used to store data. For example, in age = 5
, age is the variable with a value of 5.
In Java, we need to determine the data type of a variable before we can declare it.
// declare a variable with an integer value
int age = 25
// declare a variable with a float value
float salary = 52978.84
// declare a variable with a string value
string name = "Smith"
Here are certain rules we need to follow while naming variables in Java:
- Variable names in java must begin with a letter, dollar sign ($), or underscore (_). Subsequent characters can be letters, digits, dollar signs, or underscores.
- As variable names are case-sensitive, myVariable and myvariable are considered two different variables.
- We cannot use reserved keywords like "int" and "void" as variable names.
There are also certain naming conventions in Java to name variables. These conventions aren't strict rules, but they make your code more readable:
- We should always use descriptive variable names that reflect the purpose of a variable.
- camelCase is commonly used for naming a variable, which is simply a format where the first word is the small case, and the following word is capitalized. For example, primeNumber.
- It's also common to use snake_case, where words are separated by an underscore. For example, prime_number.
Here's a table that shows a few legal and illegal variable names in Java:
Legal Variable Names |
Illegal variable names |
firstname |
1stname |
user_id |
user-id |
_temp |
temp_ |
MAX_AGE |
Max_Age |
Input
Java provides various methods for input and output through java.util package. We need to import this package to take input from users. Here's the code to do it:
import java.util.Scanner;
Here, Scanner
is a class in java.util
package that can take numeric or string input from the user.
Given below is an example of how we can use the Scanner class to read input from the console:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner name = new Scanner(System.in);
System.out.println("Enter username");
String userName = name.nextLine();
System.out.println("Username is: " + userName);
}
}
Comments
In java, any text after a double slash //
is considered a comment.
Java code will not execute comments, but it can help you explain your code. So, commenting on your code is a good coding practice while working collaboratively.
Here's an example that shows comments in Java:
public class Comments {
public static void main(String[] args) {
int marks = 80; // initialize a variable
char grade = 'A'; // initialize a second variable
System.out.println(marks + grade);
}
}
// Output: 145
Operators
Java has three main types of operators to operate on variables:
- Arithmetic operators: for performing arithmetic operations such as addition, subtraction, multiplication, and division
- Comparison operators: for comparing two values and returning a boolean result
- Logical operators: for performing logical operations such as and, or, and not
Arithmetic operators
Java supports the following arithmetic operators:
+ (addition): adds two values or variables
class Add {
public static void main(String[] args) {
int a = 32;
int b = 18;
System.out.println(a + b);
}
}
// Output: 50
- (subtraction): subtracts two values or variables
class Sub {
public static void main(String[] args) {
int a = 32;
int b = 18;
System.out.println(a - b);
}
} // Output: 14
* (multiplication): multiple two values or variables
class Mul {
public static void main(String[] args) {
int a = 30;
int b = 20;
System.out.println(a * b);
}
} // Output: 600
/ (division): divides two numbers and returns a floating point result
class Div {
public static void main(String[] args) {
int a = 30;
int b = 2;
System.out.println(a / b);
}
} // Output: 15
% (remainder): returns the remainder of the division of two values or variables
class Rem {
public static void main(String[] args) {
int a = 13;
int b = 2;
System.out.println(a % b);
}
} // Output: 1
Operator Precedence
The arithmetic operators have a defined order of precedence, that specifies which operator will be executed first if there exist multiple operators in a single expression. For example,
result = 5 * 6 + 10 / 5
Here, / is executed first, followed by * and then +
Order of operator precedence from highest to lowest:
You can use parentheses to change the order of precedence and specify which operations should be performed first.
class OpPre {
public static void main(String[] args) {
int result =5 * 6 + 10 / 5;
System.out.println(result);
}
}
// Output: 32
// / will be executed first, followed by * and then +
Assignment Operators
Java supports the following assignment operators:
= (assignment): assign a value to a variable
age = 25
name = 'Smith'
+= (addition assignment): adds the right operand to the left operand and assigns the result to the left operand
number = 12
// equivalent to number = number + 8
number += 8
-= (subtraction assignment): subtracts the right operand from the left operand and assigns the result to the left operand
number = 12
//equivalent to number = number - 8
number -= 8
*= (multiplication assignment): multiplies the left operand by the right operand and assigns the result to the left operand
number = 12
// equivalent to number = number * 8
number *= 8
/= (division assignment): divides the left operand by the right operand and assigns the result to the left operand
number = 12
// equivalent to number = number / 8
number /= 8
//= (floor division assignment): divides the left operand by the right operand and assigns the integer floor result to the left operand
number = 12
// equivalent to number = number // 8
number //= 8
%= (remainder assignment): divides the left operand by the right operand and assigns the remainder after division to the left operand
number = 12
// equivalent to number = number % 8
number %= 8
Comparison Operators
Java supports the following comparison operators:
== (equal to): checks if two values or variables are equal
a = 20
b = 30
!= (not equal to): checks if two values or variables are not equal
a = 20
b = 30
< (less than): checks if the value on the left is less than the value on the right
a = 20
b = 30
a < b // Output: True
<= (less than or equal to): checks if the value on the left is less than or equal to the value on the right
a = 20
b = 30
a <= b // Output: True
> (greater than): checks if the value on the left is greater than the value on the right
a = 20
b = 30
a > b // Output: False
>= (greater than or equal to): checks if the value on the left is greater than the value on the right
a = 20
b = 30
a >= b // Output: False
Logical Operators
Java supports the following logical operators:
and (Logical AND): returns True
if both operands are True
, else returns False
a = 30
b = 20
c = 10
result = (a > b) and (a > c)
result = (a > b) and (a < c)
Here,
(a > b) and (a > c)
returns True
because both expressions are True
.
(a > b) and ( a < c)
returns False
because a < c
is False
.
or (Logical OR): returns True
if at least one operand is True
, else returns False
a = 30
b = 20
c = 10
result = (a < b) or (a < c)
result = (a > b) or (a < c)
Here,
(a < b) or (a < c)
returns False
because both expressions are False
.
(a > b) or (a < c)
returns True
because a > b
is True
.
not (Logical NOT): returns True
if the operand is False
, False
if the operand is True
a = 30
b = 20
result = not (a < b)
result = not (a > b)
Here,
not (a < b)
returns True
because a < b
is False
.
not (a > b)
returns False
because a > b
is True
.
Java Conditional Statements
Conditional Statements are used to control the flow of a program. Java provides the following conditional statements:
- if: executes a code block if a condition is true.
- if-else: executes a block of code if a condition is true and another block of code if the condition is false.
- switch: executes a block of code based on the value of a variable.
if Statement
Here is an example of using an if statement in Java:
class main{
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
}
}
// Output: x is greater than 5
if-else Statement
In Java, we can use the if-else statement to execute a block of code if a certain condition is true. Else, an alternate statement is executed.
class main{
public static void main(String[] args) {
int x = 10;
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}
}
}
// Output: x is greater than 5
Switch Statement
The switch statement in Java is a control flow statement that allows you to execute a block of code among many alternatives.
In Java, the switch statement has the following syntax:
switch (expression) {
case value1:
// execute code if expression == value1
break;
case value2:
// execute code if expression == value2
break;
...
default:
//execute code if the expression doesn't match any values
}
Here is an example of a switch statement:
class main{
public static void main(String[] args) {
int month = 3;
switch (month) {
case 1:
System.out.println("January");
break;
case 2:
System.out.println("February");
break;
case 3:
System.out.println("March");
break;
default:
System.out.println("Invalid month");
}
}
}
// Output: March
Loop
In Java, we can use the following loops:
- for loop: executes a block of code a certain number of times
- while loop: executes a block of code until a condition is false
for Loop
Java for loop has the following syntax::
for (initialization; condition; iteration) {
// code to be executed
}
Here is an example of a for loop in Java:
class main{
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
}
}
// Output
: 1 2 3 4 5 6 7 8 9 10
while Loop
In Java, while loop has the following syntax:
while (condition) {
// code to be executed
}
Here is an example of a while loop in Java:
class main{
public static void main(String[] args) {
int x = 0;
while (x < 10) {
System.out.println(x);
x++;
}
}
}
//Output
:
0
1
2
3
4
5
6
7
8
9
Functions
In Java, a function is a block of code that performs a specific task and optionally returns a value. Functions are also known as methods.
In Java, a function mainly has two parts:
- Parameters - the variables passed while declaring a function.
- Arguments - the actual values that are passed while calling the function.
Let us now see these two concepts in action.
Declaring a function
Declaring a function in Java means creating a function that specifies the function's name, return type, and parameters.
The function declaration does not include the function's implementation (i.e., the code that defines what the function does).
Syntax
return_type function_name(parameter_list){
// function body
}
Example
int add(int x, int y){
return x + y;
}
Calling a Function
When a function is called in Java, the program control is transferred to the function, and the function's code is executed.
After the function has completed its task, the program control is returned to the point at which it was called.
Syntax
function_name(argument_list);
Example
int sum = add(2, 3); // sum is now 5
Function Overloading
In Java, it is possible to have multiple functions with the same name as long as they have a different parameter list. This concept is referred to as function overloading.
int add(int x, int y) {
return x + y;
}
double add(double x, double y) {
return x + y;
}
In the above example, we have two functions named add
, one that takes in two int
parameters and another that takes in two double
parameters.
Default Arguments
In Java, it is possible to specify default values for function arguments. The default value is used if you don't provide an argument upon the function call.
int add(int x, int y, int z = 0) {
return x + y + z;
}
The above example has a third parameter, z
, with a default value of 0
. If the add function is called with only two arguments, z
will be set to 0
by default.
Classes and Objects
Object-Oriented Programming (OOP) is a programming paradigm where we organize our code into objects and classes.
In OOP, we think of a program as a collection of "objects" that can communicate with each other and perform certain tasks.
Similarly, classes define the attributes and behavior of objects.
Classes
In Java, a class is a blueprint for creating objects. Here is the general syntax for declaring a class in Java:
class ClassName {
// class attributes (fields)
// class methods
}
Objects
An object is an instance of a class.
To create an object in Java, you use the new operator followed by the class name and parentheses:
ClassName objectName = new ClassName();
Example
class Student // a class named student
{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();// an object of class Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Here, the Student
class is a blueprint for creating objects representing students.
There are two variables in the Student
class: id and name. These variables are used to store the id and name of a student.
The main method is the entry point for the program and is executed when the program is run. We've created a Student
object called s1
in
The System.out.println
statements print the values of the id and name variables for the s1
object. Since these variables have not been initialized, the program will print the default values 0 and null.
Exception Handling
Try-Catch Blocks
To handle exceptions in Java, you can use a try-catch block. The try block contains the code that may throw an exception, and the catch block contains the code to handle the exception.
Here is the general syntax for a try-catch block:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
}
Example
class main{
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}
The try-catch above block handles the ArithmeticException that is thrown when the code in the try block tries to divide by zero.
Finally Block
You can use a finally
block to specify the code that the program will always execute, whether or not an exception is thrown.
Here is the general syntax for a try-catch-finally block:
try {
// code that may throw an exception
} catch (ExceptionType e) {
// code to handle the exception
} finally {
// code that will always be executed
}
Example
class main{
public static void main(String[] args) {
try {
int result = 10 / 0;
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This message will always be printed.");
}
}
}
This try-catch-finally block handles the ArithmeticException that is thrown when the code in the try block tries to divide by zero and then prints a message in the finally block.
Throwing an Exception
In Java, you can throw an exception by using the throw keyword, followed by an instance of a class that extends the Exception class or any of its subclasses.
Here's how you can throw a NullPointerException in Java:
if (someObject == null) {
throw new NullPointerException("someObject is null");
}
Java Arrays
An array in Java is a collection of elements of the same data type. Arrays help store many values of the same type in a single variable.
Declaring and Initializing Arrays
Here is an example of declaring and initializing an array in Java:
int[] numbers; // declares an array
int[] numbers = new int[5]; // creates an array of size 5
int[] numbers = {1, 2, 3, 4, 5}; // initialize an array of integers with values
Accessing Array Elements
One thing to remember about Arrays is that the array index always starts at 0. So, the first element in an array will always be at the 0th position.
// Get the first element in the array
int firstElement = numbers[0];
// Get the second element in the array
int secondElement = numbers[1];
// Get the last element in the array
int lastElement = numbers[numbers.length - 1];
Modifying Array Elements
// modify the first element in an array
numbers[0] = 10;
// modify the second element in an array
numbers[1] = 20;
// modify the last element in an array
numbers[myArray.length - 1] = 100;
Iterating Through an Array
// iterate through an array using a for loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Example
class Arrays {
public static void main(String[] args) {
int[] numbers = {1,2,3,4,5};
System.out.print("The first element in the array is " + numbers[0] + "\n");
System.out.print("The second element in the array is " + numbers[1] + "\n");
System.out.print("The last element in the array is " + numbers[numbers.length-1] + "\n");
System.out.print("\n" + "Here are the array elements: " + "\n");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
numbers[0] = 10;
numbers[1] = 20;
System.out.print("\n"+ "The new array elements are: " + "\n");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
The code above defines a class named Arrays
with a main
method that declares an array of integers 1,2,3,4,5.
The code then prints out the first, second, and last elements of the array, i.e., numbers[0]
, numbers[1]
, and numbers[numbers.length -1]
.
It then iterates through the numbers array with a for
loop and prints every array element in a separate line.
Finally, we modified the first and second elements of the array and reprinted the new array.