Java is a versatile and powerful programming language widely used in web development, mobile applications, and enterprise solutions. Whether you’re a beginner or an experienced developer, this cheat sheet offers a concise guide to Java’s syntax and essential features. From variables and loops to object-oriented programming and advanced collections, this guide will help you quickly recall Java’s most important concepts.
On This Page
Table of Contents
Java Cheat Sheet: Key Concepts and Syntax
Concept | Syntax | Example / Notes |
---|---|---|
Basic Structure | public class ClassName { public static void main(String[] args) { } } | A simple Java program starts with a main method. |
Variable Declaration | datatype variableName = value; | int age = 25; |
Primitive Data Types | int , double , char , boolean , etc. | int num = 10; double pi = 3.14; char letter = 'A'; boolean flag = true; |
String | String str = "Hello"; | Strings are objects; use methods like .length() , .charAt() , .substring() . |
Operators | + , - , * , / , % , == , != , > , < , etc. | Arithmetic, relational, and logical operators are used for calculations and comparisons. |
Conditional Statement | if (condition) { } else { } | if (x > 10) { } else { } |
Switch Case | switch (variable) { case value: break; default: } | Useful for multiple conditions: switch (day) { case 1: break; } |
Loops | for , while , do-while | for (int i = 0; i < 5; i++) { } |
Enhanced for Loop | for (datatype item : array) { } | Iterate over arrays or collections: for (String s : list) { } |
Arrays | datatype[] arr = new datatype[size]; | int[] nums = {1, 2, 3}; |
ArrayList | ArrayList<Type> list = new ArrayList<>(); | list.add("Item"); Use methods like .add() , .get() , .remove() , .size() . |
HashMap | HashMap<KeyType, ValueType> map = new HashMap<>(); | map.put("Key", "Value"); Retrieve with map.get(key); . |
Method Declaration | returnType methodName(parameters) { } | public int add(int a, int b) { return a + b; } |
Class Declaration | public class ClassName { } | Classes are blueprints for objects. |
Object Creation | ClassName obj = new ClassName(); | Person person = new Person(); |
Constructor | public ClassName() { } | Special method for initializing objects. |
Inheritance | class SubClass extends SuperClass { } | Subclass inherits properties/methods from superclass. |
Polymorphism | method overriding and method overloading | Overriding: redefine a method in a subclass. Overloading: multiple methods with the same name. |
Abstract Class | abstract class ClassName { abstract void method(); } | Cannot instantiate; use for common design logic. |
Interface | interface InterfaceName { void method(); } | Use implements to inherit: class ClassName implements InterfaceName { } . |
Encapsulation | private variable with getter and setter methods | Example: private int age; public int getAge() { return age; } |
Exception Handling | try { } catch(Exception e) { } finally { } | Handle runtime errors. Use finally for cleanup code. |
Checked Exception | throws ExceptionType | Example: public void readFile() throws IOException { } . |
Unchecked Exception | Example: NullPointerException | Runtime exceptions that don’t require handling. |
File Handling | File file = new File("file.txt"); | Use FileReader and BufferedReader for reading files. |
Threads | Thread t = new Thread(); | Use start() to run threads. |
Lambda Expressions | (parameters) -> expression | list.forEach(item -> System.out.println(item)); |
Streams | list.stream().filter(x -> x > 10).collect(Collectors.toList()); | Operate on collections with functional programming style. |
Generics | <T> | List<T> ensures type safety. |
Static Method | static returnType methodName() { } | Call without object: ClassName.methodName(); . |
Final Keyword | final variable , final method , final class | Prevent modifications to variables, methods, or classes. |
Annotations | @Override , @Deprecated , @FunctionalInterface | Metadata for methods and classes. |
Packages | package packageName; | Organize code into namespaces: import packageName.ClassName; . |
Java Collections Framework | List , Set , Map | Examples: ArrayList , HashSet , HashMap . |
Inner Class | class Outer { class Inner { } } | Use to logically group classes that are only used in one place. |
Static Inner Class | static class Inner { } | Can be accessed without creating an instance of the outer class. |
Serialization | implements Serializable | Persist objects to files or streams. |
Reflection | Class<?> c = Class.forName("ClassName"); | Inspect or modify runtime behavior of classes, methods, etc. |
JDBC | DriverManager.getConnection(url, user, password); | Connect to databases using Java Database Connectivity (JDBC). |
Spring Framework | @Controller , @Service , @Repository | Annotations used in Spring for web development and dependency injection. |
Logging | Logger logger = Logger.getLogger(ClassName.class); | Use log.info("Message"); to log messages. |
JUnit Testing | @Test | Annotate test methods in JUnit for automated testing. |
In Closing
Java remains one of the most robust and versatile programming languages for developers. This cheat sheet captures its essential concepts, syntax, and usage examples, making it a handy reference for everyday programming tasks. Whether you’re working on beginner-level projects or tackling advanced enterprise applications, these Java fundamentals will keep you productive and efficient.
Keep this guide bookmarked, and never miss a beat in your Java journey!
FAQs
What is the difference between ==
and .equals()
in Java?
==
checks if two object references point to the same memory location.
.equals()
checks if two objects are logically equivalent, often comparing their values.
What are Java’s main Object-Oriented Programming (OOP) principles?
The four key principles are:
Encapsulation: Hiding data using private fields and providing access through methods.
Inheritance: Reusing code by deriving classes from parent classes.
Polymorphism: Allowing methods to behave differently based on context (overloading and overriding).
Abstraction: Defining abstract classes or interfaces for implementation details.
What is the role of the final
keyword in Java?
Final variable: Its value cannot be changed once assigned.
Final method: Cannot be overridden by subclasses.
Final class: Cannot be subclassed.
What is the Java Collections Framework?
The Java Collections Framework provides data structures like List
, Set
, and Map
.
List: Ordered collection (e.g., ArrayList
, LinkedList
).
Set: No duplicate elements (e.g., HashSet
, TreeSet
).
Map: Key-value pairs (e.g., HashMap
, TreeMap
).
What is garbage collection in Java?
Garbage collection is an automatic memory management feature in Java. It removes objects that are no longer referenced, freeing up memory for other processes. You can suggest garbage collection with System.gc()
, but it is managed by the JVM.
What is the difference between String
, StringBuilder
, and StringBuffer
?
String: Immutable sequence of characters.
StringBuilder: Mutable, fast, not thread-safe.
StringBuffer: Mutable, slower, thread-safe.
What is multithreading in Java?
Multithreading allows concurrent execution of two or more threads to perform tasks simultaneously.
Use Thread
class or implement Runnable
interface.
Methods: start()
, run()
, sleep()
, join()
.
What is the purpose of Java’s try-with-resources
?
The try-with-resources
statement ensures that resources like files or sockets are closed automatically after use.
Example:try (
BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
System.out.println(br.readLine());
}
What is the difference between checked and unchecked exceptions?
Checked exceptions: Must be handled during compilation (e.g., IOException
, SQLException
).
Unchecked exceptions: Occur during runtime and don’t need explicit handling (e.g., NullPointerException
, ArithmeticException
).
What is the significance of the static
keyword in Java?
Static variable: Shared among all instances of a class.
Static method: Called without creating an instance of the class.
Static block: Executes once when the class is loaded.
Example:class Example {
static int count = 0;
static void showCount() {
System.out.println(count);
}
}
+ There are no comments
Add yours