You are on page 1of 17

CORE JAVA

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

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


1 CORE JAVA

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

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


2 CORE JAVA

Keyword Meaning Example Keyword Meaning Example


if Conditional if (x > 5) { static Indicates a static int
statement /…/ } static member count = 0;

implements Implements an class MyClass strictfp Ensures strict strictfp void


interface in a implements floating-point myMethod() {
MyInterface { /…/ }
class /…/ } precision

import super Calls a super();


Used to import import
packages and java.util.Array superclass
List; constructor/met
classes
hod
instanceof Checks if an if (obj
instanceof switch Starts a switch switch (day) {
object is an
MyClass) { /…/ statement case 1: /…/ }
instance of a }
class synchronized Ensures thread synchronized
safety void myMethod()
int Data type for int count = 42;
{ /…/ }
integers
this Refers to the this.name =
interface Declares an interface current name;
interface MyInterface {
/…/ } instance

long throw Throws an throw new


Data type for long bigNumber
= 1234567890L; exception Exception("Some
long integers thing went
native wrong.");
Used in native native void
method myMethod(); throws Declares void myMethod()
declarations exceptions throws
MyException {
new thrown by a
Creates a new MyClass obj = /…/ }
new MyClass(); method
object
transient Used with transient int
null Represents the Object obj =
object sessionId;
absence of a null;
serialization
value
try Starts an try { /…/ }
package Declares a Java package
exception- catch
package com.example.mya
(Exception e) {
pp; handling block /…/ }
private Access modifier private int void Denotes a public void
for private age;
method that doSomething() {
members /…/ }
returns no
protected Access modifier protected value
for protected String name;
volatile Indicates that a volatile int
members
variable may be sharedVar;
public Access modifier public void modified by
for public displayInfo() { multiple
/…/ }
members threads

return Returns a value return result; while Starts a loop while


(in.hasNext())
from a method
process(in.next
short Data type for short ());
short integers smallNumber =
100;

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


3 CORE JAVA

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.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


4 CORE JAVA

Package Description Operator Example Description


java.time The Java Date and Time */% x * y, x / y, x % Multiplication,
API introduced in Java 8, y division, and
for modern date and modulo.
time handling (
+ (unary) +x, -y Unary plus and
LocalDate, Instant,
minus.
DateTimeFormatter).
! !flag Logical NOT
java.util.logging Provides a logging
(negation).
framework for
recording application ~ ~x Bitwise NOT
log messages. (complement).

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.

+- x + y, x - y Addition and PRIMITIVETYPES


PRIMITIVE TYPES
subtraction.
In Java, primitive types (also known as primitive
data types or simply primitives) are the simplest
data types used to represent single values. These

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


5 CORE JAVA

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.

byte 1 -128 to 127 Used for


small // Using a lambda expression to
integer define a Runnable
values. Runnable runnable = () -> System.
short 2 -32,768 to Useful for out.println("Hello, Lambda!");
32,767 integers
within this
range. FUNCTIONAL INTERFACES
int 4 -2^31 to Commonly
A functional interface is an interface that has
2^31 - 1 used for
exactly one abstract method, which is used to
integer
define a single unit of behavior. Below is an
arithmetic.
example of such an interface:
long 8 -2^63 to Used for
2^63 - 1 larger
integer @FunctionalInterface
values. interface Calculator {
float
int calculate(int a, int b);
4 Approxima Floating-
}
tely point with
±3.4028234 single
7E+38 precision. Implementations of this interface can be supplied
double 8 Approxima Floating- in-line as a lambda expression, as shown below:
tely point with
±1.7976931 double
348623157 precision.
// Using a lambda expression to
E+308 define addition
Calculator addition = (a, b) -> a +
char 2 0 to 65,535 Represents
b;
(Unicode a single
int result1 = addition.calculate(5,
characters) character.
3);
boolean true or Represents System.out.println("Addition: " +
false true/false
result1); // Output: Addition: 8
values.

// Using a lambda expression to


define subtraction

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


6 CORE JAVA

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);

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


7 CORE JAVA

// Sort elements using a custom // Iterate through the HashSet.


comparator. for (String word : uniqueWords) {
Collections.sort(names, new /*...*/ }
Comparator<String>() { public int
compare(String a, String b) { return // Remove an element from the
a.length() - b.length(); } }); HashSet.
uniqueWords.remove("apple");
// Do something with all elements in
the collection // Use the Stream API to check if an
names.forEach(System.out::println); element exists.
boolean containsBanana =
// Use the Stream API to filter uniqueWords.stream().anyMatch(word
elements. -> word.equals("banana"));
List<String> filteredNames = names
.stream().filter(name -> name
.startsWith("A")).collect(Collectors TREESET
.toList()); A sorted set that stores elements in natural order or
according to a specified comparator.
// Use the Stream API to perform
calculations on elements (e.g., sum
of lengths). // Create a TreeSet and add elements
int sumOfLengths = names.stream (sorted automatically).
().mapToInt(String::length).sum(); TreeSet<Integer> sortedNumbers = new
TreeSet<>();
sortedNumbers.add(3);
LINKEDLIST sortedNumbers.add(1);
sortedNumbers.add(2);
A doubly-linked list that allows efficient insertion
and removal from both ends.
// Iterate through the TreeSet (in
ascending order).
LinkedList<Integer> numbers = new for (Integer number : sortedNumbers)
LinkedList<>(); { /*...*/ }
numbers.addFirst(1);
numbers.addLast(2); // Use the Stream API to find the
numbers.removeFirst(); maximum element.
Optional<Integer> maxNumber =
sortedNumbers.stream().max(Integer::
HASHSET compareTo);

An unordered collection of unique elements,


implemented using a hash table. HASHMAP

An unordered collection of key-value pairs,


// Create a HashSet and add unique implemented using a hash table.
elements.
HashSet<String> uniqueWords = new
HashSet<>(); // Create a HashMap and add key-
uniqueWords.add("apple"); value pairs.
uniqueWords.add("banana"); HashMap<String, Integer> ageMap =

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


8 CORE JAVA

new HashMap<>(); LINKEDHASHMAP


ageMap.put("Alice", 25);
A map that maintains the order of insertion while
ageMap.put("Bob", 30);
still providing hash table efficiency.

// Iterate through the HashMap key-


value pairs. // Create a LinkedHashMap and add
for (Map.Entry<String, Integer> key-value pairs (maintains insertion
entry : ageMap.entrySet()) { /*...*/ order).
} LinkedHashMap<String, Integer>
orderMap = new LinkedHashMap<>();
// Remove a key-value pair by key. orderMap.put("First", 1);
ageMap.remove("Alice"); orderMap.put("Second", 2);

// Use the Stream API to transform // Iterate through the LinkedHashMap


key-value pairs. key-value pairs (in insertion
Map<String, Integer> doubledAgeMap = order).
ageMap.entrySet().stream().collect(C for (Map.Entry<String, Integer>
ollectors.toMap(Map.Entry::getKey, entry : orderMap.entrySet()) {
entry -> entry.getValue() * 2)); /*...*/ }

// Use the Stream API to extract


TREEMAP keys in insertion order.
List<String> keysInOrder = orderMap
A sorted map that stores key-value pairs in natural
order or according to a specified comparator. .keySet().stream().collect(Collector
s.toList());

// Create a TreeMap and add key-


value pairs (sorted by key). STACK
TreeMap<String, Double> salaryMap =
A data structure that follows the Last-In-First-Out
new TreeMap<>();
(LIFO) principle.
salaryMap.put("Alice", 55000.0);
salaryMap.put("Bob", 60000.0);
// Use a Stack to push and pop
// Iterate through the TreeMap keys elements (LIFO).
(in ascending order). Stack<String> stack = new Stack<>();
for (String name : salaryMap. stack.push("Item 1");
keySet()) { /*...*/ } stack.push("Item 2");
String topItem = stack.pop();
// Iterate through the TreeMap
values (in ascending order of keys).
for (Double salary : salaryMap QUEUE
.values()) { /*...*/ }
A data structure that follows the First-In-First-Out
(FIFO) principle.
// Use the Stream API to calculate
the total salary.
double totalSalary = salaryMap // Use a LinkedList as a Queue to
.values().stream().mapToDouble(Doubl offer and poll elements (FIFO).
e::doubleValue).sum(); Queue<String> queue = new
LinkedList<>();

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


9 CORE JAVA

queue.offer("Task 1"); OUTPUT


OUTPUTFORMATTING
FORMATTINGWITH
WITHPRINTF
PRINTF
queue.offer("Task 2");
Here’s a typical example of output formatting using
String nextTask = queue.poll();
the printf method. For a full list of format specifiers
and flags visit our comprehensive guide here.

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.

Escape Sequence Description


\\ Backslash // Matching a Simple Pattern
\'
String text = "Hello, World!";
Single quote
String pattern = "Hello, .*";
(apostrophe)
boolean matches = text.matches
\" Double quote (pattern);
\n Newline (line feed)
\r Carriage return
// Finding All Email Addresses in a
Text
\t Tab
String text = "Contact us at
\b Backspace john@example.com and jane@test.org
\f Form feed
for assistance.";
String emailPattern =
\uXXXX Unicode character in
"\\b\\S+@\\S+\\.[A-Za-z]+\\b";
hexadecimal format
Pattern pattern = Pattern.compile
(e.g., \u0041 for 'A')
(emailPattern);
Matcher matcher = pattern.matcher
(text);

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


10 CORE JAVA

while (matcher.find()) { Syntax Description


String email = matcher.group(); [^] Defines a negated
// Process or store the found character class, matches
email addresses any one character NOT
} in the specified set. You
can include characters,
// Replacing All Occurrences of a ranges or even
Word character classes. For
String text = "The quick brown fox example, [^0-9] matches
jumps over the lazy dog."; any character that is not
a digit.
String replacedText = text
.replaceAll("fox", "cat"); * Matches the preceding
element zero or more
// Splitting a String into Words times.
String text = "Java is a versatile + Matches the preceding
programming language."; element one or more
String[] words = text.split("\\s+"); times.
? Matches the preceding
// Validating a Date Format element zero or one
String date = "2023-10-05"; time (optional).
String datePattern = "\\d{4}-\\d{2}- {n} Matches the preceding
\\d{2}";
element exactly n times.
boolean isValid = date.matches
{n,} Matches the preceding
(datePattern);
element at least n times.
{n,m} Matches the preceding
Below are some of the most commonly used regular
element between n and m
expression syntax elements in Java.
times (inclusive).

Syntax Description XY Matches any string from


X, followed by any string
. Matches any character
from Y.
except a newline.
X|Y Matches any string from
\t, \n, \r, \f, \a, \e The control characters
X or Y.
tab, newline, return,
form feed, alert, and () Groups expressions
escape. together, enabling
quantifiers to apply to
[] Defines a character
the entire group.
class, matches any one
character from the \ Escapes a
specified set. You can metacharacter, allowing
include characters, you to match characters
ranges or even like '.', '[', ']', etc., literally.
character classes. For ^ Anchors the match at
example, [abc0-9\s&&[^ the beginning of the line
\t]] matches 'a', 'b', 'c', a (or input).
digit or a whitespace
$ Anchors the match at
character that is not
space or tab. the end of the line (or
input).

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


11 CORE JAVA

Syntax Description Flag Description


\b Matches a word Pattern.UNICODE_CASE Enables Unicode case-
boundary. ((?u)) folding.
\B Matches a non-word Pattern.COMMENTS ((?x)) Allows whitespace and
boundary. comments in the pattern
\d for readability.
Matches a digit
(equivalent to [0-9]). Pattern.UNIX_LINES ( Only '\n' is recognized as
\D (?d)) a line terminator when
Matches a non-digit
matching ^ and $ in
(equivalent to [^0-9]).
multiline mode.
\s Matches a whitespace
Pattern.CANON_EQ ((?c)) Matches canonical
character (e.g., space,
equivalence, treating
tab etc. Equivalent to [
composed and
\t\n\r\f\x0B]).
decomposed forms as
\S Matches a non- equivalent.
whitespace character.
Pattern.LITERAL Treats the entire pattern
\w Matches a word as a literal string,
character disabling metacharacter
(alphanumeric or interpretation.
underscore, equivalent
to [a-zA-Z0-9_]).
LOGGING
LOGGING
\W Matches a non-word
character. In Java’s core logging implementation
(java.util.logging), the logging configuration is
specified through a properties file
MATCHING FLAGS
(jre/lib/logging.properties). You can specify
Pattern matching can be adjusted with flags. You another file by using the system
can embed them at the beginning of the pattern of property`java.util.logging.config.file`when running
use them as shown below: your application. Below are some common
properties used in the logging.properties file, along
with their descriptions:
Pattern pattern = Pattern.compile
(patternString, Pattern Property Description
.CASE_INSENSITIVE + Pattern .level Sets the default logging
.UNICODE_CASE) level for all loggers.
handlers Specifies which
Flag Description handlers (output
destinations) to use for
Pattern.CASE_INSENSITIV Enables case-insensitive
log records.
E ((i)) matching.
<logger>.level Defines the log level for
Pattern.MULTILINE ((?m)) Enables multiline mode,
a specific logger.
where ^ and $ match the
java.util.logging.Conso Sets the log level for the
start/end of each line.
leHandler.level ConsoleHandler.
Pattern.DOTALL ((?s)) Enables dotall mode,
java.util.logging.Conso Specifies the formatter
allowing . to match any
leHandler.formatter for log messages sent to
character, including
newlines. the console.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


12 CORE JAVA

Property Description # Handlers specify where log records


are output
java.util.logging.FileH Sets the log level for the
andler.level handlers = java.util.logging
FileHandler (logging to
.ConsoleHandler
files).
java.util.logging.FileH Defines the pattern for
andler.pattern
# Specify the log level for a
log file names.
specific logger
java.util.logging.FileH Specifies the maximum com.example.myapp.MyClass.level =
andler.limit size (in bytes) for each FINE
log file before rolling
over. # ConsoleHandler properties
java.util.logging.FileH Sets the maximum java.util.logging.ConsoleHandler.lev
andler.count number of log files to el = INFO
keep. java.util.logging.ConsoleHandler.for
java.util.logging.FileH Specifies the formatter matter = java.util.logging
andler.formatter for log messages written .SimpleFormatter
to files.
java.util.logging.Simpl Allows customization of # FileHandler properties
eFormatter.format log message format for java.util.logging.FileHandler.level
SimpleFormatter. = ALL
java.util.logging.FileHandler.patter
java.util.logging.Conso Specifies a filter for log
leHandler.filter n = %h/java%u.log
records to be sent to the
java.util.logging.FileHandler.limit
console.
= 50000
java.util.logging.FileH Specifies a filter for log
andler.filter
java.util.logging.FileHandler.count
records to be written to
= 1
files.
java.util.logging.FileHandler.format
java.util.logging.Conso Specifies the character ter = java.util.logging
leHandler.encoding encoding for console .SimpleFormatter
output.
java.util.logging.FileH Specifies the character
andler.encoding encoding for file output.
PROPERTYFILES
PROPERTY FILES
java.util.logging.Conso Defines the error
A properties file is a simple text file used to store
leHandler.errorManager manager for handling
configuration settings or key-value pairs. It is
errors in the
commonly used for configuring applications, as it
ConsoleHandler.
provides a human-readable and editable format.
java.util.logging.FileH Defines the error Properties files are commonly used for application
andler.errorManager manager for handling configuration, internationalization, and other
errors in the scenarios where key-value pairs need to be stored
FileHandler. in a structured and easily editable format.

An example logging configuration file is provided • Properties files typically use the .properties file
below. extension.

• Each line in the properties file represents a key-


value pair. The key and value are separated by
# Set the default logging level for an equal sign (=) or a colon (:).
all loggers
• You can include comments in properties files
.level = INFO
by prefixing a line with a hash (#) or an
exclamation mark (!). Comments are ignored

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


13 CORE JAVA

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

Properties properties = new -classpath or -cp Specifies the location of


Properties(); user-defined classes and
try { packages.
FileInputStream fileInputStream = -d <directory> Specifies the destination
new FileInputStream directory for compiled
("config.properties"); class files.
properties.load(fileInputStream); -source <release> Specifies the version of
fileInputStream.close(); the source code (e.g.,
"1.8" for Java 8).
// Access properties -target <version> Generates class files
String value = properties compatible with the
.getProperty("key"); specified target version
System.out.println("Value for key: (e.g., "1.8").
" + value);
-encoding <charset> Sets the character
encoding for source
// Update properties files.
properties.setProperty("key1",
-verbose Enables verbose output
"value1");
during compilation.
properties.setProperty("key2",
"value2"); -deprecation Shows a warning
FileOutputStream fileOutputStream message for the use of
= new FileOutputStream deprecated classes and
methods.
("config.properties");
properties.store(fileOutputStream, -nowarn Disables all warnings
"My Configuration"); during compilation.
fileOutputStream.close(); -Xlint[:<key>] Enables or disables
specific lint warnings.
} catch (IOException e) { -Xlint:-<key> Disables specific lint
e.printStackTrace();
warnings.
}
-g Generates debugging
information for source-
JAVACCOMMAND
JAVAC COMMAND level debugging.
-g:none Disables generation of
javac is the Java Compiler, a command-line tool debugging information.
included in the Java Development Kit (JDK). Its
-Werror Treats warnings as
main purpose is to compile Java source code files
(files with a .java extension) into bytecode files errors.
(files with a .class extension) that can be executed
by the Java Virtual Machine (JVM).

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


14 CORE JAVA

Option Description Option Description


-sourcepath Specifies locations to C <dir> Change to the specified
search for source files. directory before
-Xmaxerrs <number> performing the
Sets the maximum
operation.
number of errors to
print. M Do not create a manifest
-Xmaxwarns <number> file for the entries.
Sets the maximum
number of warnings to m <manifest> Include the specified
print. manifest file.
e Sets the application
JARCOMMAND
JAR COMMAND entry point (main class)
for the JAR file’s
Jar (Java Archive) files are a common way to manifest.
package and distribute Java applications, libraries, i <index> Generates or updates
and resources.
the index information
for the specified JAR file.
• Jar files are archive files that use the ZIP
format, making it easy to compress and bundle 0 Store without using ZIP
multiple files and directories into a single file. compression.

• 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

options and what they do: executing Java applications.

Below are some of the common options used with


Option Description
the java command for controlling the behavior of
c Create a new JAR file. the Java Virtual Machine (JVM) and Java
x applications. Depending on your specific use case,
Extract files from an
you may need to use some of these options to
existing JAR file.
configure the JVM or your Java application.
t List the contents of a JAR
file. Option Description
u Update an existing JAR -classpath or -cp Specifies the classpath
file with new files. for finding user-defined
f <jarfile> Specifies the JAR file to classes and libraries.
be created or operated -version Displays the Java
on. version information.
v Verbose mode. Display -help Shows a summary of
detailed output. available command-line
options.

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


15 CORE JAVA

Option Description and improving code quality. Depending on your


project’s requirements, you may find these libraries
-Xmx<size> Sets the maximum heap and others to be valuable additions to your Java
size for the JVM (e.g., toolkit.
-Xmx512m sets it to 512
MB).
Library Name Description
-Xms<size> Sets the initial heap size
Apache Commons Lang Provides a set of utility
for the JVM (e.g.,
classes for common
-Xms256m sets it to 256
programming tasks,
MB).
such as string
-Xss<size> Sets the stack size for manipulation, object
each thread (e.g., -Xss1m handling, and more.
sets it to 1 MB).
Jackson (JSON A widely used library
-D<property>=<value> Sets a system property Processor) for working with JSON
to a specific value. data, allowing for easy
serialization and
-ea or -enableassertions Enables assertions
deserialization between
(disabled by default).
Java objects and JSON.
-da or Disables assertions.
-disableassertions Log4j A flexible and highly
configurable logging
-XX:+<option> Enables a specific non- framework that
standard JVM option. provides various logging
-XX:-<option> Disables a specific non- options for Java
standard JVM option. applications.

-XX:<option>=<value> Sets a specific non- Spring Framework A comprehensive


standard JVM option to framework for building
a value. Java applications,
offering modules for
-verbose:class Displays information
dependency injection,
about class loading.
data access, web
-verbose:gc Displays information applications, and more.
about garbage
Hibernate An Object-Relational
collection.
Mapping (ORM)
-Xrunhprof:format Generates heap and CPU framework that
profiling data. simplifies database
interaction by mapping
-Xdebug Enables debugging
Java objects to database
support.
tables.
-Xrunjdwp:<options> Enables Java Debug
Apache HttpClient A library for making
Wire Protocol (JDWP)
HTTP requests and
debugging.
interacting with web
services, supporting
POPULAR3RD
POPULAR 3RDPARTY
PARTYJAVA
JAVALIBRARIES various authentication
methods and request
Java has an enormous ecosystem of third-party customization.
libraries and frameworks. Below are just a few
available that will greatly improve the development
experience. Each library serves a specific purpose
and can significantly simplify various aspects of
your code, from handling data to simplifying testing

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!


16 CORE JAVA

Library Name Description

JUnit A popular testing


framework for writing
and running unit tests in
Java, ensuring the
reliability and
correctness of code.

Mockito A mocking framework


for creating mock
objects during unit
testing, allowing you to
isolate and test specific
parts of your code.

Apache Commons IO Provides a set of utility


classes for input/output
operations, such as file
handling, stream
management, and more.

Lombok A library that simplifies


Java code by generating
boilerplate code for
common tasks like
getter and setter
methods, constructors,
and logging.

JAX-RS (Java API for A standard API for


RESTful Web Services) building RESTful web
services in Java, often
used with frameworks
like Jersey or RESTEasy.

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

JAVACODEGEEKS.COM | © EXELIXIS MEDIA P.C. VISIT JAVACODEGEEKS.COM FOR MORE!

You might also like