Java Cheatsheet
Java Cheatsheet
Back to Top
Data Conversion
String to Number
int i = Integer.parseInt(_str_);
double d = Double.parseDouble(_str_);
Back to Top
String s = String.valueOf(_value_);
Back to Top
Numeric Conversions
int i = (int) _numeric expression_;
Back to Top
Operators
Operator Category Operators
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)
Back to Top
Statements
If Statement
if ( _expression_ ) {
_statements_
} else if ( _expression_ ) {
_statements_
} else {
_statements_
}
Back to Top
While Loop
while ( _expression_ ) {
_statements_
}
Back to Top
Do-While Loop
do {
_statements_
} while ( _expression_ );
Back to Top
For Loop
Back to Top
Back to Top
Switch Statement
switch ( _expression_ ) {
case _value_:
_statements_
break;
case _value2_:
_statements_
break;
default:
_statements_
}
Back to Top
Exception Handling
try {
statements;
} catch (_ExceptionType_ _e1_) {
statements;
} catch (Exception _e2_) {
catch-all statements;
} finally {
statements;
}
Back to Top
String Methods
Command Description
length length of string
charAt(i) extract _i_th character
substring(start, end) substring from start to end-1
toUpperCase() returns copy of s in ALL CAPS
toLowerCase() 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)
Searches the specified string s2 , and returns a new string where
replace(s2)
the specified values are replaced
toCharArray() Converts the string to a new character array
Back to Top
Back to Top
Types of Variables
Variable Type Scope Lifetime
Throughout the class except in Until the object is available in the
Instance variable
static methods memory
Class variable Throughout the class Until the end of the program
Within the block in which it is Until the control leaves the block
Local variable
declared in which it is declared
Back to Top
Java Regex
Matcher Class
Method Description
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
Back to Top
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.
1. Single Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Hybrid Inheritance
Back to Top
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
}
Back to Top
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
}
Back to Top
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
}
Back to Top
Hybrid Inheritance:
Hybrid Inheritance is the combination of more than one type of inheritance in a single program.
Back to Top
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.
Back to Top
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.
Back to Top
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.*
Back to Top
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
1. Abstract class
2. Interface
Back to Top
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_
}
}
Back to Top
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_
}
}
Back to Top
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).
Back to Top
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;}
}
Back to Top
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")};
}
Back to Top
Collections
Collection Description
Set is a collection of elements which can not contain duplicate values. Set is
Set
implemented in HashSets, LinkedHashSets, TreeSet etc
List is a ordered collection of elements which can have duplicates. Lists are
List
classified into ArrayList, LinkedList, Vectors
FIFO approach, while instantiating Queue interface you can either choose
Queue
LinkedList or PriorityQueue.
LIFO approach, stack is a sub ordinate of vector which helps in performing
Stack
different functions.
Collection Description
Deque(Double Ended Queue) is used to add or remove elements from both
Deque
the ends of the Queue(both head and tail)
Map contains key-values pairs which don't have any duplicates. Map is
Map
implemented in HashMap, TreeMap etc.
Back to Top