Java Cheat Sheet: Key Concepts & Syntax
Java Cheat Sheet: Key Concepts & Syntax
Typecasting In Java
Java is a programming language and platform that has been widely used since its Arrays in Java
Strings in Java
development by James Gosling in 1982. It follows the Object oriented Programming
Java Regex
concept and can run programs written in any programming language. Java is a high-
Java Exception Handling
level, object-oriented, secure, robust, platform-independent, multithreaded, and Java Commands
portable programming language all those words are collectively called Java Buzzwords. Java Generics
Java
Multithreading
It is commonly used for programming web-based, window, enterprise, and mobile
java Collections
applications. This Java Cheat Sheet article has been written by experts in Java and
based on the experience of students who have recently undergone Java interviews.
1. Java Programming Terminologies
JVM: executes the bytecode generated by the compiler. Bytecode: The Javac
This Core Java Cheat Sheet has been designed by Java experts, based on the experience
compiler of JDK compiles the Java source code into bytecode so that it can be
of students who have recently undergone Java interviews. Whether you are a beginner
executed by JVM.
or an experienced Java developer, this Java Cheat Sheet for competitive programming
is a valuable resource for quickly accessing essential syntax, concepts, and best JDK: It is a complete Java development kit that includes everything including compiler,
practices related to Java Programming. Java Runtime Environment (JRE), java debuggers, java docs, etc.
JRE: allows the Java program to run, however, we cannot compile it. Garbage
Collector: To delete or recollect that memory JVM has a program called Garbage
Collector.
Java Cheat Sheet for Competitive Programming: Basics to Finalize method: this function is triggered by the garbage collector just before an object is
deleted or destroyed.
Advanced Concepts
Java Programming Terminologies
2
1
Java Basics
2. Java Basics
Java Program to Print “Hello World” Now, we will explore some of the fundamental concepts often utilized in the Java
Dataypes in Java
programming language.
Java Comments
Java Variables
Access Modifiers in Java
Operators in Java
Identifiers in Java
Control Flow in Java
Methods in Java
Java Input-output (I/O operations)
Java Polymorphism
Java Inheritance
Object – An object refers to an entity that possesses both behavior and state, such as a Interface (optional): If the class implements an interface, we use the implements keyword
bike, chair, pen, marker, table, and car. These objects can be either tangible or intangible, followed by the name of the interface after the class name.
including the financial system as an example of an intangible object.
State: The data (value) of an object is represented by its state. Behaviour: The
Keyword – In Java, Reserved words are also known as keywords. These are particular
functionality of an object, such as deposit, withdrawal, and so on, is represented
terms that hold specific meanings. Java has 61 Reserved Keywords that are predefined
by the term behaviour. and cannot be used as variable, object, or class names. Here’s a list of the keywords
Identity: A unique ID is often used to represent an object’s identification. The value of used in Java:-
the ID is hidden from the outside user. The JVM uses it internally to uniquely identify
each object. Keyword Use Case
Class – A class is a collection of objects with similar attributes. It’s a blueprint or abstract Used to declare an abstract class or abstract method
template from which objects are made. It’s a logical thing. It can’t be physical. In Java,
assert Used to check assertions during debugging
a class definition can have the following elements:
Modifiers: A class can be private or public, or it can also have a default access boolean Represents a boolean value (true or false)
level class keyword: To construct a class, we use the class keyword. class
break Exits from a loop or a switch statement
name: The name of the class should usually start with a capital letter.
Superclass (optional): If the class has any superclass, we use the extends keyword byte Represents a signed 8-bit integer
and we mention the name of the superclass after the
case Used in a switch statement to define a case
3
4
class name.
char Represents a 16-bit Unicode character instanceof Tests if an object is an instance of a specific class
const* Not used in Java, reserved for future use interface Declares an interface
continue Skips the rest of the loop and starts the next iteration long Represents a 64-bit integer
default Used in a switch statement as a default case module* Defines a module, reserved for future use
double Represents a 64-bit double-precision floating-point number new Creates a new object
else Used in an if-else statement open Used in module declarations to specify open packages
enum Declares an enumeration type opens Used in module declarations to specify opened packages
exports Used in module declarations to specify exported packages private Defines a private access modifier
extends Indicates a class is derived from another class protected Defines a protected access modifier
final Declares a variable, method, or class as final (unchangeable) provides Used in module declarations to specify service providers
finally Defines a block of code to be executed after try-catch public Defines a public access modifier
float Represents a 32-bit single-precision floating-point number requires Used in module declarations to specify required modules
for Starts a for loop return Exits a method and returns a value
goto* Not used in Java, reserved for future use short Represents a 16-bit integer
5 6
Output
Hello World!
In Java, primitive data types serve as the foundation for manipulating data. They are the
most basic types of data that the Java programming language uses. Java has several
3 . J a v a P r o g r a m t o P r in t “H e l l o W o r l d ” primitive data types, including:
Java
2. Multi-line comment
If you need to comment on multiple lines of code, you can utilize the syntax of a double forward slash “/*”. Simply enter your message between the two symbols, and complete the comment with
“*/”. This is a widely used syntax in coding.
Non-primitive datatypes are created from primitive datatypes. Examples of non-primitive datatypes include
arrays, stacks, and queues.
5. Java Comments
There are three types of comments in Java
To comment on a single line of code, you can use a double forward slash “//”
Output
followed by your message. This syntax is commonly used for coding.
Type Size Example Literals Range of values 9 0
0 to 255
short
16
int
-2,147,483,648
32
-2,-1,0,1,2 to
bits
2,147,483,647
long
-9,223,372,036,854,775,808
64
-2L,-1L,0L,1L,2L to
bits
9,223,372,036,854,775,807
When working on a project or software package, it is often helpful to use this method as it can assist in creating a documentation page for reference. This page can provide information on available
methods, their parameters, and more, making it a useful tool for learning about the project.
Syntax:
6. Java Variables
Variables are the containers that save the data values. Each variable is assigned according to the data type it
is assigned.
Syntax:
data_type var_name;
Types of Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
2. Instance Variables
Output
Instance variables are non-static variables and are declared in a class
outside of any method, constructor, or block. Before Calling function count:0
10
3. Static Variables
After Calling function count:1
Static variables are also known as class variables. The static variables
1 2
Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It provides security, accessibility, etc to the user depending upon
the access modifier used with the element
Case matters when it comes to Java Identifiers. For example 𠆋it’ and 𠆋IT’ would be
considered as different identifiers in Java.
The length of the identifier is not limited, however, it is recommended that it be kept
to a maximum of 4� letters.
Using reserved words as identifiers is not allowed in Java. This includes the term
“while,” as it is one of the 53 reserved terms.
The length of the identifier is not limited, however, it is recommended that it be kept
to a maximum of 4� letters.
5 6
Switch Statement
7 8
Java Methods are collections of statements that perform some specific task
2. println and
return the result.
Cursor Moves to a new line
Syntax of Method
Formatted Print
7 is the Field width and .5 is the precision fo the floating number printed . So, answer will be 3.14159
Output
0 1 2
1 2 3
2 3 4
1. print
The cursor remains on the same line
9 0
javac [Link] java GFG This is just to
just to check 2 Output: Check
2
This
is
2. Buffer Reader Class
InputStreamReader() is a function that converts the input stream of bytes into a stream of
characters so that it can be read as BufferedReader expects a stream of characters.
ABC
11
Entered Integer : 11
ABC
65 Output
Name :ABC
3
Marks :65
7.370000000000001
Method Overloading: If there are multiple functions that have the same name but different parameters, it is
known as
overloading.
Alterations in the
number or type of
arguments can result
in the overloading of
functions.
Example:
Output
Salary : 70000
Benefits : 15000
3 4
Math.function_name <parameters>
E value of e (constant value)
Type Casting is a method in which we convert from one data type to another.
cos( int θ ) cosine of θ
Type Conversion in Java is a technique where we can convert from double, int, and float to double.
toRadians( int θ ) Convert angle in degrees(θ) to radians
exp( int a ) a
exponential value e
log( int a )
natural log -> logea
b
B e l o w is t h e i m p l e m e n t a t io n o f t h e a b o v e m e t h o d s :
pow( int a, int b ) power a
Java Java
round( double a ) round to the nearest integer
5 6
arr[3] :40
Output arr[4] :50
3.0
Multidimensional Arrays in Java
Syntax:
int[][] arr= new int[3][3];
int arr[][]=new int[3][3];
// Both Methods are correct
7 8
Output StringBuilder str = new StringBuilder();
[Link]("GFG");
1 2 3
4 5 6
3. String Tokenizer
7 8 9
Strings are the type of objects that can store the character of values. A string acts the
19. Java Regex
same as an array of characters in Java.
Syntax:
9
Regular Expressions, or Regex for short, is a Java API that allows users to define
String abc=" ";
String patterns for searching, manipulating, and modifying strings. It is commonly
used for setting limits on various areas of strings such as email validation and
CharSequence Interface in Java passwords. The [Link] package contains regular expressions and consists of
three classes and one interface. The following table lists the three classes included in
1. StringBuffer the [Link] package:
Pattern class: This class does not have any public constructors. Instead, it consists of a
group of regular expressions that can be utilized to define different types of patterns. To
do this, simply execute the compile() method with a regular expression as the first
input. After execution, the method will return a pattern.
The table below provides a list of the methods in this class along with their descriptions.
Method Description
Method Description
matches() It’s used to see if the pattern matches the regular expression.
Finally Block: When programming in Java, the finally block is a section of code that Below is a table that outlines the distinctions between the terms final, finally, and
will always run, regardless of whether or not an exception has been caught. If there finalize:
is a catch block following a try block, it will be executed before the finally block.
final
However, if there is no catch block, the finally block will be executed immediately
after the try block. A final keyword can be used with classes, methods, and variables.
A final class cannot be inherited.
Example:- A final method cannot be overridden.
A final variable cannot be reassigned.
try {
finally
finalize
java -version: Displays the version of the Java Runtime Environment (JRE) the generic method. The compiler handles each method. that is installed on your computer. java
-help: Displays a list of all of the Java commands.
java -cp: Specifies the classpath for the Java program that you are running.
java -X: Specifies a non-standard option for the Java Virtual Machine (JVM).
javap: Disassembles a Java class file. jdb: A Java debugger. jconsole: A Java monitoring and management tool. jvisualvm: A Java profiling and diagnostic tool.
work with different data types. An entity such as class, interface, or method Output that operates on a parameterized type
is a generic entity.
[Link] = 11
[Link] = GeeksForGeeks
Types of Java Generics [Link] = 1.0
Generic Method: Generic Java method takes a parameter and returns some
23. Java Multithreading
value after performing a task. It is exactly like a normal function, however, a
Multithreading is a Java feature that allows concurrent execution of two or
generic method has type parameters that are cited by actual type. This more parts of a program for maximum utilization of CPU. Each part of such
allows the generic method to be used in a more general way. The compiler program is called a thread. So, threads are light-weight processes within a
takes care of the type of safety which enables programmers to code easily process.
since they do not have to perform long, individual type castings.
Threads can be created by using two mechanisms :
// To create an instance of generic class
Extending the Thread class
BaseType <Type> obj = new BaseType <Type>()
Implementing the Runnable Interface
Generic Functions: We can also write generic functions that can be called
with different types of arguments based on the type of arguments passed to Example: – Thread creation by extending the Thread class
5 6
To create a new thread in Java, we can extend the [Link] class and override Thread 14 is running
its run() method. This is where the thread’s execution starts. Then, we can create an Thread 12 is running
instance of our class and call the start() method to begin the execution of the thread. Thread 13 is running
The start() method will then call the run() Thread 18 is running
Thread 11 is running
Thread 16 is running
Output
Thread 15 is running
Thread 17 is running
L is t I n te r fa c e
List Interface List <T> al = new ArrayList<> ();
Q u e u e In t e r f a c e
D e q u e In t e r f a c e List <T> ll = new LinkedList<> ();
Interfaces Syntax
programming language. A rule in Java also known as WORA states that code only has Desktop GUI Applications
to be written once and may execute anywhere. Java’s high level of security, which Artificial intelligence
shields the code from hackers, viruses, and other dangers, is another factor in its Scientific Applications
popularity. Java also enables the creation of many jobs that may run concurrently Cloud Applications
within a programme, making it quicker and more effective. Java provides a clever Embedded Systems Gaming
method for generating code that primarily concentrates on. Applications