Java is a programming language and platform that has been widely used since its development by James Gosling in 1991. It follows the Object-oriented Programming concept and can run programs written on any OS platform. Java is a high-level, object-oriented, secure, robust, platform-independent, multithreaded, and portable programming language all those words are collectively called Java Buzzwords.
It is commonly used for programming web-based, Windows, enterprise, and mobile applications. This Java Cheat Sheet article has been written by experts in Java and is based on the experience of students who have recently undergone Java interviews.
This Core Java Cheat Sheet has been designed by Java experts, based on the experience of students who have recently undergone Java interviews. Whether you are a beginner or an experienced Java developer, this Java Cheat Sheet for competitive programming is a valuable resource for quickly accessing essential syntax, concepts, and best practices related to Java Programming .
Now, we will explore some of the fundamental concepts often utilized in the Java programming language.
Object – An object refers to an entity that possesses both behavior and state, such as a bike, chair, pen, marker, table, and car. These objects can be either tangible or intangible, including the financial system as an example of an intangible object.
There are three characteristics of an object:
Class – A class is a collection of objects with similar attributes. It’s a blueprint or template from which objects are made. It’s a logical thing. It can’t be physical. In Java, a class definition can have the following elements:
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 initialization.
Keyword – In Java, Reserved words are also known as keywords. These are particular terms that hold specific meanings. Java has 61 Reserved Keywords that are predefined and cannot be used as variable, object, or class names. Here’s a list of the keywords used in Java:-
Keyword | Use Case |
---|---|
abstract | Used to declare an abstract class or abstract method |
assert | Used to check assertions during debugging |
boolean | Represents a boolean value (true or false) |
break | Exits from a loop or a switch statement |
byte | Represents a signed 8-bit integer |
case | Used in a switch statement to define a case |
catch | Catches exceptions thrown in a try block |
char | Represents a 16-bit Unicode character |
class | Declares a class |
const* | Not used in Java, reserved for future use |
continue | Skips the rest of the loop and starts the next iteration |
default | Used in a switch statement as a default case |
do | Starts a do-while loop |
double | Represents a 64-bit double-precision floating-point number |
else | Used in an if-else statement |
enum | Declares an enumeration type |
exports | Used in module declarations to specify exported packages |
extends | Indicates a class is derived from another class |
final | Declares a variable, method, or class as final (unchangeable) |
finally | Defines a block of code to be executed after try-catch |
float | Represents a 32-bit single-precision floating-point number |
for | Starts a for loop |
goto* | Not used in Java, reserved for future use |
if | Used in an if statement |
implements | Indicates a class is implementing an interface |
import | Imports classes, packages, or individual members |
instanceof | Tests if an object is an instance of a specific class |
int | Represents a 32-bit integer |
interface | Declares an interface |
long | Represents a 64-bit integer |
module* | Defines a module, reserved for future use |
native | Indicates a method is implemented in platform-specific code |
new | Creates a new object |
open | Used in module declarations to specify open packages |
opens | Used in module declarations to specify opened packages |
private | Defines a private access modifier |
protected | Defines a protected access modifier |
provides | Used in module declarations to specify service providers |
public | Defines a public access modifier |
requires | Used in module declarations to specify required modules |
return | Exits a method and returns a value |
short | Represents a 16-bit integer |
static | Declares a static variable or method |
strictfp | Ensures consistent floating-point calculations |
super | Refers to the parent class |
switch | Selects one of many code blocks to be executed |
synchronized | Defines a synchronized block or method |
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 |
Hello World!
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:-
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 primitive data types, including:
Type
Size
Example Literals
Range of values
characters representation of ASCII values
1.23e100f , -1.23e-100f , .3f ,3.14F
upto 7 decimal digits
1.23456e300d , -123456e-300d , 1e1d
upto 16 decimal digits
Non-primitive datatypes are created from primitive datatypes. Examples of non-primitive datatypes include arrays, stacks, and queues.
There are three types of comments in Java
To comment on a single line of code, you can use a double forward slash “//” followed by your message. This syntax is commonly used for coding.
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.
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
*This is
*sample comment */
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;
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
Instance variables are non-static variables and are declared in a class outside of any method, constructor, or block.3. Static Variables
Static variables are also known as class variables. The static variables are declared using the static keyword within a class outside of any method, constructor, or block.
Below is the Example of the above topic:
Before Calling function count:0 10 After Calling function count:1 Instance variable value:11
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
There are four types of access modifiers available in Java:
Comparison Operators are the Operators which return a boolean value as the result means the answer will be either true or false.
Less Than Equal to
Greater Than Equal to
Here is the table representing the precedence order of Java operators from high to low as we move from top to bottom.
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 |
==, !== | Left to Right | Equality |
& | Left to Right | Boolean Logical AND |
^ | Left to Right | Boolean Logical Exclusive OR |
| | Left to Right | Boolean Logical Inclusive OR |
&& | Left to Right | Conditional AND |
|| | Left to Right | Conditional OR |
?: | Right to Left | Conditional |
=, +=, -=, *=, /=, %= | Right to Left | Assignment |
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.
2. Nested if – else
A nested if is an if statement that is the target of another if or else. Nested if statements mean an if statement inside an if statement.
i is smaller than 15 i is smaller than 12 too
Friday
Loops are used for performing the same task multiple times. There are certain loops available in Java as mentioned below:
Java
Java
1 2 3 4 5
Java Methods are collections of statements that perform some specific task and return the result.
( list_of_parameters)
//body
>
0 1 2 1 2 3 2 3 4
We can only print using System.out but can use different print varieties in it:
The cursor remains on the same line
System.out.print(" GFG " + x);
Cursor Moves to a new line
System.out.println(" GFG " + x);
The cursor remains on the same line
System.out.printf(" GFG %d",x);
System.out.printf("%7.5f", Math.PI);
7 is the Field width and .5 is the precision fo the floating number printed . So, answer will be 3.14159
We can take input using the Command line simp
javac GFG.java
java GFG This is just to check 2
Output:
This
is
just
to
Check
2
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
Entered String : ABC
Entered Integer : 11
Syntax:
Scanner scn = new Scanner(System.in);
Below is the implementation of the above method:
ABC
65
Name :ABC
Marks :65
Polymorphism: It is the ability to differentiate between entities with the same name efficiently.
Compile-time polymorphism: Static polymorphism, also called compile-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:
3 7.370000000000001
Inheritance: It is the mechanism in Java by which one class is allowed to inherit the features (fields and methods) of another class.
Salary : 70000 Benefits : 15000
In Java, there exists a Math Library that can simplify intricate calculations
import java.lang.Math;
Use:
Math.function_name
Returns or Calculates
minimum of a and b
maximum of a and b
toRadians( int θ )
Convert angle in degrees(θ) to radians
toDegrees( int θ )
Convert angle int radians(θ) to degrees
exponential value e a
natural log -> log e a
pow( int a, int b )
round to the nearest integer
returns the random value in [0,1)
the square root of a
value of e (constant value)
Value of π(constant value)
Note: All the functions mentioned above can be used with either data-types not bounded any single data-types.
Type Casting is a method in which we convert from one data type to another.
Type Conversion in Java is a technique where we can convert from double, int, and float to double.
display the casted value Java
Arrays are the type of data structure that can store data of similar data types. Arrays are allocated in contiguous memory allocation with a fixed size.
Syntax:
// Both Methods are correct
int arr[]=new int[20];
int[] arr=new int[20];
Below is the implementation of the above method:
arr[0] :10 arr[1] :20 arr[2] :30 arr[3] :40 arr[4] :50
Arrays are not bounded to be single-dimensional but can store elements in multidimensional.
Syntax:
int[][] arr= new int[3][3];
int arr[][]=new int[3][3];
Below is the implementation of the above method:
1 2 3 4 5 6 7 8 9
Strings are the type of objects that can store the character of values. A string acts the same as an array of characters in Java.
Syntax:
String abc=" ";
StringBuffer s = new StringBuffer("GeeksforGeeks");
StringBuilder str = new StringBuilder();
str.append("GFG");
public StringJoiner(CharSequence delimiter)
Regular Expressions, or Regex for short, is a Java API that allows users to define 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 passwords. The java.util.regex package contains regular expressions and consists of three classes and one interface. The following table lists the three classes included in the java.util.regex package:
Class | Description |
---|---|
util.regex.Pattern | It is used to define patterns. |
util.regex.Matcher | It is used to conduct match operations on text using patterns. |
PatternSyntaxException | In a regular expression pattern, it’s used to indicate a 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 flags) | Turns a regular expression into a pattern using the flags provided. |
flags() | Gets the match flags for this pattern. |
matcher(CharSequence input) | Builds a matcher that compares the given input to the pattern. |
matches(String regex, CharSequence input) | Matches a regular expression and tries to match it against the given input. |
pattern() | Gets the regular expression that was used to create this pattern. |
quote(String s) | Generates a literal pattern String from the given String. |
split(CharSequence input) | Splits the given input sequence around patterns that match this pattern. |
split(CharSequence input, int limit) | Divides the given input sequence into sections based on matches to this pattern. The number of times the pattern is applied is controlled by the limit parameter. |
toString() | Returns the pattern’s string representation. |
Matcher Class: T o evaluate previously described patterns through match operations on an input string in Java, the ‘object’ is utilized. No public constructors are defined here. One can execute a matcher() on any pattern object to achieve this. The table below displays the methods present in this class along with their descriptions:To evaluate previously described patterns through match operations on an input string in Java, the ‘object’ is utilized. No public constructors are defined here. One can execute a matcher() on any pattern object to achieve this.
The table below displays the methods present in this class along with their descriptions:
Method | Description |
---|---|
find() | find() is mostly used to look for multiple occurrences of regular expressions in a text. |
find(int start) | It is used to find occurrences of regular expressions in the text starting from the provided index. |
start() | start() is used to retrieve the start index of a match found with the find() method. |
end() | It’s used to acquire the end index of a match discovered with the find() method. |
groupCount() | groupCount() is a function that returns the total number of matched subsequences. |
matches() | It’s used to see if the pattern matches the regular expression. |
Exception: – An Exception is an unexpected error that occurs during the run-time of a program.
When a program encounters an error, it means there is a significant issue that a well-designed program should not try to fix. On the other hand, an exception indicates a particular situation that a well-designed program should try to handle.
Types of Exceptions:-
Checked Exception :- This mainly includes IO Exceptions and Compile time Exceptions
Unchecked Exceptions: – This covers both Runtime Exceptions and Null Pointer Exceptions.
try block : The try block comprises a set of statements that may throw an exception.
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 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 will always run, regardless of whether or not an exception has been caught. If there is a catch block following a try block, it will be executed before the finally block. However, if there is no catch block, the finally block will be executed immediately after the try block.
Example:-
tryBelow is a table that outlines the distinctions between the terms final, finally, and finalize:
final
finally
finalize
throw keyword:- When using Java, the throw keyword is utilized to throw an exception from a block of code or a method. It is possible to throw either a checked or unchecked exception. The throw keyword is frequently used for throwing custom exceptions.
throws keyword:- If a try/catch block is not present, the throws keyword can be used to manage exceptions. This keyword specifies the specific exceptions that a method should throw if an exception happens.
Here are the most commonly used Java commands:
Here are some other useful Java commands:
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 that operates on a parameterized type is a generic entity.
Generic Method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters that are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.
// To create an instance of generic class
BaseType obj = new BaseType ()
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 the generic method. The compiler handles each method.
java.lang.Integer = 11 java.lang.String = GeeksForGeeks java.lang.Double = 1.0
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
Example: – Thread creation by extending the Thread class
To create a new thread in Java, we can extend the java.lang.Thread class and override its run() method. This is where the thread’s execution starts. Then, we can create an instance of our class and call the start() method to begin the execution of the thread. The start() method will then call the run() method of the Thread object.
Thread 15 is running Thread 17 is running Thread 14 is running Thread 12 is running Thread 13 is running Thread 18 is running Thread 11 is running Thread 16 is running
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:
List al = new ArrayList<> ();
List ll = new LinkedList<> ();
List v = new Vector<> ();
Queue pq = new PriorityQueue<> ();
Queue ad = new ArrayDeque<> ();
Deque ad = new ArrayDeque<> ();
Set hs = new HashSet<> ();
Set lhs = new LinkedHashSet<> ();
Set ts = new TreeSet<> ();
Sorted Set Interface
SortedSet ts = new TreeSet<> ();
Map hm = new HashMap<> ();
Map tm = new TreeMap<> ();
Java is simple for programmers to learn. Java is frequently chosen as the first programming language to learn. Furthermore, the sector continues to benefit from Java’s prominence. The majority of websites and apps in the government, healthcare, defence, and educational sectors continue to use Java technology. Java is thus worthwhile to learn and use. If you choose a career in Java, you can follow a number of different career routes. Almost anything that Java can accomplish.
Because Java includes a unique tool called the Java Virtual Machine that ensures the 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 programming language. A rule in Java also known as WORA states that code only has to be written once and may execute anywhere. Java’s high level of security, which shields the code from hackers, viruses, and other dangers, is another factor in its popularity. Java also enables the creation of many jobs that may run concurrently within a programme, making it quicker and more effective. Java provides a clever method for generating code that primarily concentrates on.
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 is simple to learn programming language because doesn’t contain concepts like: Pointers and operator overloading and it is secure and portable.
C++ | JAVA |
C++ is platform dependent. | Java is platform-independent. |
C++ uses a compiler only. | Java uses a compiler and interpreter both. |
C++ support pointers and operator overloading. | Java doesn’t support pointers and operator overloading concepts. |
C++ does not support the multithreading concept. | Java supports the multithreading concept. |
The most important features of Java are Platform Independent and Object Oriented. That’s why Java is the most popular among high-level programming languages.
Java is useful in developing real-world web or mobile applications, and also useful to build servers. There are a lot of things you can do in Java, there are multiple libraries, and using that you can do anything. The application built in Java can be distributed over the internet or on any network.
The developer community of Java is so vast and is the strength of the Java language. This technology is growing at a fast pace and job opportunities are also increasing for Java developers having good knowledge of Java technologies. As Java is scalable, you can find Java in mobile applications, software applications, servers, and web applications.