There are two types of comments in Java: inline and block.
// This is an inline comment. It only includes this line. /* This is a block comment. Anything between the asterisks is part of the comment. */
In Java, you can print statements using System.out.print() and System.out.println(). The latter ends with a new line.
System.out.print("I'm first!"); System.out.println("I'm second!"); System.out.print("I'm last!"); /* Prints: I'm first!I'm second! I'm last! */
Variables are used to name, store, and reference different types of data.
// int - stores whole numbers: int num = 10; // double - stores decimal numbers: double dec = 4.99; // boolean - stores true or false values: boolean isTrue = true; // char - stores a single character value: char firstLetter = 'A'; // String - stores multiple characters: String message = "hello there";
Primitive data types are predefined types of data and include int, double, boolean, and char.
public class NumberManipulation { public static void main(String[] args) { int a = 3; int b = 5; // Basic arithmetic operations System.out.println("Addition: " + (a + b)); // 8 System.out.println("Subtraction: " + (a - b)); // -2 System.out.println("Multiplication: " + (a * b)); // 15 System.out.println("Division: " + (b / a)); // 1 System.out.println("Modulus: " + (b % a)); // 2 // Compound assignment int num = 10; num += a; // num = num + a System.out.println("After += : " + num); // 13 num *= 2; // num = num * 2 System.out.println("After *= : " + num); // 26 } }
Conditional statements execute code based on the truth value of given boolean expressions.
boolean expression1 = false; boolean expression2 = false; boolean expression3 = true; if (expression1) { System.out.println("The first expression is true"); } else if (expression2) { System.out.println("The second expression is true"); } else if (expression3) { System.out.println("The third expression is true"); } else { System.out.println("All other expressions were false"); } // Prints: The third expression is true
Different math operations can be applied to int, double, and float data types.
// Comparison Operators: int a = 1; int b = 5; System.out.println(a > b); // Prints: false System.out.println(a < b); // Prints: true System.out.println(a >= 1); // Prints: true System.out.println(a + 4 <= b); // Prints: true System.out.println(a == 1); // Prints: true System.out.println(b != 5); // Prints: false // Logical Operators: System.out.println(!true); // Prints: false System.out.println(!false); // Prints: true System.out.println(true && true); // Prints: true System.out.println(true && false); // Prints: false System.out.println(false && true); // Prints: false System.out.println(false && false); // Prints: false System.out.println(true || true); // Prints: true System.out.println(true || false); // Prints: true System.out.println(false || true); // Prints: true System.out.println(false || false); // Prints: false
Loops are used to execute code repeatedly based on given conditions.
// An example of a while loop: int x = 0; while (x < 2) { System.out.println(x); x++; } // Prints: 0 and 1 // An example of a do-while loop: do { System.out.println("Impossible!"); } while (2 == 4); // Prints: Impossible! // An example of a for loop: for (int i = 0; i < 10; i++) { System.out.println(i); } // Prints: 0 to 9, inclusive // An example of a for-each loop: String[] colors = {"Red", "Blue", "Yellow"}; for (String c : colors) { System.out.println(c); } // Prints: Red, Blue, and Yellow
break and continue statements alter the flow of loops.
// An example of a break statement: for (int i = 0; i < 10; i++) { System.out.println(i); if (i == 4) { break; } } // Prints: 0 to 4, inclusive // An example of a continue statement: int[] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.length; i++) { if (numbers[i] % 2 == 0) { continue; } System.out.println(numbers[i]); } // Prints 1, 3, and 5
Methods define reusable blocks of code that perform specific tasks.
/* The following method is a public method called findSum. The method takes in two int parameters called int1 and int2. This method returns an int value. */ public static int findSum(int num1, int num2) { return num1 + num2; } public static void main(String[] args) { // Call the method with the arguments 3 and 4 int sum = findSum(3,4); System.out.println(sum); // Prints: 7 }
Java provides several methods for manipulating and querying strings.
// Using the .length() method: String str = "Hello World!"; System.out.println(str.length()); // Prints: 12 // Using the .concat() method: String name = "Hello"; name = name.concat("World"); System.out.println(name); // Prints: HelloWorld // Using the .equals() method: String flavor1 = "Mango"; String flavor2 = "Matcha"; System.out.println(flavor1.equals(flavor2)); // Prints: false // Using the .indexOf() method: String letters = "ABCDEFGHIJKLMN"; System.out.println(letters.indexOf("C")); // Prints: 2 // Using the .charAt() method: String currency = "Yen"; System.out.println(currency.charAt(2)); // Prints: n // Using the .substring() method String line = "It was the best of times, it was the worst of times."; System.out.println(line.substring(26)); // Prints: it was the worst of times. System.out.println(line.substring(7, 24)); // Prints: the best of times
An array is a collection of values with the same data type.
String[] animals = {"Giraffe", "Elephant", "Toucan"}; // Access an element via its index: System.out.println(animals[0]); // Prints: Giraffe // Change an element value: animals[1] = "Lion"; // Find number of elements in an array: System.out.println(animals.length); // Prints: 3 // Traverse array using for loop: for (int i = 0; i < animals.length; i++) { System.out.println(animals[i]); } /* Prints: Giraffe Lion Toucan */ // Traverse array using enhanced for loop: for (String animal : animals) { System.out.println(animal); } /* Prints: Giraffe Lion Toucan */
Multidimensional arrays allow for more complex data structures.
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // Access element at row 2, column 3: System.out.println(matrix[1][2]); // Prints: 6 // Traverse multidimensional array: for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } /* Prints: 1 2 3 4 5 6 7 8 9 */
ArrayList is a resizable array implementation of the List interface.
import java.util.ArrayList; ArrayList<string> list = new ArrayList<>(); list.add("First"); list.add("Second"); list.add("Third"); // Access an element via its index: System.out.println(list.get(1)); // Prints: Second // Remove an element: list.remove(2); // Find number of elements in ArrayList: System.out.println(list.size()); // Prints: 2 // Traverse ArrayList: for (String item : list) { System.out.println(item); } /* Prints: First Second */
Classes are blueprints for creating objects.
public class Car { String color; String model; int year; // Method to display car details public void displayDetails() { System.out.println("Model: " + model); System.out.println("Color: " + color); System.out.println("Year: " + year); } } // Create an instance of Car and use it: Car myCar = new Car(); myCar.color = "Red"; myCar.model = "Toyota"; myCar.year = 2020; myCar.displayDetails(); /* Prints: Model: Toyota Color: Red Year: 2020 */
Inheritance allows one class to inherit the fields and methods of another.
public class Animal { String name; public void makeSound() { System.out.println("Animal sound"); } } public class Dog extends Animal { public void bark() { System.out.println("Woof!"); } } // Use inheritance: Dog myDog = new Dog(); myDog.name = "Buddy"; myDog.makeSound(); // From Animal class myDog.bark(); // From Dog class /* Prints: Animal sound Woof! */
Polymorphism allows methods to do different things based on the object it is acting upon.
class Bird { public void fly() { System.out.println("Bird flies"); } } class Penguin extends Bird { @Override public void fly() { System.out.println("Penguins can't fly"); } } // Use polymorphism: Bird myBird = new Bird(); Bird myPenguin = new Penguin(); myBird.fly(); // Prints: Bird flies myPenguin.fly(); // Prints: Penguins can't fly
Encapsulation is the concept of wrapping data and methods into a single unit or class.
public class Person { private String name; private int age; // Getter and setter for name public String getName() { return name; } public void setName(String name) { this.name = name; } // Getter and setter for age public int getAge() { return age; } public void setAge(int age) { this.age = age; } } // Use encapsulation: Person p = new Person(); p.setName("John"); p.setAge(30); System.out.println(p.getName()); // Prints: John System.out.println(p.getAge()); // Prints: 30
HashMap stores key-value pairs and allows for fast retrieval based on keys.
import java.util.HashMap; HashMap<string, integer=""> map = new HashMap<>(); map.put("One", 1); map.put("Two", 2); map.put("Three", 3); // Retrieve a value: System.out.println(map.get("Two")); // Prints: 2 // Remove a key-value pair: map.remove("Three"); // Iterate over HashMap: for (String key : map.keySet()) { System.out.println(key + " : " + map.get(key)); } /* Prints: One : 1 Two : 2 */
HashSet is a collection that does not allow duplicate elements.
import java.util.HashSet; HashSet<string> set = new HashSet<>(); set.add("Apple"); set.add("Banana"); set.add("Apple"); // Print HashSet: for (String fruit : set) { System.out.println(fruit); } /* Prints: Apple Banana */
LinkedList is a doubly-linked list implementation of the List and Deque interfaces.
import java.util.LinkedList; LinkedList<string> list = new LinkedList<>(); list.add("First"); list.add("Second"); list.addLast("Third"); // Retrieve an element: System.out.println(list.get(1)); // Prints: Second // Remove an element: list.removeFirst(); // Iterate over LinkedList: for (String item : list) { System.out.println(item); } /* Prints: Second Third */
Welcome to our comprehensive collection of programming language cheatsheets! Whether you're a seasoned developer or a beginner, these quick reference guides provide essential tips and key information for all major languages. They focus on core concepts, commands, and functions—designed to enhance your efficiency and productivity.
ManageEngine Site24x7, a leading IT monitoring and observability platform, is committed to equipping developers and IT professionals with the tools and insights needed to excel in their fields.
Monitor your IT infrastructure effortlessly with Site24x7 and get comprehensive insights and ensure smooth operations with 24/7 monitoring.
Sign up now!