Core Java

Core Java Cheatsheet

Introduction

Java is one of the most popular programming languages in the world, used in million of devices from servers and workstations to tablets, mobile phones and wearables. With this cheatsheet we strive to provide the main concepts and key aspects of the Java programming language. We include details on core language features such as lambda expressions, collections, formatted output, regular expressions, logging, properties as well as the most commonly used tools to compile, package and execute java programs.

Java Keywords

Let’s start with the basics, what follows is a list containing some of the most commonly used Java keywords, their meanings, and short examples. Please note that this is not an exhaustive list of all Java keywords, but it covers many of the commonly used ones. So be sure to consult the documentation for the most up-to-date information.

KeywordMeaningExample
abstractUsed to declare abstract classesabstract class Shape { /*...*/ }
assertUsed for testing assertionsassert (x > 0) : "x is not positive";
booleanData type for true/false valuesboolean isJavaFun = true;
breakUsed to exit a loop or switch statementfor (int i = 0; i < 5; i++) { if (i == 3) break; }
byteData type for 8-bit integersbyte b = 42;
caseUsed in a switch statementswitch (day) { case 1: /*...*/ break; }
catchUsed to catch exceptionstry { /*...*/ } catch (Exception e) { /*...*/ }
charData type for character datachar grade = 'A';
classDeclares a classclass MyClass { /*...*/ }
continueSkips the current iteration in a loopfor (int i = 0; i < 5; i++) { if (i == 3) continue; }
defaultUsed in a switch statementswitch (day) { case 1: /*...*/ default: /*...*/ }
doStarts a do-while loopdo { /*...*/ } while (condition);
doubleData type for double-precision floating-point numbersdouble pi = 3.14159265359;
elseUsed in an if-else statementif (x > 5) { /*...*/ } else { /*...*/ }
enumDeclares an enumerated typeenum Day { MONDAY, TUESDAY, WEDNESDAY }
extendsIndicates inheritance in a classclass ChildClass extends ParentClass { /*...*/ }
finalUsed to make a variable or method finalfinal int maxAttempts = 3;
finallyUsed in exception handlingtry { /*...*/ } catch (Exception e) { /*...*/ } finally { /*...*/ }
floatData type for single-precision floating-point numbersfloat price = 19.99f;
forStarts a for loopfor (int i = 0; i < 5; i++) { /*...*/ }
ifConditional statementif (x > 5) { /*...*/ }
implementsImplements an interface in a classclass MyClass implements MyInterface { /*...*/ }
importUsed to import packages and classesimport java.util.ArrayList;
instanceofChecks if an object is an instance of a classif (obj instanceof MyClass) { /*...*/ }
intData type for integersint count = 42;
interfaceDeclares an interfaceinterface MyInterface { /*...*/ }
longData type for long integerslong bigNumber = 1234567890L;
nativeUsed in native method declarationsnative void myMethod();
newCreates a new objectMyClass obj = new MyClass();
nullRepresents the absence of a valueObject obj = null;
packageDeclares a Java packagepackage com.example.myapp;
privateAccess modifier for private membersprivate int age;
protectedAccess modifier for protected membersprotected String name;
publicAccess modifier for public memberspublic void displayInfo() { /*...*/ }
returnReturns a value from a methodreturn result;
shortData type for short integersshort smallNumber = 100;
staticIndicates a static memberstatic int count = 0;
strictfpEnsures strict floating-point precisionstrictfp void myMethod() { /*...*/ }
superCalls a superclass constructor/methodsuper();
switchStarts a switch statementswitch (day) { case 1: /*...*/ }
synchronizedEnsures thread safetysynchronized void myMethod() { /*...*/ }
thisRefers to the current instancethis.name = name;
throwThrows an exceptionthrow new Exception("Something went wrong.");
throwsDeclares exceptions thrown by a methodvoid myMethod() throws MyException { /*...*/ }
transientUsed with object serializationtransient int sessionId;
tryStarts an exception-handling blocktry { /*...*/ } catch (Exception e) { /*...*/ }
voidDenotes a method that returns no valuepublic void doSomething() { /*...*/ }
volatileIndicates that a variable may be modified by multiple threadsvolatile int sharedVar;
whileStarts a loopwhile (in.hasNext()) process(in.next());
Java Keywords

Java Packages

In Java, a package is a mechanism for organizing and grouping related classes and interfaces into a single namespace. Below you can find some of the most commonly used and the functionality their classes provide. Java has a rich ecosystem of libraries and frameworks, so the packages you use may vary depending on your specific application or project. Remember to import the necessary packages at the beginning of your Java classes to access their functionality.

PackageDescription
java.langProvides fundamental classes (e.g., String, Object) and is automatically imported into all Java programs.
java.utilContains utility classes for data structures (e.g., ArrayList, HashMap), date/time handling (Date, Calendar), and more.
java.ioProvides classes for input and output operations, including reading/writing files (FileInputStream, FileOutputStream) and streams (InputStream, OutputStream).
java.netUsed for network programming, including classes for creating and managing network connections (Socket, ServerSocket).
java.awtAbstract Window Toolkit (AWT) for building graphical user interfaces (GUIs) in desktop applications.
javax.swingPart of the Swing framework, an advanced GUI toolkit for building modern, platform-independent desktop applications.
java.sqlProvides classes for database access using JDBC (Java Database Connectivity).
java.util.concurrentContains classes and interfaces for handling concurrency, including thread management and synchronization (Executor, Semaphore).
java.nioNew I/O (NIO) package for efficient I/O operations, including non-blocking I/O and memory-mapped files (ByteBuffer, FileChannel).
java.textOffers classes for text formatting (DateFormat, NumberFormat) and parsing.
java.securityProvides classes for implementing security features like encryption, authentication, and permissions.
java.mathContains classes for arbitrary-precision arithmetic (BigInteger, BigDecimal).
java.util.regexSupports regular expressions for pattern matching (Pattern, Matcher).
java.awt.eventEvent handling in AWT, used to handle user-generated events such as button clicks and key presses.
java.util.streamIntroduces the Stream API for processing collections of data in a functional and declarative way.
java.timeThe Java Date and Time API introduced in Java 8, for modern date and time handling (LocalDate, Instant, DateTimeFormatter).
java.util.loggingProvides a logging framework for recording application log messages.
javax.servletContains classes and interfaces for building Java-based web applications using the Servlet API.
javax.xmlOffers XML processing capabilities, including parsing, validation, and transformation.
Java Packages

Java Operators

Operators are a cornerstone aspect to every programming language. They allow you to manipulate data, perform calculations, and make decisions in your programs. Java provides a wide range of operators. Following are the ones most commonly used. The descriptions provide a brief overview of their purposes and usage. The operators at the top of the table have higher precedence, meaning they are evaluated first in expressions. Operators with the same precedence level are evaluated left to right. Be sure to use parentheses to clarify the order of evaluation when needed.

OperatorExampleDescription
()(x + y)Parentheses for grouping expressions.
++ --x++, --yIncrement and decrement operators.
+ -x + y, x - yAddition and subtraction.
* / %x * y, x / y, x % yMultiplication, division, and modulo.
+ (unary)+x, -yUnary plus and minus.
!!flagLogical NOT (negation).
~~xBitwise NOT (complement).
<< >> >>>x << 1, x >> 2, x >>> 3Bitwise left shift, right shift (with sign extension), and right shift (zero extension).
< <= > >=x < y, x <= y, x > y, x >= yRelational operators for comparisons.
== !=x == y, x != yEquality and inequality comparisons.
&x & yBitwise AND.
^x ^ yBitwise XOR (exclusive OR).
&&x && yConditional AND (short-circuit).
? :result = (x > y) ? x : yConditional (Ternary) Operator.
=x = yAssignment operator.
+= -= *= /= %=x += y, x -= y, x *= y, x /= y, x %= yCompound assignment operators.
<<= >>= >>>=x <<= 1, x >>= 2, x >>>= 3Compound assignment with bitwise shifts.
Java Operators

Primitive Types

In Java, primitive types (also known as primitive data types or simply primitives) are the simplest data types used to represent single values. These types are built into the language itself and are not objects like instances of classes and reference types. Java’s primitive types are designed for efficiency and are used to store basic values in memory. Below is a table listing all of Java’s primitive data types, their size in bytes, their range, and some additional notes. Keep in mind that you can convert from byte to short, short to int, char to int, int to long, int to double and float to double without loosing precision since the source type is smaller in size compared to the target one. On the other hand converting from int to float, long to float or long to double may come with a precision loss.

Data TypeSize (Bytes)RangeNotes
byte1-128 to 127Used for small integer values.
short2-32,768 to 32,767Useful for integers within this range.
int4-2^31 to 2^31 – 1Commonly used for integer arithmetic.
long8-2^63 to 2^63 – 1Used for larger integer values.
float4Approximately ±3.40282347E+38Floating-point with single precision.
double8Approximately ±1.7976931348623157E+308Floating-point with double precision.
char20 to 65,535 (Unicode characters)Represents a single character.
booleantrue or falseRepresents true/false values.
Java Primitive Types

Lambda Expressions

Lambda expressions provide a way to define small, self-contained, and unnamed functions (anonymous functions) right where they are needed in your code. They are primarily used with functional interfaces, which are interfaces with a single abstract method. Lambda expressions provide a way to implement the abstract method of such interfaces without explicitly defining a separate class or method.

The syntax for lambda expressions is concise and consists of parameters surrounded by parenthesis (()), an arrow (->), and a body. The body can be an expression or a block of code.

// Using a lambda expression to define a Runnable
Runnable runnable = () -> System.out.println("Hello, Lambda!");

Functional Interfaces

A functional interface is an interface that has exactly one abstract method, which is used to define a single unit of behavior. Below is an example of such an interface:

@FunctionalInterface
interface Calculator {
    int calculate(int a, int b);
}

Implementations of this interface can be supplied in-line as a lambda expression, as shown below:

// Using a lambda expression to define addition
Calculator addition = (a, b) -> a + b;
int result1 = addition.calculate(5, 3);
System.out.println("Addition: " + result1); // Output: Addition: 8
        
// Using a lambda expression to define subtraction
Calculator subtraction = (a, b) -> a - b;
int result2 = subtraction.calculate(10, 4);
System.out.println("Subtraction: " + result2); // Output: Subtraction: 6

Method References

Method references provide a concise way to reference static methods, constructors, or instance methods of objects, pass them as method parameters or return them, much like anonymous functions; making your code more readable and expressive when working with functional interfaces. Let’s update the calculator example to use method references:

public class MethodReferenceCalculator {
    // A static method that performs addition
    public static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        // Using a method reference to the static add method
        Calculator addition = MethodReferenceCalculator::add;
        
        int result = addition.calculate(5, 3);
        System.out.println("Addition result: " + result); // Output: Addition result: 8
    }
}

Collections

Collections play a pivotal role in Java development. Following are some of the most commonly used collection implementation classes along with code snippets illustrating typical use cases. Depending on your specific requirements, you can choose the appropriate one to suit your data storage and retrieval needs.

ArrayList

An array-based list that dynamically resizes as elements are added or removed.

// Create an ArrayList and add elements.
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");

// Iterate through the ArrayList.
for (String name : names) { /*...*/ }

// Add an element by index.
names.set(i, "Charlie");

// Remove an element by index.
names.remove(0);

// Add multiple elements using addAll.
names.addAll(Arrays.asList("David", "Eve"));

// Remove multiple elements using removeAll.
names.removeAll(Arrays.asList("Alice", "Bob"));

// Retrieve an element by index.
String firstPerson = names.get(0);

// Convert ArrayList to an array.
String[] namesArray = names.toArray(new String[0]);

// Convert an array to an ArrayList.
List<String> namesList = Arrays.asList(namesArray);

// Sort elements in natural order.
Collections.sort(names);

// Sort elements using a custom comparator.
Collections.sort(names, new Comparator<String>() { public int compare(String a, String b) { return a.length() - b.length(); } });

// Do something with all elements in the collection
names.forEach(System.out::println);

// Use the Stream API to filter elements.
List<String> filteredNames = names.stream().filter(name -> name.startsWith("A")).collect(Collectors.toList());

// Use the Stream API to perform calculations on elements (e.g., sum of lengths).
int sumOfLengths = names.stream().mapToInt(String::length).sum();

LinkedList

A doubly-linked list that allows efficient insertion and removal from both ends.

LinkedList<Integer> numbers = new LinkedList<>();
numbers.addFirst(1);
numbers.addLast(2);
numbers.removeFirst();

HashSet

An unordered collection of unique elements, implemented using a hash table.

// Create a HashSet and add unique elements.
HashSet<String> uniqueWords = new HashSet<>();
uniqueWords.add("apple");
uniqueWords.add("banana");

// Iterate through the HashSet.
for (String word : uniqueWords) { /*...*/ }

// Remove an element from the HashSet.
uniqueWords.remove("apple");

// Use the Stream API to check if an element exists.
boolean containsBanana = uniqueWords.stream().anyMatch(word -> word.equals("banana"));

TreeSet

A sorted set that stores elements in natural order or according to a specified comparator.

// Create a TreeSet and add elements (sorted automatically).
TreeSet<Integer> sortedNumbers = new TreeSet<>();
sortedNumbers.add(3);
sortedNumbers.add(1);
sortedNumbers.add(2);

// Iterate through the TreeSet (in ascending order).
for (Integer number : sortedNumbers) { /*...*/ }

// Use the Stream API to find the maximum element.
Optional<Integer> maxNumber = sortedNumbers.stream().max(Integer::compareTo);

HashMap

An unordered collection of key-value pairs, implemented using a hash table.

// Create a HashMap and add key-value pairs.
HashMap<String, Integer> ageMap = new HashMap<>();
ageMap.put("Alice", 25);
ageMap.put("Bob", 30);

// Iterate through the HashMap key-value pairs.
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) { /*...*/ }

// Remove a key-value pair by key.
ageMap.remove("Alice");

// Use the Stream API to transform key-value pairs.
Map<String, Integer> doubledAgeMap = ageMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue() * 2));

TreeMap

A sorted map that stores key-value pairs in natural order or according to a specified comparator.

// Create a TreeMap and add key-value pairs (sorted by key).
TreeMap<String, Double> salaryMap = new TreeMap<>();
salaryMap.put("Alice", 55000.0);
salaryMap.put("Bob", 60000.0);

// Iterate through the TreeMap keys (in ascending order).
for (String name : salaryMap.keySet()) { /*...*/ }

// Iterate through the TreeMap values (in ascending order of keys).
for (Double salary : salaryMap.values()) { /*...*/ }

// Use the Stream API to calculate the total salary.
double totalSalary = salaryMap.values().stream().mapToDouble(Double::doubleValue).sum();

LinkedHashMap

A map that maintains the order of insertion while still providing hash table efficiency.

// Create a LinkedHashMap and add key-value pairs (maintains insertion order).
LinkedHashMap<String, Integer> orderMap = new LinkedHashMap<>();
orderMap.put("First", 1);
orderMap.put("Second", 2);

// Iterate through the LinkedHashMap key-value pairs (in insertion order).
for (Map.Entry<String, Integer> entry : orderMap.entrySet()) { /*...*/ }

// Use the Stream API to extract keys in insertion order.
List<String> keysInOrder = orderMap.keySet().stream().collect(Collectors.toList());

Stack

A data structure that follows the Last-In-First-Out (LIFO) principle.

// Use a Stack to push and pop elements (LIFO).
Stack<String> stack = new Stack<>();
stack.push("Item 1");
stack.push("Item 2");
String topItem = stack.pop();

Queue

A data structure that follows the First-In-First-Out (FIFO) principle.

// Use a LinkedList as a Queue to offer and poll elements (FIFO).
Queue<String> queue = new LinkedList<>();
queue.offer("Task 1");
queue.offer("Task 2");
String nextTask = queue.poll();

PriorityQueue

A priority-based queue, where elements are dequeued based on their priority.

// Use a PriorityQueue to offer and poll elements based on priority.
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.offer(3);
priorityQueue.offer(1);
int highestPriority = priorityQueue.poll();

Character Escape Sequences

Character escape sequences are used to represent special characters in Java strings. For example, \" is used to include a double quote within a string, and \n represents a newline character. The \uXXXX escape sequence allows you to specify a Unicode character by its hexadecimal code point. Below are some of the most common Character escape sequences in Java.

Escape SequenceDescription
\\Backslash
\'Single quote (apostrophe)
\"Double quote
\nNewline (line feed)
\rCarriage return
\tTab
\bBackspace
\fForm feed
\uXXXXUnicode character in hexadecimal format (e.g., \u0041 for ‘A’)
Character Escape Sequences

Output Formatting With printf

Here’s a typical example of output formatting using the printf method. For a full list of format specifiers and flags visit our comprehensive guide here.

String name = "Alice";
int age = 30;
double salary = 55000.75;
boolean married = true;

// Format and print using printf. The %n specifier is used to insert a platform-specific newline character
System.out.printf("Name: %s%n", name); // %s for String
System.out.printf("Age: %d%n", age);   // %d for int
System.out.printf("Salary: %.2f%n", salary); // %.2f for double with 2 decimal places
System.out.printf("Married: %b%n", married); // %b for boolean


 

Regular Expressions

Regular expressions are powerful tools for pattern matching and text manipulation. Below are some typical use cases.

// Matching a Simple Pattern
String text = "Hello, World!";
String pattern = "Hello, .*";
boolean matches = text.matches(pattern);

// Finding All Email Addresses in a Text
String text = "Contact us at john@example.com and jane@test.org for assistance.";
String emailPattern = "\\b\\S+@\\S+\\.[A-Za-z]+\\b";
Pattern pattern = Pattern.compile(emailPattern);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
    String email = matcher.group();
    // Process or store the found email addresses
}

// Replacing All Occurrences of a Word
String text = "The quick brown fox jumps over the lazy dog.";
String replacedText = text.replaceAll("fox", "cat");

// Splitting a String into Words
String text = "Java is a versatile programming language.";
String[] words = text.split("\\s+");

// Validating a Date Format
String date = "2023-10-05";
String datePattern = "\\d{4}-\\d{2}-\\d{2}";
boolean isValid = date.matches(datePattern);

Below are some of the most commonly used regular expression syntax elements in Java.

SyntaxDescription
.Matches any character except a newline.
\t, \n, \r, \f, \a, \eThe control characters tab, newline, return, form feed, alert, and escape.
[]Defines a character class, matches any one character from the specified set. You can include characters, ranges or even character classes. For example, [abc0-9\s&&[^ \t]] matches ‘a’, ‘b’, ‘c’, a digit or a whitespace character that is not space or tab.
[^]Defines a negated character class, matches any one character NOT in the specified set. You can include characters, ranges or even character classes. For example, [^0-9] matches any character that is not a digit.
*Matches the preceding element zero or more times.
+Matches the preceding element one or more times.
?Matches the preceding element zero or one time (optional).
{n}Matches the preceding element exactly n times.
{n,}Matches the preceding element at least n times.
{n,m}Matches the preceding element between n and m times (inclusive).
XYMatches any string from X, followed by any string from Y.
X|YMatches any string from X or Y.
()Groups expressions together, enabling quantifiers to apply to the entire group.
\Escapes a metacharacter, allowing you to match characters like ‘.’, ‘[‘, ‘]’, etc., literally.
^Anchors the match at the beginning of the line (or input).
$Anchors the match at the end of the line (or input).
\bMatches a word boundary.
\BMatches a non-word boundary.
\dMatches a digit (equivalent to [0-9]).
\DMatches a non-digit (equivalent to [^0-9]).
\sMatches a whitespace character (e.g., space, tab etc. Equivalent to [ \t\n\r\f\x0B]).
\SMatches a non-whitespace character.
\wMatches a word character (alphanumeric or underscore, equivalent to [a-zA-Z0-9_]).
\WMatches a non-word character.
Most Common Regular Expression Syntax Elements

Matching Flags

Pattern matching can be adjusted with flags. You can embed them at the beginning of the pattern of use them as shown below:

Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE + Pattern.UNICODE_CASE)
FlagDescription
Pattern.CASE_INSENSITIVE ((i))Enables case-insensitive matching.
Pattern.MULTILINE ((?m))Enables multiline mode, where ^ and $ match the start/end of each line.
Pattern.DOTALL ((?s))Enables dotall mode, allowing . to match any character, including newlines.
Pattern.UNICODE_CASE ((?u))Enables Unicode case-folding.
Pattern.COMMENTS ((?x))Allows whitespace and comments in the pattern for readability.
Pattern.UNIX_LINES ((?d))Only ‘\n’ is recognized as a line terminator when matching ^ and $ in multiline mode.
Pattern.CANON_EQ ((?c))Matches canonical equivalence, treating composed and decomposed forms as equivalent.
Pattern.LITERALTreats the entire pattern as a literal string, disabling metacharacter interpretation.
Pattern Matching Flags

Logging

In Java’s core logging implementation (java.util.logging), the logging configuration is specified through a properties file (jre/lib/logging.properties). You can specify another file by using the system property java.util.logging.config.file when running your application. Below are some common properties used in the logging.properties file, along with their descriptions:

PropertyDescription
.levelSets the default logging level for all loggers.
handlersSpecifies which handlers (output destinations) to use for log records.
<logger>.levelDefines the log level for a specific logger.
java.util.logging.ConsoleHandler.levelSets the log level for the ConsoleHandler.
java.util.logging.ConsoleHandler.formatterSpecifies the formatter for log messages sent to the console.
java.util.logging.FileHandler.levelSets the log level for the FileHandler (logging to files).
java.util.logging.FileHandler.patternDefines the pattern for log file names.
java.util.logging.FileHandler.limitSpecifies the maximum size (in bytes) for each log file before rolling over.
java.util.logging.FileHandler.countSets the maximum number of log files to keep.
java.util.logging.FileHandler.formatterSpecifies the formatter for log messages written to files.
java.util.logging.SimpleFormatter.formatAllows customization of log message format for SimpleFormatter.
java.util.logging.ConsoleHandler.filterSpecifies a filter for log records to be sent to the console.
java.util.logging.FileHandler.filterSpecifies a filter for log records to be written to files.
java.util.logging.ConsoleHandler.encodingSpecifies the character encoding for console output.
java.util.logging.FileHandler.encodingSpecifies the character encoding for file output.
java.util.logging.ConsoleHandler.errorManagerDefines the error manager for handling errors in the ConsoleHandler.
java.util.logging.FileHandler.errorManagerDefines the error manager for handling errors in the FileHandler.
Logging Properties

An example logging configuration file is provided below.

# Set the default logging level for all loggers
.level = INFO

# Handlers specify where log records are output
handlers = java.util.logging.ConsoleHandler

# Specify the log level for a specific logger
com.example.myapp.MyClass.level = FINE

# ConsoleHandler properties
java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

# FileHandler properties
java.util.logging.FileHandler.level = ALL
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter

Property Files

A properties file is a simple text file used to store configuration settings or key-value pairs. It is commonly used for configuring applications, as it provides a human-readable and editable format. Properties files are commonly used for application configuration, internationalization, and other scenarios where key-value pairs need to be stored in a structured and easily editable format.

  • Properties files typically use the .properties file extension.
  • Each line in the properties file represents a key-value pair. The key and value are separated by an equal sign (=) or a colon (:).
  • You can include comments in properties files by prefixing a line with a hash (#) or an exclamation mark (!). Comments are ignored when reading properties.
  • Whitespace characters (spaces and tabs) before and after the key and value are ignored.
  • You can escape special characters like spaces, colons, and equals signs using a backslash (\).

Below is an example of loading and storing data in a properties file programmatically.

Properties properties = new Properties();
try {
  FileInputStream fileInputStream = new FileInputStream("config.properties");
  properties.load(fileInputStream);
  fileInputStream.close();

  // Access properties
  String value = properties.getProperty("key");
  System.out.println("Value for key: " + value);

  // Update properties
  properties.setProperty("key1", "value1");
  properties.setProperty("key2", "value2");
  FileOutputStream fileOutputStream = new FileOutputStream("config.properties");
  properties.store(fileOutputStream, "My Configuration");
  fileOutputStream.close();

} catch (IOException e) {
  e.printStackTrace();
}

javac command

javac is the Java Compiler, a command-line tool included in the Java Development Kit (JDK). Its main purpose is to compile Java source code files (files with a .java extension) into bytecode files (files with a .class extension) that can be executed by the Java Virtual Machine (JVM).

Below are some of the most commonly used options with the javac command. They allow you to customize the compilation process, specify source and target versions, control error handling, and manage classpaths and source file locations. You can use these options to tailor the compilation of your Java code to your project’s specific requirements.

OptionDescription
-classpath or -cpSpecifies the location of user-defined classes and packages.
-d <directory>Specifies the destination directory for compiled class files.
-source <release>Specifies the version of the source code (e.g., “1.8” for Java 8).
-target <version>Generates class files compatible with the specified target version (e.g., “1.8”).
-encoding <charset>Sets the character encoding for source files.
-verboseEnables verbose output during compilation.
-deprecationShows a warning message for the use of deprecated classes and methods.
-nowarnDisables all warnings during compilation.
-Xlint[:<key>]Enables or disables specific lint warnings.
-Xlint:-<key>Disables specific lint warnings.
-gGenerates debugging information for source-level debugging.
-g:noneDisables generation of debugging information.
-WerrorTreats warnings as errors.
-sourcepathSpecifies locations to search for source files.
-Xmaxerrs <number>Sets the maximum number of errors to print.
-Xmaxwarns <number>Sets the maximum number of warnings to print.
Common javac Options

jar command

Jar (Java Archive) files are a common way to package and distribute Java applications, libraries, and resources.

  • Jar files are archive files that use the ZIP format, making it easy to compress and bundle multiple files and directories into a single file.
  • Jar files can contain both executable (class files with a main method) and non-executable (resources, libraries) components.
  • 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 version information.
  • Java provides command-line tools like jar and jarsigner to create, extract, and sign jar files.

Below is a table with some common jar command options and what they do:

OptionDescription
cCreate a new JAR file.
xExtract files from an existing JAR file.
tList the contents of a JAR file.
uUpdate an existing JAR file with new files.
f <jarfile>Specifies the JAR file to be created or operated on.
vVerbose mode. Display detailed output.
C <dir>Change to the specified directory before performing the operation.
MDo not create a manifest file for the entries.
m <manifest>Include the specified manifest file.
eSets the application entry point (main class) for the JAR file’s manifest.
i <index>Generates or updates the index information for the specified JAR file.
0Store without using ZIP compression.
J<option>Passes options to the underlying Java VM when running the jar command.
Common jar Options

java command

The java command is used to run Java applications and execute bytecode files (compiled Java programs) on the Java Virtual Machine (JVM). It serves as the primary entry point for launching and executing Java applications.

Below are some of the common options used with the java command for controlling the behavior of the Java Virtual Machine (JVM) and Java applications. Depending on your specific use case, you may need to use some of these options to configure the JVM or your Java application.

OptionDescription
-classpath or -cpSpecifies the classpath for finding user-defined classes and libraries.
-versionDisplays the Java version information.
-helpShows a summary of available command-line options.
-Xmx<size>Sets the maximum heap size for the JVM (e.g., -Xmx512m sets it to 512 MB).
-Xms<size>Sets the initial heap size for the JVM (e.g., -Xms256m sets it to 256 MB).
-Xss<size>Sets the stack size for each thread (e.g., -Xss1m sets it to 1 MB).
-D<property>=<value>Sets a system property to a specific value.
-ea or -enableassertionsEnables assertions (disabled by default).
-da or -disableassertionsDisables assertions.
-XX:+<option>Enables a specific non-standard JVM option.
-XX:-<option>Disables a specific non-standard JVM option.
-XX:<option>=<value>Sets a specific non-standard JVM option to a value.
-verbose:classDisplays information about class loading.
-verbose:gcDisplays information about garbage collection.
-Xrunhprof:formatGenerates heap and CPU profiling data.
-XdebugEnables debugging support.
-Xrunjdwp:<options>Enables Java Debug Wire Protocol (JDWP) debugging.
Common java Options

Popular 3rd party Java Libraries

Java has an enormous ecosystem of third-party 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 and improving code quality. Depending on your project’s requirements, you may find these libraries and others to be valuable additions to your Java toolkit.

Library NameDescription
Apache Commons LangProvides a set of utility classes for common programming tasks, such as string manipulation, object handling, and more.
Jackson (JSON Processor)A widely used library for working with JSON data, allowing for easy serialization and deserialization between Java objects and JSON.
Log4jA flexible and highly configurable logging framework that provides various logging options for Java applications.
Spring FrameworkA comprehensive framework for building Java applications, offering modules for dependency injection, data access, web applications, and more.
HibernateAn Object-Relational Mapping (ORM) framework that simplifies database interaction by mapping Java objects to database tables.
Apache HttpClientA library for making HTTP requests and interacting with web services, supporting various authentication methods and request customization.
JUnitA popular testing framework for writing and running unit tests in Java, ensuring the reliability and correctness of code.
MockitoA mocking framework for creating mock objects during unit testing, allowing you to isolate and test specific parts of your code.
Apache Commons IOProvides a set of utility classes for input/output operations, such as file handling, stream management, and more.
LombokA 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 RESTful Web Services)A standard API for building RESTful web services in Java, often used with frameworks like Jersey or RESTEasy.
Popular 3rd Party Libraries

Java Code Geeks

JCGs (Java Code Geeks) is an independent online community focused on creating the ultimate Java to Java developers resource center; targeted at the technical architect, technical team lead (senior developer), project manager and junior developers alike. JCGs serve the Java, SOA, Agile and Telecom communities with daily news written by domain experts, articles, tutorials, reviews, announcements, code snippets and open source projects.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button