My Brain Cells

Easiest (and best) learning materials for anyone with a curiosity for machine learning and artificial intelligence, Deep learning, Programming, and other fun life hacks.

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: 

  1. JVM (Java Virtual Machine): It runs the java bytecode. 
  2. JDK (Java Development Kit): JRE + Compiler + Debugger. 
  3. JRE (Java Runtime Environment): JVM + Libraries + Other Components (to run applets and other java applications).

JAVA BUZZWORDS:

  1. Simple
  2. Object-Oriented
  3. Portable
  4. Platform Independent
  5. Interpreted
  6. Robust and Secure
  7. Architectural-neutral
  8. High Performance
  9. Multi-Threaded
  10. Distributed
  11. Dynamic

DATA TYPES: 

  1. 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. 
  2. 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

  1. Combination of letters, numbers, $ and under-score(_) 
  2. Cannot start with a number 
  3. Cannot be a keyword 
  4. No limit on length of identifier 

KEYWORDS

  1. Primitives Datatype: byte, short, int, long, float, double, char, boolean 
  2. Flow Control: if, else, for, do, while, switch, case, default, break, continue, return 
  3. Exception Handling: try, catch, finally, throw, throws, assert 
  4. Modifiers: public, private, protected, final, static, native, abstract, volatile, transient, synchronized.
  5. Class Related: class, interface, package, extends, implements, import 
  6. Object Related: new, instanceof, super, this 
  7. Literals: true, false, null 
  8. Others: void, enum 
  9. Unused: goto, const 

LITERALS


Any primitive data type value in source code is called Literal.

There are four types of literals: 

  1. Integer & Long 
  2. Floating Point 
  3. Boolean 
  4. Double

USING JAVA AND JAVAC:


Compilation: command used to compile a java file..
Syntax: javac file_name.java
Execution: command used to execute java file.
Syntax: java file_name


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. 

  1. byte -> short -> char -> int -> long -> float -> double. 

Narrowing Casting (manually): converting a larger type to a smaller size type. 

  1. double -> float -> long -> int -> char -> short -> byte. 

COMMENTS

  1. The Java comments are the statements that are not executed by the compiler and interpreter. 
  2. The comments can be used to provide information about variables, methods, etc. 
  3. 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.

  1. Variable declaration: datatype variable_name; 
  2. Variable Initialization: datatype variable_name = value; 

Types of variables


Local variable

  1. A variable declared inside the body of the method is called local variable. 
  2. A local variable cannot be defined with “static” keyword.

Instance variable:

  1. A variable declared inside the class but outside the body of the method.
  2. It is not declared as “static”. 

Static variable

  1. A variable which is declared as static is called static variable. 
  2. 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. 

  1. Arithmetic Operators: { +, – , * , / , % }. 
  2. Relational Operators: { > , < , >= , <= , == , != } 
  3. Assignment Operators: { = , += , -+ , *= , /= , %= , &= , |= , <<= , >>= } 
  4. Increment and Decrement Operator: { ++ , — } 
  5. Conditional or Ternary Operator: { exp1 ? exp2 : exp3}
  6. Bitwise Operator: { ^, & , | }
CONDITIONAL STATEMENTS

Conditional statements are used to control the flow of the program. 

  1. if: Executes a code block if the condition has been satisfied or it returns true.
  2. if-else: Executes a code block if the condition has been satisfied or it returns true, if condition not satisfied else block gets executed.
  3. 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 

        }

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

  1. Class and ObjectA class is a structure which provides a blueprint of functionality, a class is a collection of methods and attributes. 
  2. Data AbstractionData Abstraction is an integration of data encapsulation with data abstraction we can hide the data from the user
  3. EncapsulationWith the help of data encapsulation, we can wrap a collection of data to a single entity. 
  4. Inheritance: With inheritance concept we can inherit the properties and methods from one class to another. 


TYPES OF INHERITANCE

  1. Single InheritanceThe child class inherits properties and behavior from a single parent class
  2. Multilevel Inheritance: The child class inherits properties from its parent class, which in turn is a child class to another parent class.
  3. Multiple Inheritance: When a child class has two parent classes. In Java, this concept is achieved by using interfaces.
  4. Hierarchical Inheritance: When a parent class has two child classes inheriting its properties

POLYMORPHISM: 

  1. Polymorphism is defined as the ability to take more than one form. 
  2. It allows creating clean and readable code. 
  3. Poly means “many” Morph means “form”. 
  4. 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: 

  1. A constructor initializes an object on creation. 
  2. They have the same name as the class. 
  3. They do not have any return type, not even void. 
  4. The constructor cannot be static, abstract or final.

In java constructors are of two types: 

  1. Non-Parameterized or Default Constructor: Invoked automatically even if not declared.
  2. Parameterized Constructor: Used to initialize the fields of the class with predefined values from the user.

ARRAYS:

  1. Array is a group of like-type variables that are referred by a common name, having continuous memory.
  2. Primitive values or objects can be stored in an array. 
  3. 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:

  1. data_type array_name[];
  2. data_type[] array_name;

Multi-Dimensional Array: Elements are stores as row and column.

Syntax:

  1. data_type array_name[rows][columns];
  2. data_type[rows][columns] array_name;


STRINGS:

  1. Strings are a non-primitive data type that represents a sequence of characters.
  2. String type is used to declare string variables.
  3. Array of strings can also be declared.
  4. Java strings are immutable, we cannot change them.
  5. Whenever a string variable is created, a new instance is created.

Syntax:

  1. String string_name;
  2. String string_name = new String();

String methods: The string methods are used for string manipulation tasks.

  1. toLowerCase(): converts string to lowercase.
  2. toUpperCase(): converts string to uppercase.
  3. length(): returns length of string.
  4. charAt(n): retruns the nth character of string.
  5. trim(): removes whitespaces at beginning and end.
  6. concat(): concatenates two strings.
  7. substring(n): returns substring from nth character.
  8. substring(a,b): returns substring starting from a to b.
  9. equals(): returns true if strings are equal.
  10. indexOf(“n”): returns position of first occurrence of n in the string.

STRING BUFFER v/s STRING BUILDER:


String Buffer:

  1. StringBuffer operations are thread-safe and synchronized
  2. StringBuffer is to used when multiple threads are working on the same String 
  3. StringBuffer performance is slower when compared to StringBuilder
  4. Syntax: StringBuffer var = new StringBuffer(str);
String Builder:

  1. StringBuilder operations are not thread-safe are not-synchronized.
  2. StringBuilder is used in a single-threaded environment.
  3. StringBuilder performance is faster when compared to StringBuffer
  4. Syntax: StringBuilder var = new StringBuilder(str);

INTERFACES:

  1. A class’s interface can be full abstracted from its implementation using the “interface” keyword.
  2. They are similar to class except that they lack instance variables and their methods are declared without anybody.
  3. Interfaces are used to implement multiple inheritances.
  4. 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 ()

  1. super () refers immediate parent class instance. 
  2. 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 ()

  1. this () – refers current class instance. 
  2. 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

  1. Static variable: The static variable gets memory only once in the class area at the time of class loading. 
  2. Static method: The static method can be invoked without the need for creating an instance of a class. 
  3. 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

  1. Static variables are initialized as 0 if not initialized explicitly. 
  2. A Static Method cannot use a non-Static Variable or Method directly.
  3. The Keyword This & Super cannot be used in Static Context.

MULTITHREADING: 


This can be achieved in two ways:

  1. Process-based multitasking (Multitasking)
  2. 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:

  1. public void run(): It is called when thread is started.
  2. public void start(): Causes the thread to move to runnable state.
  3. public void sleep(long milliseconds): Blocks or suspends a thread temporarily.
  4. public void suspend(): to suspend the thread, used with resume() method.
  5. public void resume(): To resume the suspended thread.
  6. public void stop(): To kill the thread.

EXCEPTION HANDLING: 

  1. Exceptions are abnormal errors often occur at run time due to some irregular input or conditions. 
  2. 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. 
  3. Checked exceptions: The exceptions that are checked during the compile-time are termed as checked exceptions in Java. 
  4. Unchecked exceptions: An exception that occurs during the execution of a program is called an unchecked or a runtime exception. 

Common java exceptions:

  1. ArithmeticException: caused by math errors
  2. ArrayIndexOutOfBoundException: caused by bad array indexes
  3. FileNotFoundException: caused by attempt to access a nonexistent file
  4. IOException: caused by general I/O failures.
  5. NullPointerException: caused by referencing a null object.
  6. 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 variableWe 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. 

  1. Instance variable: scope of an instance variable is throughout the class except in static methods. 
  2. Class variable: scope of a class variable is throughout the class.
  3. 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. 

  1. Instance variable: lifetime of an instance variable is until the object stays in memory. 
  2. Local variable: lifetime of a local variable is until the control leaves the block in which it is declared. 
  3. 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. 

  1. Public: The classes, methods, or variables which are defined as public, can be accessed by any class or method. 
  2. 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.
  3. Default: Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope. 
  4. Private: The private class, methods, or variables defined as private can be accessed within the class only.


PACKAGES: 

  1. A package in Java is used to group related classes. 
  2. Think of it as a folder in a file directory. 
  3. 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: 

  1. java.lang: Contains language support classes(e.g classed which defines primitive data types, math operations). This package is automatically imported.
  2. java.io: Contains classed for supporting input / output operations. 
  3. java.util: Contains utility classes. 
  4. java.applet: Contains classes for creating Applets.
  5. 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:  

  1. javac -d directory javafilename 
  2. 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.

  1. To Compile: javac -d . fiename.java
  2. 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: 

  1. Java has several methods for creating, reading, updating, and deleting files.
  2. The File class from the java.io package, allows us to work with files.
  3. 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: 

  1. canRead(): Tests whether the file is readable or not  
  2. canWrite(): Tests whether the file is writable or not 
  3. delete(): Deletes a file 
  4. exists(): Tests whether the file exists 
  5. getName(): Returns the name of the file 
  6. 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: 

  1. Byte Stream Classes: provides support for handling I/O operation on bytes. 
  2. 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

  1. The Collection in Java is a framework that provides architecture to store and manipulate the group of objects. 
  2. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.
  3. Framework: It provides readymade architecture. 

ARRAYLIST

  1. The ArrayList class implements the List interface. 
  2. It uses a dynamic array to store the duplicate element of different data types.
  3. The ArrayList class maintains the insertion order and is non-synchronized. 
  4. 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:

  1. HashSet class implements Set Interface.
  2. It represents the collection that uses a hash table for storage.
  3. 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:

  1. Process of allocating new objects
  2. Properly removing unused objects (garbage collection).

Storage: 

  1. The Java compiler stores the program properties into either heap or stack memory. 
  2. The local variables and methods are stored in stack memory. 
  3. The instances are stored in heap memory.


Anthony

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top