Core Java Cheat Sheet (VJ) PDF
Core Java Cheat Sheet (VJ) PDF
Java was modeled in its final form keeping in consideration with the primary objective of having
the following features:
Object-Oriented
Architectural-neutral
High Performance
Multi-Threaded
Distributed
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0 8 byte
Data Type
String
Array
Class
Interface
TYPECASTING
It is a method of converting a variable of one data type to another data type so that functions
can process these variables correctly.
Java defines two types of typecasting:
● Implicit Type Casting (Widening)
3
OPERATORS IN JAVA
Java supports a rich set of operators that can be classified into categories as below :
Assignment operator =, +=, −=, ×=, ÷=, %=, &=, ^=, |=, <<=, >>=, >>>=
Conditional operators ?:
Java code can also be written in any text editor and compiled on the terminal with following
commands :
$ java [file_name].java
$ java [file_name]
Note: File name should be the same as the class name containing the main() method, with a
.java extension.
VARIABLES IN JAVA
Variables are the name of the memory location. It is a container that holds the value while the
java program is executed. Variables are of three types in Java :
4
Declared and initialized inside Declared inside the class but Declared using a “static”
the body of the method, block or outside of the method, block or keyword. It cannot be local.
constructor. constructor. If not initialized, the
default value is 0.
It has an access only within the Variables are created when an Variables created creates a
method in which it is declared instance of the class is created single copy in the memory which
and is destroyed later from the and destroyed when it is is shared among all objects at a
block or when the function call is destroyed. class level.
returned.
class TestVariables
void someMethod()
RESERVED WORDS
Also known as keywords, are particular words which are predefined in Java and cannot be used
as variable or object name. Some of the important keywords are :
5
Keywords Usage
METHODS IN JAVA
1. if-else
Tests condition, if condition true if block is executed else the else block is executed.
class TestIfElse
{
public static void main(String args[])
{
int percent = 75;
2. Switch
Test the condition, if a particular case is true the control is passed to that block and executed.
The rest of the cases are not considered further and the program breaks out of the loop.
class TestSwitch
{
public static void main(String args[])
{
int weather = 0;
switch(weather)
{
case 0 :
System.out.println("Sunny");
7
break;
case 1 :
System.out.println("Rainy");
break;
case 2 :
System.out.println("Cold");
break;
case 3 :
System.out.println("Windy");
break;
default :
System.out.println("Pleasant");
}
}
}
LOOPS IN JAVA
Loops are used to iterate the code a specific number of times until the specified condition is
true. There are three kinds of loop in Java :
For Loop
Iterates the code for a specific number of times until class TestForLoop
the condition is true. {
public static void main (String args[])
{
for(int i=0;i<=5;i++)
System.out.println("*");
}
}
While Loop
If condition in the while is true the program enters the class TestWhileLoop
loop for iteration. {
public static void main (String args[])
{
int i = 1;
while(i<=10)
{
System.out.println(i);
i++;
}
}
}
Do While Loop
8
The program enters the loop for iteration at least once class TestDoWhileLoop
irrespective of the while condition being true. For {
further iterations, it is depends on the while condition public static void main (String args[])
to be true. {
int i = 1;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
An object-oriented paradigm offers the following concepts to simplify software development and
maintenance.
Objects are basic runtime entities in an object-oriented system, which contain data and code to
manipulate data. This entire set of data and code can be made into user-defined data type using
the concept of class. Hence, a class is a collection of objects of a similar data type.
Example: apple, mango, and orange are members of class fruit.
The wrapping or enclosing up of data and methods into a single unit is known as encapsulation.
Take medicinal capsule as an example, we don’t know what chemical it contains, we are only
concerned with its effect.
This insulation of data from direct access by the program is called data hiding. For instance,
while using apps people are concerned about its functionality and not the code behind it.
3.Inheritance
Inheritance provides the concept of reusability, it is the process by which objects of one class
(Child class or Subclass) inherit or derive properties of objects of another class (Parent class).
Single Inheritance
9
The child class inherits properties and behavior from a single parent class.
Multilevel Inheritance
The child class inherits properties from its parent class, which in turn is a child class to another parent class
Multiple Inheritance
When a child class has two parent classes. In Java, this concept is achieved by using interfaces.
Hierarchical Inheritance
When a parent class has two child classes inheriting its properties.
class A
{
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A objA = new A();
B objB = new B();
// The superclass may be used by itself.
objA.i = 10;
objA.j = 20;
System.out.println("Contents of objA: ");
objA.showij();
System.out.println();
/* The subclass can access to all public members of
its superclass. */
objB.i = 7;
objB.j = 8;
objB.k = 9;
10
4. Polymorphism
Defined as the ability to take more than one form. Polymorphism allows creating clean and
readable code.
In Java Polymorphism is achieved by the concept of method overloading and method
overriding, which is the dynamic approach.
● Method Overriding
In a class hierarchy, when a method in a child class has the same name and type signature as a
method in its parent class, then the method in the child class is said to override the method in
the parent class.
In the code below, if we don’t override the method the output would be 4 as calculated in
ParentMath class, otherwise, it would be 16.
class ParentMath
{
void area()
{
int a =2;
System.out.printf("Area of Square with side 2 = %d %n", a * a);
System.out.println();
}
}
void area()
{
int a =4;
System.out.printf("Area of Square with side 4= %d %n", a * a);
}
● Method Overloading
Java programming can have two or more methods in the same class sharing the same name,
as long as their arguments declarations are different. Such methods are referred to as
overloaded, and the process is called method overloading.
1. Number of parameters
example: add(int, int)
add(int, int, int)
class Shape
{
void area()
{
System.out.println("Area of the following shapes are : ");
}
}
12
class InheritanceOverload
{
public static void main(String[] args)
{
int length = 5;
int breadth = 7;
Shape s = new Shape();
//object of child class square
Square sq = new Square();
//object of child class rectangle
13
//calling the area methods of all child classes to get the area of different objects
s.area();
sq.area(length);
rec.area(length,breadth);
cir.area(length);
}
}
ABSTRACT CLASS
Superclass that only defines a generalized form that will be shared by all of its subclasses,
leaving it to each subclass to implement its methods.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class Abstract {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
INTERFACES
14
A class’s interface can be full abstracted from its implementation using the “interface” keyword.
They are similar to class except that they lack instance variables and their methods are
declared without any body.
interface Area
{
final static float pi = 3.14F;
float compute(float x , float y);
}
class InterfaceTest
{
public static void main (String args[])
{
float x = 2.0F;
float y = 6.0F;
Rectangle rect = new Rectangle(); //creating object
Circle cir = new Circle();
CONSTRUCTORS IN JAVA
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxVol {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
16
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized :
Used to initialize the fields of the class with predefined values from the user.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxVolP {
public static void main(String args[]) {
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
ARRAYS IN JAVA
17
Array is a group of like-type variables that are referred by a common name, having continuous
memory. Primitive values or objects can be stored in an array. It provides code optimization
since we can sort data efficiently and also access it randomly. The only flaw is that we can have
a fixed-size elements in an array.
import java.util.Scanner;
class SingleArray
{
public static void main(String args[])
{
int len = 0;
//declaration
int [] numbers = {3,44,12,53,6,87};
Scanner s = new Scanner(System.in);
class MatrixArray
18
//printing matrix
for(int a=0;a<=m1.length;a++)
for(int b=0;b<=m2.length;b++)
System.out.println();
//matrix addition
for(int a=0;a<=m1.length;a++)
for(int b=0;b<=m2.length;b++)
System.out.println();
STRINGS IN JAVA
Creating String
String Methods
The String class which implements CharSequence interface defines a number of methods for
string manipulation tasks. List of most commonly used string methods are mentioned below:
20
class SortStrings {
static String arr[] = {
"Now", "the", "is", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "county"
};
public static void main(String args[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareTo(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
21
arr[i] = t;
}
}
System.out.println(arr[j]);
} }
}
● For mutable strings, we can use StringBuilder and StringBuffer classes which as well
implement CharSequence interface.
● These classes represent growable and writable character interface.
● They automatically grow to make room for additions , and often has more characters
preallocated than are actually needed, to allow room for growth.
MULTITHREADING
● Process-based multitasking.(Multitasking)
● Thread-based multitasking (Multithreading)
Multitasking Multithreading
OS concept in which multiple tasks are performed Concept of dividing a process into two or more
simultaneously. subprocess or threads that are executed at the
same time in parallel.
Process has to switch between different programs Processor needs to switch between different
or processes. parts or threads of the program.
program or process in the smallest unit in the thread is the smallest unit
environment
A thread is always in one of the following five states, it can move from state to another by a
variety of ways as shown.
New thread: Thread object is created. Either it can be scheduled for running using start()
method.
Runnable thread : Thread is ready for execution and waiting for processor.
Running thread: It has got the processor for execution.
Blocked thread: Thread is prevented from entering into runnable state.
Dead state: Running thread ends its life when it has completed executing its run() method.
23
Creating Thread
public void sleep(long Blocks or suspends a thread temporarily for entering into
milliseconds) runnable and subsequently in running state for specified
milliseconds.
public void yield Temporarily pauses currently executing thread object and allows
other threads to be executed.
public void suspend() to suspend the thread, used with resume() method.
public void stop() to cause premature death of thread, thus moving it to dead state.
{
for(int i=1;i<=5;i++)
{
System.out.println("From thread A : i " + i);
}
System.out.println("Exit from A ");
}
}
{
for(int i=0;i<=5;i++)
{
System.out.println("From thread B : i " + i);
}
System.out.println("Exit from B ");
}
}
class ThreadTest
{
public static void main(String args[])
{
25
new A().start();
new B().start();
new C().start();
}
}
The run( ) method that is declared in the Runnable interface which is required for implementing
threads in our programs.
class RunnableTest
{
public static void main(String args[])
{
X runnable = new X ();
Thread threadX = new Thread(runnable);
threadX.start();
System.out.println("End of main Thread");
}
}
26
Derived class extending Thread class itself is a Runnable Interface simply defines the unit of work
thread object and hence, gains full control over that will be executed in a thread, so it doesn’t
the thread life cycle. provide any control over thread life cycle.
The derived class cannot extend other base Allows to extend base classes if necessary
classes
Used when program needs control over thread life Used when program needs flexibility of extending
cycle classes.
EXCEPTION HANDLING
Exception is an abnormality or error condition that is caused by a run-time error in the program,
if this exception object thrown by error condition is not caught and handled properly, the
interpreter will display an error message. If we want to avoid this and want the program to
continue then we should try to catch the exceptions.This task is known as exception handling.
Checked Exceptions :
● Handled explicitly in the code itself with the help of try catch block.
● Extended from java.lang.Exception class
Unchecked Exceptions :
27
● Not essentially handled in the program code, instead JVM handles such exceptions.
● Extended from java.lang.RuntimeException class
Try keyword is used to preface a block of code that is likely to cause an error condition and
“throw” an exception. A catch block defined by the keyword catch “catches” the exception
“thrown” by the try block and handles it appropriately.
A code can have more than one catch statement in the catch block, when exception in try block
is generated, multiple catch statements are treated like cases in a switch statement.
class Error
{
public static void main(String args[])
{
int a [] = {5,10};
int b = 5;
try
{
int x = a[2]/b-a[1];
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexError");
}
catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y = a[1]/a[0];
System.out.println("y = " + y);
}
}
28
FINALLY
Finally statement: used to handle exceptions that is not caught by any of the previous catch
statements. A finally block in guaranteed to execute, regardless of whether or not an exception
is thrown.
We can edit the above program and add the following finally block.
finally
{
int y = a[1]/a[0];
System.out.println("y = " + y);
}
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x = 5 , y = 1000;
try
{
float z = (float) x / (float) y ;
if(z < 0.01)
{
throw new MyException("Number is too small");
29
}
}
catch (MyException e)
{
System.out.println("Caught my exception ");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}
}
}
MANAGING FILES IN JAVA
● Temporary Storage: The data is lost when variable goes out of scope or when program
is terminates.
● Large data: It is difficult
Such problems can be solved by storing data on secondary devices using the concept of files.
Collection of related records stored in a particular area on the disk, termed as file. The files
store and manage data by the concept of file handling.
● Creating files
● Updating files
● Manipulation of data
STREAMS
Java uses concept of streams to represent ordered sequence of data, which is a path along
which data flows. It has a source and a destination.
● Input Stream: which extracts i.e. reads data from source file and sends it to the
program.
● Output Stream: which takes the data from the program and send i.e writes to the
destination.
STREAM CLASSES
Designed to provide functionality for creating and manipulating streams and files for
reading/writing bytes.
Since streams are unidirectional there are two kinds of byte stream classes :
They are used to read 8-bit bytes include a super class known as InputStream. InputStream is
an abstract class and defines the methods for input functions such as :
Method Description
read(byte b [ ], int n, int m) Reads m bytes into b starting from the nth byte of b
These classes are derived from the base class OutputStream. OutputStream is an abstract
class and defines the methods for output functions such as :
Method Description
write(byte b[ ]) Writes all the bytes in the array b to the output stream
write(byte b[ ], int n, int m) Writes m bytes from array b starting from the nth byte
READING/WRITING BYTES
Two common subclasses used are FileInputStream and FileOutputStream that handle 8-bit
bytes.
FileOutputStream is used for writing bytes to a file as demonstrated below:
import java.io.*;
class WriteBytes
{
public static void main(String args[])
{
bytes cities [] = {'C','A','L','I','F','O','R','N','I','A', '\n',
'V','E','G','A','S','\n','R','E','N','O','\n'};
System.exit(-1);
}
}
}
import java.io.*;
class ReadBytes
{
public static void main(String args[])
{
//Create an input file stream
FileInputStream infile = null;
int b;
try
{
//connect the infile stream to required file
infile = new FileInputStream(args [ 0 ]);
READING/WRITING CHARACTERS
The two subclasses of Reader and Writer classes for handling characters in files are FileReader
and FileWriter.
import java.io.*;
class CopyCharacters
{
public static void main (String args[])
{
//Declare and create input and output files
File inFile = new File("input.dat");
File outFile = new File("output.dat");
FileReader ins = null; //creates file stream
ins
FileWriter outs = null; //creates file stream
outs
try
{
ins = new FileReader(inFile); //opens inFile
outs = new FileWriter(outFile); //opens outFile
outs.write(ch);
}
}
catch(IOException e)
{
System.out.println(e);
System.exit(-1);
}
finally
{
try
{
ins.close();
outs.close();
}
catch (IOException e)
{}
}
}
}
JAVA COLLECTIONS
The collections framework contained in the java.util package defines a set of interfaces and their
implementations to manipulate collections, which serve as a container for a group of objects.
INTERFACES
Collection framework contains many interfaces such as Collection, Map and Iterator.
The interfaces and their description are mentioned below:
Interface Description
CLASSES
The classes available in the collection framework implement the collection interface and
sub-interfaces. They also implement Map and Iterator interfaces.
Class Interface
AbstractCollection Collection
AbstarctList List
Abstract Queue
AbstractSequentialList List
LinkedList List
AbstractSet Set
EnumSet Set
HashSet Set
PriorityQueue Queue
TreeSet Set
import java.util.*;
class Num
{
public static void main(String args[])
{
ArrayList num = new ArrayList ();
num.add(9);
36
num.add(12);
num.add(10);
num.add(16);
num.add(6);
num.add(8);
num.add(56);
//getting size
System.out.println("Size of array list is: ");
num.size();
//removing an element
num.remove(4);
import java.util.Scanner;
class LinkedList
{
public static void main (String args[])
{
Scanner s = new Scanner(System.in);
List list = new List();
System.out.println("Enter the number of elements you want to enter in LL
: ");
int num_elements = s.nextInt();
37
int x;
for(int i =0;i<=num_elements;i++)
{
System.out.println("Enter element : ");
x = s.nextInt();
list.insert(x);
}
System.out.println(">>>>> LINKED LIST AFTER INSERTION IS : ");
list.print();
int size = list.count();
System.out.println(">>>>> SIZE OF LL => "+size);
System.out.println("Enter the node to be inserted in the middle: ");
int mid_element = s.nextInt();
list.insertMiddle(mid_element);
System.out.println(">>>> LL AFTER INSERTING THE NEW ELEMENT
IN THE MIDDLE ");
list.print();
}
}
HashSet Implementation
import java.util.*;
class HashSetExample
{
public static void main(String args[])
{
HashSet hs = new HashSet();
hs.add("D");
hs.add("W");
hs.add("G");
hs.add("L");
hs.add("Y");
System.out.println("The elements available in the hash set are :" + hs);
}
}
import java.util.*;
class TreeSetExample
{
public static void main(String args[])
38
{
TreeSet ts = new TreeSet();
ts.add("D");
ts.add("W");
ts.add("G");
ts.add("L");
ts.add("Y");
System.out.println("The elements available in the hash set are :" + ts);
}
}
import java.util.*;
class VectorExample
{
public static void main(String args[])
{
Vector fruits = new Vector ();
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Grapes");
fruits.add("Pineapple");
Iterator it = fruits.iterator();
while (it.hasNext())
{
System.out.println(it.next);
}
}
}
import java.util.*;
st.push("Objects");
st.push("Multithreading");
st.push("Programming");
import java.util.*;
Enumeration e = ht.keys();
while(e.hasMoreElements())
{
String str = (String) e.nextElement();
System.out.println(ht.get(str));
}
}
}
Memory management is :
40
import java.util.Scanner;
class Circle
{
public static void main (String args [])
{
double r,dia,peri,area ;
System.out.println("Enter the radius of circle : ");
42
dia = 2*r;
peri = 2*Math.PI*r;
area = Math.PI*r*r;
import java.util.Scanner;
class EvenOdd
{
public static void main (String args[])
{
int x,y;
Scanner s = new Scanner (System.in);
System.out.println("Enter the values x , y : ");
x = s.nextInt();
y = s.nextInt();
import java.util.Scanner;
class Prime
{
public static void main (String args[])
{
double num;
int n;
boolean isPrime = true;
Scanner s = new Scanner(System.in);
n = (int) Math.sqrt(num);
for(int i=2;i<=n;i++)
{
if(num % i == 0)
{
isPrime = false;
}
else
{
isPrime = true;
}
}
if(isPrime)
{
System.out.println("***** NUMBER IS PRIME !!!! ****** ");
}
else
{
System.out.println("***** NUMBER IS NOT PRIME !!!! ****** ");
}
}
}
import java.util.Scanner;
class Palindrome
{
public static void main(String args[])
{
int num,reverse=0,mode;
Scanner s = new Scanner(System.in);
if(reverse == number)
{
System.out.println(" **** PALINDROME !!! **** ");
}
else
{
System.out.println(" **** NOT A PALINDROME !!! **** ");
}
}
}
5. Pattern printing
*
**
45
***
****
*****
import java.util.Scanner;
class TriStars
{
public static void main(String args[])
{
for(int i=0;i<=5;i++)
{
for(int j=0;j<i;j++)
{
System.out.print(" * ");
}
System.out.println();
}
System.out.println();
}
}