Java Cheat Sheet

Java Cheat Sheet: A Quick Reference

April 3rd, 2026
2074
10:00 Minutes

Struggling to understand Java syntax or want to understand the newly introduced features? You are not alone. Many individuals find Java overwhelming at first because of its strict rules and structure. But once you get familiar with the basics, Java becomes one of the simplest and most reliable languages to learn. It helps you organize logic, automate tasks, and build applications with confidence.

This Java cheat sheet guides you step by step, with clear explanations and real examples. It also provides everything you need to know about the latest Java features. It is your practical tool to get started or learn everything about Java programming.

Who is This Java Cheat Sheet for?

  • Beginners learning programming for the first time
  • Students preparing assignments or projects
  • Developers shifting from other languages
  • Anyone preparing for coding interviews
  • Professionals who want a quick refresher

What is Java?

Java is a powerful, general-purpose programming language known for its reliability, security, and ability to run on almost any device. It follows the idea “Write Once, Run Anywhere,” meaning you can write a program once and run it across multiple operating systems because Java uses the JVM (Java Virtual Machine) to execute code.

It is widely used in Android apps, backend systems, finance applications, enterprise software, and automation tools. Java gives you structure, clarity, and strong foundations that make learning other languages easier later.

Example of Java Hello World Program

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Installing and Running Java

You need the Java Development Kit to compile and run programs. And guess what, the Java installation is more easy then you can imagine. We have explained the complete installation process in our Java Installation Guide. After installation, you write your code, compile it using javac, and run it using java. These steps help you understand exactly how Java executes your program.

Example

javac Hello.java   // compile
java Hello         // run

Java Program Structure

Every Java program begins with a class and a main() method. The class acts like a blueprint, and the main() method is where your program starts running. The structure is simple, and once you understand it, everything else becomes easier.

Example of Basic Java Program

public class App {
    public static void main(String[] args) {
        System.out.println("Program Started");
    }
}

Java Data Types

Java has two categories of data types, including primitive types and non-primitive types. Primitive types store simple values. Non-primitive types store complex data like strings, arrays, or objects.

Primitive Data Types in Java

TypeDescriptionExample
intStores whole numbersint age = 25;
doubleStores decimal numbersdouble price = 99.5;
booleanStores true/false valuesboolean isOpen = true;
charStores a single characterchar grade = 'A';
longStores large whole numberslong views = 100000L;
floatStores floating values (smaller than double)float temp = 25.6f;
byteStores tiny numbers (1 byte)byte level = 3;
shortStores small whole numbersshort count = 120;

Non-Primitive Data Types in Java

TypeDescriptionExample
StringStores textString name = "Amit";
ArrayStores multiple valuesint[] nums = {1,2,3};
ClassCreates custom objectsStudent s = new Student();
InterfaceBlueprint for classesRunnable r = ...

Variables in Java

ActionDescriptionExample
Declare variableCreates a space in memoryint x;
InitializeAssigns a valuex = 10;
Declare + initializeCombines bothint age = 20;
ConstantValue cannot changefinal double PI = 3.14;

Conditional Statements

Now comes conditional statements. These are the most important parts of any programming language. Do you know why? Conditions help your program make decisions. They are essential for input validation, comparisons, calculations, and business logic.

Example on Using Conditional Statements in Java

int score = 85;

if (score >= 90) {
System.out.println("A");
} else {
System.out.println("Not A");
}

Loops (for, while, for-each)

Loops are another important aspect of programming. Imagine you write a code for a task and now you do not have to do it again and again. Not exactly the automation, but kind of. They help you repeat tasks automatically. They are used in calculations, arrays, file processing, and data handling.

Loop Data Types

Loop TypeWhen to UseExample
forWhen number of iterations is knownfor(int i=0;i<5;i++)
whileRepeat until condition becomes falsewhile(x < 10)
do-whileRun at least once before checking conditiondo { } while();
for-eachLoop through collections or arraysfor(String s : names)

Methods (Functions)

Think of Methods or Functions as a cousin of Loops. They also allow you to reuse code and keep your program organized. They improve readability and help divide large tasks into smaller parts. Here is an example how these are used:

Example

public static int add(int a, int b) {
    return a + b;
}

OOP Concepts (Very Beginner-Friendly)

Java uses Object-Oriented Programming to structure applications. The OOP has four pillars that make your code cleaner and easier to scale. It is one of the essential concepts for any developer in any industry.

The Four Pillar of OPP in Java

ConceptMeaningWhy It Matters
EncapsulationHide data using private fields + getters/settersProtects data and reduces mistakes
InheritanceOne class inherits features from anotherReuse code without rewriting
PolymorphismOne action behaves differently based on objectFlexible and extendable programs
AbstractionShow only essential detailsRemoves complexity and focuses on purpose

Example on Using OOP in Java

class Animal { public void sound() { System.out.println("Sound..."); } }

class Dog extends Animal {
public void sound() {
System.out.println("Bark");
}
}

Arrays & Collections in Java

You might be familiar with arrays and collections, if you are from a technical background. Don’t worry, if you are not. It is an easy topic. Arrays store fixed-size lists. Collections grow automatically and are used everywhere in real applications.

Array Operations

ActionDefinitionExample
AccessRetrieve elementarr[1]
LengthCount itemsarr.length
LoopProcess all valuesfor(int n : arr)

Common Collection Types in Java Programming

TypeDescriptionExample
ArrayListResizable listnew ArrayList<>();
HashMapKey-value pairsmap.put("Amit", 25);
HashSetStores unique itemsnew HashSet<>();

Error Handling (try-catch)

Error handling in Java is the process of anticipating, detecting, and resolving errors and exceptions that can occur during the execution of a program. Its main goal is to prevent a program from crashing and to ensure it can recover gracefully or provide meaningful feedback to the user. Do you know how it works? Java uses try-catch blocks to prevent your program from crashing due to unexpected issues like invalid input or missing files.

Example

try {
    int x = 10 / 0;
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

Constructors in Java

Constructors in Java initialize objects when they are created. They look like methods but have the same name as the class and no return type. Constructors set starting values, allocate memory, and prepare objects for use. They matter in real-life situations like creating student profiles, user accounts, product items, or any component with initial data.

Constructors help beginners understand how objects live and behave. Many new learners confuse constructors with methods, but remembering that constructors run automatically during object creation makes them easier to grasp.

Example

class Student { String name; int age;
Student(String n, int a) {
    name = n;
    age = a;
}


}

Types of Constructors

TypeMeaningExample
DefaultProvided automatically by JavaStudent s = new Student();
ParameterizedCreated with your own inputsnew Student("Amit", 21)

Strings in Java

Strings in Java represent text such as names, messages, city names, or user input. They are extremely common because almost every application displays or processes text. Strings are easy to use but remain immutable, which means once created, the original value cannot be changed. This protects your data and avoids unexpected behavior.

Strings matter in real tasks like message formatting, user input analysis, data cleaning, text extraction, and search functionality. Beginners sometimes forget that Strings behave differently from numbers, but with a few examples, the concept becomes simple.

Example

String city = "mumbai";
System.out.println(city.toUpperCase());

Common String Operations

ActionDefinitionExample
LengthCount characterss.length()
UppercaseConvert texts.toUpperCase()
SubstringExtract parts.substring(0,4)
ReplaceChange characterss.replace("a","o")
SplitBreak texts.split(",")

Exceptions in Java

Exceptions in Java help you catch errors without crashing your program. Real-world applications face unpredictable issues such as missing files, wrong inputs, network failures, or invalid numbers. Exceptions allow you to handle these gracefully and keep your program stable.

Beginners often get scared when they see error messages, but exceptions actually protect your program. Once you write your first try–catch block, the entire idea becomes easier.

Example

try {
    int n = 10 / 0;
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
}

Exception Types

TypeMeaningExample
CheckedMust be handledIOException
UncheckedOccur at runtimeNullPointerException
CustomCreated by youclass MyError extends Exception {}

Access Modifiers in Java

Access modifiers in Java define who can use your classes, methods, and variables. They help you control visibility and protect sensitive data. At first, these keywords may feel confusing because they look similar, but each one plays a different role in keeping your program organized and safe. Access levels matter in real projects where multiple developers work together or when you build large applications that must hide internal details.

Using access modifiers properly also prevents accidental changes, improves readability, and keeps your classes clean. Beginners often struggle with the idea of "who can access what," but once you understand the four levels, the rules become simple and predictable.

Example

public class BankAccount {
    private double balance;
}

Access Modifiers Table

ModifierDefinitionWhere It Can Be Accessed
publicOpen to everyoneAnywhere in the project
privateFully restrictedOnly inside the same class
protectedSemi-privateSame package + subclasses
default (no keyword)Package-only accessSame package only

Keywords in Java

Keywords in Java are special words that have fixed meanings in the language. You cannot use them as variable names or method names. These keywords control behavior like object creation, inheritance, method return values, and constant creation. Learning them helps you read Java code confidently and understand what each part is doing.

Keywords matter because they define the structure of your program. They tell Java what to do, how to treat information, and how to behave at runtime. Beginners sometimes remember keywords slowly, but once you start writing small programs, they become second nature.

Example

final int MAX = 100;

Important Java Keywords

KeywordMeaningExample Snippet
staticBelongs to the classstatic int count;
finalCannot be changedfinal double PI = 3.14;
thisRefers to current objectthis.name = name;
superRefers to parent classsuper.showInfo();
returnSends value backreturn result;
newCreates new objectsnew Student();

File Handling in Java

File handling in Java allows you to read, write, and process files such as logs, text files, reports, and configuration data. Most real applications interact with files at some point, whether you are saving user data, reading product listings, or exporting reports. Java provides simple methods that make file access easier for beginners while still keeping the process safe.

File handling matters because data often lives outside the code. You may need to load values from a text file, write logs for debugging, or export results after processing. Many beginners feel nervous about file operations, but with a few examples, it becomes straightforward.

Example

String data = Files.readString(Path.of("notes.txt"));
System.out.println(data);

Java File Handling Actions

ActionMeaningExample Snippet
Read fileLoad file contentFiles.readString(path);
Write fileCreate or update fileFiles.write(path, data.getBytes());
Check if existsVerify file presenceFiles.exists(path);
Delete fileRemove fileFiles.delete(path);

New Java Features Added in the Last Year

Java continues to evolve with features that make coding simpler, faster, and more expressive. The latest releases focused on readability, performance, and smarter patterns. These updates help beginners write cleaner code with fewer mistakes.

Key New Features (Java 21 → Java 22)

FeatureMeaningWhy It Helps
Unnamed Variables (_)Ignore unused variablesCleaner method signatures
Unnamed ClassesWrite simple programs fasterPerfect for beginners
Pattern Matching EnhancementsSmarter type checksLess boilerplate code
Record PatternsExtract components easilyGreat for data handling
Sequenced CollectionsOrdered iteration for all listsMore predictable behavior
Virtual ThreadsExtremely lightweight threadsFaster concurrency

Practice Problems

Learning Java becomes easier when you practice small, focused problems that build confidence. These tasks help you apply loops, strings, methods, classes, file handling, and basic logic. They also prepare you for assignments and coding interviews by improving your clarity and speed. Try these simple but useful problems:

  1. Create a method that returns the square of a number.
  2. Write a program that checks if a word is a palindrome.
  3. Read a text file and print the number of lines it contains.
  4. Create a class Employee with fields name and salary, then print both values using a constructor.
  5. Write a program that counts how many times a character appears in a string.
  6. Use a loop to print numbers from 1 to 50 that are divisible by 3.
  7. Create a list of five names and display only those with more than four letters.
  8. Save a short message to a file named message.txt.
  9. Create a simple calculator using methods for add, subtract, multiply, and divide.
  10. Store product prices in a map and print the highest price.

Wrapping Up

Java is one of the most stable and widely used programming languages. It teaches discipline, clean structure, and powerful logic building. With this Java cheat sheet, you now have a beginner-friendly roadmap to start writing simple programs, experimenting with conditions, loops, OOP, arrays, and collections.

The more you practice, the faster Java becomes comfortable. Try writing small programs daily, reuse methods, explore object creation, and solve simple problems to sharpen your skills. Java becomes easier with every line of code you write.

FAQs

1. Is Java hard for beginners?

Not really. It looks strict at first, but once you learn the basics, Java becomes predictable and easy to read.

2. Do I need to start with OOP immediately?

No. Start with variables, conditions, loops, and methods. OOP becomes easier once the basics are strong.

3. Is Java good for jobs?

Yes. Java is used in finance, healthcare, enterprise companies, Android development, and backend systems. Learning it builds long-term career opportunities.

Articles You Can Also Read:

Course Schedule

Course NameBatch TypeDetails
Java TrainingEvery WeekdayView Details
Java TrainingEvery WeekendView Details
About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.