Java Cheat Sheet 2023
Java is a versatile and widely-used programming language, known for its simplicity and robustness. Whether you are just starting out in Java or you are an experienced developer, having a comprehensive cheat sheet at your disposal can make a big difference. In this blog post, we’ll provide you with a full Java cheat sheet, organized by headers, that will help you understand the language and write code more efficiently. Additionally, we will also include code snippets to provide examples for each concept.
Data Types
Java supports several data types, including primitive and reference types. Here are some of the most commonly used data types in Java:
- byte: 8-bit signed integer
- short: 16-bit signed integer
- int: 32-bit signed integer
- long: 64-bit signed integer
- float: 32-bit floating-point number
- double: 64-bit floating-point number
- char: 16-bit Unicode character
- boolean: true/false value
Here is an example of how to declare and initialize each of these data types:
byte a = 127;
short b = 32767;
int c = 2147483647;
long d = 9223372036854775807L;
float e = 3.1415f;
double f = 3.141592653589793;
char g = 'A';
boolean h = true;
Strings
Strings are a fundamental data type in Java that represent a sequence of characters.
They are declared using the String keyword, and can be initialized using a string literal or by calling the String() constructor. Strings are immutable in Java.Once String object is created its data or state can’t be changed but a new String object is created. However, you can create new strings by concatenating existing strings using the + operator or the concat() method. Here is an example of how to create and use a string in Java:
// creating a string using a string literal
String message = "Hello, world!";
//Print the String
System.out.println(message);
// accessing the length of the string
System.out.println(message.length()); // prints 13
// accessing a character of the string using its index
System.out.println(message.charAt(1)); // prints 'e'
This code creates a string named message using a string literal, and demonstrates how to access its length and individual characters using the length() and charAt() methods.
Strings are a powerful and versatile data type in Java, and are used extensively in many Java programs.
Operators
Java provides several operators that can be used to manipulate values, including arithmetic, assignment, comparison, and logical operators. Here are some examples:
- Arithmetic: +, -, *, /, %
- Assignment: =, +=, -=, *=, /=, %=
- Comparison: ==, !=, <, >, <=, >=
- Logical: &&, ||, ! Here is an example of how to use some of these operators:
int x = 10;
int y = 3;
int z = x + y; // 13
z = x - y; // 7
z = x * y; // 30
z = x / y; // 3
z = x % y; // 1
x += y; // x is now 13
x -= y; // x is now 10 again
x *= y; // x is now 30
x /= y; // x is now 10
x %= y; // x is now 1
Arrays
Arrays are a fundamental data structure in Java that allow you to store multiple values of the same type in a single variable.
1 Dimensional:
An array is declared by specifying the data type of its elements, followed by its name and size in square brackets. You can then assign values to the elements of the array using their index, which starts at 0. Here is an example of how to create and use an array in Java:
// creating an array of integers
int[] numbers = {1, 2, 3, 4, 5};
// accessing the elements of the array using their index
System.out.println(numbers[0]); // prints 1
System.out.println(numbers[2]); // prints 3
// changing the value of an element of the array
numbers[4] = 6;
System.out.println(numbers[4]); // prints 6
This code creates an array of integers named numbers with a size of 5, and initializes its elements with the values 1, 2, 3, 4, and 5.
The elements of the array are accessed using their index, which starts at 0, and can be changed by assigning a new value to them. Arrays are useful when you want to store a collection of values of the same type in a single variable, and allow for efficient and easy access to their elements.
2 Dimensional
In addition to 1-dimensional arrays, Java also supports 2-dimensional arrays, which are essentially arrays of arrays.
Here is an example of how to create and use a 2-dimensional array in Java:
// creating a 2-dimensional array of integers
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// accessing the elements of the 2-dimensional array using their indexes
System.out.println(matrix[0][0]); // prints 1
System.out.println(matrix[1][2]); // prints 6
// changing the value of an element of the 2-dimensional array
matrix[2][1] = 10;
System.out.println(matrix[2][1]); // prints 10
This code creates a 2-dimensional array of integers named matrix with 3 rows and 3 columns, and initializes its elements with the values 1, 2, 3, 4, 5, 6, 7, 8, and 9. The elements of the array are accessed using their row and column indexes, which start at 0, and can be changed by assigning a new value to them. 2-dimensional arrays are useful when you want to store and manipulate data in a matrix-like format, and allow for efficient and easy access to their elements.
If you have trouble understanding a 2D Array, here is a visualization of it:
*Control Structures
*
Java provides several control structures that allow you to manipulate the flow of your code. Here are some of the most commonly used control structures:
- if/else statements: used to conditionally execute code based on a Boolean expression
- for loops: used to iterate over a collection of items
- while loops: used to repeatedly execute code as long as a Boolean expression is true
- switch statements: used to execute different code blocks based on the value of a variable
- break and continue statements: used to modify the flow of loops and switch statements
Here is an example of how to use some of these control structures:
if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is less than or equal to 5");
}
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
int i = 0;
while (i < 10) {
System.out.println(i);
i++;
}
int day = 3;
switch (day) {
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;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
break;
}
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue; // skip to the next iteration
}
if (i == 8) {
break; // exit the loop
}
System.out.println(i);
}
Methods
Java methods are blocks of code that perform specific tasks and can be called by an object of a class.
They can accept parameters and return values, allowing for flexibility in their use. Methods can also be overloaded, meaning that multiple methods with the same name can exist in a single class as long as their parameter types or number of parameters differ.
Here are two examples of how to create methods in Java, one with parameters and one without:
Example 1: Method with Parameters
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// calling the greet() method with a parameter
greet("Alice");
This code creates a method named greet() that accepts a String parameter named name and prints “Hello, [name]!” to the console. The method is then called with the parameter “Alice” using its name and parentheses.
Example 2: Method without Parameters
public static void greet() {
System.out.println("Hello, world!");
}
// calling the greet() method
greet();
This code creates a method named greet() that doesn’t accept any parameters and simply prints “Hello, world!” to the console. The method is then called using its name and parentheses. Methods without parameters are useful when you want to execute a block of code that doesn’t require any additional input, while methods with parameters allow you to customize the behavior of your code by accepting input from the caller.
Example 3: Return a value
public static int add(int a, int b) {
return a + b;
}
// calling the add() method and storing the result in a variable
int result = add(3, 4);
System.out.println(result); // prints 7
This code creates a method named add() that accepts two int parameters named a and b and returns their sum using the return keyword. The method is then called with the parameters 3 and 4 using its name and parentheses, and the result is stored in a variable named result. The value of result is then printed to the console, which should be 7. Methods that return values are useful when you want to perform a calculation or operation and pass the result back to the caller for further processing.
In this case the syntax of the method is “public static int” because the methods returns a int value. If we want to return a String we have to declare it in the header of the method (switch “int” to “String”).
Recursion
Recursion is a powerful technique in programming that involves a function calling itself repeatedly until a certain condition is met.
In Java, recursion is used to solve problems that can be broken down into smaller subproblems that are identical in nature. Recursive functions typically have a base case that defines the condition for stopping the recursion, and a recursive case that defines how the function calls itself with smaller subproblems. Here is an example of how to use recursion in Java:
public static int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
// calling the factorial() method with a parameter
int result = factorial(5);
System.out.println(result); // prints 120
This code creates a method named factorial() that uses recursion to calculate the factorial of a given number.
The method accepts an int parameter named n and has a base case that returns 1 if n is 0, and a recursive case that multiplies n by the result of factorial(n - 1).
The method is then called with the parameter 5 using its name and parentheses, and the result is stored in a variable named result.
The value of result is then printed to the console, which should be 120.
Recursive functions can be a powerful tool for solving complex problems that can be broken down into smaller, identical subproblems.
Classes and Objects
Java is an object-oriented programming language, which means that it organizes code into classes and objects.
Here are some key concepts related to classes and objects:
- Class: a blueprint or template for creating objects
- Attributes: The variables of a Object
- Object: an instance of a class
- Constructor: a special method that is used to create new objects
- Method: a block of code that performs a specific task and can be called by an object of a class
- Inheritance: a mechanism that allows one class to inherit the properties and methods of another class
- Polymorphism: a mechanism that allows objects of different classes to be treated as if they are of the same class
Here is an example of how to use these concepts:
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
class Student extends Person {
private String major;
public Student(String name, int age, String major) {
super(name, age);
this.major = major;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am a " + major + " major.");
}
}
Person person = new Person("John", 30);
person.sayHello();
Student student = new Student("Jane", 20, "Computer Science");
student.sayHello();
In general, attributes are declared as private in Java classes to enforce encapsulation, which is the idea of hiding the internal workings of an object from the outside world. This helps to prevent unintended access or modification of an object’s attributes by external code, which can cause bugs and security vulnerabilities. By encapsulating its attributes, a class can ensure that its behavior is predictable and consistent, making it easier to maintain and extend over time.
Exception Handling
Java provides a robust exception handling mechanism that allows you to gracefully handle errors that might occur during program execution. Here are some key concepts related to exception handling:
- Exception: an event that occurs during program execution that disrupts the normal flow of code
- try/catch/finally blocks: used to catch and handle exceptions that might occur during program execution
- throw statement: used to explicitly throw an exception
- Checked and Unchecked Exceptions: Checked exceptions must be caught or declared in the method signature, while unchecked exceptions do not need to be caught or declared. Here is an example of how to use these concepts:
try {
int[] numbers = {1, 2, 3};
int x = numbers[3];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("An exception occurred: " + e.getMessage());
} finally {
System.out.println("This code will always be executed.");
}
public void deposit(double amount) throws IllegalArgumentException {
if (amount < 0) {
throw new IllegalArgumentException("Amount cannot be negative.");
}
balance += amount;
}
Executing Code
If you want to run the Java Programm without a IDE you have to open the terminal in your project root and run:
javac [filename.java]
java [filename]
Note: Filename should be the same as the class name containing the main() method, with a .java extension.
Conclusion
In this blog post, we’ve provided you with a full Java cheat sheet that covers some of the most commonly used features of the language. By using this cheat sheet, you’ll be able to write Java code more efficiently and with greater confidence. Whether you are a beginner or an experienced Java developer
If you are interested in more Coding Tutorial you can check out our Coding Category or our blog
Top comments (0)