Core Java Cheatsheet
Core Java Cheatsheet
Core Java
TABLE OF CONTENTS
Preface 1
Introduction 1
Java Keywords 1
Java Packages 3
Java Operators 4
Primitive Types 4
Lambda Expressions 5
Functional Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Method References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Collections 6
ArrayList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
LinkedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
HashSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
TreeSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
HashMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
TreeMap. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
LinkedHashMap. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Queue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
PriorityQueue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Character Escape Sequences 9
Output Formatting With printf 9
Regular Expressions 9
Matching Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Logging 11
Property Files 12
javac command 13
jar command 14
java command 14
Popular 3rd party Java Libraries 15
PREFACE
PREFACE Keyword Meaning Example
catch Used to catch try { /…/ }
This cheatsheet is designed to provide you with
exceptions catch
concise and practical information on the core (Exception e) {
concepts and syntax of Java. It’s intended to serve /…/ }
as a handy reference that you can keep at your char Data type for char grade =
desk, save on your device, or print out and pin to 'A';
character data
your wall.
class Declares a class class MyClass {
/…/ }
INTRODUCTION
INTRODUCTION
continue Skips the for (int i = 0;
current i < 5; i++) {
Java is one of the most popular programming if (i == 3)
languages in the world, used in million of devices iteration in a continue; }
from servers and workstations to tablets, mobile loop
phones and wearables. With this cheatsheet we default Used in a switch (day) {
strive to provide the main concepts and key aspects switch case 1: /…/
of the Java programming language. We include default: /…/ }
statement
details on core language features such as lambda
do Starts a do- do { /…/ }
expressions, collections, formatted output, regular
while loop while
expressions, logging, properties as well as the most (condition);
commonly used tools to compile, package and
double Data type for double pi =
execute java programs. 3.14159265359;
double-
precision
JAVAKEYWORDS
JAVA KEYWORDS
floating-point
numbers
Let’s start with the basics, what follows is a list
else Used in an if- if (x > 5) {
containing some of the most commonly used Java
else statement /…/ } else {
keywords, their meanings, and short examples. /…/ }
Please note that this is not an exhaustive list of all
enum Declares an enum Day {
Java keywords, but it covers many of the commonly
enumerated MONDAY,
used ones. So be sure to consult the documentation TUESDAY,
for the most up-to-date information. type WEDNESDAY }
extends Indicates class
Keyword Meaning Example inheritance in a ChildClass
extends
abstract Used to declare abstract class class ParentClass {
abstract classes Shape { /…/ } /…/ }
assert Used for testing assert (x > 0) final Used to make a final int
: "x is not variable or maxAttempts =
assertions
positive"; 3;
method final
boolean Data type for boolean
isJavaFun = finally Used in try { /…/ }
true/false catch
true; exception
values (Exception e) {
handling /…/ } finally
break Used to exit a for (int i = 0;
{ /…/ }
loop or switch i < 5; i++) {
if (i == 3) float Data type for float price =
statement break; } single-precision 19.99f;
byte Data type for 8- byte b = 42; floating-point
bit integers numbers
case Used in a switch (day) { for Starts a for loop for (int i = 0;
case 1: /…/ i < 5; i++) {
switch
break; } /…/ }
statement
JAVA
JAVAPACKAGES
PACKAGES Package Description
java.sql Provides classes for
In Java, a package is a mechanism for organizing
and grouping related classes and interfaces into a database access using
single namespace. Below you can find some of the JDBC (Java Database
most commonly used and the functionality their Connectivity).
classes provide. Java has a rich ecosystem of java.util.concurrent Contains classes and
libraries and frameworks, so the packages you use interfaces for handling
may vary depending on your specific application or concurrency, including
project. Remember to import the necessary thread management and
packages at the beginning of your Java classes to synchronization
access their functionality. (Executor, Semaphore).
java.nio New I/O (NIO) package
Package Description
for efficient I/O
java.lang Provides fundamental operations, including
classes (e.g., String, non-blocking I/O and
Object) and is memory-mapped files
automatically imported (ByteBuffer,
into all Java programs. FileChannel).
java.util Contains utility classes java.text Offers classes for text
for data structures (e.g., formatting (DateFormat,
ArrayList, HashMap), NumberFormat) and
date/time handling ( parsing.
Date, Calendar), and
java.security Provides classes for
more.
implementing security
java.io Provides classes for features like encryption,
input and output authentication, and
operations, including permissions.
reading/writing files
java.math Contains classes for
(FileInputStream,
arbitrary-precision
FileOutputStream) and
arithmetic (BigInteger,
streams (InputStream,
BigDecimal).
OutputStream).
java.util.regex Supports regular
java.net Used for network
expressions for pattern
programming, including
matching (Pattern,
classes for creating and
Matcher).
managing network
connections (Socket, java.awt.event Event handling in AWT,
ServerSocket). used to handle user-
generated events such
java.awt Abstract Window
as button clicks and key
Toolkit (AWT) for
presses.
building graphical user
interfaces (GUIs) in java.util.stream Introduces the Stream
desktop applications. API for processing
collections of data in a
javax.swing Part of the Swing
functional and
framework, an
declarative way.
advanced GUI toolkit for
building modern,
platform-independent
desktop applications.
javax.servlet Contains classes and << >> >>> x << 1, x >> 2, x Bitwise left
interfaces for building >>> 3 shift, right shift
Java-based web (with sign
applications using the extension), and
Servlet API. right shift (zero
extension).
javax.xml Offers XML processing
capabilities, including < <= > >= x < y, x <= y, x Relational
parsing, validation, and > y, x >= y operators for
transformation. comparisons.
== != x == y, x != y Equality and
JAVAOPERATORS
JAVA OPERATORS inequality
comparisons.
Operators are a cornerstone aspect to every & x & y Bitwise AND.
programming language. They allow you to
^ x ^ y Bitwise XOR
manipulate data, perform calculations, and make
decisions in your programs. Java provides a wide (exclusive OR).
range of operators. Following are the ones most && x && y Conditional
commonly used. The descriptions provide a brief AND (short-
overview of their purposes and usage. The circuit).
operators at the top of the table have higher
? : result = (x > Conditional
precedence, meaning they are evaluated first in
y) ? x : y (Ternary)
expressions. Operators with the same precedence
level are evaluated left to right. Be sure to use Operator.
parentheses to clarify the order of evaluation when = x = y Assignment
needed. operator.
+= -= *= /= %= x += y, x -= y, x Compound
Operator Example Description
*= y, x /= y, x assignment
() (x + y) Parentheses for %= y operators.
grouping
<<= >>= >>>= x <<= 1, x >>= Compound
expressions.
2, x >>>= 3 assignment
++ -- x++, --y Increment and with bitwise
decrement shifts.
operators.
types are built into the language itself and are not LAMBDA
LAMBDAEXPRESSIONS
EXPRESSIONS
objects like instances of classes and reference types.
Java’s primitive types are designed for efficiency Lambda expressions provide a way to define small,
and are used to store basic values in memory. self-contained, and unnamed functions
Below is a table listing all of Java’s primitive data (anonymous functions) right where they are needed
types, their size in bytes, their range, and some in your code. They are primarily used with
additional notes. Keep in mind that you can convert functional interfaces, which are interfaces with a
from byte to short, short to int, char to int, int to single abstract method. Lambda expressions
long, int to double and float to double without provide a way to implement the abstract method of
loosing precision since the source type is smaller in such interfaces without explicitly defining a
size compared to the target one. On the other hand separate class or method.
converting from int to float, long to float or long to
double may come with a precision loss. The syntax for lambda expressions is concise and
consists of parameters surrounded by parenthesis
Data Type Size Range Notes (()), an arrow (→), and a body. The body can be an
(bytes) expression or a block of code.
Calculator subtraction = (a, b) -> a your specific requirements, you can choose the
- b; appropriate one to suit your data storage and
retrieval needs.
int result2 = subtraction.calculate
(10, 4);
System.out.println("Subtraction: " + ARRAYLIST
result2); // Output: Subtraction: 6
An array-based list that dynamically resizes as
elements are added or removed.
METHOD REFERENCES
// Create an ArrayList and add
Method references provide a concise way to
elements.
reference static methods, constructors, or instance
methods of objects, pass them as method
List<String> names = new
parameters or return them, much like anonymous ArrayList<>();
functions; making your code more readable and names.add("Alice");
expressive when working with functional names.add("Bob");
interfaces. Let’s update the calculator example to
use method references: // Iterate through the ArrayList.
for (String name : names) { /*...*/
}
public class
MethodReferenceCalculator {
// Add an element by index.
// A static method that performs
names.set(i, "Charlie");
addition
public static int add(int a, int
// Remove an element by index.
b) {
names.remove(0);
return a + b;
}
// Add multiple elements using
addAll.
public static void main(String[]
names.addAll(Arrays.asList("David",
args) {
"Eve"));
// Using a method reference
to the static add method
// Remove multiple elements using
Calculator addition =
removeAll.
MethodReferenceCalculator::add;
names.removeAll(Arrays.asList("Alice
", "Bob"));
int result = addition
.calculate(5, 3);
// Retrieve an element by index.
System.out.println("Addition
String firstPerson = names.get(0);
result: " + result); // Output:
Addition result: 8
// Convert ArrayList to an array.
}
String[] namesArray = names.toArray
}
(new String[0]);
COLLECTIONS
COLLECTIONS
// Convert an array to an ArrayList.
List<String> namesList = Arrays
Collections play a pivotal role in Java development. .asList(namesArray);
Following are some of the most commonly used
collection implementation classes along with code // Sort elements in natural order.
snippets illustrating typical use cases. Depending on Collections.sort(names);
PRIORITYQUEUE
String name = "Alice";
A priority-based queue, where elements are
dequeued based on their priority. int age = 30;
double salary = 55000.75;
boolean married = true;
// Use a PriorityQueue to offer and
poll elements based on priority. // Format and print using printf.
PriorityQueue<Integer> priorityQueue The %n specifier is used to insert a
= new PriorityQueue<>(); platform-specific newline character
priorityQueue.offer(3); System.out.printf("Name: %s%n",
priorityQueue.offer(1); name); // %s for String
int highestPriority = priorityQueue System.out.printf("Age: %d%n", age);
.poll(); // %d for int
System.out.printf("Salary: %.2f%n",
salary); // %.2f for double with 2
CHARACTERESCAPE
CHARACTER ESCAPESEQUENCES
SEQUENCES
decimal places
System.out.printf("Married: %b%n",
Character escape sequences are used to represent
special characters in Java strings. For example, \" is
married); // %b for boolean
used to include a double quote within a string, and
\n represents a newline character. The \uXXXX
REGULAREXPRESSIONS
REGULAR EXPRESSIONS
escape sequence allows you to specify a Unicode
character by its hexadecimal code point. Below are
Regular expressions are powerful tools for pattern
some of the most common Character escape
matching and text manipulation. Below are some
sequences in Java.
typical use cases.
An example logging configuration file is provided • Properties files typically use the .properties file
below. extension.
when reading properties. Below are some of the most commonly used options
with the javac command. They allow you to
• Whitespace characters (spaces and tabs) before
customize the compilation process, specify source
and after the key and value are ignored.
and target versions, control error handling, and
• You can escape special characters like spaces, manage classpaths and source file locations. You
colons, and equals signs using a backslash (\). can use these options to tailor the compilation of
your Java code to your project’s specific
Below is an example of loading and storing data in requirements.
a properties file programmatically.
Option Description
• Jar files can contain both executable (class files J<option> Passes options to the
with a main method) and non-executable underlying Java VM
(resources, libraries) components. when running the jar
command.
• A special file called META-INF/MANIFEST.MF can be
included in a jar file. It contains metadata
about the jar file, such as its main class and JAVACOMMAND
JAVA COMMAND
version information.
The java command is used to run Java applications
• Java provides command-line tools like jar and
and execute bytecode files (compiled Java
jarsigner to create, extract, and sign jar files.
programs) on the Java Virtual Machine (JVM). It
Below is a table with some common jar command serves as the primary entry point for launching and
JCG delivers over 1 million pages each month to more than 700K software
developers, architects and decision makers. JCG offers something for everyone,
including news, tutorials, cheat sheets, research guides, feature articles, source code
and more.
CHEATSHEET FEEDBACK
WELCOME
support@javacodegeeks.com
Copyright © 2014 Exelixis Media P.C. All rights reserved. No part of this publication may be SPONSORSHIP
reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, OPPORTUNITIES
mechanical, photocopying, or otherwise, without prior written permission of the publisher. sales@javacodegeeks.com