0% found this document useful (0 votes)
17 views32 pages

Java Cheat Sheet: Key Concepts & Syntax

Uploaded by

Devesh Nath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views32 pages

Java Cheat Sheet: Key Concepts & Syntax

Uploaded by

Devesh Nath
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Cheat Sheet  Java Maths Class

 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.

Constructors: In Java, a constructor is a block of code similar to a method. Whenever a


new class instance is created, the constructor is called. The memory allocation for the
object only happens when the constructor is invoked.

There are two types of constructors in Java. They are as follows:-

Default Constructor – A default constructor is a type of constructor that does not


require any parameters. When we do not declare a constructor for a class, the compiler
automatically generates a default constructor for the class with no arguments.

Parameterised Constructor – A parameterized constructor is a type of constructor that


requires parameters. It is used to assign custom values to a class’s fields during
There are three characteristics of an object:
initialization.

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.

Keyword Use Case Keyword Use Case

[Link] /45 [Link] /45


catch Catches exceptions thrown in a try block import Imports classes, packages, or individual members

char Represents a 16-bit Unicode character instanceof Tests if an object is an instance of a specific class

class Declares a class int Represents a 32-bit integer

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

do Starts a do-while loop native Indicates a method is implemented in platform-specific code

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

if Used in an if statement static Declares a static variable or method


implements Indicates a class is implementing an interface strictfp Ensures consistent floating-point calculations

5 6

// Java Pro gram to Print


// Hello Wo rld
cl ass GF G {
pu blic sta tic v oid main (Str ing [] ar gs) {
Sy stem. out .print ln( "Hell o Wor ld! ");
}
}

Output

Hello World!

Editing, Compiling, and Executing

4. Data Types in Java


Data Types in Java are the different values and sizes that can be stored in the
variable according to the requirements.

Java Datatype are further two types:-

1. Primitive Data Type in Java

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

Type Size Example Literals Range of values

[Link] /45 [Link] /45


Keyword Use Case

boolean 1 bit true, false true, false


super Refers to the parent class

switch Selects one of many code blocks to be executed


byte 8 bits (none) -128 to 127

synchronized Defines a synchronized block or method


7 8

this Refers to the current instance of the class

throw Throws an exception

throws Declares exceptions that a method may throw

to Used in switch expressions to specify case values

transient Indicates a member variable should not be serialized

while Starts a while loop

transitive Used in module declarations to specify transitive dependencies

try Defines a block of code to be tested for exceptions

uses Used in module declarations to specify service uses

void Defines a method that does not return a value

volatile Indicates a variable may be modified by multiple threads

with Used in switch expressions to specify pattern matching

_ Reserved for future use


Output GFG!

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.

2. Non-primitive Data Type

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

1. Single Line comment

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

char 16 𠆊’, ‘\u0041’, ‘\101’, ‘\\’, characters representation of ASCII


bits ‘\’, ‘\n’, ‘β’ values

0 to 255

short
16

bits (none) -32,768 to 32,767

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

float 32 1.23e100f , -1.23e-


bits 100f , .3f ,3.14F upto 7 decimal digits

double 64 1.23456e300d , upto 16 decimal digits


bits -123456e-300d , 1e1d

Below is the Example of the above topic: GFG!

3. JavaDoc Type Comment

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:

/** Comment starts

[Link] 1 /45 [Link] 1 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced
*This is
*sample comment */

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

There are 3 types of Data types in Java as mentioned below:

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

Instance variable value:11


are declared using the static keyword within a class outside of any

method, constructor, or block. 7. Access Modifiers in Java

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

Types of Access Modifiers in Java

[Link] 1 /45 [Link] 1 /45


Operators Meaning True False
Precedence and Associativity of
Operator in Java
>= Greater Than Equal to 3>=3 2>=3
There are four types of access modifiers available in Java:
D e f a u l t – N o k e y w o r d r e q u ir e d
Here is the table representing the precedence
P r iv a t e
order of Java operators from high to low as we move from top to bottom.
P rote c ted
P u b l ic
Operators Associativity Type

++, – Right to Left Unary postfix

++, –, +, -, ! Right to Left Unary prefix

/, *, % Left to Right Multiplicative

+, – Left to Right Additive

<, <=, >, >= Left to Right Relational


8 . O p e r a t o r s in J a v a
==, !== Left to Right Equality
Comparison Operators are the Operators which return a boolean value as the result means the answer will be
either true or false.
& Left to Right Boolean Logical AND

^ Left to Right Boolean Logical Exclusive OR


Operators Meaning True False

| Left to Right Boolean Logical Inclusive OR


== Equal 1==1 1==2

&& Left to Right Conditional AND


!=
Not Equal 1!=2 1!=1 || Left to Right Conditional OR

< Less Than 1<2 2<1 ?: Right to Left Conditional

=, +=, -=, *=, /=, %= Right to Left Assignment


<= Less Than Equal to 1<=1 2<=1

> Greater Than 3>2 2>3


34

[Link] 1 /45 [Link] 1 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

9. Identifiers in Java else


S yste [Link] t.p ri ntl n(a);

S yste [Link] t.p ri ntl n(a + "== " + b);


The name that we give to the class, variable, and methods are formally called identifiers in Java. and for }
defining Identifier there are some rules of it we need to take care of that while defining Identifiers. }

Rules of defining Java identifiers:-


Output
Valid Java Identifiers have strict guidelines to avoid compile-time errors.
2
Similar rules apply to C and C++
Only letters (both upper and lowercase), numbers, dollar signs, and 2. Nested if – else
underscores are allowed as identifiers in Java. Special characters like “@” A nested if is an if statement that is the target of another if or else. Nested if are not permitted. statements mean an if
statement inside an if statement.

[Link] 1 /45 [Link] 1 /45


Numbers should not be used to begin identifiers ([0-9]). �geeks,” for example, is not a
valid Java identifier.

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.

[Link] 1 /45 [Link] 1 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

10. Control Flow in Java

1. If, else-if, else

5 6

[Link] 1 /45 [Link] 1 /45


2.

[Link] 1 /45 [Link] 1 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

Switch Statement
7 8

[Link] 1 /45 [Link] 1 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

11. Methods in Java [Link](" GFG " + x);

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

[Link](" GFG " + x);


<access_modifier> <return_type> <method_name>( list_of_parameters)
{
3. printf
//body
The cursor remains on the same line }

Below is the implementation of the above method: [Link](" GFG %d",x);

Formatted Print

[Link]("%7.5f", [Link]); Explanation of the above statement:

7 is the Field width and .5 is the precision fo the floating number printed . So, answer will be 3.14159

Taking Input in Java

1. Parsing Command-line arguments

We can take input using the Command line simp

Output

[Link] 1 /45 [Link] 2 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

0 1 2
1 2 3
2 3 4

12. Java Input-output (I/O operations)


We can only print using [Link] but can use different print varieties in it:

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.

Below is the implementation of the above method:

ABC
11

[Link] 2 /45 [Link] 2 /45


}
}
7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

Entered String : ABC O ut p ut :


2

Entered Integer : 11

3. Scanner Class Syntax:

Scanner scn = new Scanner([Link]);

Below is the implementation of the above method:

[Link] 21/45 [Link] 2 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

ABC

65 Output
Name :ABC
3
Marks :65
7.370000000000001

13. Java Polymorphism 14. Java Inheritance


Polymorphism: It is the ability to differentiate between entities with the same name
efficiently.

Inheritance: It is the mechanism in Java by which one class is allowed to


Compile-time polymorphism: Static polymorphism, also called compileinherit the features (fields and methods) of another class. time polymorphism, is achieved through function
overloading in Java. Static polymorphism, also called compile-time polymorphism, is achieved through function overloading in Java.

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:

[Link] 2 /45 [Link] 2 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

Output

Salary : 70000
Benefits : 15000

15. Java Maths Class


In Java, there exists a Math Library that can simplify intricate calculations

3 4

[Link] 21/45 [Link] 2 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

Library: import [Link]; Use: Functions Returns or Calculates

Math.function_name <parameters>
E value of e (constant value)

Functions Returns or Calculates


Note: All the functions mentioned above can be PI Value of π(constant value) used with either
datatypes not bounded any single data-types.
min( int a,int b ) minimum of a and b

max( int a,int b ) maximum of a and b


16. Typecasting In Java
sin( int θ ) sine of θ
1. Type Casting in Java

Type Casting is a method in which we convert from one data type to another.
cos( int θ ) cosine of θ

2. Type Conversion in Java


tan( int θ) tangent 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

toDegrees( int θ ) Convert angle int radians(θ) to degrees

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

random() returns the random value in [0,1)

[Link] 2 /45 [Link] 2 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

sqrt( int a ) the square root of a

arr[3] :40
Output arr[4] :50

3.0
Multidimensional Arrays in Java

17. Arrays in Java


Arrays are not bounded to be single-dimensional but can store elements in
Arrays are the type of data structure that can store data of similar data multidimensional. types. Arrays are allocated in contiguous
memory allocation with a fixed size. Syntax:

Syntax:
int[][] arr= new int[3][3];
int arr[][]=new int[3][3];
// Both Methods are correct

int arr[]=new int[20]; Below is the implementation of the above method:


int[] arr=new int[20];

Below is the implementation of the above method:

[Link] 2 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced
for ( int i = 0; i < 3; i+ +) {
f or (i nt j = 0 ; j < 3 ; j++ )
Sys tem .out. pri nt(ar r[i][ j] + " ");

S ystem. ou [Link] tln ();


}
}
}

7 8
Output StringBuilder str = new StringBuilder();
[Link]("GFG");
1 2 3
4 5 6
3. String Tokenizer
7 8 9

18. Strings in Java public StringJoiner(CharSequence delimiter)

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:

StringBuffer s = new StringBuffer("GeeksforGeeks"); Class Description

2. StringBuilder [Link] It is used to define patterns.

[Link] 2 /45 [Link] 2 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

It is used to conduct match operations on text using


[Link]
patterns.

In a regular expression pattern, it’s used to indicate a


PatternSyntaxException
syntax problem.

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

compile(String regex) Compiles a regular expression into a pattern.

compile(String regex, int Turns a regular expression into a pattern using


flags) the flags provided.

flags() Gets the match flags for this pattern.

matcher(CharSequence Builds a matcher that compares the given input


input) to the pattern.
0

[Link] 2 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

Method Description

It is used to find occurrences of regular expressions in the text


find(int start)
starting from the provided index.

start() is used to retrieve the start index of a match found with


start()
the find() method.

It’s used to acquire the end index of a match discovered with


end()
the find() method.

groupCount() is a function that returns the total number of


groupCount()
matched subsequences.

matches() It’s used to see if the pattern matches the regular expression.

20. Java Exception Handling


Exception:– An Exception is an unexpected error that occurs during the runtime of a program.

Error vs Exception: What is the difference?


Matcher Class: To evaluate previously described patterns through match operations on an
input string in Java, the ‘object’ is utilized. No public
When a program encounters an error, it means there is a significant issue
constructors are defined here. One can execute a matcher() on any pattern that a well-designed program should not try to fix. On the other hand, an
object to achieve this. The table below displays the methods present in this exception indicates a particular situation that a well-designed program
class along with their descriptions:To evaluate previously described patterns should try to handle.
through match operations on an input string in Java, the ‘object’ is utilized.
Types of Exceptions:-
No public constructors are defined here. One can execute a matcher() on any
pattern object to achieve this. Checked Exception:- This mainly includes IO Exceptions and Compile time
Exceptions
The table below displays the methods present in this class along with their
descriptions: Unchecked Exceptions:– This covers both Runtime Exceptions and Null

[Link] 3 /45 [Link] 3 /45


7/4/24, 12:02 AM Method Description
Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

matches(String regex, Matches a regular expression and tries to match


CharSequence input) it against the given input.

Gets the regular expression that was used to


pattern()
create this pattern.

Generates a literal pattern String from the given


quote(String s)
String.

Splits the given input sequence around patterns


split(CharSequence input)
that match this pattern. Pointer Exceptions.

Divides the given input sequence into sections Method Description

split(CharSequence input, based on matches to this pattern. The number of


find() is mostly used to look for multiple occurrences of regular
int limit) times the pattern is applied is controlled by the find()
expressions in a text.
limit parameter.
1 2
// block of code to monitor for errors
toString() Returns the pattern’s string representation.
// the code you think can raise an exception
Handle Exceptions } catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1 } catch (ExceptionType2
exOb) {
try block: The try block comprises a set of statements that may throw an exception.
// exception handler for ExceptionType2
} // optional finally { // block of code to be executed after try block ends
Catch Block: When there is an uncertain condition in the try block, the catch block
}
comes in handy to handle it. It is mandatory to have a catch block right after the try
final vs finally vs finalize
block to handle any exceptions that may be thrown by the try block.

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 {

[Link] 3 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

finally

A finally block is always executed, regardless of whether an


exception is thrown or not.

The finally block is executed after the try block


and catch block, but before the program
control returns to the calling method. The finally
block can be used to close resources, such as files
and database connections.

finalize

The finalize() method is called by the garbage collector


when an object is no longer needed.

The finalize() method can be used to perform cleanup


operations, such as releasing resources or writing data to a
file.
throws keyword:- If a try/catch block is not present, the throws keyword can be used
The finalize() method is not guaranteed to be called, so it
to manage exceptions. This keyword specifies the specific exceptions that a method
should not be used to perform critical operations.
should throw if an exception happens.

throw keyword:- When using Java, the throw keyword is


21. Java Commands
utilized to throw an exception from a block of code or a
Here are the most commonly used Java commands:
method. It is possible to throw either a checked or
unchecked exception. The throw keyword is frequently
used for throwing custom exceptions. 3 4

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 -jar: Runs a Java Archive (JAR) file.

[Link] 3 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

java -D: Sets a system property.

java -X: Specifies a non-standard option for the Java Virtual Machine (JVM).

Here are some other useful Java commands:

javac: Compiles a Java source file into bytecode.

javap: Disassembles a Java class file. jdb: A Java debugger. jconsole: A Java monitoring and management tool. jvisualvm: A Java profiling and diagnostic tool.

22. Java Generics


Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that

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

[Link] 3 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

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

24. Java Collections


The collection is a framework in Java that provides an architecture to store and
manipulate objects in Java. It contains the interface as mentioned below:

Output

Thread 15 is running
Thread 17 is running

[Link] 3 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced

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

S e t In t e r f a c e List <T> v = new Vector<> ();


S o r t e d S e t In t e r f a c e
M a p In te r fa c e
Queue Interface Queue <T> pq = new PriorityQueue<> ();
C o l l e c t io n I n t e r f a c e
It e r a b l e In t e r f a c e Queue <T> ad = new ArrayDeque<> ();

Syntax of the Interfaces:

Interfaces Syntax

Iterable Interface Iterator iterator();

[Link] 3 /45 [Link] 3 /45


7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced 7/4/24, 12:02 AM Java Cheat Sheet (2023): Freshers and Experienced
Interfaces Syntax

Deque Interface Deque<T> ad = new ArrayDeque<> ();

Why Use Java? Features of Java


Set Interface Set<T> hs = new HashSet<> ();
Java is simple
Set<T> lhs = new LinkedHashSet<> (); 9
for Java is an Object Oriented Programming language.
Set<T> ts = new TreeSet<> (); programmers Java is Platform Independent because it comes with its own platform to run
to learn. Java is applications.
frequently
Sorted Set Interface Simple to learn programming language because doesn’t contain Pointers and operator
SortedSet<T> ts = new TreeSet<> (); chosen as the
overloading.
first
Map Interface Map<T> hm = new HashMap<> (); programming Java is secure because the Java program runs on Java virtual machine(JVM) so, if
language to there is any problem occurred in the program it will remain inside the JVM only, it
Map<T> tm = new TreeMap<> ();
learn. will not affect the operating system. Java is Architecture neutral because it is
Furthermore, independent of the platform so we do not have to design the program for
the sector continues to benefit from Java’s prominence. The majority of websites and different devices differently. Java is portable because, after the compilation of
apps in the government, healthcare, defence, and educational sectors continue to use any Java program, it generates a bytecode that can run on any machine which
Java technology. Java is thus worthwhile to learn and use. If you choose a career in has JVM. Java is Robust means Java comes with automatic garbage collection
Java, you can follow a number of different career routes. Almost anything that Java can management and strong exception handling.
accomplish. Java supports multithreading, It is possible in Java that we can divide a program into
two or many subprograms and run these programs/threads at the same time.
Why is Java so Popular?
Because Java includes a unique tool called the Java Virtual Machine that ensures the
Applications of Java Programming language
code functions consistently everywhere, it is feasible for Java to execute without any
issues on many types of computers and machines. This makes Java a popular Mobile Applications

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

[Link] 3 /45 [Link] 4 /45


Conclusion
This Java Cheat Sheet serves as a quick reference guide for both beginners and
experienced developers working with Java. By summarizing essential syntax, key
concepts, and common commands, it aims to enhance your productivity and ensure
you have the critical information at your fingertips. Whether you’re preparing for an
interview, working on a project, or simply refreshing your knowledge, this cheat sheet
is designed to make your Java development process more efficient and effective.

Java Cheat Sheet – FAQs

[Link] 4 /45 [Link] 4 /45


[Link] 4 /45

You might also like