Skip to content

Latest commit

 

History

History
453 lines (339 loc) · 11.6 KB

java-cheatsheet.md

File metadata and controls

453 lines (339 loc) · 11.6 KB
title description created
Java CheatSheet
The most commonly used java concepts are given here.
2022-10-21

Table of Contents

Java CheatSheet for Developers

Data Types

Data Type Size
boolean 1 bit
char 2 byte
int 4 byte
short 2 byte
long 8 byte
float 4 byte
double 8 byte

🔼Back to Top

Data Conversion

String to Number

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

🔼Back to Top

Any Type to String

	String s = String.va­lueOf(_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

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

🔼Back to Top

For Each Loop

for ( _var_ : _collection_ ) {  
­ _statements_  
} 

🔼Back to Top

Switch Statement

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

🔼Back to Top

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;  
}

🔼Back to Top

String Methods

Command Description
length length 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

🔼Back to Top

Math Library Methods

Command Description
abs(x) abstract value of x
max(a, b maximum of a and b
min(a, b) minimum of a and b
E value of e (constant)
sin(theta) sine of theta
cos(theta cosine of theta
tan(theta) tangent of theta
round(x) Returns the value of x rounded to its nearest integer

🔼Back to Top

Types of Variables

Variable Type Scope Lifetime
Instance variable Throughout the class except in
static methods
Until the object is available in the
memory
Class variable Throughout the class Until the end of the program
Local variable Within the block in which it is
declared
Until the control leaves the block
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.

Java supports 4 types of inheritance:

  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.

Encapsulation in Java can be achieved through packages

🔼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.

Abstraction can be achieved in 2 ways in Java

  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 Set is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
List List is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
Queue FIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
Stack LIFO approach, stack is a sub ordinate of vector which helps in performing different functions.
Deque Deque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
Map Map contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.

🔼Back to Top