Java Cheatsheet

by anupmaurya

Java is a very popular programming language. Java can be used to develop anything and almost everything like web applications, web servers, application servers, mobile applications and so on.


Sample Java program

import java.util.Date; public class HelloWorld { public static void main(String[] args) { Date now = new Date(); System.out.println("Hello World!"); System.out.println("now: " + now); } }
Code language: Java (java)
  • import – used to import java libraries
  • class keyword – to declare a class in java.
  • public keyword – access modifier represents visibility. Public is visible to all.
  • static keyword – no need to create an object to invoke the static method. There is no need to create an object to invoke the main method and it’s invoked by JVM and saves memory.
  • void – return type of the method and it doesn’t return any value.
  • main – starting point of the program.
  • String[] args – for command line arguments
  • System.out.println() – used to print statement.

To Compile a Java program

Go to Command prompt and navigate to the folder where java files are stored.

Code language: CSS (css)

To Run Java program

java example


// – single line comment

Data types

Two groups of data types

1. Primitive data types

Data typeDescriptionRangeSize
intused to store whole numbers-2,147,483,648 to 2,147,483,6474 bytes
shortused to store whole numbers-32,768 to 32,7672 bytes
longused to store whole numbers-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8078 bytes
byteused to store whole numbers-128 to 1271 byte
floatused to store fractional numbers6 to 7 decimal digits4 bytes
doubleused to store fractional numbers15 decimal digits8 bytes
booleancan either store true or falseeither true or false1 bit
charused to store a single characterone character2 bytes


int a = 99999; short b = 999; long c = 99999999999L; byte d = 99; double e = 99.99d; boolean f = true; char g = 'A';
Code language: JavaScript (javascript)

2. Non-Primitive data types

Non-primitive data types specifies the complex data values. For example, strings, arrays and classes can be referred as Non-primitive data types.


data-type variable-name = value;

Naming convention of variables

  • Case sensitive.
  • Must should begin with a lower case letter. For second word should be a capital like this: firstName, pinCode etc.
  • Cannot contain white spaces like first name.
  • special characters like $ and _ can be used to begin a variable name.

Types of Variables

  • Local Variables
  • Instance Variables
  • Static Variables
Class Sum { int n1 = 10; // value of Instance Variables are are instance specific. static int n2 = 20; //static variable is Common for all the instances of the class. void sum(){ int n3 = 30; //local variable and they are Inside the body of a method. int total = n1+n2+n3; } }
Code language: Java (java)

Data Conversions

  • String to Numberint i = Intege­r.p­ars­eIn­t(­str); double d =­rse­Dou­ble­(s­tr);
  • Other types to StringString str =­lue­Of(­va­l);


Operator typeDescription
Arithmetic Operator+ , – , * , / , %
comparision Operator< , > , <= , >=, != , ==
Bitwise Operator& , ^ , |
Logical Operator&& , `
Assignment Operator= , += , -= , *= , /= , %=
Auto-increment and Auto-decrement Operators++ , —
Ternary Operator? :


Array is a collection of similar data which is stored in continuous memory addresses.

data-type[] array-name; // one dimensional array data-type[][] array-name; // two dimensional array
Code language: PHP (php)


String[] mobiles = {"iPhone", "Samsung", "OnePlus"}; for (int i = 0; i < mobiles.length; i++) { System.out.println(mobiles[i]); } mobiles[1] = "Oppo"; // change an array element
Code language: Java (java)

Conditional Statements

1. If

if(conditional-expression) { //code }
Code language: JavaScript (javascript)

2. If-else

if(conditional-expression) { //code } else { //code }
Code language: Java (java)

3. If-else-if ladder

if(conditional-expression-1) { //code } else if(conditional-expression-2) { //code } else if(conditional-expression-3) { //code } .... else { //code }
Code language: Java (java)

4. Nested-If

if(conditional-expression-1) { //code if(conditional-expression-2) { //code if(conditional-expression-3) { //code } } }
Code language: Java (java)

5. Switch

switch(conditional-expression){ case value1: //code break; //optional case value2: //code break; //optional ... default: //code to be executed when all the above cases are not matched; }
Code language: Java (java)


1. For

for(Initialization; Condition; Increment/decrement){ //code }
Code language: JavaScript (javascript)

2. While

while(condition){ //code }
Code language: JavaScript (javascript)

3. Do-While

do{ //code }while(condition);
Code language: JavaScript (javascript)


SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don’t have any duplicates. Map is implemented in HashMap, TreeMap etc.

String Methods

char charAt(int index)returns char value at the specific indexstr.charAt(0) //prints o
int compareTo(String str)to compare two strings lexicographicallyStr1.compareTo(Str2) //returns 0 if str1 and str2 are equal
int length()returns string lengthstr.length()
static String format(String format, Object… args)returns a formatted string.String.format(“String is %s”,str);
String substring(int beginIndex, int endIndex)to return substring from given begin index to end index.str.substring(0,3) //prints one
String substring(int beginIndex)to return substring from given begin indexstr.substring(3) //prints compiler
boolean contains(CharSequence s)returns true or false after matching the sequence given in the stringstr.contains(“compiler”) // returns true
static String join(CharSequence delimiter, CharSequence… elements)returns a joined string.String.join(“..”,”Hello”,”Happy”, “Learning”); //returns Hello..Happy..Learning
boolean equals(Object another)checks the equality of string with another and returns true if they are equal.str1.equals(str2);
boolean isEmpty()to check if the given string is empty.str.isEmpty() // returns false
String concat(String str)concatenates the provided string with the another string.str.concat(” is used to compile code online”)
String replace(char old, char new)replaces all occurrences of the specified char value with new char value.str.replace(‘r’,’t’);
String replace(CharSequence old, CharSequence new)replaces all occurrences of the specific CharSequence with new one.str.replace(‘one’,’Online’);
static String equalsIgnoreCase(String another)compares another string with out considering case.str1.equalsIgnoreCase(str2)
String[] split(String regex, int limit)returns a split string matching regex and limit. here limit is optionalstr.split(“\s”)//splits string based on whitespaces
int indexOf(String substring, int fromIndex)returns the specified substring index starting with given index. here index is optionalstr.indexOf(“compiler”,2);
String toLowerCase()returns a string in lowercase.str.toLowercase();
String toUpperCase()returns a string in uppercase.str.toUpperCase();
String trim()removes beginning and trailing spaces of a given string.str.trim();


1. Class

Class is the blueprint of an object and class keyword is required to create a class.

class class_name { fields; methods; }
Code language: Java (java)

2. Object

Object is a basic unit in OOP, and is an instance of the class.

class_name obj_name;

3. Abstraction

Data abstraction is a technique which provides only the required data to be visible or accessible to outside world.
abstract keyword is used for classes and methods.

abstract class Mobiles { // abstract class public abstract void features(); // abstract method public void method-name() { //code } }
Code language: PHP (php)

4. Encapsulation

Encapsulation is a mechanism to protect private hidden from other users. It wraps the data and methods as a single bundle. private is the keyword used to declare the variables or methods as private. You can make public set and get methods to access private variables.

5. Polymorphism

Polymorphism gives the meaning many forms, usually it occurs when multiple classes are present and have been inherited.

class Child-class extends Parent-Class { //code }
Code language: Java (java)

If you have quires and suggestions put them in the comments.Hope this Java Cheatsheet useful to you, Share & Help Other to learn 🙂

You may also like