Java Cheat Sheet
JAVA CHEAT SHEET
Java is an Object-Oriented programming language. It is the most powerful and widely used programming language. It was developed by James Gosling in 1991 and released by Sun Microsystems in 1996 and is currently owned by Oracle.
JRE | JVM | JDK:
- JVM (Java Virtual Machine): It runs the java bytecode.
- JDK (Java Development Kit): JRE + Compiler + Debugger.
- JRE (Java Runtime Environment): JVM + Libraries + Other Components (to run applets and other java applications).
JAVA BUZZWORDS:
- Simple
- Object-Oriented
- Portable
- Platform Independent
- Interpreted
- Robust and Secure
- Architectural-neutral
- High Performance
- Multi-Threaded
- Distributed
- Dynamic
DATA TYPES:
- Primitive Data Type: Primitive data types in Java are predefined by the Java language and named as the reserved keywords. The primitive data types include boolean, char, byte, short, int, long, float and double.
- Non Primitive Data Type: The non-primitive data types include Classes, Interfaces, and Arrays.
IDENTIFIERS:
Names given to a class, method, interface, variables are called identifiers.
Legal Identifier Names:
- Combination of letters, numbers, $ and under-score(_)
- Cannot start with a number
- Cannot be a keyword
- No limit on length of identifier
KEYWORDS:
- Primitives Datatype: byte, short, int, long, float, double, char, boolean
- Flow Control: if, else, for, do, while, switch, case, default, break, continue, return
- Exception Handling: try, catch, finally, throw, throws, assert
- Modifiers: public, private, protected, final, static, native, abstract, volatile, transient, synchronized.
- Class Related: class, interface, package, extends, implements, import
- Object Related: new, instanceof, super, this
- Literals: true, false, null
- Others: void, enum
- Unused: goto, const
LITERALS:
Any primitive data type value in source code is called Literal.
There are four types of literals:
- Integer & Long
- Floating Point
- Boolean
- Double
USING JAVA AND JAVAC:
TYPECASTING:
Type casting is a method or process that converts a data type into another data type in both ways manually and automatically.
Widening Casting (automatically): converting a smaller type to a larger type size.
- byte -> short -> char -> int -> long -> float -> double.
Narrowing Casting (manually): converting a larger type to a smaller size type.
- double -> float -> long -> int -> char -> short -> byte.
COMMENTS:
- The Java comments are the statements that are not executed by the compiler and interpreter.
- The comments can be used to provide information about variables, methods, etc.
- There are three types of comments in Java.
Single Line Comment: The single line comment is used to comment only one line.
Ex: //This is single line comment.
Multi Line Comment: The multi-line comment is used to comment multiple lines.
Ex: /* This is
multi line comment
*/
Documentation Comment: The documentation comment is used to create the documentation API.
Ex: /** This is
documentation
comment */
VARIABLES:
A variable is a name given to a memory location. It is the basic unit of storage in a program.
- Variable declaration: datatype variable_name;
- Variable Initialization: datatype variable_name = value;
Types of variables:
Local variable:
- A variable declared inside the body of the method is called local variable.
- A local variable cannot be defined with “static” keyword.
Instance variable:
- A variable declared inside the class but outside the body of the method.
- It is not declared as “static”.
Static variable:
- A variable which is declared as static is called static variable.
- Memory allocation for static variable happens only once when the class is loaded in the memory.
Example:
public class Main{
int a = 10; //instance variable
static int b = 100; //static variable
void met(){
int c=90; //local variable
}
}
OPERATORS:
Operators are used to perform operations on variables and values.
- Arithmetic Operators: { +, - , * , / , % }.
- Relational Operators: { > , < , >= , <= , == , != }
- Assignment Operators: { = , += , -+ , *= , /= , %= , &= , |= , <<= , >>= }
- Increment and Decrement Operator: { ++ , -- }
- Conditional or Ternary Operator: { exp1 ? exp2 : exp3}
- Bitwise Operator: { ^, & , | }
Conditional statements are used to control the flow of the program.
- if: Executes a code block if the condition has been satisfied or it returns true.
- if-else: Executes a code block if the condition has been satisfied or it returns true, if condition not satisfied else block gets executed.
- else-if: Use the else if statement to specify a new condition if the first condition is false.
Syntax : if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
- switch: Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) {
case x: // code block break;
case y: // code block break;
default: // code block
}
LOOPING STATEMENTS:
for: Iterates the code for a specific number of times until the condition is true.
Example:
public class ForLoop{
public static void main (String args[]){
for(int i=0;i<=5;i++) System.out.print("Hello");
}
}
O/p: Hello is printed 5 times
while: If condition in the while is true the program enters the loop for iteration.
Example:
int i=1;
while(i<5){
System.out.print("Hello");
i++;
}
O/p: Hello is printed 4 times.
do-while: The program enters the loop for iteration at least once irrespective of the while condition being true. For further iterations, it is depends on the while condition to be true.
Example: int i = 1;
do{ System.out.print(i);
i++; }
while(i<=5);
O/p: Hello is printed 5 times.
break: break statement breaks out of a loop.
Example:
for (int i = 0; i < 10; i++) {
System.out.print(i);
if (i == 5) {
break;
}
}
O/p: 12345
continue: continue statement skips rest of the statements in the loop and starts next iteration.
Example:
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
System.out.print(i);
}
O/p: 012346789
OOPS CONCEPTS:
- Class and Object: A class is a structure which provides a blueprint of functionality, a class is a collection of methods and attributes.
- Data Abstraction: Data Abstraction is an integration of data encapsulation with data abstraction we can hide the data from the user
- Encapsulation: With the help of data encapsulation, we can wrap a collection of data to a single entity.
- Inheritance: With inheritance concept we can inherit the properties and methods from one class to another.
TYPES OF INHERITANCE:
- Single Inheritance: 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
POLYMORPHISM:
- Polymorphism is defined as the ability to take more than one form.
- It allows creating clean and readable code.
- Poly means “many” Morph means “form”.
- It is achieved by the concept of Method Overloading and Method Overriding.
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. Method overloading is also called as “Compile time Polymorphism”.
Method Overriding: 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. Method overriding is also called as “Run time Polymorphism”.
ABSTRACT CLASS:
A class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body).
CONSTRUCTORS:
- A constructor initializes an object on creation.
- They have the same name as the class.
- They do not have any return type, not even void.
- The constructor cannot be static, abstract or final.
In java constructors are of two types:
- Non-Parameterized or Default Constructor: Invoked automatically even if not declared.
- Parameterized Constructor: Used to initialize the fields of the class with predefined values from the user.
ARRAYS:
- 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.
They are of two types:
Single Dimensional Array: Elements are stored in a single row.
Syntax:
- data_type array_name[];
- data_type[] array_name;
Multi-Dimensional Array: Elements are stores as row and column.
Syntax:
- data_type array_name[rows][columns];
- data_type[rows][columns] array_name;
STRINGS:
- Strings are a non-primitive data type that represents a sequence of characters.
- String type is used to declare string variables.
- Array of strings can also be declared.
- Java strings are immutable, we cannot change them.
- Whenever a string variable is created, a new instance is created.
Syntax:
- String string_name;
- String string_name = new String();
String methods: The string methods are used for string manipulation tasks.
- toLowerCase(): converts string to lowercase.
- toUpperCase(): converts string to uppercase.
- length(): returns length of string.
- charAt(n): retruns the nth character of string.
- trim(): removes whitespaces at beginning and end.
- concat(): concatenates two strings.
- substring(n): returns substring from nth character.
- substring(a,b): returns substring starting from a to b.
- equals(): returns true if strings are equal.
- indexOf("n"): returns position of first occurrence of n in the string.
STRING BUFFER v/s STRING BUILDER:
String Buffer:
- StringBuffer operations are thread-safe and synchronized
- StringBuffer is to used when multiple threads are working on the same String
- StringBuffer performance is slower when compared to StringBuilder
- Syntax: StringBuffer var = new StringBuffer(str);
- StringBuilder operations are not thread-safe are not-synchronized.
- StringBuilder is used in a single-threaded environment.
- StringBuilder performance is faster when compared to StringBuffer
- Syntax: StringBuilder var = new StringBuilder(str);
INTERFACES:
- 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 anybody.
- Interfaces are used to implement multiple inheritances.
- To implement an interface, a class must create a complete set of methods as defined by an interface.
Example:
interface Sample{
public void method1();
public void method2();
}
class Demo implements Sample{
public void method1(){
System.out.println("implementation of method1");
}
public void method2(){
System.out.println("implementation of method2");
}
public static void main(String arg[]){
Sample obj = new Demo();
obj.method1();
}
}
O/p:
implementation of method1
11
“super” and “this” keyword:
super () :
- super () refers immediate parent class instance.
- super () acts as immediate parent class constructor and should be first line in child class constructor.
Example:
class B{
int a = 10;
}
class A extends B {
void M(){
System.out.println(super.a);
}
public static void main(String[] args)
{
new A().M();
}
}
O/p: 10
this ():
- this () - refers current class instance.
- this () acts as current class constructor and can be used in parameterized constructors.
Example:
class A {
int a = 10;
void M(){
this.a = 100;
System.out.println(a);
}
public static void main(String[] args){
new A().M();
}
}
O/p: 100
Static variable, Static method, Static block:
- Static variable: The static variable gets memory only once in the class area at the time of class loading.
- Static method: The static method can be invoked without the need for creating an instance of a class.
- Static block: Is used to initialize the static data member. It is executed before the main method at the time of class loading.
Example:
public class Main {
static int x = 10;
static int y;
static void func(int z) {
System.out.println("x = " + x);
System.out.println("y = " + y);
}
static {
System.out.println("Static block.");
y=x+1;
}
public static void main(String args[]) {
func(8);
}
}
O/p:
Static block.
x = 10 y = 11
Note:
- Static variables are initialized as 0 if not initialized explicitly.
- A Static Method cannot use a non-Static Variable or Method directly.
- The Keyword This & Super cannot be used in Static Context.
MULTITHREADING:
This can be achieved in two ways:
- Process-based multitasking (Multitasking)
- Thread-based multitasking (Multithreading)
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:
Methods of Thread class:
- public void run(): It is called when thread is started.
- public void start(): Causes the thread to move to runnable state.
- public void sleep(long milliseconds): Blocks or suspends a thread temporarily.
- public void suspend(): to suspend the thread, used with resume() method.
- public void resume(): To resume the suspended thread.
- public void stop(): To kill the thread.
EXCEPTION HANDLING:
- Exceptions are abnormal errors often occur at run time due to some irregular input or conditions.
- 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.
- Checked exceptions: The exceptions that are checked during the compile-time are termed as checked exceptions in Java.
- Unchecked exceptions: An exception that occurs during the execution of a program is called an unchecked or a runtime exception.
Common java exceptions:
- ArithmeticException: caused by math errors
- ArrayIndexOutOfBoundException: caused by bad array indexes
- FileNotFoundException: caused by attempt to access a nonexistent file
- IOException: caused by general I/O failures.
- NullPointerException: caused by referencing a null object.
- NumberFormatException: caused when a conversion b/w strings and number fails.
Try-catch block:
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.
Finally:
A finally block is executed, regardless of whether or not an exception is thrown.
Throw:
Own exceptions can be defined using throw keyword.
Throws:
It is used to declare exceptions. This keyword is used to indicate that an exception might occur in the program or method.
Example:
public class Main {
public static void main(String args[]) {
int n1, n2;
try {
n1 = 0;
n2 = 1 / n1;
System.out.println(n2);
}
catch (ArithmeticException e) {
System.out.println("ArithmeticException :: Divide by Zero");
}
finally{
System.out.println("Finally Block");
}
}
}
O/p:
ArithmeticException :: Divide by Zero
Finally Block
Final variable, Final method, Final class:
Final variable: We cannot change the value of a final variable once it is initialized.
Example:
class Main {
public static void main(String[] args) {
final int a = 5;
a = 10;
System.out.println("Value of a is: " +a);
}
}
O/p:
Compilation error cannot assign a value to final variable a
a = 10;
Final method: If a method is declared as final in Java, then it cannot be overridden by any subclass of the class in which it is declared.
Example:
class Final {
public final void display() {
System.out.println("This is a final method.");
}
}
class Main extends Final{
public final void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
O/p:
Compilation error.
public final void display() {
overridden method is final
Final class: If a class is declared as final in Java, then it cannot be extended.
Example:
final class Final_Class {
public void display() {
System.out.println("This is a final method.");
}
}
class Main extends Final_Class {
public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
O/p:
Compilation error.
cannot inherit from final Final_Class
class Main extends Final_Class {
SCOPE AND LIFETIME:
Scope: The area of our program where we can actually access variable is the scope of that variable.
- Instance variable: scope of an instance variable is throughout the class except in static methods.
- Class variable: scope of a class variable is throughout the class.
- Local variable: scope of a local variable is within the block in which it is declared.
Lifetime: Life time of any variable is the time for which the particular variable outlives in memory during running of the program.
- Instance variable: lifetime of an instance variable is until the object stays in memory.
- Local variable: lifetime of a local variable is until the control leaves the block in which it is declared.
- Class variable: lifetime of a class variable is until the end of the program or as long as the class is loaded in memory.
ACCESS SPECIFIERS:
In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable.
In Java, there are four access specifiers given below.
- Public: The classes, methods, or variables which are defined as public, can be accessed by any class or method.
- Protected: Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
- Default: Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
- Private: The private class, methods, or variables defined as private can be accessed within the class only.
PACKAGES:
- A package in Java is used to group related classes.
- Think of it as a folder in a file directory.
- We use packages to avoid name conflicts, and to write a better maintainable code.
Packages are divided into two categories:
Built-in package: These packages consist of a large number of classes which are a part of Java API.
Some of them are:
- java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.
- java.io: Contains classed for supporting input / output operations.
- java.util: Contains utility classes.
- java.applet: Contains classes for creating Applets.
- java.net: Contain classes for supporting networking operations.
User-defined package: These are the packages that are defined by the user. First we create a directory myPackage (name should be same as the name of the package). Then create the MyClass inside the directory with the first statement being the package names.
Example:
package myPackage;
public class MyClass{
public void getNames(String s){
System.out.println(s);
}
}
How to compile java package program:
- javac -d directory javafilename
- javac -d . filename.java
The -d switch specifies the destination where to put the generated class file. How to run java package program:
You need to use fully qualified name e.g. mypack.file_name etc to run the class.
- To Compile: javac -d . fiename.java
- To Run: java mypack.filename
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents the current folder.
FILES:
- Java has several methods for creating, reading, updating, and deleting files.
- The File class from the java.io package, allows us to work with files.
- To use the File class, create an object of the class, and specify the filename or directory name.
Example:
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
File class methods:
- canRead(): Tests whether the file is readable or not
- canWrite(): Tests whether the file is writable or not
- delete(): Deletes a file
- exists(): Tests whether the file exists
- getName(): Returns the name of the file
- length(): Returns the size of the file in bytes
STREAMS:
Java uses the concept of streams to represent ordered sequence of data.
Streams are classified into two basic types:
Input Stream: which reads data from source file and sends it to the program.
Output Stream: which takes the data from the program and writes to the destination.
Stream Classes:
They are contained in java.lang.io package.
They are categorized into two groups:
- Byte Stream Classes: provides support for handling I/O operation on bytes.
- Character Stream Classes: provides support for managing I/O operations on characters.
Reading / Writing bytes:
Two common subclasses used are FileInputStream and FileOutputStream that handle 8-bit bytes.
COLLECTIONS:
- The Collection in Java is a framework that provides architecture to store and manipulate the group of objects.
- Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
- Framework: It provides readymade architecture.
ARRAYLIST:
- The ArrayList class implements the List interface.
- It uses a dynamic array to store the duplicate element of different data types.
- The ArrayList class maintains the insertion order and is non-synchronized.
- The elements stored in the ArrayList class can be randomly accessed.
Example:
import java.util.*;
class ArrayListExample{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>(); //Creating arraylist
list.add("A"); //Adding object in arraylist
list.add("B");
list.add("C");
list.add("D");
Iterator itr=list.iterator(); //Traversing list through Iterator
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
O/p:
A
B
C
D
HASHSET:
- HashSet class implements Set Interface.
- It represents the collection that uses a hash table for storage.
- Hashing is used to store the elements in the HashSet. It contains unique items.
Example:
import java.util.*;
public class HashSetExaple{
public static void main(String args[]){
HashSet<String> set=new HashSet<String>(); //Creating HashSet and adding elements
set.add("A");
set.add("B");
set.add("A");
set.add("C");
Iterator<String> itr=set.iterator(); //Traversing elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
O/p:
B
A
C
MEMORY MANAGEMENT:
Memory is a collection of data represented in the binary format.
Memory management is:
- Process of allocating new objects
- Properly removing unused objects (garbage collection).
Storage:
- The Java compiler stores the program properties into either heap or stack memory.
- The local variables and methods are stored in stack memory.
- The instances are stored in heap memory.
No comments
If you have any doubts, Please let me know