Java Cheat Sheet: Essential Concepts for Beginners

This cheat sheet covers the most essential Java concepts that beginners need to know, including variables, data types, operators, functions, classes, and objects. This cheat sheet is perfect for beginners who want to learn Java quickly and easily.

Java CheatSheet for Developers

Data Types

Data TypeSize
boolean1 bit
char2 byte
int4 byte
short2 byte
long8 byte
float4 byte
double8 byte

Data Conversion

String to Number

    int i = Intege­r.p­ars­eInt(_str_);  
	double d = Double.pa­rse­Double(_str_);

Any Type to String

	String s = String.va­lueOf(_value_);  

Numeric Conversions

	int i = (int) _numeric expression_; 

Operators

Operator CategoryOperators
Arithmetic operators+, -, /, *, %
Relational operators<, >, <=, >=,==, !=
Logical operators&&, ||
Assignment operator=, +=, −=, ×=, ÷=, %=, &=, ^=, |=, <<=, >>=, >>>=
Increment and Decrement operator++ , - -
Conditional operators?, :
Bitwise operators^, &, |
Special operators. (dot operator to access methods of class)

Statements

If Statement

if ( _expression_ ) {  
­ _statements_  
} else if ( _expression_ ) {  
­ _statements_  
} else {  
­ _statements_  
}  

While Loop

while ( _expression_ ) {  
­ _statements_  
}  

Do-While Loop

do {  
­ _statements_  
} while ( _expression_ ); 

For Loop

for ( int i = 0; i < _max_; ++i) {  
­ _statements_  
}  

For Each Loop

for ( _var_ : _collection_ ) {  
­ _statements_  
} 

Switch Statement

switch ( _expression_ ) {  
­ case _value_:  
­ ­ ­ _statements_  
­ ­ ­ ­break;  
­ case _value2_:  
­ ­ ­ _statements_  
­ ­ ­ ­break;  
­ ­def­ault:  
­ ­ ­ _statements_  
} 

Exception Handling

try {  
­ ­sta­tem­ents;  
} catch (_Except­ionType_  _e1_) {  
­ ­sta­tem­ents;  
} catch (Exception _e2_) {  
­ ­cat­ch-all statem­ents;  
} finally {  
­ ­sta­tem­ents;  
}

String Methods

CommandDescription
lengthlength of string
charAt(i)extract _i_th character
subst­ring(start, end)substring from start to end-1
toUpp­erC­ase()returns copy of s in ALL CAPS
toLow­erC­ase()returns copy of s in lowercase
indexOf(x)index of first occurrence of x
replace(old, new)search and replace
split(regex)splits string into tokens
trim()trims surrounding whitespace
equals(s2)true if s equals s2
equalsIgnoreCase(s2)true if s equals s2 ignoring the upper/lowercase
compareTo(s2)0 if equal/+ if s > s2/- if s < s2
concat(s2)appends s2 to the end of s
contains(s2)Checks whether a s contains a sequence of characters (s2)
replace(s2)Searches the specified string s2 , and returns a new string where the specified values are replaced
toCharArray()Converts the string to a new character array

Math Library Methods

CommandDescription
abs(x)abstract value of x
max(a, bmaximum of a and b
min(a, b)minimum of a and b
Evalue of e (constant)
sin(theta)sine of theta
cos(thetacosine of theta
tan(theta)tangent of theta
round(x)Returns the value of x rounded to its nearest integer

Types of Variables

Variable TypeScopeLifetime
Instance variableThroughout the class except in
static methods
Until the object is available in the
memory
Class variableThroughout the classUntil the end of the program
Local variableWithin the block in which it is
declared
Until the control leaves the block
in which it is declared

Java Regex

Matcher Class

MethodDescription
matches()tests whether the regex matches the pattern
find()finds the next expression that matches the pattern
find(int a)finds the next expression that matches from the start number a
group()returns the matched subsequence
start()returns the starting index of the matched subsequence
end()returns the ending index of the matched subsequence

Inheritance in Java

Inheritance - It is the property of a child/derived/subclass, allowing it to inherit the properties() and functionalities or data members methods from its parent/base/superclass.

Java supports 4 types of inheritance:

  1. Single Inheritance
  2. Multi-level Inheritance
  3. Hierarchical Inheritance
  4. Hybrid Inheritance

Single Inheritance:

As the title indicates, just one class is subject to this kind of inheritance. The parent class gives rise to just one child class.

Syntax:

Class A{
  //your parent class code
}
Class B extends A {
   //your child class code
} 

Multi-Level Inheritance:

In multi-level inheritance, one class has more than one parent class but at different levels of inheritance.

Syntax:

Class A{
  //your parent class code
}
Class B extends A {
   //your code
}
Class C extends B {
    //your code 
} 

Hierarchical Inheritance

In hierarchical inheritance, one parent can have one or more child/sub/derived classes.

Syntax:

Class A{
  //your parent class code
}
Class B extends A {
   //your child class code
}
Class C extends A {
    //your child class code 
}

Hybrid Inheritance:

Hybrid Inheritance is the combination of more than one type of inheritance in a single program.

NOTE

Multiple inheritance is not supported in Java as it leads to the diamond problem. 
We can achieve Multiple inheritance in Java by using the concept of Abstraction.

Encapsulation in Java

Encapsulation - It is wrapping of data members (variables) and functions (methods) together as a single unit. It is also known as data hiding, as variables of class is hidden from other classes and can be accessed only through methods of that class.

Encapsulation in Java can be achieved through packages

Java Packages

A java package is a group of similar types of classes, interfaces and sub-packages. It provides access protection and prevents naming collision.

package mypack; public class Demo{ public static void main(String args[]){ ­ _statements_   } }

To Compile: javac -d . Demo.java To Run: java mypack.Demo Accessing package from another package: import package.* or import package.className.*

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Abstraction can be achieved in 2 ways in Java

  1. Abstract class
  2. Interface

Abstract class

Class declared with abstract keyword, which cannot be instatiated and has to be extended by other classes for its methods to be implemented. It can have both abstract and non-abstract methods.

    abstract class A{  
      abstract void demo();  
    }  
	//Abstract class extended by other class to implement its methods
	class B extends A{
		void demo(){
			_statements_  
		}
	}

Interface

Interface is blueprint of class having public abstract methods and public static final constants. It cannot be instatiated. Interface is extended by other interfaces and implemented by class.

interface Printable{
	void print(); //empty method body
}
class Demo implements Printable{
	public void print(){
		_statements_
	}
}

Polymorphism in Java

Polymorphism is a concept by which we can perform single action in different ways. It is of two types: compile-time polymorphism (method overloading) and run-time polymorphism (method overriding).

Method overloading

It is compile-time polymorphism. If a class has multiple methods having same name but different parameters, it is known as Method Overloading. Parameters can differ in number of arguments or data type of arguments.

class Demo{
	int add(int a, int b){return a+b;}
	double add(double a, double b, double c){return a+b+c;}
}

Method overriding

It is run-time polymorphism. If a child class provides specific implementation of method declared in parent class, it is known as method overriding.

class Vehicle{
	void run(){System.out.println("Vehicle is running")};
}
class Car{
	void run(){System.out.println("Car is running")};
}

Collections

CollectionDescription
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.
StackLIFO approach, stack is a sub ordinate of vector which helps in performing different functions.
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.

#java

Java Cheat Sheet: Essential Concepts for Beginners
7.20 GEEK