Java Cheat Sheet

By | February 10, 2021
Java Cheat Sheet
  • Java is an Object-Oriented programming language.
  • It is the most powerful and widely used programming language.
  • It is an Open Source, so everyone is free to use java.
  • Available for cross-platform.
  • Its byte code is platform-independent.
  • Garbage Collected language
  • The static type of language which fast performance.

Java Characteristics

Here are some characteristics of Java which makes it the most used programming language.

  • Simple
  • Pure Object-Oriented.
  • Portable
  • Platform Independent
  • High Scalability
  • High Performance.
  • Multi-Threading
  • Static Typed language.

Data Types in Java

Java has two types of Data Types.

  • Primitive Data Types
  • Non-Primitive data types.

Primitive Data Type

Those data types which can not be divided further, these are also known as atomic data types.

Primitive Data Types Size Default Value
int 4 bytes 0
char 2 bytes ” ” <SPACE>
boolean 1 bit False
float 4 bytes 0.0f
double 8 bytes 0.0d
long 8 bytes 0
short 2 bytes 0

Non-Primitive Data types

Non-Primitive data types can be divided further into primitive data types.

  • Array
  • String
  • Class
  • Interface

Type Casting

Type Casting is a method by which data type of one variable gets converted into another data types. There are two types of Typecasting

  • Implicit typecasting: In Implicit Typecasting Java Compiler, itself change the data type of variable, without user intervention.
  • Explicit Typecasting: In Explicit Typecasting user, itself change the data type of the variable from one to another using the reserved keywords.

Operators in Java

There are many standard operators present in Java.

Category Operators
Arithmetic Operators
  • +
  • *
  • /
  • %
Relational Operators
  • >
  • <
  • <=
  • >=
  • ==
  • !=
Logical Operators
  • &&
  • ||
Assigment Operators
  • =
  • +=
  • -+
  • *=
  • /=
  • %=
  • &=
  • |=
  • <<=
  • >>=
  • >>>=
Increment Operator
  • ++
Decrement Operator
Conditional Operator
  • ?:
Bitwise Operators
  • ^
  • &
  • |
Dot Operator to call class method and attributes
  • .

Best IDE for Java

There are many IDE’s and Text Editors on the internet on which you can code for java, here are the two most suggested IDE’s for Java development.

  • Eclipse
  • IntelliJ IDEA Community Edition

Variables in Java

Variables or Identifiers are the names given to an object which is stored at a particular address, with the variable we can access that object or value very easily.

In Java there are 3 types of Variables:

  • Local Variable
  • Global Variable
  • Static Variable.
Types Description
Local Variables
  • Variables declared inside the block of methods and constructor.
  • Local variables are limited to the method block in which they are declared.
  • The lifecycle of the local variable starts with method calling and end with method termination
Global Variables
  • Variables declared outside the block of methods or constructor.
  • Any method can access a global variable.
Static Variable
  • We use static keyword to create a static variable.
  • Static variables create a single memory and other variables can share it.


class Variables
int g = 20; // Global variable
static int s = 10; //static variable
void method()
int l = 100;            //local variable


There are many words in Java, which are reserved, and we can not use those as a variable or identifier, they are also known as reserved words.

Some Keywords of Java:

  • for
  • if
  • abstract
  • class
  • catch
  • else
  • enum
  • finally
  • new
  • static
  • int
  • char
  • float
  • switch
  • this
  • throw
  • super
  • try
  • except
  • implement

Java Methods

We use methods in Java to provide the functionality to our program, and methods increase the reusability of codes. Methods are the functions defined inside a class.

There are some notations we should take care of while we write a method in Java.

  • Return Type of the method (void, int, float)
  • Name of the method (method name, like a variable)
  • Arguments (paraments we pass in the method)
  • return (a return statement, which returns a single value when we call the function, no return statement with a void return type)

Syntax example:

return_type name (arguments)
//body of the method
//return value ()               // except void return_type

Conditional Statements in Java

Conditional Statements Description
if-else It contains two blocks if block and else block, the if statement works on a boolean value, if the boolean value is true, the if block will execute, otherwise the else block execute.
switch It consists of different cases and the case which matches with the switch parameter value that block of case get to execute.

Example (if-else):

class IFELSE
public static void main(String args[])
int num = 70;
if(num > 75)
System.out.println("Number is greater than 75");
System.out.println("Number is less than 75");

Example (switch):

class Switch_Case
public static void main(String args[])
int day = 0;
case 0 :
case 1 :
case 2 :
case 3 :
case 4 :
case 5 :
case 6 :
case 7 :

Loops in Java

Loops are often used to execute a same block of statement again and again, up to finite time. In java we have 3 types of Loop:

Loops Description
for We use for a loop when we are certain to a specific number of times we want to iterate over a block of code.
while The while loop executes the same statement of code again and again its condition is true.
do-while It is similar to while loop, but even the condition is False the while loop iterate over its block of code once.

Example (loops):

for loop

class For_LOOP
public static void main (String args[])
for(int i=0;i<=10;i++)

While Loop:

class While_LOOP
public static void main (String args[])
int i = 1;

do while:

class Do_While_Loop
public static void main (String args[])
int i = 1;

Java OOP’s

Java is an Object-Oriented programming language because it supports the basic property of Object-oriented programming such as polymorphism, Class, Objects, Inheritance, abstraction, etc. With the help of Object-Oriented concept, we can increase the efficiency of programming and software development.

Properties of Object-Oriented Programming:

  • Class and Objects
  • Data Abstraction and Encapsulation
  • Inheritance
  • Polymorphism
Class and Object

A class is a structure which provides a blueprint of functionality, a class is a collection of methods and attributes where methods are the user-defined functions and attributes are the variables associated with that class

A class come in existence when its object gets created. With the help of object, we can access the class properties which includes class attributes and methods.

Data Abstraction and Encapsulation

With data encapsulation, we can wrap a collection of data to a single entity.  For example, with a class, we wrap many methods and attributes.

Data Abstraction is an integration of data encapsulation with data abstraction we can hide the data from the user. User deal with the object, with no knowledge of class and its method working.


Inheritance is one of the major concepts of Object-Oriented programming, with inheritance concept we can inherit the properties and methods from one class to another.

  • A derived class can not inherit the private members of the base class.
  • A constructor can also be not inherited.
Types of Inheritance
  • Single Inheritance: In single inheritance, there is only one base and one derived class. Minimum 2 classes required for single inheritance.
  • Multilevel Inheritance: In multilevel inheritance, the derived class itself is a base class for another class. Minimum 3 class required for multiple inheritances.
  • Multiple Inheritance: In Multiple inheritances, the child or derived class can 2 or more than 2 base or parent classes. Java does not have standard support for Multiple inheritance here we use Java interface.
  • Hierarchical Inheritance: When two or more than two child class inherit properties from same base or parent class.
class A
void a_method() {
System.out.println(" From Class A");
class B extends A {
void b_method() {
System.out.println("From Class B" );
class Inheritance {
public static void main(String args[]) {
A a = new A();
B b = new B();

Polymorphism deals with, the same operator performing different tasks. In Java to perform a polymorphism concept, we do method overloading and method overriding.

Method Overriding

When the child class has the same method name, with the same data types of argument as parent class. Here the child class override the method of the parent class.


class Base
void method()
System.out.printf("Method of Base");
class Derived extends Base
void method()
System.out.printf("Method of Derived");
public static void main (String args[])
Derived obj = new Derived();

Method Overloading

When a class has two or more methods with the same name but different parameters are known as method overloading.


class Overloading
    public void over(int i)
    public void over(int i, int num) 
         System.out.println(i +num);
class Main_Class
   public static void main(String args[])
       Overloading obj = new Overloading();

Abstract Class

To define an Abstract class, we use the abstract keyword before the class itself. The abstract class can not be inherited by any class.


abstract class Bus{
abstract void buy();
class Tata extends Bus{
void buy()
System.out.println("Go For it");
static void main(String args[]){
Bus obj = new Tata ();;


An interface in Java helps to implement the concept of abstraction, in an interface class, we only have abstract methods no method body. With Interface we can also achieve multiple inheritance in Java.


interface Sun{  
void rays();  
class Mercury implements Sun{  
public void rays(){System.out.println("Mercury");}  
class Earth implements Sun{  
public void rays(){System.out.println("Earth");}  
class Sunlight{  
public static void main(String args[]){  
Sun e =new Earth(); 

Java Constructor

  • A Constructor is a special method of a class which call automatically when we initialize the class object.
  • The Constructor shear the same name as Class
  • The constructor does not have any return type.
  • The Constructor can’t be static, abstract or final.
  • A constructor can have parameters.


class Cons {
Cons()   // Constructor of Box
class BoxVol {
public static void main(String args[])
Cons mybox1 = new Cons();  // initializing object and calling constructor


An Array is a collection of similar data types, which stores its all items in a contagious memory location. We can store primitive data types in an array. The array supports indexing that’s how we can randomly access any item of the array.

Java supports two types of array:

  • One Dimensional Array
  • 2 Dimensional arrays.


int [] numbers = {3,44,12,53,6,87};
int [][] m1 = { {1,5,7}, {2,4,6}};
int [][] m2 = {{1,2,1},{4,4,3}};

Strings in Java

A string is a sequential collection of characters inside “ ” double-quotes. It is an array of char data types. By default, the last element of a string is ‘\0’ (Null).

Strings are immutable, which mean once a string is declared we cannot modify its elements. To define a string, we use String keyword.

Syntax to define a String:

<String_Type> <string_variable> = “<sequence_of_string>”;
<String_Type> <string_variable> = new String  (“<sequence_of_string>”); 


String str = " TechGeekBuzz "
String str = new String("TechGeekbuzz");

Java String Standard Methods

There are many Standard Methods associated with the Java Stings:

Method Description
toLowerCase() Conversion of string to lowercase
toUpperCase() Conversion of string to upper case
replace(‘x’ , ‘y’) replaces all value of ‘x’ with ‘y’
trim() Remove the end and beginning whitespace
equals() To check whether two strings are equal or not, return a boolean value
equalsIgnoreCase() To check whether two strings are equal or not, return a boolean value.
length() Return the total number of characters in the string
CharAt(n) Return the nth character value
compareTo() Compare two strings.
concat() Join Two strings
substring(n) Return the part of the string from nth index
substring(n,m) Return a sequence of string between n to m
toString() Help to provide a string representation
indexOf(‘x’) Return the index value of “x” character
indexOf(‘x’,n) Return the index value of x after the nth index
ValueOf (Variable) converts the parameter value to the string representation


It is an extension of string data type, which provides more functionality, and it creates a CharSequence which is better than sting for some cases. The CharSequence generated by StringBuffer is growable and writable.


StringBuffer s = new StringBuffer("TechGeekBuzz");


StringBuilder creates a mutable string.
StringBuilder str = new StringBuilder();

Compare two String in Java:

public class TechGeekBuzz {
         public static int Compare_String(String str1, String str2)
        int len1 = str1.length();
        int len2 = str2.length();
        int lenmin = Math.min(len1, len2);
        for (int i = 0; i < lenmin; i++) {
            int str1_ch = (int)str1.charAt(i);
            int str2_ch = (int)str2.charAt(i);
              if (str1_ch != str2_ch) {
                return str1_ch - str2_ch;
        if (len1 != len2) {
            return len1 - len2;
        else {
            return 0;
    public static void main(String args[])
        String string1 = new String("TechGeekBuzz");
        String string2 = new String("Tech");
          System.out.println( Compare_String(string1, string2));

Multithreading in Java

In java, we have a multithreading feature, which allows our different methods to work concurrently so we optimize the CPU utilization with different methods. As threads are the small processes inside a process, and with multithreading, we can concurrently execute each thread for better performance.

Thread Life Cycle

New Thread —>   Runnable Thread  —>    Running Thread —–>   Block Thread –> Dead State

Exception Handling in Java

Exceptions are abnormal errors often occur at run time due to some irregular input or conditions. There are the bugs which affect the efficiency and the working of the complete program.

So, to tackle the exception we have some reserved keywords in Java which can catch and raise errors if there is an exception in the program.

Here are some Common Exception (Runtime Errors) you will see in Java.

Exceptions Description
ArithmeticException Error because of Arithmetic Expression
ZeroDivisionException Dividing a value with 0
ArrayIndexOutOfBoundException No such index number
ArrayStoreException When trying to insert different data type in an array
FileNotFoundException Accessing that file which does not exist
IOException Input or output error
NullPointerException referencing a null object.
NumberFormatException When typecasting does not work
OutOfMemoryException No memory for the variable
StringIndexOutOfBoundException When there is no index for a particular string.

try…..catch Statement in Java.

Try and Catch are the two statements work alike if…else statement. We use to try and catch statements to handle the exception.

The try block contains the code which could contain some exception, and catch block contains the code which will execute if an exception occurs in try block.

There is another keyword “throw” which is used to raise an error and terminate the complete program.


class Exception_Handaling
public static void main(String args[])
int x = 10/0;
catch(ArithmeticException e)
System.out.println("Division by zero");

Finally, Statement:

With try and catch we can also use the finally statement, the main thing about finally statement is, no matter what happens, whether the try or catch block execute, the code inside the finally block will execute in any case.


//try block
//finally block


the throw is a special keyword in Java which is used to raise an exception in the program. With throw keyword, we can raise our own exceptions.

Files in Java

Though we have data structures to save data, but the problem with data structure is they are temporary and once the program is completely executed al the data get destroyed. So, to save the data we use file handling.

In java with code, we can create txt files on which we can store data. The file we have created we can read it too, whenever we want.

Once we have created a file, we can perform various operations on it which include, write on the file, read from the file, and delete the file.

Java File Streams

As by its name, stream determine the flow of data, when we deal with the file the stream decide which path and pattern should we follow to perform appropriate operations. In Java, we have two streams Input and output stream

  • Input Stream: With input stream, we can read data from a file.
  • Output Stream: Output stream accept data from user and write it into the file.

File Reading and Writing Process

import –>  Create or Open File –> Read or Write in to file –> Close the file


// Create a file
File Obj = new File("file.txt");
// Write in the file
FileWriter write_file = new FileWriter("file.txt");
write_file.write(“   ”)       // write in the file
write_file.close()                              //close file
//Read from a File:
File read_file = new File("File.txt"); 

Memory Management in Java

Whenever we write the program all of its function and variables require some memory to execute, so the compiler provides two memory types of memory to the different methods and variables. Java has garbage collector which automatically allocate and deallocate memory.

  • The Java Compiler store the program properties into either heap or stack memory.
  • The local variables and methods store in Stack Memory.
  • The instances are stored in heap memory.

People Also Read:

Leave a Reply

Your email address will not be published. Required fields are marked *