YuWebdesign



Java Interview Questions

By YuwebDesign


Java Fundamentals

  1. Java is a high-level programming language.
  2. Java is platform independent.
  3. Java is a statically typed language.
  4. Java is a collection of objects.
  5. It was developed by Sun Microsystems.
  6. There are a lot of applications, websites and Games that are developed using Java.

Java is statically typed – variables are given data types up front (before compiling).
In dynamically typed languages variables do not have types.

The correct structure of inclusion is: JVM -> JRE -> JDK
(JDK is a part of JRE and JRE is included inside JVM)

JDK JRE JVM
stands for Java Development Kit stands for Java Runtime Environment stands for Java Virtual Machine
It is the tool necessary to compile, document and package Java programs. JRE refers to a runtime environment in which Java bytecode can be executed. It is an abstract machine.
It is a specification that provides a run-time environment in which Java bytecode can be executed.

  1. JVM loads the code
  2. verifies the code
  3. executes the code
  4. manages memory
It contains JRE + development tools. It’s an implementation of the JVM which physically exists. JVM follows three notations: Specification, Implementation, and Runtime Instance.

JIT stands for Just-In-Time compiler in Java.
It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor.

  1. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked.
  2. The JIT compiler then compiles the bytecode of the invoked method into native machine code.
  3. Jit compiles it “just in time” to execute.
  4. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it.
  5. This is why it is often responsible for the performance optimization of Java applications at the run time.

main() in Java is the entry point for any Java program.
It is always written as public static void main(String[] args).

  1. public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.
  2. static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class.
  3. void: It is the return type of the method. Void defines the method which will not return any value.
  4. main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.
  5. String args[]: It is the parameter passed to the main method.

  1. Platform independence means that execution of the program does not depend on type of operating system.
    It could be any: Linux, Windows, Mac etc.
  2. Java is both compiler(javac) and interpreter(jvm) based lauguage.
  3. Your java source code is first compiled into byte code using javac compiler.
  4. This byte code can be easily converted to equivalent machine code using JVM.
  5. JVM(Java Virtual Machine) is available in all operating systems we install.
  6. Hence, byte code generated by javac is universal and can be converted to machine code on any operating system.
    This is the reason why Java is platform independent.

  1. Object-oriented Language following OOPs concepts:
    1. Inheritance
    2. Encapsulation
    3. Polymorphism
    4. Abstraction
  2. Platform independent: A single program works on different platforms without any modification.
  3. High Performance: JIT (Just In Time compiler) enables high performance in Java. JIT converts the bytecode into machine language and then JVM starts the execution.
  4. Multi-threaded: A flow of execution is known as a Thread. JVM creates a thread which is called main thread. The user can create multiple threads by extending the thread class or by implementing Runnable interface.

Java uses Just In Time compiler to enable high performance. JIT is used to convert the instructions into bytecodes.

The technical term for a class/method/object or variable name is an identifier.

IntelliJ and Eclipse are the most popular IDE’s for Java, NetBeans was also widely used in the past and still is the IDE of choice in some companies.

Cohesion refers to the level of a component that performs a single well-defined task.

Levels of Cohesion
  • A single well-defined task is done by a highly cohesive method.
  • The weakly cohesive method will split the task into separate parts.

The java.io package is a highly cohesive package because it has I/O related classes and interface.
However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.

Packages and Imports

Packages in Java, are the collection of related classes and interfaces which are bundled together.

By using packages, developers can easily modularize the code and optimize its reuse.

Also, the code within the packages can be imported by other classes and reused.

Package advantages
  1. Packages help in avoiding name clashes
  2. They provide easier access control on the code
  3. Packages can also contain hidden classes which are not visible to the outer classes and only used within the package
  4. Creates a proper hierarchical structure which makes it easier to locate the related classes

Package in Java is a mechanism to encapsulate a group of related classes, sub packages and interfaces together.

These classes will all be related in some way, e.g.:

  1. belonging to the same category
    e.g., they might all have to do with a specific application;
  2. having similar functionality,
    e.g., they perform a specific set of tasks.

A package can contain the following types:

  1. classes,
  2. interfaces,
  3. enumerations,
  4. annotation types.

Packages help to:

  1. Avoid naming conflicts
    A Java package organizes Java classes into namespaces,
    providing a unique namespace for each type it contains.

    We can define two classes with the same name in different packages to avoid name collision.
    E.g., there can be two classes with name Employee in two packages,
    college.staff.cse.Employee and college.staff.ee.Employee

  2. Write a better maintainable code
  3. Reusability
    Define reusable code in form of classes inside a package.
    After that we can simply import a class from existing packages and use it in our program.
    We can reuse existing classes from the packages as many times as we need it in our program.
  4. Better Organization makes it easier to search for/locate and use classes, interfaces, enumerations, and annotations.

    For several hundreds of classes, it is always required to group the similar types of classes in a meaningful package name so that you can organize your project better and when you need something you can quickly locate it and use it, which improves the efficiency.

  5. Controlled access:
    public, protected and default have package level access control.

    Public members and classes are visible everywhere
    and private members are visible only in the same class.

    Classes in the same package can access each other’s package-private and protected members.

    A protected member is accessible by
    classes in the same package
    and its subclasses
    (classes in other packages that are subclasses of the declaring class).

    A default member (package-private) is accessible by
    classes in the same package only.

  6. Packages can be considered as data encapsulation (or data-hiding).
  7. Java packages can be stored in compressed files called JAR files, allowing classes to be downloaded faster as groups rather than individually.

Package naming conventions

The Java Language Specification establishes package naming conventions
to avoid the possibility of two published packages having the same name.

The naming conventions describe how to create unique package names,
so that packages that are widely distributed will have unique namespaces.

This allows packages to be separately, easily and automatically installed and catalogued.

Packages are usually defined using a hierarchical naming pattern,
levels in the hierarchy are separated by periods (., pronounced “dot”).

Although packages lower in the naming hierarchy
are often referred to as “subpackages
of the corresponding packages higher in the hierarchy,
there is almost no semantic relationship between packages.
E.g., java.util.Scanner
→ java is a top level package
→ util is a sub package
→ Scanner is a class which is present in the sub package util.

Packages are named in reverse order of domain names,
(highest hierarchy on the left):

  1. top level domain name of the organization
  2. .(dot)
  3. organization’s domain
  4. .(dot)
  5. any subdomains
  6. .(dot)
  7. organization can then choose a specific name for its package
  8. .(dot)
  9. subsequent components of the package name
    (vary according to an organization’s own internal naming conventions)

You can visualize a package as a folder/sub-folder structure in a file directory.

E.g, if a package name is college.staff.cse,
then there are three directories, college, staff and cse;
cse is located in staff and staff is located in college
(think of it as college/staff/cse in terms of folders in a file directory).
i.e., org.tarima.yuwebdesign
(think of it as org/tarima/yuwebdesign in terms of folders in a file directory).

The directory college is accessible through CLASSPATH variable,
i.e., path of parent directory of college is present in CLASSPATH.
The idea is to make sure that classes are easy to locate.

Types of Java packages
    Packages are divided into two categories:

  1. Built-in Packages (packages from the Java API)
  2. User-defined Packages (create your own packages)

Access/Visibility Modifiers

Methods and instance variables are known as members.

Public

Public members are visible in the same package as well as the outside package that is for other packages.
Public Access Modifier in Java
Public members in Class A are visible to Class B (Same package) as well as Class C (Different package).
Read more about Public Access Modifier in Java >>>

Private

Private members are visible in the same class only and not for the other classes in the same package as well as classes in the outside packages.
Private Access Modifier in Java
Private members in class A is visible only in that class. It is invisible for class B as well as class C.

Read more about Private Modifier in Java >>>

Default

Methods and variables declared in a class without any access specifiers are called default.

Default  Acccess Modifier  Java

Default members in Class A are visible to the other classes which are inside the package and invisible to the classes which are outside the package.

So Class A members are visible to the Class B and invisible to the Class C.

Read more about Default Access Modifier in Java >>>

Protected

Protected Access Modifier in Java

Protected is same as Default but if a class extends then it is visible even if it is outside the package.

Class A members are visible to Class B because it is inside the package. For Class C it is invisible but if Class C extends Class A then the members are visible to the Class C even if it is outside the package.

Read more about Protected Access Modifier in Java >>>

What is import?

Imports are a mechanism for accessing classes inside a package.

Regular Import

A class can have only one package declaration but it can have more than one package import statements.

A package name should be included in the import statement.

package abcpackage; //single package declaration
import xyzpackage;
import anotherpackage;
import anything;
  1. All the classes and interfaces of this package will be accessible but not subpackages.
    import package.*;

    E.g., import all the classes from util package contained inside java.

    import java.util.*; 
  2. Only mentioned class of this package will be accessible.
    import package.classname;

    E.g., import Vector class from util package contained inside java.

    import java.util.vector; 

    Class name is generally used to avoid conflict
    when two packages have same class name.

    import java.util.Date;
    import my.packag.Date;
Static Import

Static import is a feature introduced in Java (ver. 5+)
that allows members (fields and methods)
defined in a class as public static
to be used in Java code
without specifying the class
in which the field is defined.

You can use fully qualified name (package_name.class_name) to avoid the import statement.

Regular import:

//Declaring a package
package somepackage;
//importing a package
import letmecalculate.Calculator;

public class Demo {
   public static void main(String args[]){
	Calculator obj = new Calculator();
	System.out.println(obj.add(100, 200));
   }
}

Static import:

//Declaring a package
package anotherpackage;

public class Example {
   public static void main(String args[]){
        //Using fully qualified name instead of import
	letmecalculate.Calculator obj = 
		new letmecalculate.Calculator();
	System.out.println(obj.add(100, 200));
   }
}

Coupling refers to the knowledge or information or dependency of another class.
It arises when classes are aware of each other.

Levels of coupling
  1. If a class has the details information of another class, there is strong coupling.
  2. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field.
  3. You can use interfaces for the weaker coupling because there is no concrete implementation.

Java Variables and Variable Datatypes

The technical term for a class/method/object or variable name is an identifier.

  1. All Java variables must be identified with unique names.
  2. These unique names are called identifiers.
  3. Common convention in naming variables is using camelCase.

  1. Variables are containers for storing data values.
  2. A variable is the name given to a memory location. It is
    the basic unit of storage in a program.
  3. The value stored in a variable can be changed during
    program execution.

    int x = 10; myObj.x = 25;
  4. If you don’t want the ability to override existing
    values, declare the attribute as final. Useful
    when you want a variable to always store the same value, like PI
    (3.14159…). The final keyword is called a “modifier”.

    final int x = 10; myObj.x = 25; // will generate an error: cannot
                                //assign a value to a final variable 
  5. class attributes are variables within a
    class
  6. public variables are also called properties,
    e.g.

    public String firstName;
  7. private variables are also called fields,
    e.g.
    String favoriteFood;

  1. In Java, all the variables must be declared before use.
  2. To create (declare) a variable, you must specify the
    type.
  3. When you assign a value (or literal) to the variable it
    is initialized.
  4. Value: initial value stored in the variable. Value can be
    changed
  5. The words literal and a value can be used
    interchangeably, e.g. you can say that you assigned a value or a
    literal to the variable.
  1. Declaring and Initializing a variable: datatype
    variableName = value; //Declaring and Initializing a variable
  2. Declaring a variable, assigning the
    value (initialize) later:
    datatype variableName;
    //Declaring a variable variableName = value; //Initializing a
    variable
  3. Declaring more than one variable of the
    same type, using a comma-separated list:
    int x = 5,
    y = 6, z = 50;
  4. Assigning expressions to variables: String
    text = "This is my text" + " :) ";

You can access attributes by:

  1. creating an object of the class MyClass
    myObj = new MyClass();
  2. by using the dot syntax (.) System.out.println(myObj.attributeName);

The println() method is often used to display variables. To combine
both text and a variable(s), use the + character:
public class MyClass { public static void
main(String[] args) { String firstName = "John "; String lastName
= "Doe"; String fullName = firstName + lastName;
System.out.println(fullName); } }

For numeric values, the + character works as a mathematical
operator (notice that integer variables are used here):

public class MyClass { public static void
main(String[] args) { int x = 5; int y = 6; System.out.println(x +
y); // Print the value of x + y = 11 (not 56!) } }

Generally, in Java there are primitive data types and there are objects.

Similarity between objects and primitives types

Primitive types and objects have in common
that they are declared with

data type + a variable.

Primitive Data Types

Primitive types are initialized with a value (e.g., number):

int variableName = 5;
double differentName = 2.0;

The actual value (e.g., number) of primitive variables
is represented by the variableName,
so it is directly “behind” it.

You can make operations like

double sum = variableName + differentName;

The type of the variables (e.g., integer) defines,
which kind of values the variableName may contain (e.g., int, char)
With classes it is similar:

Objects

Object classes are comparable to data types of primitive variables.

Primitive variable types
define the type of a variable,
whereas object classes are more or less
a set of different primitive data types
that are put together to create something new.

The primitive data types
are more or less used
to describe attributes/characteristics of a class
and to describe methods
that can be executed with the class.

class Car {

  //attributes (characteristics)
  int numberOfWheels;
  String color;
  double volumeOfGasTank;

  //constructor
  Car(int numberWheels, String colour, double volumeTank) {
    this.numberOfWheels = numberWheels;
    this.color = colour;
    this.volumeOfGasTank = volumeTank;
  }

  //methods
  void changeColorOfCar(String colorName) {
    this.color = colorName;
  }
}

A class is a blue print for a data (object) type.

It helps you to create similar objects
by adding specific values
to the attributes of the blue print car.

These objects are created with the method “constructor”:

car myCar = new car(4, red, 100);

Now we have created a specific object, i. e. myCar,
having specif values (color, number of wheels,…),
with the help of the blue print “car”.

As you know, there are different types of cars, big ones, small ones.
Some have special characteristics, but all have a few things in common.

So, what you can do is, create a super class, e. g. car.
This class has e. g. the attribute numberOfWheels, because every car has wheels etc.

Then, for the specialized cars,
you can created sub classes that inherit attributes of the super class,
such as numberOfWheels,
but have also their own attributes that super classes do not have,
e.g., volumeOfExcavatorShovel,
to create a blue print for cars that are used in construction business.

Difference between objects and primitives types

The variable name of an object, e. g. myCar,
does not contain the values of the object.

It just contains a reference to the memory location
where the object values are saved.

The variable name myCar is more or less an address (pointer)
directing towards a specific place in the memory
where the data of this object is saved.

If I e. g. say

car anotherCar = myCar;

then another “address” with the variable name “anotherCar” is created,
which points to the same object as myCar does.

Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers from 3.4e−038 to 3.4e+038.
Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers from 1.7e−308 to 1.7e+038.
Sufficient for storing 15 decimal digits
boolean 1 byte Stores true or false values
char 2 bytes Stores a single character/letter

int myNum = 5; float myFloatNum = 5.99f; char myLetter
= 'D'; boolean myBool = true;

  1. String Arrays,
  2. Classes,
  3. Interface

String myText = "Hello";

Wrapper classes convert the Java primitives into the reference types (objects).
Every primitive data type has a class dedicated to it.
These are known as wrapper classes because they “wrap” the primitive data type into an object of that class.

  1. Widening Casting (automatically/implicitly) – converting a smaller type to a larger type size.
    E.g of Type Promotion: byte -> short -> char -> int -> long -> float -> double
    Java Type Casting Type Promotion

    int myInt = 9;
    double myDouble = myInt; // Automatic casting: int to double
    System.out.println(myInt);      // Outputs 9
    System.out.println(myDouble);   // Outputs 9.0
    
  2. Narrowing Casting (manually/explicitly) – converting a larger type to a smaller size type
    double -> float -> long -> int -> char -> short -> byte

    double myDouble = 9.78;
    int myInt = (int) myDouble; // Manual casting: double to int
    System.out.println(myDouble);   // Outputs 9.78
    System.out.println(myInt);      // Outputs 9
    

Primitive Types vs Objects

Java has 8 kinds of primitive data types.
Object (instance of a class, class is the datatype): unlimited object types because of unlimited classes.

Autoboxing in Java

Conversion of primitives to objects is called autoboxing.

int x = 5; //primitive
Integer y = 5; //object 5 is autoboxed)

  1. Local Variables
  2. Instance Variables
  3. Static (or Class or Global) Variables
  4. Parameter
  5. Argument

import java.io.*; 
class Marks 
{    
    //These variables are instance variables. 
    //These variables are in a class and are not inside any function
    //Each object will have its own copies of instance variables 
    int engMarks; 
    int mathsMarks; 
    int phyMarks; 
} 
  
class MarksDemo 
{ 
    public static void main(String args[]) 
    {   //first object 
        Marks obj1 = new Marks(); 
        obj1.engMarks = 50; 
        obj1.mathsMarks = 80; 
        obj1.phyMarks = 90; 
  
        //second object 
        Marks obj2 = new Marks(); 
        obj2.engMarks = 80; 
        obj2.mathsMarks = 60; 
        obj2.phyMarks = 85; 
  
        //displaying marks for first object 
        System.out.println("Marks for first object:"); 
        System.out.println(obj1.engMarks); 
        System.out.println(obj1.mathsMarks); 
        System.out.println(obj1.phyMarks); 
      
        //displaying marks for second object 
        System.out.println("Marks for second object:"); 
        System.out.println(obj2.engMarks); 
        System.out.println(obj2.mathsMarks); 
        System.out.println(obj2.phyMarks); 
    } 
}

Output:

Marks for first object:
50
80
90
Marks for second object:
80
60
85

  1. Local variable is defined within the method
    and scope of the variable is within the block.
  2. Instance variable is defined
    inside the class and outside the method,

    scope is bound to the instance of the object
    it is created with
    and is destroyed when the object is destroyed.

Local Variable Instance Variable
Declared within defined within a block or method or constructor non-static variable declared inside the class but outside the method, constructor or block.
Created in memory It gets memory at compile time: created when the block is entered or the function is called It gets memory at runtime: bounded to its object itself and created when an object or instance is created.
Destroyed in Memory destroyed after exiting from the block or when the call returns from the function destroyed when the object is destroyed.
Initialization Initialization of Local Variable is Mandatory Initilisation of Instance Variable is not Mandatory. Its default value is 0
Access specifiers Access modifiers can not be used for local variables Access modifiers may be used for instance variables.
Default will be used if no access specifier is defined.
Scope exists only within the scope of a block in which the variable is declared.
Can be accessed only within that block.
If we use local variable outside block/function, the compiler will produce an error.
Instance Variable can be accessed only by creating objects.
Benefits The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable. Every object of that class will create it’s own copy of the variable while using it.
Thus, any changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.
Example
if(x > 100){
String test = "under 100";
}
class Test {
public String EmpName;
public int empAge;
}

We have the "blue print" for creating an object
and every specific instance of such an object
has characteristics.

Let's say we create a blue print for a circle.

We know the circle has a diameter and a circumference.

Those are the objects/instances variables
and each instance of the object class "circle"
has different variable values
for the characteristics diameter and circumference.

class Circle {

//class variable
static final double Pi = 3.141...;
static int numberOfInstances = 0;

//(instance/object) attributes (characteristics, states)
double diameter;
double circumference;

//constructor
Circle(double diaMeter, double circumFerence) {
this.diameter = diaMeter;
this.circumference = circumFerence;
this.numberOfInstances += 1;
}

//Method (object's behavior)
double calculateSomethingWithPi {
//calculates something with Pi
return doubleValue;
}
}

  • declared similarly as instance variables,
    the difference is that
    static variables are declared using the static keyword
    within a class
    outside any method constructor or block.
  • Unlike instance variables,
    we can only have one copy
    of a static variable per class
    irrespective of how many objects we create.
  • created at start of program execution
    and destroyed automatically when execution ends.
  • Initialization of Static Variable is not Mandatory.
    Its default value is 0
  • If we access the static variable like Instance variable (through object),
    compiler will show the warning message
    and it wont halt the program.
    Compiler will replace the object name to class name automatically.
  • If we access the static variable without classname,
    Compiler will automatically append the class name.
  • To access static variables,
    we don't need to create (instantiate) any object of that class,
    we can simply access the variable as:

    className.variableName;

Example of a static variable:

import java.io.*; 
class Emp { 
  
   // static variable salary 
   public static double salary; 
   public static String name = "Harsh"; 
} 
  
public class EmpDemo 
{ 
     public static void main(String args[]) { 
        
      //accessing static variable without object          
      Emp.salary = 1000; 
      System.out.println(Emp.name + "'s average salary:" + Emp.salary); 
   } 
      
} 

Output:

Harsh's average salary:1000.0

Static (or Class) Variables are associated with the class
and are common for all the instances of a class.

E.g., If we create three objects of a class and access this static variable,
it would be common for all,
changes made to the variable using one of the object
would reflect when you access it through other objects:

public class StaticVarExample {
   public static String myClassVar="class or static variable";
	
   public static void main(String args[]){
      StaticVarExample obj = new StaticVarExample();
      StaticVarExample obj2 = new StaticVarExample();
      StaticVarExample obj3 = new StaticVarExample();
      
      //All three will display "class or static variable"
      System.out.println(obj.myClassVar);
      System.out.println(obj2.myClassVar);
      System.out.println(obj3.myClassVar);

      //changing the value of static variable using obj2
      obj2.myClassVar = "Changed Text";

      //All three will display "Changed Text"
      System.out.println(obj.myClassVar);
      System.out.println(obj2.myClassVar);
      System.out.println(obj3.myClassVar);
   }
}

Output:

class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text

As you can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this:

System.out.println(myClassVar);

Only static variables can be accessed like this.
This doesn’t apply for instance and local variables.

  1. Reference
    contains value which is address to some object (usable) on heap
  2. Primitive data type
    directly contains usable value.

Java Operators Interview Questions

Operator works on operands to produce a value.
Operators make the expression possible

Operand - the thing operator works on.

In expression 5 + 3,
5 and 3 are operators,
"+" is an operand.
When the expression is evaluated it will return a value of "8".

Java divides the operators into the following groups:
  1. Arithmetic operators
  2. Assignment operators
  3. Comparison operators
  4. Logical operators
  5. Bitwise operators

Expression evaluates to a value, e.g.,

String myString = new String("Hello World!")
System.out.println(string + "How are you")
//everything within () is an expression

Conditional operator is ?: can be thought of as shorthand for an if-then-else statement.

This operator is also known as the ternary operator because it uses three operands.

Syntax

result = condition ? iftrue : iffalse

This operator should be read as:
"If someCondition is true, assign the value of value1 to result.
Otherwise, assign the value of value2 to result."

Usage:
Use the ?: operator instead of an if-then-else statement if it makes your code more readable;
e.g., when the expressions are compact and without side-effects (such as assignments).

class ConditionalDemo2 {

    public static void main(String[] args){
        int value1 = 1;
        int value2 = 2;
        int result;
        boolean someCondition = true;
        result = someCondition ? value1 : value2;

        System.out.println(result);
    }
}

Because someCondition is true, this program prints "1" to the screen.

Read more >>>

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand.

The code result++; and ++result; will both end in result being incremented by one.

The only difference is that

  • the prefix version (++result) evaluates to the incremented value,
  • the postfix version (result++) evaluates to the original value.
Action Operator Description
Post-increment val = a++; Store the value of "a" in "val" then increments.
Post-decrement val = a--; Store the value of "a" in "val" then decrements.
Pre-increment val = ++a; Increments "a" then store the new value of "a" in "val".
Pre-decrement val = --a; Decrements "a" then store the new value of "a" in "val".
class PrePostDemo {

    public static void main(String[] args){
        int i = 3;
        int y = i++;

        System.out.println(i); // prints 3      	   
        System.out.println(y); // prints 3
   }
}
class PrePostDemo {

    public static void main(String[] args){
        int i = 3;
        int y = ++i;

        System.out.println(i); // prints 3      	   
        System.out.println(y); // prints 4
   }
}

If you are just performing a simple increment/decrement, it doesn't really matter which version you choose.

But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

Read more on Oracle website >>>

Watch this

Equals() method is defined in Object class in Java.
It is used for checking equality of two objects defined by business logic.

“==” or Equality Operator in Java is a binary operator provided by Java programming language.
It is used to compare primitives and objects.

public boolean equals(Object o) is the method provided by the Object class.
The default implementation uses == operator to compare two objects.
For example: method can be overridden like String class.equals() method is used to compare the values of two objects.

Control Flow

break continue
Usage In switch and loop (for, while, do while) statements Only in loop statements
Causes the switch or loop statements to terminate the moment it is executed Doesn’t terminate the loop but causes the loop to jump to the next loop iteration
Example
for (int i = 0; i < 5; i++) 
{
if (i == 3)
{
break;
}
System.out.println(i);
}
for (int i = 0; i < 5; i++)
{
if(i == 2)
{
continue;
}
System.out.println(i);
}

  1. An infinite loop is an instruction sequence in Java
    that loops endlessly when a functional exit isn’t met.
  2. This type of loop can be the result of a programming error
    or may also be a deliberate action based on the application behavior.
  3. An infinite loop will terminate automatically once the application exits.
public class InfiniteForLoop {
public static void main(String[] arg) {
for(;;)
System.out.println("Welcome to the Neverending Story!");
}}

Syntax:

for (type var : array) 
{ 
    statements using var;
}

is equivalent to the following for loop:

for (int i = 0; i < arr.length; i++) 
{ 
    type var = arr[i];
    statements using var;
}

Example of For-Each loop:

class ForEachLoopExample      
{ 
    public static void main(String[] arg) 
    { 
        { 
            int[] marks = { 125, 132, 95, 116, 110 }; 
              
            int highest_marks = maximum(marks); 
            System.out.println("The highest score is " + highest_marks); 
        } 
    } 
    
    public static int maximum(int[] numbers) 
    {  
        int maxSoFar = numbers[0]; 
          
        // for each loop 
        for (int num : numbers)  
        { 
            if (num > maxSoFar) 
            { 
                maxSoFar = num; 
            } 
        } 
    return maxSoFar; 
    } 
} 

Output:

The highest score is 132

Limitations of for-each loop

  1. For-each loops are not appropriate when you want to modify the array:
    for (int num : marks) 
    {
        // only changes num, not the array element
        num = num*2; 
    }
    
  2. For-each loops do not keep track of indexes.
    We can not obtain array indexes using For-Each loop:

    for (int num : numbers) 
    { 
        if (num == target) 
        {
            return ???;   // do not know the index of num
        }
    }
    
  3. For-each only iterates forward over the array in single steps
    // cannot be converted to a for-each loop
    for (int i=numbers.length-1; i>0; i--) 
    {
          System.out.println(numbers[i]);
    }
    
  4. For-each cannot process two decision making statements at once
    // cannot be easily converted to a for-each loop 
    for (int i=0; i
    

Iterator In Java

Iterator
is an interface provided by collection framework
to traverse a collection
and for a sequential access of items in the collection.

   
   // Iterating over collection 'c' using Iterator
   for (Iterator i = c.iterator(); i.hasNext(); ) 
       System.out.println(i.next());

For-Each In Java

For-Each loop
is meant for traversing items in a collection.

// Iterating over collection 'elements' that stores Element type items 
   for (Element e: elements)
       System.out.println(e);

We read the ‘:’ used in For-Each loop as “in”.
So loop reads as “for each element e in elements”

.forEach In Java

In Java 8 using lambda expressions
we can simply replace For-Each loop with

elements.forEach (e -> System.out.println(e) );

Iterator vs For-Each (or .forEach) in Java

  1. With iterator we can modify collection.
    If we have to modify collection, we need to use Iterator.

    ***Modifying a collection
    simply means removing an element
    or changing content of an item
    stored in the collection.

  2. In for-each loop, we can’t modify collection,
    it will throw a ConcurrentModificationException.

    This occurs because For-Each loop implicitly creates an iterator
    but it is not exposed to the user
    thus we can’t modify the items in the collection.

  3. While using nested for loops
    it is better to use for-each loop:

    // Java program to demonstrate working of nested iterators 
    // may not work as expected and throw exception. 
    import java.util.*; 
      
    public class Main 
    { 
        public static void main(String args[]) 
        { 
            // Create a link list which stores integer elements 
            List l = new LinkedList(); 
      
            // Now add elements to the Link List 
            l.add(2); 
            l.add(3); 
            l.add(4); 
      
            // Make another Link List which stores integer elements 
            List s=new LinkedList(); 
            s.add(7); 
            s.add(8); 
            s.add(9); 
      
            // Iterator to iterate over a Link List 
            for (Iterator itr1=l.iterator(); itr1.hasNext(); ) 
            { 
                for (Iterator itr2=s.iterator(); itr2.hasNext(); ) 
                { 
                    if (itr1.next() < itr2.next()) 
                    { 
                        System.out.println(itr1.next()); 
                    } 
                } 
            } 
        } 
    } 
    

    Output:

    Exception in thread "main" java.util.NoSuchElementException
        at java.util.LinkedList$ListItr.next(LinkedList.java:888)
        at Main.main(Main.java:29)
    

    The above code throws java.util.NoSuchElementException.

    In the above code
    we are calling the next() method again and again for itr1 (i.e., for List l).

    We are advancing the iterator
    without even checking if it has any more elements
    left in the collection(in the inner loop),
    thus we are advancing the iterator
    more than the number of elements in the collection
    which leads to NoSuchElementException.

    For-each loops are tailor made for nested loops:

    // Java program to demonstrate working of nested for-each 
    import java.util.*; 
    public class Main 
    { 
        public static void main(String args[]) 
        { 
            // Create a link list which stores integer elements 
            List l=new LinkedList(); 
      
            // Now add elements to the Link List 
            l.add(2); 
            l.add(3); 
            l.add(4); 
      
            // Make another Link List which stores integer elements 
            List s=new LinkedList(); 
            s.add(2); 
            s.add(4); 
            s.add(5); 
            s.add(6); 
      
            // Iterator to iterate over a Link List 
            for (int a:l) 
            { 
                for (int b:s) 
                { 
                    if (a < b) 
                        System.out.print(a + " "); 
                } 
            } 
        } 
    } 
    

    Output:

    2 2 2 3 3 3 4 4
    

Sources: geeksforgeeks.org, oracle javase 7, oracle javase 8, stackoverflow

Performance Analysis

same performance = same time complexity of traversals

  1. for collections with no random access
    Iterator and for-each loop are faster than simple for loop
  2. For collections which allow random access
    there is no performance change with for-each loop/for loop/iterator.

If you iterate using the old styled C for loop
then we might increase the time complexity drastically.

// Here l is List ,it can be ArrayList /LinkedList and n is size of the List

for (i=0;i < n;i++)
   System.out.println(l.get(i));
ArrayList vs. LinkedList Iteration
  1. If the list l is an ArrayList
    then we can access it in O(1) time since it is allocated contiguous memory blocks (just like an array) i.e random access is possible.
  2. But if the collection is LinkedList,
    then random access is not possible since it is not allocated contiguous memory blocks, so in order to access a element we will have to traverse the link list till you get to the required index, thus the time taken in worst case to access an element will be O(n).

Read more: geeksforgeeks.org, oracle javase 7, oracle javase 8, stackoverflow

Cursor in Java

Cursor
is an interface
used to retrieve data from collection object,
one by one.

Three Types of cursors

  1. Iterator Interface
  2. ListIterator Interface
  3. EnumerationIterator Interface
Iterator Interface

Iterator
is an interface
provided by collection framework
to traverse a collection
and for a sequential access of items in the collection.

   
   // Iterating over collection 'c' using terator
   for (Iterator i = c.iterator(); i.hasNext(); ) 
       System.out.println(i.next());
Iterator has 3 methods
  1. boolean hasNext()
    Returns true if the iterator has more elements.
  2. elements next()
    Returns the next element in the iterator.
  3. void remove()
    Removes from the collection
    the last element
    returned by the iterator.
import java.util.*; 
public class IteratorDemo 
{ 
    public static void main(String args[]) 
    { 
        //create a Hashset to store strings 
        HashSet hs = new HashSet() ; 
  
        // store some string elements 
        hs.add("India"); 
        hs.add ("America"); 
        hs.add("Japan"); 
  
        // Add an Iterator to hs. 
        Iterator it = hs.iterator(); 
  
        // Display element by element using Iterator 
        while (it.hasNext()) 
            System.out.println(it.next()); 
    } 
} 

Output:

America
Japan
India
ListIterator Interface

ListIterator Interface
interface that contains methods
to retrieve the elements from a collection object,
both in forward and reverse directions.

This iterator is for list based collections.

ListIterator has 7 methods
  1. booleanhasNext()
    Returns true if the ListIterator has more elements
    when traversing the list in the forward direction.
  2. booleanhasPrevious()
    Returns true if the ListIterator has more elements
    when traversing the list in the reverse direction.
  3. element next()
    Returns the next element in the list.
  4. element previous()
    Returns the previous element in the list.
  5. void remove()
    Removes from the list the last element
    that was returned by the next() or previous() methods.
  6. int nextIndex()
    Returns the index of the element
    that would be returned by a subsequent call to next().

    Returns list size if the list iterator is at the end of the list.

  7. int previousIndex()
    Returns the index of the element
    that would be returned by a subsequent call to previous().
    Returns -1 if the list iterator is at the beginning of the list.

Read more: oracle javase 7

EnumerationIterator Interface

EnumerationIterator Interface:
interface useful to retrieve elements one by one.

EnumerationIterator is based on data from Enumeration

EnumerationIterator has 2 Methods
  1. booleanhasMoreElements()
    Tests if Enumeration has more elements.
  2. element nextElement()
    Returns the next element
    available in elements
    that is available in Enumeration

Read more: geeksforgeeks.org,

  1. Iterator
    can retrieve elements only in forward direction.
  2. ListIterator
    can retrieve elements in forward and reverse direction.
    ListIterator is preferred to Iterator.
  3. Using ListItarator, we can get iterator’s current position
  4. Since ListIterator can access elements in both directions
    and supports additional operators,
    ListIterator cannot be applied on Set (e.g., HashSet and TreeSet).
  5. We can use LisIterator with vector and list (e.g. ArrayList ).

ListIterator Example:

import java. util.* ; 
  
class ListIteratorDemo 
{ 
    public static void main(String args[]) 
    { 
        // take a vector to store Integer objects 
        Vector v = new Vector(); 
  
        // Adding Elements to Vector 
        v.add(10); 
        v.add(20); 
        v.add(30); 
  
        // Creating a ListIterator 
        ListIterator lit = v.listIterator(); 
        System.out.println("In Forward direction:"); 
  
        while (lit.hasNext()) 
            System.out.print(lit.next()+" ") ; 
  
        System.out.print("\n\nIn backward direction:\n") ; 
        while (lit.hasPrevious()) 
            System.out.print(lit.previous()+" "); 
    } 
} 

Output :

In Forward direction:
10 20 30 

In backward direction:
30 20 10 

  1. Iterator has an option to remove elements from the collection
    which is not available in Enumeration.
  2. Also, Iterator has methods whose names are easy to follow
    and Enumeration methods are more difficult to remember.
import java.util.Vector; 
import java.util.Enumeration; 
public class Test 
{ 
    public static void main(String args[]) 
    { 
        Vector dayNames = new Vector(); 
        dayNames.add("Sunday"); 
        dayNames.add("Monday"); 
        dayNames.add("Tuesday"); 
        dayNames.add("Wednesday"); 
        dayNames.add("Thursday"); 
        dayNames.add("Friday"); 
        dayNames.add("Saturday"); 
  
        // Creating enumeration  
        Enumeration days = dayNames.elements(); 
  
        // Retrieving elements of enumeration 
        while (days.hasMoreElements()) 
            System.out.println(days.nextElement()); 
    } 
}

Output:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Java Keywords Interview Questions

Static Method Non-Static Method
Static keyword must be used before the method name No static keyword
Called as className.methodName Called like any general method
Can’t access any non-static instance variables or methods Can access any static method and any static variable without creating an instance of the class

  1. Keyword "super" is a reference variable that is used to refer parent class objects.
  2. The keyword “super” came into the picture with the concept of Inheritance.

Keyword "super" is used to refer:

  1. Immediate parent class variable

    When a derived class and base class has same data members,
    the use of keyword "super" helps to avoid a possibility of ambiguity for the JVM.

  2. Immediate parent class method

    When parent and child classes have the same method names,
    the use of keyword "super" helps to resolve ambiguity.

  3. Immediate parent class constructor

    Keyword "super" can be used to access the parent class constructor.
    Keyword "super" can call both parametric and non-parametric constructors depending on the situation.

    Important points:

    1. Call to super() must be first statement in derived class constructor.
    2. If a constructor does not explicitly invoke a Superclass constructor,
      the Java compiler automatically inserts a call to the no-argument constructor of the Superclass.

      If the Superclass does not have a no-argument constructor, you will get a compile-time error.
      Object does have such a constructor, so if Object is the only Superclass, there is no problem.

    3. If a subclass constructor invokes a constructor of its Superclass, either explicitly or implicitly,
      the whole chain of constructors gets called, all the way back to the constructor of Object.
      This is called constructor chaining.

In Java, super() and this(), both are special keywords that are used to call the constructor.

this() super()
Represents current instance of a class current instance of a parent/base class
Calls default constructor of the same class default constructor of the parent/base class
Accesses Methods of the current class Methods of the base class
Points to Current class instance Superclass instance
a block

"Final" is a special keyword in Java that is used as a non-access modifier.

Final variable Final method Final class
Creates constant variable
  • The value of a final variable can’t be changed once assigned.
  • When a final variable is a reference to an object, then this final variable is called reference final variable.
    Internal state of the object pointed by the reference variable can be changed.
    This is not re-assigning. This property of final is called non-transitivity.

    Arrays are objects in java. Arrays with final keyword are also called final arrays.
    You can add or remove elements from final array or final collection.

  • It is good practice to represent final variables in all uppercase, using underscore to separate words.
  • Final variable must be initialized, otherwise compiler will throw compile-time error.
    1. You can initialize a final variable when it is declared.
      This approach is the most common.

      When a final variable is created inside a method/constructor/block, it is called local final variable.
      It must be initialized when declared.

    2. A final variable is called blank final variable, if it is not initialized while declaration.

      It can be initialized inside instance-initializer block or inside constructor.

      If you have more than one constructor in your class then it must be initialized in all of them,
      otherwise compile time error will be thrown.

    3. A blank final static variable can be initialized inside static block.
  • Prevents Method Overriding
    A final method can’t be overridden by the subclass.

    Prevents Inheritance

    1. A final class can’t be extended by any subclass class
      but it can extend other classes.

      E.g., all Wrapper Classes like Integer, Float etc. are final classes. We can not extend them.

    2. The other use of final with classes is to create an immutable class, e.g., predefined String class.

      Immutable class means that once an object is created, its content can not be changed.
      You can not make a class immutable without making it final.

    Read more on GeeksForGeeks >>>

    Final Finally Finalize
    1. Final is used to apply restrictions on class, method, and variable.
    2. A final class can’t be inherited,
      final method can’t be overridden
      and final variable value can’t be changed.
    1. The finally keyword is used in association with a try/catch block.
      It can be used:

      1. When exceptions do not occur in the program,
        Finally guarantees that a section of code will be executed,
        even if an exception is thrown.
      2. Exception occurs and corresponding catch block matches.
        Finally executes whether exception occurs or not
        or whether corresponding catch block found or not.
      3. Exception occurs and corresponding catch block is not found
    2. The finally block will be executed after the try and catch blocks,
      but before control transfers back to its origin.
    3. Application of finally block: resource deallocation.
      All the resources opened in try block (Network Connections, Database Connections)
      need to be closed in finally block.
      This ensures that we won’t lose our resources as opened.
    1. Finalize is not a reserved keyword.
      It is a method that the Garbage Collector always calls just before the object is garbage collected to perform clean-up activity.
    2. Clean-up activity means closing the resources associated with that object
      e.g., Database Connection, Network Connection or we can say resource de-allocation.
    3. Once finalize method completes, Garbage Collector destroys that object.
    4. Finalize method belongs to the Object class, which is Superclass of all Java classes.
      Since it is available for all Java classes, Garbage Collector can call finalize method on any Java object.
    5. Syntax:
      protected void finalize throws Throwable{}

      Since Object class contains finalize method hence
      Finalize method has empty implementation and has to be overriden to define custom clean-up activities.

    6. There is no guarantee about the time when finalize is called.
      It may be called any time after the object is not being referred anywhere (cab be garbage collected).
      System.gc() is just a request to JVM to execute the Garbage Collector.
      It’s up-to JVM to call Garbage Collector or not.
      Usually JVM calls Garbage Collector when there is not enough space available in the Heap area or when the memory is low.
    7. JVM does not ignore all exceptions while executing finalize method,
      but it ignores only Unchecked exceptions.
      If the corresponding catch block is there then JVM won’t ignore
      and corresponding catch block will be executed.
    Final Finally Finalize
    class FinalVarExample {
    public static void main( String args[]){
    final int a=10;   // Final variable
    a=50;             //Error as value can't be changed
    }
    
    class FinallyExample {
    public static void main(String args[]){
    try {
    int x=100;
    }
    catch(Exception e) {
    System.out.println(e);
    }
    finally {
    System.out.println("finally block is executing");}
    }}}
    
    class FinalizeExample {
    public void finalize() {
    System.out.println("Finalize is called");
    }
    public static void main(String args[])
    {
    FinalizeExample f1=new FinalizeExample();
    FinalizeExample f2=new FinalizeExample();
    f1= NULL;
    f2=NULL;
    System.gc();
    }}
    

    In java, you will never see a class or method declared with both final and abstract keywords.

    Abstract Final
    For classes final is used to prevent inheritance abstract classes depend upon their child classes for complete implementation
    For methods final is used to prevent overriding abstract methods need to be overridden in sub-classes

    Java Built-in Methods

    These methods allow you to exercise much more control over your print output.

    The java.io package includes a PrintStream class
    that has two formatting methods
    that you can use to replace print and println.

    These two java.io.PrintStream methods, format and printf, are equivalent to one another.

    Syntax:

    public PrintStream format(String format, Object... args)
    
    1. format is a string that specifies the formatting to be used
    2. args is a list of the variables to be printed using that formatting.

    Example:

    System.out.format("The value of " + "the float variable is " +
         "%f, while the value of the " + "integer variable is %d, " +
         "and the string is %s", floatVar, intVar, stringVar); 
    
    1. The first parameter, format, is a format string
      specifying how the objects in the second parameter, args,
      are to be formatted.
    2. The format string contains
      1. plain text
      2. as well as format specifiers,
        which are special characters
        that format the arguments of Object... args.
    3. The notation Object... args is called varargs,
      which means that the number of arguments may vary.
    4. Format specifiers begin with a percent sign (%) and end with a converter.

      The converter is a character
      indicating the type of argument to be formatted.

      In between the percent sign (%) and the converter
      you can have optional flags and specifiers.

    5. There are many converters, flags, and specifiers, which are documented in java.util.Formatter

    Example

    int i = 461012;
    System.out.format("The value of i is: %d%n", i);
    

    The %d specifies that the single variable is a decimal integer.
    The %n is a platform-independent newline character.

    Output

    The value of i is: 461012
    

    Example

    long n = 461012;
          System.out.format("%d%n", n);      //  -->  "461012"
          System.out.format("%08d%n", n);    //  -->  "00461012"
          System.out.format("%+8d%n", n);    //  -->  " +461012"
          System.out.format("%,8d%n", n);    // -->  " 461,012"
          System.out.format("%+,8d%n%n", n); //  -->  "+461,012"
    

    The System.out is a PrintStream object,
    so you can invoke PrintStream methods on System.out, e.g.,

    System.out.format(.....);
    

    Read more on oracle website

    Java Exception Interview Questions

    An Exception is a problem that can occur during the normal flow of an execution.

    A method can throw an exception when something fails at runtime.
    If that exception couldn’t be handled, then the execution gets terminated before it completes the task.

    If we handled the exception, then the normal flow gets continued.

    Exceptions are a subclass of java.lang.Exception.

    Example for handling Exception:

    try{
    //Risky codes are surrounded by this block
    }catch(Exception e){
    //Exceptions are caught in catch block
    }
    

    1. The normal flow of the execution won’t be terminated if exception got handled
    2. We can identify the problem by using catch declaration

    Exception Hierarchy in Java

    Exception Hierarchy in Java
    Throwable is a parent class of all Exception classes.
    Exception is further divided into Exceptions and Errors.
    There are two types of Exceptions: Checked exceptions and UncheckedExceptions or RunTimeExceptions.
    All Errors are unchecked.

    Read more about Exceptions on Oracle website >>>

    Read more about Errors in Oracle Javadoc >>>

    See all Error Subclasses on Oracle Website >>>

    See all Exception Subclasses on Oracle Website >>>

    Error vs. Exception in Java
    Errors Exceptions
    Recoverability Impossible to recover from an Error

    Though error can be caught in the catch block
    but the execution of application will come to a halt and is not recoverable.

    Possible to recover from an Exception

    Exceptions are conditions that occur because of bad input or human error etc.
    E.g., FileNotFoundException will be thrown if the specified file does not exist.
    Or a NullPointerException will take place if you try using a null reference.

    In most of the cases it is possible to recover from an exception
    E.g., by giving the user feedback for entering proper values.

    Checked vs. Unchecked Unchecked Can be both: checked and unchecked
    When happen Run-time Can be both:compile-time and run-time
    Caused by Application running environment Application itself

    1. Throwable is the Superclass of all exceptions and errors.
    2. You can use it in a catch clause, but you should never do it!
    3. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application.
    4. Typical examples for that are the OutOfMemoryError or the StackOverflowError.

    Checked Exception
    1. These exceptions are checked by the compiler at compile-time.
    2. Classes that extend Throwable class except RuntimeException and Error are called checked Exception.
    3. Checked Exceptions must either declare the exception using throws keyword (or) surrounded by appropriate try/catch.

    E.g. ClassNotFound Exception, IOException, SQLException

    Unchecked Exception
    1. The classes that extend RuntimeException are known as unchecked exceptions.
    2. These exceptions are not checked at compile-time by the compiler.
    3. The compiler doesn’t force to handle these exceptions.

    E.g., ArithmeticException, NullPointerException, ArrayIndexOutOfBounds Exception

    There are five keywords used to handle exceptions in Java:

    1. try
    2. catch
    3. finally
    4. throw
    5. throws
    try

    When a risky code is surrounded by a try block. An exception occurring in the try block is caught by a catch block. Try can be followed either by catch (or) finally (or) both. But any one of the blocks is mandatory.

    catch

    This is followed by try block. Exceptions are caught here.

    finally

    This is followed either by try block (or) catch block. This block gets executed regardless of an exception. So generally clean up codes are provided here.

    Using try/catch

    A risky code is surrounded by try block.
    If an exception occurs, then it is caught by the catch block which is followed by the try block.

    class Manipulation{
    public static void main(String[] args){
    add();
    }
    Public void add(){
    try{
    addition();
    }catch(Exception e){
    e.printStacktrace();
    }}}
    
    By declaring throws keyword

    At the end of the method, we can declare the exception using throws keyword.

    class Manipulation{
    public static void main(String[] args){
    add();
    }
    public void add() throws Exception{
    addition();
    }}
    

    Yes we can have multiple catch blocks under single try block but the approach should be from specific to general.

    public class Example {
    public static void main(String args[]) {
    try {
    int a[]= new int[10];
    a[10]= 10/0;
    }
    catch(ArithmeticException e)
    {
    System.out.println("Arithmetic exception in first catch block");
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
    System.out.println("Array index out of bounds in second catch block");
    }
    catch(Exception e)
    {
    System.out.println("Any exception in third catch block");
    }
    }
    

    throw throws
    Usage Used to explicitly throw an exception. Used to declare an exception
    Propagation Checked exceptions can not be propagated with throw only. Checked exception can be propagated with throws.
    Followed by Throw is followed by an instance. Throws is followed by class.
    Where used Within the method. With the method signature.
    Multiple exceptions You cannot throw multiple exceptions. You can declare multiple exceptions.
    E.g. public void method()throws IOException,SQLException.

    1. Finally block always executes a set of statements.
    2. It is always associated with a try block regardless of any exception that occurs or not.

    Finally will not be executed

    1. if the program exits either by calling System.exit()
    2. or by causing a fatal error that causes the process to abort.

    1. Exception and all of it’s Subclasses do not provide any specific methods.
    2. All of the methods are defined in the base class Throwable.
    Method Description
    String getMessage() This method returns the message String of Throwable about the exception.
    The message can be provided while creating the exception through it’s constructor.
    String getLocalizedMessage() This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message.
    Synchronized Throwable getCause() This method returns the cause of the exception
    or null id the cause is unknown
    as represented by a Throwable object.
    String toString() This method returns the information about Throwable in String format.
    The returned String contains the name of Throwable class and localized message.
    void printStackTrace() This method prints the stack trace information to the standard error stream.
    This method is overloaded and we can pass PrintStream or PrintWriter as an argument to write the stack trace information to the file or stream.
    public StackTraceElement[] getStackTrace() This method returns an array containing each element on the stack trace.
    The element at index 0 represents the top of the call stack
    whereas the last element in the array represents the method at the bottom of the call stack.

    To create you own exception extend the Exception class or any of its subclasses.

    class New1Exception extends Exception { }               // this will create Checked Exception
    class NewException extends IOException { }             // this will create Checked exception
    class NewException extends NullPonterExcpetion { }  // this will create UnChecked exception
    

    Exception is first thrown from the method which is at the top of the stack. If it doesn’t catch, then it pops up the method and moves to the previous method and so on until they are got.

    This is called Exception propagation.

    public class Manipulation{
    public static void main(String[] args){
    add();
    }
    public void add(){
    addition();
    }
    

    From the above example, the stack looks like as shown below:

    addition()
    add()
    main()

    If an exception occurred in the addition() method is not caught, then it moves to the method add().
    Then it is moved to the main() method and then it will stop the flow of execution.
    It is called Exception Propagation.

    OutOfMemoryError is the subclass of java.lang.Error which generally occurs when our JVM runs out of memory.

    Java Threads Interview Questions

    In Java, the flow of a execution is called Thread.

    1. A thread is the smallest piece of programmed instructions which can be executed independently by a scheduler.
    2. All java programs have at least one thread known as the main thread
    3. The Main thread is created by JVM when the program starts its execution. The main thread is used to invoke the main() of the program.
    4. The user can define their own threads by extending Thread class (or) by implementing Runnable interface.
    5. Threads are executed concurrently.
    public static void main(String[] args){
       //main thread starts here
    }
    

    Java Thread Lifecycle


    Thread has the following states:

    1. New
    2. Runnable
    3. Running
    4. Non-runnable (Blocked)
    5. Terminated
    New

    In New state, Thread instance has been created but start () method is not yet invoked. Now the thread is not considered alive.

    Runnable

    The Thread is in runnable state after invocation of the start () method, but before the run () method is invoked. But a thread can also return to the runnable state from waiting/sleeping. In this state the thread is considered alive.

    Running

    The thread is in running state after it calls the run () method. Now the thread begins the execution.

    Non-Runnable(Blocked)

    The thread is alive but it is not eligible to run. It is not in runnable state but also, it will return to runnable state after some time.

    E.g., wait, sleep, block.

    Terminated

    Once the run method is completed then it is terminated. Now the thread is not alive.

    There are two ways available to create a thread in Java:

    1. By extending the Thread class.
    2. By implementing the Runnable interface.
    Extend Thread class

    Extending a Thread class and override the run method.
    The thread is available in java.lang.thread.

    Public class Addition extends Thread {
    public void run () {
    }
    }
    

    The disadvantage of using a thread class is
    that we cannot extend any other classes
    because we have already extend the thread class.
    We can overload the run() method in our class.

    Implement Runnable interface

    Another way is implementing the runnable interface.
    For that we should provide the implementation for run() method which is defined in the interface.

    Public class Addition implements Runnable {
    public void run () {
    }
    }
    

    Process Thread
    Definition An executing instance of a program is called a process. A thread is a subset of the process.
    Communication Processes must use inter-process communication to communicate with sibling processes. Threads can directly communicate with other threads of its process.
    Control Processes can only exercise control over child processes. Threads can exercise considerable control over threads of the same process.
    Changes Any change in the parent process does not affect child processes. Any change in the main thread may affect the behavior of the other threads of the process.
    Memory Run in separate memory spaces. Run in shared memory spaces.
    Controlled by Operating system. Programmer in a program.
    Dependence Processes are independent. Threads are dependent.

    If we need our class to extend some other classes other than the thread
    then we can go with the Runnable interface
    because in java we can extend only one class.

    If we are not going to extend any class then we can extend the thread class.

    Start() method creates new thread and the code inside the run() method is executed in the new thread.

    If we directly called the run() method then a new thread is not created and the currently executing thread will continue to execute the run() method.

    Join() method is used to join one thread with the end of the currently running thread.

    public static void main (String[] args){
    Thread t = new Thread();
    t.start();
    t.join();
    }
    
    1. From the above code, the main thread started the execution.
    2. When it reaches the code t.start() then ‘thread t’ starts the own stack for the execution.
    3. JVM switches between the main thread and ‘thread t’.
    4. Once it reaches the code t.join() then ‘thread t’ alone is executed and completes its task,
      then only main thread started the execution.

    Join() is a non-static method.
    Join() method has overloaded version.
    So we can mention the time duration in join() method also “.s”.

    A yield() method moves the currently running thread to a runnable state and allows the other threads for execution.
    So that equal priority threads have a chance to run.
    It is a static method.
    It doesn’t release any lock.

    Yield() method moves the thread back to the Runnable state only, and not the thread to sleep(), wait() (or) block.

    public static void main (String[] args){
    Thread t = new Thread ();
    t.start ();
    }
    public void run(){
    Thread.yield();
    }
    }
    

    notify() notifyAll()
    This method is used to send a signal to wake up a single thread in the waiting pool. This method sends the signal to wake up all the threads in a waiting spool.

    We can stop a thread by using the following thread methods.

    1. Sleeping
    2. Waiting
    3. Blocked

    Sleep

    Sleep() method is used to sleep the currently executing thread for the given amount of time.
    Once the thread is wake up it can move to the runnable state.
    So sleep () method is used to delay the execution for some period.

    It is a static method.

    Thread. Sleep (2000)
    

    So it delays the thread to sleep 2 milliseconds.
    Sleep () method throws an uninterrupted exception, hence we need to surround the block with try/catch.

    public class ExampleThread implements Runnable{
    public static void main (String[] args){
    Thread t = new Thread ();
    t.start();
    }
    public void run(){
    try{
    Thread.sleep(2000);
    }catch(InterruptedException e){
    }
    }
    

    Wait() method is used to make the thread to wait in the waiting pool.
    When a wait() method is executed during a thread execution then immediately the thread gives up the lock on the object and goes to the waiting pool.
    Wait() method tells the thread to wait for a given amount of time.

    Then the thread will wake up after notify() (or) notify all() method is called.

    Wait() and the other above-mentioned methods do not give the lock on the object immediately until the currently executing thread completes the synchronized code. It is mostly used in synchronization.

    public static void main (String[] args){
    Thread t = new Thread ();
    t.start();
    Synchronized(t) {
    Wait();
    }
    }
    

    Multiple threads are executed simultaneously. Each thread starts their own stack based on the flow (or) priority of the threads.

    public class MultipleThreads implements Runnable {
    public static void main (String[] args){//Main thread starts here
    Runnable r = new runnable ();
    Thread t=new thread();
    t.start ();//User thread starts here
    Addition add = new addition();
    }
    public void run(){
    go();
    }//User thread ends here
    }
    

    On the 1st line execution, JVM calls the main method and the main thread stack looks as shown below:

    Main thread
    Main()

    Once the execution reaches, t.start () line then a new thread is created and the new stack for the thread is also created. Now JVM switches to the new thread and the main thread are back to the runnable state.

    The two stacks look as shown below.

    Main thread User thread
    Start() run()
    Run()

    Now, the user thread executed the code inside the run() method.

    Main thread User thread
    Start() go()
    Run() run()

    Once the run() method has completed, then JVM switches back to the main thread and the User thread has completed the task and the stack was disappeared.

    JVM switches between each thread until both the threads are completed. This is called Multi-threading.

    1. Synchronization refers to multi-threading.
    2. Only one thread can access a block of code at a time =
      a synchronized block of code can be executed by only one thread at a time.
    3. As Java supports execution of multiple threads, two or more threads may access the same fields or objects.
    4. If multiple thread accesses the same block of code, there is a chance for inaccurate results at the end.
    5. To avoid this issue, we can provide synchronization for the sensitive block of codes.
      Synchronization is a process which keeps all concurrent threads in execution to be in sync.
      Synchronization avoids memory consistency errors caused due to inconsistent view of shared memory.
    6. When a method is declared as synchronized the thread holds the monitor for that method’s object.
      If another thread is executing the synchronized method the thread is blocked until that thread releases the monitor.
    7. The synchronized keyword means that a thread needs a key in order to access the synchronized code.
      Every Java object has a lock. A lock has only one key.
      A thread can access a synchronized method only if the thread can get the key to the objects lock.
    public class ExampleThread implements Runnable{
     public static void main (String[] args){
     Thread t = new Thread ();
     t.start ();
     } 
     public void run(){
     synchronized(object){
     {}
    }
    

    Java Multithreading and Threads Synchronization

    Synchronization is not recommended to implement all the methods.
    Because if one thread accesses the synchronized code then the next thread should have to wait.
    So it slows performance on the other end.

    Java Serialization Interview Questions

    Converting a file into a byte stream is known as Serialization. The objects in the file is converted to the bytes for security purposes. For this, we need to implement java.io.Serializable interface. It has no method to define.

    Variables that are marked as transient will not be a part of the serialization. So we can skip the serialization for the variables in the file by using a transient keyword.

    Transient variables are not part of the serialization process.
    During deserialization, the transient variables values are set to default value.
    It is not used with static variables.

    transient int numbers;

    Volatile variable values are always read from the main memory and not from thread's cache memory.
    This is used mainly during synchronization.
    It is applicable only for variables.

    volatile int number;

    ObjectOutputStream and ObjectInputStream classes are higher level java.io. package.
    We will use them with lower level classes FileOutputStream and FileInputStream.

    ObjectOutputStream.writeObject --> Serialize the object and write the serialized object to a file.

    ObjectInputStream.readObject --> Reads the file and deserializes the object.

    To be serialized, an object must implement the serializable interface.
    If superclass implements Serializable, then the subclass will automatically be serializable.

    Serialization Deserialization
    Serialization is the process which is used to convert the objects into byte stream Deserialization is the opposite process of serialization where we can get the objects back from the byte stream.
    An object is serialized by writing it an ObjectOutputStream. An object is deserialized by reading it from an ObjectInputStream.

    Whenever an object is Serialized, the object is stamped with a version ID number for the object class.
    This ID is called the SerialVersionUID.
    This is used during deserialization to verify that the sender and receiver that are compatible with the Serialization.

    JDBC Interview Questions

    What is JDBC Driver?

    JDBC Driver is a software component that enables java application to interact with the database.

    There are 4 types of JDBC drivers:

    1. JDBC-ODBC bridge driver
    2. Native-API driver (partially java driver)
    3. Network Protocol driver (fully java driver)
    4. Thin driver (fully java driver)

    Steps to Connect to a Database in Java
    1. Registering the driver class
    2. Creating connection
    3. Creating statement
    4. Executing queries
    5. Closing connection

    JDBC API components
    Interfaces Classes
    1. Connection
    2. Statement
    3. PreparedStatement
    4. ResultSet
    5. ResultSetMetaData
    6. DatabaseMetaData
    7. CallableStatement etc.
    1. DriverManager
    2. Blob
    3. Clob
    4. Types
    5. SQLException etc.

    Role of JDBC DriverManager Class
    1. The DriverManager class manages the registered drivers.
    2. It can be used to register and unregister drivers.
    3. It provides factory method that returns the instance of Connection.

    1. The Connection interface maintains a session with the database.
    2. It can be used for transaction management.
    3. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

    Java JDBC Connection Interface

    Purpose of JDBC ResultSet Interface

    The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

    JDBC ResultSetMetaData Interface

    The ResultSetMetaData interface returns the information of table
    such as total number of columns, column name, column type etc.

    JDBC DatabaseMetaData Interface

    The DatabaseMetaData interface returns the information of the database
    such as username, driver name, driver version, number of tables, number of views etc.

    Batch Processing in JDBC
    1. Batch processing helps you to group related SQL statements into a batch
      and execute them instead of executing a single query.
    2. By using batch processing technique in JDBC, you can execute multiple queries which makes the performance faster.

    Execute vs. executeQuery vs. executeUpdate

    Statement execute(String query)
    is used to execute any SQL query and it returns TRUE if the result is an ResultSet such as running Select queries. The output is FALSE when there is no ResultSet object such as running Insert or Update queries. We can use getResultSet() to get the ResultSet and getUpdateCount() method to retrieve the update count.

    Statement executeQuery(String query)
    is used to execute Select queries and returns the ResultSet. ResultSet returned is never null even if there are no records matching the query. When executing select queries we should use executeQuery method so that if someone tries to execute insert/update statement it will throw java.sql.SQLException with message “executeQuery method can not be used for update”.

    Statement executeUpdate(String query)
    is used to execute Insert/Update/Delete (DML) statements or DDL statements that returns nothing. The output is int and equals to the row count for SQL Data Manipulation Language (DML) statements. For DDL statements, the output is 0.

    You should use execute() method only when you are not sure about the type of statement else use executeQuery or executeUpdate method.

    JDBC Statements
    1. JDBC statements are used to send SQL commands to the database and retrieve data back from the database.
    2. Various methods like execute(), executeUpdate(), executeQuery, etc. are provided by JDBC to interact with the database.
    3. JDBC supports 3 types of statements:
      1. Statement: Used for general purpose access to the database and executes a static SQL query at runtime.
      2. PreparedStatement: Used to provide input parameters to the query during execution.
      3. CallableStatement: Used to access the database stored procedures and helps in accepting runtime parameters.






    Sources: tutorialspoint.com, oralce


    Leave a Reply or Comment

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