Java Syntax Cheat Sheet

Artistic digital representation of Java Syntax Cheat Sheet focusing on key syntax and concepts in Java programming with examples

When developing software at IOFLOOD, having a solid understanding of Java syntax and concepts is essential for creating the dedicated cloud hosting ecosystem that meet our clients’ needs. To streamline the learning process and help developers grasp Java fundamentals quickly, we’ve crafted this comprehensive Java Syntax Cheat Sheet.

This reference guide covers all the important uses of Java programming. It serves as a comprehensive Reference for the Java language and syntax, and offers practical code examples.

Let’s embark on this journey to unlock Java’s full potential. Let’s code!

Command Reference

Before providing the code example, we will list all of the essential Java Programming commands and concepts. These terms will be used in action in the code examples following this section. Utilize this reference to learn more about the example code as well as boost your Java development workflow.

Data Types

Data TypeDescriptionSyntax Example
intInteger data type (whole number)int i = 10;
doubleDouble-precision floating point data typedouble d = 20.5;
booleanBoolean data type (true or false)boolean b = true;
charSingle character data typechar c = ‘A’;
StringSequence of characters data typeString s = “Hello”;


Relational Operators

OperatorDescriptionSyntax Example
==Equal toif (a == b)
!=Not equal toif (a != b)
>Greater thanif (a > b)
<Less thanif (a < b)
>=Greater than or equal toif (a >= b)
<=Less than or equal toif (a <= b)

Logical Operators

OperatorDescriptionSyntax Example
&&Logical ANDif (a > b && c > d)
| Logical OR | if (a > b || c > d)
!Logical NOTif (!a)

Assignment Operators

OperatorDescriptionSyntax Example
=Assign valuea = b;
+=Add and assigna += b;
-=Subtract and assigna -= b;
*=Multiply and assigna *= b;
/=Divide and assigna /= b;
%=Modulus and assigna %= b;

Unary Operators

OperatorDescriptionSyntax Example
++Increment operatora++;
Decrement operatora–;

String Manipulation

ConceptDescriptionSyntax Example
ConcatenationCombines stringsString fullName = firstName + ” ” + lastName;
ComparisonCompares two stringsif (str1.equals(str2))

String Methods

MethodDescriptionSyntax Example
length()Returns the length of the len = str.length();
charAt()Returns the character at the specified index.char ch = str.charAt(2);
contains()Checks if the string contains the specified sequence of char values.boolean b = str.contains("abc");
equals()Compares two strings for content equality.boolean eq = str1.equals(str2);
equalsIgnoreCase()Compares two strings, ignoring case considerations.boolean eq = str1.equalsIgnoreCase(str2);
toLowerCase()Converts all characters in the string to lower case.String lower = str.toLowerCase();
toUpperCase()Converts all characters in the string to upper case.String upper = str.toUpperCase();
trim()Removes leading and trailing spaces.String trimmed = str.trim();
substring()Returns a new string that is a substring of this string.String sub = str.substring(1,4);
replace()Replaces each substring of this string that matches the literal target sequence.String replaced = str.replace('a', 'b');
indexOf()Returns the index within this string of the first occurrence of the specified index = str.indexOf('a');
replaceAll()Replaces each substring that matches the given regular expression.String updated = str.replaceAll("text", "txt");
split()Splits this string around matches of the given regular expression.String[] parts = str.split(" ");
isEmpty()Checks if the string is empty.boolean empty = str.isEmpty();
compareTo()Compares two strings diff = str1.compareTo(str2);
join()Joins strings with a specified delimiter.String joined = String.join("-", "Java", "is", "cool");

StringBuilder Methods

MethodDescriptionExample Usage
append()Appends the specified string to this character sequence.StringBuilder sb = new StringBuilder("Hello"); sb.append(" World");
insert()Inserts the specified string at the specified, " Dear");
delete()Removes the characters in a substring of this, 10);
deleteCharAt()Removes the char at the specified;
replace()Replaces the characters in a substring of this sequence with characters in the specified, 5, "Hi");
reverse()Causes this character sequence to be replaced by the reverse of the;
toString()Returns a string representing the data in this sequence.String s = sb.toString();
length()Returns the length (character count).int len = sb.length();
setCharAt()Sets the character at the specified, 'H');
substring()Returns a new String that contains a subsequence of characters currently contained in this sequence.String sub = sb.substring(1, 4);

Note: ‘String’ in Java is immutable, once created, it cannot be changed. Meanwhile StringBuilder offers a mutable character sequence, allowing for in-place modifications without creating new objects. This makes StringBuilder more efficient for operations that involve frequent changes to a string’s content.


Comment TypeDescriptionSyntax Example
Single-lineUsed for brief comments, ends at the line break// This is a single-line comment
Multi-lineUsed for longer comments that span multiple lines/* This is a multi-line comment that can span multiple lines until it's closed */
DocumentationSpecial comments that can be converted to HTML documentation by the Javadoc tool/** This is a documentation comment used by Javadoc to generate HTML docs */

Exception Handling

ConceptDescriptionSyntax Example
try-catchCatches exceptions thrown in the try block.try { ... } catch (ExceptionType name) { ... }
multiple catchHandles different types of exceptions separately.try { ... } catch (ExceptionType1 e1) { ... } catch (ExceptionType2 e2) { ... }
try-catch-finallyThe finally block always executes regardless of exception occurrence.try { ... } catch (Exception e) { ... } finally { ... }
try-with-resourcesAutomatically closes resources used within the try block.try (ResourceType resource = new ResourceType()) { ... }
throwsIndicates that a method can throw exceptions of specified types.public void myMethod() throws IOException, AnotherException { ... }
throwExplicitly throws an exception.throw new ExceptionType("Error message");
custom exceptionsAllows defining user-specific exception classes.class MyException extends Exception { ... }

Common Exceptions

ExceptionCauseHow to Fix
NullPointerExceptionAttempting to use an object reference that is null.Ensure objects are properly initialized before use.
ArrayIndexOutOfBoundsExceptionAccessing an array with an illegal index (either negative or beyond the array size).Check your indices are within bounds before accessing the array.
ClassCastExceptionTrying to cast an object to a subclass of which it is not an instance.Use instanceof to check type before casting.
IllegalArgumentExceptionPassing illegal or inappropriate arguments to a method.Validate method arguments to ensure they fall within expected ranges or conditions.
IllegalStateExceptionWhen an environment or application is not in an appropriate state for the requested operation.Ensure all required states or conditions are met before operation.
IOExceptionFailure during input or output operations, often due to issues with file or network access.Check file existence, permissions, or network connectivity before I/O operations.
FileNotFoundExceptionAttempting to open a file that does not exist.Ensure the file exists and the path is correctly specified.
ArithmeticExceptionExceptional arithmetic conditions like divide by zero.Check arithmetic operations to avoid exceptional conditions (e.g., division by zero).

Object-Oriented Programming (OOP) Concepts

ConceptDescriptionPractical Example
ClassBlueprint from which individual objects are created.public class Dog { ... }
ObjectAn instance of a class containing state and behavior.Dog myDog = new Dog();
InheritanceMechanism where one class acquires properties of another class.public class GermanShepherd extends Dog { ... }
PolymorphismAbility of an object to take on many forms, typically through method overriding.Overriding the bark() method in GermanShepherd class.
AbstractionHiding the implementation details from the user, showing only functionality.Declaring abstract class Animal { abstract void makeSound(); }
EncapsulationKeeping the data (state) and codes acting on the data (behavior) together, while preventing outside interference and misuse.Using private variables and public getters and setters.

Access Modifiers

privateAccessible only within the declared class itself.
defaultAccessible only within classes in the same package.
protectedAccessible within the same package and subclasses in any package.
publicAccessible from any other class.

Note: Access modifiers in Java determine the visibility of classes, methods, and variables within other classes and packages.

Control Structures and Loops

if statementExecutes a block of code if its condition evaluates to true.if (condition) { ... }
else statementExecutes a block of code if the if statement’s condition is false.if (condition) { ... } else { ... }
else if statementA series of if statements to execute different blocks of code.if (condition) { ... } else if (condition) { ... }
switch statementSelects one of many code blocks to be executed.switch(expression) { ... }
caseA switch block label that specifies a new branch of code to x: ...
defaultSpecifies the default block of code to execute if no case value matches the switch expression.default: ...
breakTerminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.break;
for loopExecutes a block of code a certain number of times.for (initialization; condition; update) { ... }
while loopRepeats a block of code as long as its condition remains true.while (condition) { ... }
do-while loopExecutes a block of code once, and then repeats the loop as long as its condition remains { ... } while (condition);
Enhanced For LoopSimplifies the traversal of collections and arrays.for (Type item : collection) { ... }
continue (Loop Control)Skips the current iteration of the loop and proceeds with the next iteration.Used inside loops as continue;

Data Structures

Data StructureDescriptionExample Usage
ArrayStores a fixed-size sequential collection of elements of the same[] arr = new int[5];
ArrayListA resizable array that grows as needed, from the Java Collections Framework.ArrayList<String> list = new ArrayList<>();
LinkedListDoubly-linked list implementation of the List and Deque interfaces.LinkedList<String> linkedList = new LinkedList<>();
HashMapStores key-value pairs in a hash table.HashMap<String, Integer> map = new HashMap<>();
HashSetImplements the Set interface, backed by a hash table (actually a HashMap instance).HashSet<String> set = new HashSet<>();
StackLast-in-first-out (LIFO) stack of objects.Stack<Integer> stack = new Stack<>();
QueueTypically orders elements in FIFO (first-in-first-out) manner.Queue<Integer> queue = new LinkedList<>();

Data Structure Methods

MethodDescriptionData Structures
add()Adds an element. For queues, offer() might be used instead.ArrayList, LinkedList, Stack, Queue (as offer())
remove()Removes an element. For queues, poll() might be used instead.ArrayList, LinkedList, Stack, Queue (as poll())
get()Retrieves an element at a specific position.ArrayList, LinkedList
set()Replaces an element at a specific position.ArrayList, LinkedList
push()Pushes an item onto the top of the stack.Stack
pop()Removes the item at the top of the stack and returns it.Stack
peek()Looks at the object at the top of the stack without removing it.Stack, Queue
put()Associates a specific value with a specific key in a map.HashMap

Sort Functions

Sort AlgorithmDescriptionComplexity
Bubble SortRepeatedly steps through the list, compares adjacent elements, and swaps them if in the wrong order.Worst: O(n^2)
Merge SortDivides the array into halves, sorts each half, and merges them back together.Average: O(n log n)
Quick SortPicks an element as a pivot and partitions the array around the pivot.Average: O(n log n)
Insertion SortBuilds the final sorted array one item at a time, with each item being inserted in its proper place.Worst: O(n^2)
Selection SortSelects the smallest (or largest) element from the unsorted section and moves it to the beginning (or end).Worst: O(n^2)

Method Parameters

Parameter TypeDescriptionExample Usage
Formal ParametersParameters defined in the method declaration. They act as placeholders for the values passed to the method when it’s called.void add(int a, int b) { ... }
Actual ParametersThe real values passed to the method. These values are assigned to the corresponding formal parameters of the method.add(5, 10);
Default ParametersJava does not support default parameters directly. Default behavior can be simulated using method overloading.void printMessage(String message) { ... } void printMessage() { printMessage("Default Message"); }
Variable Arguments (VarArgs)Allows passing an arbitrary number of values of the specified type to a method.void printAllStrings(String... strings) { ... }

Variable Arguments (VarArgs)

Usage ContextDescriptionExample Usage
Simple Collection of ArgumentsPassing a variable number of values of the same type to a method.public void printNumbers(int... numbers) { for (int number : numbers) { System.out.println(number); } }
Combining VarArgs with Other ParametersVarArgs can be used alongside other parameters, but VarArgs must be the last parameter.public void printMixed(String message, int... numbers) { System.out.println(message); for (int number : numbers) { System.out.println(number); } }
Overloading with VarArgsJava Methods can be overloaded with VarArgs for more flexible parameter handling.public void print(); public void print(String... messages);
Using VarArgs for FormattingVarArgs are useful for methods that require a format string followed by a variable number of arguments, similar to printf.public void formatPrint(String format, Object... args) { System.out.printf(format, args); }

Casting and Conversion

Method/TechniqueDescriptionExample Usage
Implicit CastingAutomatic conversion of a smaller type to a larger i = 100; long l = i;
Explicit CastingManual conversion of a larger type to a smaller type.long l = 100; int i = (int) l;
Using Wrapper ClassesConversion between primitives and their corresponding object i = 5; Integer integer = Integer.valueOf(i);
parseXxx() MethodsConverting strings to different data i = Integer.parseInt("123");
toString() MethodConverting other data types to strings.String s = Integer.toString(123);
valueOf() MethodConverts strings to wrapper class objects or primitives to wrapper objects.Integer integer = Integer.valueOf("123");

Web Development and Frameworks

FrameworkDescriptionExample Use Cases
Servlet APILow-level API for handling HTTP requests and responses.Basic web applications, form processing.
JavaServer Pages (JSP)Technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types.Dynamic content generation, web page templates.
JavaServer Faces (JSF)Java specification for building component-based user interfaces for java web applications.Enterprise-level web applications, form-based applications with complex UI.
Spring FrameworkComprehensive framework for enterprise Java development, with support for web applications through Spring MVC.Enterprise applications, RESTful web services, microservices architecture.
Spring BootConvention-over-configuration centric framework from the creators of the Spring Framework, simplifying the setup and development of new Spring applications.Microservices, standalone web applications, quick project bootstrapping.
HibernateObject-relational mapping tool for Java, facilitating the mapping of an object-oriented domain model to a traditional relational database.Data persistence and retrieval in web applications, database integration.
JerseyOpen source framework for developing RESTful Web Services in Java that provides support for JAX-RS APIs.RESTful services, JSON and XML web services.
Apache StrutsFramework for creating enterprise-ready Java web applications, based on the Model-View-Controller (MVC) architecture.Form-based applications, large scale web projects.
VaadinWeb application framework for rich Internet applications, focusing on UX accessibility.Business applications, complex web UIs, single-page applications (SPAs).
Play FrameworkHigh-velocity web framework for Java and Scala, emphasizes convention over configuration, hot code reloading, and display of errors in the browser.Modern web applications, reactive applications.

Java Versions

VersionRelease DateNotable Differences
Java SE 8March 2014Introduced lambda expressions, streams, new date and time API, default and static methods in interfaces.
Java SE 9September 2017Introduced the module system (Project Jigsaw), jshell (REPL), private methods in interfaces.
Java SE 11September 2018LTS version. New HTTP Client, local-variable syntax for lambda parameters, Flight Recorder, ZGC.
Java SE 17September 2021LTS version. Sealed classes, pattern matching for switch (preview), new macOS rendering pipeline, Foreign Function & Memory API (Incubator).

Note: LTS stands for Long Term Support, indicating a version with extended support and updates.

Code Examples

In this segment, we will delve into a simple Java program designed to showcase how various Java Programming Concepts work together, encompassing everything from basic syntax to more complex concepts such as exception handling and streams. This reference can be used to gain more information about the code examples above.

Before the code examples, we will walk you through setting up a Java environment, in case you don’t have one set up already. The following instructions are for general use, so for OS specific instructions you can check out our Java Installation Guides!

Setting Up The Environment

  1. Install Java Development Kit (JDK): The JDK is necessary for compiling and running Java applications. If you don’t have it installed, you can download it from the Oracle website or adopt an OpenJDK version from an open-source provider.

  2. Set Up an Integrated Development Environment (IDE): While you can compile and run Java programs from the command line, using an IDE like IntelliJ IDEA, Eclipse, or NetBeans can simplify the process and provide additional tools for debugging and managing your projects. Download and install an IDE of your choice.

  3. Create a New Java Project: Open your IDE and create a new Java project. This process will vary depending on the IDE, but generally, you’ll need to specify a project name and location on your filesystem.

  4. Add Java Classes: Within your new project, create two new Java class files named and Copy and paste the provided code for each class into the respective files.

  5. Compile and Run: Use your IDE’s built-in features to compile and run the JavaSyntaxReference class. This class contains the main method, which serves as the entry point for the application.

Alternative: Command Line Compilation

For those who prefer working directly from the command line:

  1. Save the Classes: Save the provided and code into two separate files within the same directory.

  2. Open a Terminal/Command Prompt: Navigate to the directory where you saved the files.

  3. Compile the Classes: Run the command javac to compile both files, producing .class files runnable on the Java Virtual Machine (JVM).

  4. Run the Main Class: Execute the command java JavaSyntaxReference to run the compiled main class.

Note: The provided code is designed to be as dependency-free as possible, focusing on raw Java without external libraries. This ensures that a basic Java setup can compile and run the examples with minimal effort.

Sample Class

Before we dive into the main program, we begin with an example Java class. Defining and utilizing classes allows us to encapsulate data and behavior, promoting code reusability and scalability. This class, used in our main sample program, provides an example of Object Oriented Programming, one of the core principles in Java Programming.

public class Book {
    // Variables: Define attributes of the Book class
    private String title;
    private boolean isAvailable;

    // Constructor: Initializes a new instance of the Book class
    public Book(String title) {
        this.title = title;
        this.isAvailable = true; // By default, a new book is available

    // Method: Gets the title of the book
    public String getTitle() {
        return title;

    // Method: Checks if the book is available
    public boolean isAvailable() {
        return isAvailable;

    // Control Structure (if-else): Borrow the book if it is available
    public void borrow() {
        if (isAvailable) {
            isAvailable = false;
            System.out.println(title + " has been borrowed.");
        } else {
            System.out.println(title + " is not available for borrowing.");

    // Method: Return the book and make it available again
    public void returnBook() {
        isAvailable = true;
        System.out.println(title + " has been returned.");

// Extending the Book class to create a Magazine subclass
class Magazine extends Book {
    public Magazine() {
        super("Generic Magazine Title"); // Magazines typically don't have authors like books do, so we use a generic title

    // Overriding the borrow method to demonstrate polymorphism
    public void borrow() {
        if (isAvailable()) {
            System.out.println(getTitle() + " has been borrowed. Remember, magazines have a shorter borrowing period!");
        } else {
            System.out.println(getTitle() + " is not available for borrowing.");

In the main program, we will create an instance of Book, then call its methods to simulate borrowing and returning the book.

Java Sample Code

Presented here is our main sample class, intended to showcase a variety of Java programming techniques. We invite you to explore and study its construction for a hands-on understanding of Java syntax and operations.

public class JavaSyntaxReference {
    // Import statements to insure package inclusion
    import java.util.Arrays;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Scanner;

    public static void main(String[] args) {
    /* The above line of code is the entry point of a Java application. 
    "public" makes it accessible from anywhere; 
    "static" means it belongs to the class, not instances of the class; 
    "void" indicates it returns no value. 
    "main" is the name recognized by the JVM as the starting point, 
    "String[] args" allows the program to accept an array of strings from command line arguments. */

        // Data Types
        String text = "Hello Java";
        double doubleVar = 10.5;
        boolean booleanVar = true;
        int integerVar = 10;        
        char charVar = 'A';     
        // Output: 10
        // Output: A

        // Logical Operators
        boolean result = (integerVar < 20) && (doubleVar > 5.0);
        // Output: true

        // Stack Data Structures
        java.util.Stack<Integer> stack = new java.util.Stack<>();
        // Output: 10

        // ArrayList and an example of an ArrayList method (add(), remove(), get(), set())
        ArrayList<String> books = new ArrayList<>();
        books.add("Java Basics");
        books.set(0, "Advanced Java"); // Replaces "Java Basics" with "Advanced Java"
        books.remove("Advanced Java"); // Removes "Advanced Java", the list is now empty
        books.add("Java Concurrency"); // Adds "Java Concurrency" to the list
        System.out.println("ArrayList example: " + books); 
        // Output: ArrayList example: [Java Concurrency]

        // HashMap and an example of an HashMap method (put(), get(), remove())
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Java");
        map.put(2, "Python");
        String language = map.get(1);
        // Output: Java

        // Array Manipulation: Fill an array with a specific value using Arrays.fill()
        int[] myArray = new int[5]; // Initializes an array of length 5
        Arrays.fill(myArray, 9); // Fills the entire array with 9
        // Output: [9, 9, 9, 9, 9]

        // Java Sort Functions - Using Arrays.sort

        int[] numbers = {5, 3, 4, 1, 2};
        // Output: [1, 2, 3, 4, 5]

        // Bubble Sort - Method defined below
        int[] numbers = {5, 3, 8, 4, 2};
        System.out.println("Bubble Sorted: ");
        for (int num : numbers) {
            System.out.print(num + " ");  
            // Expected output: 2 3 4 5 8
        System.out.println();  // Moves to the next line after printing the array

        // Selection Sort - Method defined below
        int[] moreNumbers = {22, 11, 99, 88, 9, 7, 42};
        System.out.println("Selection Sorted: ");
        for (int num : moreNumbers) {
            System.out.print(num + " ");  
            // Expected output: 7 9 11 22 42 88 99
        System.out.println();  // Moves to the next line after printing the array

        // Casting or Conversion
        double myDouble = 9.78;
        int myInt = (int) myDouble; // Explicit casting from double to int
        // Output: 9

        // String Conversions: Using toString(), String.valueOf()
        int numForString = 500;
        String fromInt = String.valueOf(numForString);
        System.out.println("String.valueOf(): " + fromInt); 
        // Output: String.valueOf(): 500

        // StringBuilder
        StringBuilder sb = new StringBuilder();
        sb.append("StringBuilder ").append("Example");
        // Output: StringBuilder Example

        // String Manipulation - String Methods
        String text = "Hello Java";
        String upperText = text.toUpperCase();
        // Output: HELLO JAVA

        // Java Math Library
        double sqrtResult = Math.sqrt(25); // Square root
        // Output: 5.0

        // Java Time Library
        java.time.LocalDate currentDate =;
        // Output: [Current Date]

        // Java File Handling myFile = new"example.txt");
        // Creates a File object that represents a reference to "example.txt" in the file system.

        // Appending text to "example.txt" w/ FileWriter
        try (FileWriter writer = new FileWriter("example.txt", true)) { // true to append
            writer.write("\nI love Java!"); // Appends a new line with the text "I love Java!" to the file.
        } catch (IOException e) {
            System.out.println("An error occurred while writing to the file: " + e.getMessage());

        // Reading from "example.txt" using Scanner and printing its contents
        try (Scanner scanner = new Scanner(new File("example.txt"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                /* Expected console output:
                Learning Java with IOFlood is a blast!
                I love Java! */
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());

        // Reading from "example.txt" using Scanner and printing its contents
        try (Scanner scanner = new Scanner(new File("example.txt"))) {
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                /* Expected console output:
                Learning Java with IOFlood is a blast!
                I love Java! */
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + e.getMessage());

        // Java Regular Expressions
        String pattern = ".*Java.*";
        boolean matches = "Hello Java".matches(pattern);
        // Output: true     

        // Control Structure: if-else
        int a = 5, b = 10;
        if (a < b) {
            System.out.println("a is less than b");
        } else {
            System.out.println("a is not less than b");
         // Output: a is less than b

        // Loop: for
        for (int i = 0; i < 3; i++) {
            System.out.println("for loop iteration: " + i);  // Output will show for each iteration

        // Loop: while
        int whileCounter = 3;
        while (whileCounter > 0) {
            System.out.println("while loop iteration");  // Output shown for each iteration

        // Loop: do-while
        int doWhileCounter = 2;
        do {
            System.out.println("do-while loop iteration"); 
        } while (doWhileCounter > 0);
        /* Expected output:
        do-while loop iteration
        do-while loop iteration */      

        // Loop: Enhanced for
        int[] numbers = {1, 2, 3};
        for (int number : numbers) {
            System.out.println("Enhanced for loop: " + number);
        /* Expected output:
        Enhanced for loop: 1
        Enhanced for loop: 2
        Enhanced for loop: 3 */

        // Use of 'continue' in a Java loop
        for(int i = 0; i < 5; i++) {
            if(i == 2) continue; // Skips the rest of the loop when i is 2
        /* Expected output:
        4 */

        // Switch-case
        int month = 4;
        switch (month) {
            case 1:
            case 2:
                System.out.println("Other Month");
        // Expected output:
        // Other Month

        // Simple Method Call - Method defined below        
        System.out.println("Calling printMessage with a single string:");
        printMessage("This is a method call.");
        // Output: This is a method call.

        //VarArgs Method Call
        System.out.println("Calling printVarArgs with multiple strings:");
        printVarArgs("VarArgs Example:", "One", "Two", "Three");
        /* Output:
        VarArgs Example:
        Three */

        // Exception Handling: try-catch
        try {
            int result = a / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e.getMessage());
        // Expected output:
        // Exception caught: / by zero

        // Java 8 Stream
        int[] streamNumbers = {4, 5, 6};;
        /* Expected output:
        6 */

        // Note: The System.out::println syntax is used in within Java 8 Streams as a method reference,
        // a shorthand notation used when passing methods as arguments.

        // Object Instantiation with Constructors
        Book myFavoriteBook = new Book("The Art of Java");
        System.out.println("Book created: " + myFavoriteBook.getTitle()); 
        // Output: Book created: The Art of Java

        // Demonstrating Inheritance and Polymorphism
        Book myMagazine = new Magazine();
        // Output: Generic Magazine Title has been borrowed. Remember, magazines have a shorter borrowing period!

        // Method invocation: Borrowing the book
        System.out.println("Attempting to borrow the book...");
        // Output: The Art of Java has been borrowed.

        // Checking if the book can be borrowed again (condition checking)
        System.out.println("Attempting to borrow the book again...");
        // Output: The Art of Java is not available for borrowing.

        // Returning the book
        System.out.println("Returning the book...");
        // Output: The Art of Java has been returned.

        // Attempting to borrow the book after returning it
        System.out.println("Attempting to borrow the book after returning...");
        // Output: The Art of Java has been borrowed.

        // Exception Handling with try-catch: Handling a NullPointerException
        try {
            Book myBook = null; // Intentionally set to null to trigger a NullPointerException
            System.out.println(myBook.getTitle()); // Attempting to access a method on a null reference
        } catch (NullPointerException e) {
            System.out.println("Caught a NullPointerException. Make sure your Book object is initialized before use.");


    // Method Definition
    static void printMessage(String message) {

    // VarArgs Method
    static void printVarArgs(String... args) {
        for (String arg : args) {

    // Bubble Sort method
    static void bubbleSort(int[] arr) {
        boolean swapped;
        for (int i = 0; i < arr.length - 1; i++) {
            swapped = false; // Track if a swap occurred
            // Iterate through the array, excluding the last sorted elements
            for (int j = 0; j < arr.length - i - 1; j++) {
                // Compare adjacent elements
                if (arr[j] > arr[j + 1]) {
                    // Swap if elements are in wrong order
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    swapped = true; // Mark swap occurred
            // If no swap occurred, the array is sorted
            if (!swapped) break;

    // Selection Sort method
    static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIdx = i; // Assume current index as minimum
            // Find the minimum element in unsorted part
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[minIdx]) {
                    minIdx = j; // Update minimum index
            // Swap the found minimum element with the first element
            int temp = arr[minIdx];
            arr[minIdx] = arr[i];
            arr[i] = temp;


Our example code tackles a range of Java fundamentals and advanced concepts, from variable declaration and control structures to method definition and lambda expressions. Remember to utilize the reference section, and other java tutorials for more info on the concepts used in the example!


Java’s versatility and robustness as a programming language underscore the importance of mastering Object-Oriented Programming (OOP) and its concepts. This cheat sheet aims to equip you with a solid understanding of Java syntax and best practices. Whether you’re a novice stepping into the world of programming or a seasoned developer brushing up on Java, this guide is a valuable resource in your journey. We wish you good luck as you continue to excel in the realm of Java programming!