Quick Java Interview Handbook

Subscribe to my newsletter and never miss my upcoming articles

If you have a Java interview coming up and need to brush up on your basics, this one is for you. You'll brush up on everything from the fundamentals to more advanced functionality that you're likely to be asked about.

Even if you use Java every day, you may not have been exposed to certain parts of it in a long time, so it's always a good idea to stay up to date. You'll be able to browse questions by topic, as well as see detailed answers and live code examples where applicable. Begin immediately.

Table of Contents

  1. What is JDK JRE and JVM
  2. What is Variable and Data Type
    1. Primitive data types
    2. Non Primitive data types
  3. Decision Making in Java
  4. Object Class and Method
  5. Naming Convention in Java
  6. Constructors
    1. When is a Constructor called
    2. Rules for creating Java constructor
    3. Types of Java constructors
    4. Default Constructor Example
    5. Parameterized Constructor Example
    6. How constructors are different from methods in Java
    7. This In Java
  7. Static And Non Static Member of Class
  8. Return Type
  9. Access modifiers
  10. Local And Global Variable
  11. Method Overloading In Java
  12. Method overriding In Java
  13. Inheritance in Java
  14. Interface in Java
  15. Abstract Class in Java
  16. Exception
  17. Throw in Java
  18. Throws Keyword in Java
  19. Finally block in Java
  20. Collection Framework
  21. Strings
  22. Key technical differences between an abstract class and an interface

What is JDK JRE and JVM

JDK : Java Development Kit (in short JDK) is Kit which provides the environment to develop and execute(run) the Java program. JDK is a kit (or package) which includes two things

JRE : Java Runtime Environment (to say JRE) is an installation package which provides environment to only run (not develop) the java program (or application) onto your machine. JRE is only used by them who only wants to run the Java Programs i.e. end users of your system.

JVM : Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line hence it is also known as interpreter.

Note: JDK is only used by Java Developers.

What is Variable and Data Type

Example

Variable: Reserve area in memory (int data=50)

  • local variable
  • instance variable
  • static variable

Example

public class Test { 
int x = 75; //instance variable
static int y =20; //static variable
public void testLogin(int a) {
int p =90; //local variable
}

Data Type: Data types represents the different values to be stored in the variable. In java, there are two types of data types:

  • primitive data types
  • Non primitive data types image.png

Primitive data types :

The primitive data types include boolean, char, byte, short, int, long, float and double.

image.png

Non Primitive data types :

The non-primitive data types include Classes, Interfaces, and Arrays.

  • String s1;
  • Student obj;
  • Employee emp;

Decision Making in Java

  • By Java If-else
  • By JAVA Switch
  • By JAVA For Loop
  • BY JAVA While Loop
  • JAVA Break
  • JAVA Continue

If-else Statement : The Java if statement is used to test the condition. it checks Boolean Condition: true or false.

if(true) {
}
else {
}

Switch Statement : The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.

Example

public class SwitchExample {
public void checkBookTypeAndPrice(String bookName) {
String s1;
switch (bookName) {
case "MATH":
s1 = "Author Aryabhata Price=200";
System.out.println(s1);
break;
case "PHYSICS":
s1 = "Author Bhanu Prata Price=100";
System.out.println(s1);
break;
case "CHEMISTRY":
s1 = "Author Pratap Price=300";
System.out.println(s1);
break;
default:
System.out.println("No Book Found Supply Proper Input");
}
}
public static void main(String[] args) {
SwitchExample switchExample = new SwitchExample();
switchExample.checkBookTypeAndPrice("MATH");
}
}

For Loop : The Java for loop is a control flow statement that iterates a part of the programs multiple times.

for (int i = 0; i < 8; i++) {
}

For Loop consists of four parts:

  1. Initialization: It is the initial condition which is executed once when the loop starts. Here, we can initialize the variable, or we can use an already initialized variable. It is an optional condition.
  2. Condition: It is the second condition which is executed each time to test the condition of the loop. It continues execution until the condition is false. It must return boolean value either true or false. It is an optional condition.
  3. Statement: The statement of the loop is executed each time until the second condition is false.
  4. Increment/Decrement: It increments or decrements the variable value. It is an optional condition

Example :

public class ForLoopExample {
public static void main(String[] args) {

for (int i = 0; i < 8; i++) {
String string = "Running For Loop and count is=" + i; 
System.out.println(string);
}
}
}

While Loop : The Java while loop is used to iterate a part of the program several times. If the number of iteration is not fixed, it is recommended to use while loop.

while (condition) {
}

Example :

public class WhileLoopExample {

public static void main(String[] args) {

int i = 5;
while (i <= 10) {
System.out.println(i); i++;
}
}
}

Do While Loop : if the number of iteration is not fixed and you must have to execute the loop at least once, it is recommended to use do while loop.

do{
}while(Condition)

Example :

public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 0;
do {

i++;
} while (i < 5);
}
}

Break : The Java break is used to break loop or switch statement

Example :

public class BreakExample1 {

public static void main(String[] args) {
int i = 0;
while (i >= 0) {
if (i == 10) {
break;
}
System.out.println("i counter="+i); i++;
}
}
}

Continue : * The Java Continue statement is one of the most useful statement to controls the flow of loops. We generally use this statement inside the For Loop, While Loop and Do While Loop. While executing these loops, if compiler find the Java Continue statement inside them, it will stop the current loop iteration and starts the new iteration from the beginning.

Example :

public class ContinueExample1 {

public static void main(String[] args) {
int array[] = { 120, 230, 404, 560, 708, 90, 10, 20 };
for (int i = 0; i < array.length; i++) {
if (array[i] < 560) {
continue;
}
System.out.println("number is=" + array[i]);
}
}
}

Java Comments

  • Single line comments
// single line comment
  • Multi line comments
/*
*Multi line comment
*/

Object Class and Method

A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. Class has

  1. Modifiers : A class can be public or has default access.
  2. Class name : The name should begin with a initial letter (capitalized by convention).
  3. Superclass(if any) : The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. Interfaces(if any) : A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  5. Body : The class body surrounded by braces, { }.

Objects correspond to things found in the real world.

An object consists of :

  1. State : It is represented by attributes of an object. It also reflects the properties of an object.
  2. Behaviour : It is represented by methods of an object. It also reflects the response of an object with other objects.
  3. Identity : It gives a unique name to an object and enables one object to interact with other objects.

image.png

If we make 5 Object of same class, each object will have one copy of attributes/Behaviour

image.png

Method in Java : In Java, a method is like a function which is used to expose the behaviour of an object.

Advantage of Method

  • Code reusability
  • Code optimisation.
public class Example1 {

int age;

public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;

}
public static void main(String[] args) { 

Example1 obj1 = new Example1(); obj1.setAge(4);
obj1.getAge();

Example1 obj2 = new Example1(); obj1.setAge(6);
obj2.getAge();
}

}

public static void main(String[] args)

Java main method is the entry point of any java program. Its syntax is always public static void main(String[] args). You can only change the name of String array argument, for example you can change args to myStringArgs. Also String array argument can be written as String... args or String args[].

Public

This is the access modifier of the main method. It has to be public so that java runtime can execute this method. Remember that if you make any method non-public then it’s not allowed to be executed by any program, there are some access restrictions applied. So it means that the main method has to be public.

Static

When java runtime starts, there is no object of the class present. That’s why the main method has to be static so that JVM can load the class into memory and call the main method. If the main method won’t be static, JVM would not be able to call it because there is no object of the class is present

Void

Java programming mandates that every method provide the return type. Java main method doesn’t return anything, that’s why it’s return type is void. This has been done to keep things simple because once the main method is finished executing, java program terminates. So there is no point in returning anything, there is nothing that can be done for the returned object by JVM. If we try to return something from the main method, it will give compilation error as an unexpected return value.

public class Example1 {

public static void main(String[] args) {
return 0;
}
}

String[] args

Java main method accepts a single argument of type String array. This is also called as java command line arguments.

Naming Convention in Java

  • Class name Should always start with Uppercase.
  • Method should start with lower class.
  • Package name should always be lowercase.
  • Constant should be in uppercase.
  • Variable name should start with lower case letter
  • Interface name should start with upper case letter
package classExample; 
public class Example1 {
int age;
static final int MAX_AGE = 18;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Example1 obj1 = new Example1(); 
obj1.setAge(4);
obj1.getAge();
Example1 obj2 = new Example1(); obj1.setAge(6);
obj2.getAge();
}
}

Constructors

Constructors are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation

Constructors are used to assign values to the class variables at the time of object creation, either explicitly done by the programmer or by Java itself (default constructor).

When is a Constructor called

Each time an object is created using new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of the same class.

Rules for creating Java constructor

There are three rules defined for the constructor.

  1. Constructor name must be the same as its class name
  2. A Constructor must have no explicit return type
  3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors

There are two types of constructors in Java:

  • Default constructor (no-arg constructor)
  • Parameterized constructor

Default Constructor Example

package constructor; 

public class Example1 {
public String name;
public int i;

Example1() {
}

public static void main(String[] args) {
 Example1 obj = new Example1(); 
System.out.println(obj.name); 
System.out.println(obj.i);
}
}

Parameterized Constructor Example

package constructor; 
public class Book {
int length; 
int breadth; 
int height;
public Book(int length, int breadth, int height) {
this.length = length; 
this.breadth = breadth;
this.height = height;
}

public static void main(String[] args) { 
Book obj = new Book(10, 20, 30); 
System.out.println(obj.length); 
System.out.println(obj.breadth); 
System.out.println(obj.height);
}
}

How constructors are different from methods in Java

  • Constructor(s) must have the same name as the class within which it defined while it is not necessary for the method in java.
  • Constructor(s) do not return any type while method(s) have the return type or void if does not return any value.
  • Constructor is called only once at the time of Object creation while method(s) can be called any numbers of time.

Is it possible to create object of default constructor when we have only parameterized constructor in class

Ans : - NO ( when we explicitly create parameterized constructors in class then java compiler will not keep by default constructor in class

This In Java

  • this can be used to refer current class instance variable
  • this can be used to invoke current class method (implicitly)
  • this can be used to invoke current class constructor
  • this can be passed as an argument in the method call
  • this can be passed as an argument in the constructor call
  • this can be used to return the current class instance from the method
public class Lion {

int speed = 5;
public Lion () {
}
public Lion ( Lion l) {
}
public Lion ( int weight, Lion p) {

this();
}
public void run (int speed) {

this .speed =speed;
walk(this);
}
public Lion walk ( Lion l) {

return this;

}
public void eat() {

new  Lion (this);
}
}

Static And Non Static Member of Class

  • Static Members of class are accessed by Class Name, Since static members are class members
  • Non Static Members of class are accessed by object. Non Static members are object members
public class Example 1 {

int i;
static int j ;
public void test1() { }
public void test2() { }
public static void test3() { }
public static void main ( String[] args ) {

Example1 obj = new Example 1 ();
obj.test1();
obj.test2();
System.out.println(obj.i);
Example1.test3();
System.out.println(Example1.i);
// Here we get compile time error, 
Since we are trying to call non static variables through class name
System.out.println(Example1.test1);
//We cant call non static method through class reference. 
if we try to do that we will get compile time error.
Since non static members are object members 
}
}

Return Type

The data type of the return value must match the method's declared return type. We can't return an integer value from a method whose declaration type is void.

public class Example 1 {

//In test1() method  if we try to return integer data we will get compile time error.
since method declaration is void
public void test1() {
}
//In test2() method  if we try to return string data we will get compile time error.
since method declaration is int
public int test2() {

return 3;

}
// In test3() method  if we try to return string data we will get compile time error.
since method declaration is double
public double test3() {
return 3.3;
}
// In test4() method  if we try to return string data we will get compile time error.
since method declaration is boolean
public boolean test4() {

return true; 
}

public char test5() {

return 'a'; 
}

public String test 6() {

return "Test";

}

public Example1 test7 () 
{
return new Example 1 ();
} 
public int[] test8() {
return new int[7];
}

Access modifiers

image.png

public class Example1 {

public String s1; 
private String s2;
protected String s3; 
String s4;
protected void name1() 

{ 
System.out.println("protected method");
}

public void name2() {
System.out.println("public method");
}

private void name3() {
System.out.println("private method");
}

void name4() {
System.out.println("default method");
}

}

What are the members we can access in different class, within same package?

package accessmodifier;
public class Example2 {

public static void main(String[] args) { 
Example1 example1 = new Example1();
example1.name1(); 
example1.name2(); 
example1.name4();
System.out.println(example1.s1); 
System.out.println(example1.s3); 
System.out.println(example1.s4);
}

}

What are the members we can access in different class, in different package?

package access.modifier.test;
import accessmodifier.Example1;
public class Example3 {
public static void main(String[] args) {  
Example1 example1 = new Example1(); 
example1.name2(); 
System.out.println(example1.s1);
}

}

What are the members we can access in different class,

in different package through inheritance?

package access.modifier.test;
import accessmodifier.Example1;
public class Example4 extends Example1{
public static void main(String[] args) { 
Example4 example4 = new Example4(); 
example4.name1();
example4.name2();
System.out.println(example4.s1); 
System.out.println(example4.s3);
}
}

Local And Global Variable

Local Variables:-

  • We write local variable within method , function and block.
  • Local variables are local in nature, we can't access from outside method, function and block
  • It is possible to have local variables with the same name in different functions.

Global Variables:-

  • We write global variables outside method, function and block.
  • We can't create duplicate global variable.
  • We can access global variable by any method, function and block.
public class Example1 {
int i;
int j;
char c;
public void test(int a, int b) {
}
public void test1() {
int a = 10;
int b = 20;
}
public static void main(String[] args) {
Example1 obj = new Example1();
System.out.println(obj.i);
System.out.println(obj.a);
}

}

/*
Here when we can't access local variable through object reference
Since local variable can't be access outside method 
(int i,int j,char c) are global variables. and we can access them from any method
Where as (int a, int b) are local variables. and we can't access from outside method
*/

Method Overloading In Java

  • Method Overloading will allow us to create more than one methods with same name by changing the method arguments.
  • Method Overloading is called as compile time polymorphisms.

Arguments list can be different in following ways

  • Numbers of parameters to method
  • Data Type of parameters
  • Sequence Type of parameters

Numbers of parameters to method example

public class Example1 {
public void test1(int i) {
}
public void test1(int i, int j) {
}
public void test1(int i, int j, int k) {
}
public void test1(String i, int j) {
}

}

Method overriding In Java

Points to Note:-

  • Method Overriding is the the feature of java which allow us to create same method in parent and child class with same name and with same arguments.
  • Method Overriding is the the ability of java which will make sure method call will happen from a class for which we have created the object. Not from referenced class.
  • At compile time method call happens from reference class.
  • At Run time method call happens from object class.
  • Method Overriding is possible only by inheritance.
  • Method Overriding we also call it as run time polymorphism.
  • Method Overriding is the the feature of java which allow us to create same method in parent and child class with same name and with same arguments.
public class ParentClass {
public void test() {
System.out.println("From ParentClass test()");
}
public int test1() {
System.out.println("From ParentClass test1()");
return 3;
}
}
public class ChildClass extends ParentClass {
public void test() {
System.out.println("From ChildClass test()");
}
public int test1() {
System.out.println("From ChildClass test1()");
return 3;
}
}

Inheritance in Java

Points to Note:

  • Through inheritance child class will acquire all non static members of class.
  • We can't inherit private member of class.
  • We can't inherit static members of class. since static members are class members.
  • Final Members can not be inherit.
public class ParentClass {
public void test() {
System.out.println("From ParentClass test()");
}
public int test1() {
System.out.println("From ParentClass test1()");
return 3;
}
public void test2() {
System.out.println("From ParentClass test2()");
}
}
public class ChildClass extends ParentClass {
public static void main(String[] args) {
ParentClass obj = new ChildClass();
obj.test();
obj.test1();
obj.test2();
}
}

Interface in Java

  • Interface has only unimplemented methods.
  • Interface members are by default (Public static final).
  • We call interface as 100 % abstract class.
  • Multiple inheritance is possible in case of interface.
  • We cannot create object of interface, since all the members are unimpeded.
  • We cannot create constructor of interface. Since object creation for interface is not possible.
  • We cannot create object of class. Since members are unimplemented.

Structure of interface

public interface Example1 {
            public final static int i=90;
            int j =80;

            public void test1();
            public void test2();
            public void test3();
             void test4();
}
public class TestInterface implements Example1{
            @Override
            public void test1() {
                        // TODO Auto-generated method stub     
            }
            @Override
            public void test2() {
                        // TODO Auto-generated method stub       
            }
            @Override
            public void test3() {
                        // TODO Auto-generated method stub        
            }
            @Override
            public void test4() {
                        // TODO Auto-generated method stub

Abstract Class in Java

  • Abstract class will have implemented and unimpeded methods.
  • We Cannot create object of Abstract class.
  • We Cannot write constructor in Abstract class.
  • To make class Abstract class we need to have at least one method as Abstract method.
  • We can create Reference of Abstract class and object of child class.

Basic Structure

public abstract class ExampleAbstarct1 { 
            public abstract void test1();
            public void test2(){
             }
            public void test3(){
              }
            public abstract void test4();
            abstract void test5();
}
public class TestAbstractClass extends ExampleAbstarct1{
            @Override
            public void test1() {
            }
            @Override
            public void test4() {    
            }
            @Override
            void test5() {  
            }
public static void main(String[] args) {

ExampleAbstarct1 obj = new TestAbstractClass();
                        obj.test1();
                        obj.test2();
                        obj.test3();
                        obj.test4();
                        obj.test5();

Key technical differences between an abstract class and an interface

  • Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (they are defined public by default).
  • When inheriting an abstract class, a concrete child class must define the abstract methods, whereas an abstract class can extend another abstract class and abstract methods from the parent class don't have to be defined.
  • Similarly, an interface extending another interface is not responsible for implementing methods from the parent interface. This is because interfaces cannot define any implementation.
  • A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
  • A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public)
public class TestInterface implements Example1,Example2,Example3

public interface D extends A,B (here A, B is interface)

Exception

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Exception hierarchy in java

image.png

Difference between checked and unchecked exceptions

  • Checked Exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.
  • Unchecked Exception : The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
  • Error: Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Types of exception

public class TypesOfExceptions extends Test1{
            static String s1;
            //Exception in thread "main" java.lang.ArithmeticException: / by zero
            public static void airthmeticException(){
                        int a = 9/0;
            }
            //Exception in thread "main" java.lang.NullPointerException
            public static void nullPointerException(){
                        System.out.println(s1.concat("Test"));
            }

          //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
            public static void stackOverFlow(){
                        ArrayList<Integer> array = new ArrayList<Integer>();
                        while(true){
                                    array.add(10);
                        }
            }
 //Exception in thread "main" java.lang.NumberFormatException: For input string: "Test"
            public static void numberFormateException(){
                        String s1 = "Test";
                        int t = Integer.parseInt(s1);
                        int a = 9;
                        Double.parseDouble(s1);
                        Short.parseShort(s1);
                        Long.parseLong(s1);
                        Boolean.parseBoolean(s1);
            }

            //Exception in thread "main" java.io.FileNotFoundException: C:/Test.xls (No such file or directory)

            public static void fileNotFoundException() throws FileNotFoundException {
                        FileReader f = new FileReader("C://Test.xls");
            }
            //Exception in thread "main" java.lang.ClassNotFoundException: Test124
            public static void classNotFoundException() throws ClassNotFoundException{
                        Class.forName("Test124");
            }
            //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
            public static void arrayIndexOutodbound(){
                        int[] a = new int[5];
                        System.out.println(a[5]);
            }

            //Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
            public static void outOfMemoryException(){
                        long data[] = new long[1000000000];
            }

         //Exception in thread "main" java.lang.ClassCastException: 
        //coreJavaTutorial.ExcepionInJava.Test1
       //cannot be cast to coreJavaTutorial.ExcepionInJava.TypesOfExceptions
            public static void classCastException(){
                        Test1 obj = new Test1();
                        System.out.println((TypesOfExceptions)obj);
            }
            //Exception in thread "main" java.lang.NullPointerException
            public static void inputOutputException(){
                        InputStreamReader obj = new InputStreamReader(null);
            }
             //Exception in thread "main" java.lang.IllegalStateException: Scanner closed
            public static void illigalStateException(){
                           String s = "Hello World";
                           Scanner scanner = new Scanner(s);
                           System.out.println("" + scanner.nextLine());
                           scanner.close();
                           System.out.println("" + scanner.nextLine());             
            }
            // Checked Exception
            public void test() throws InterruptedException{
                        Thread.sleep(2000);
            }

How to handle the exception

  • By Try Catch Block:
  • As we know that when exception comes execution of program will terminate. To avoid that we need -to handle the exception.
  • We need to use try catch block to handle the exception
public class Example1 {
            public static void main(String[] args) {
                        try {
                                    int i = 9/0;
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        System.out.println("test is running evenafter exception");
              }
}
public class Example1 {

            public static void main(String[] args) {
                         String s1 = null;
                        try {
                                    s1.toLowerCase();
                        } catch (Exception e) {
                                    e.printStackTrace();
                        }
                        System.out.println("test is running evenafter exception1");
                        System.out.println("test is running evenafter exception2");
                        System.out.println("test is running evenafter exception3");
            }
}

Q: Is it possible to catch particular exception by catch block

Answer: - Yes

Q: - Is it possible to write multiple catch block for singe try block.

Answer: - Yes

public class Example2 {
            public static void main(String[] args) {
                        try {
                                    int a = 9 / 0;
                                    int[] array = new int[3];
                                    System.out.println(array[4]);
                        } catch (ArithmeticException e) {
                                    System.out.println("ArithmeticException is gettign called");
                                    e.printStackTrace();
                        } catch (ArrayIndexOutOfBoundsException e) {
                                    System.out.println("ArrayIndexOutOfBoundsException is gettign called");
                                    e.printStackTrace();
                        }
                        System.out.println("Runnign code aftre exception1");
                        System.out.println("Runnign code aftre exception2");
                        System.out.println("Runnign code aftre exception3");
            }
}
  • In above program, when we get ArithmeticException catch block with ArithmeticException will get executed.When We get ArrayIndexOutOfBoundsException catch block with ArrayIndexOutOfBoundsException will get executed.

Throw in Java

  • When we want throw exception based on condition we can use throw keyword. This will help us to throw exception on run time.

In This example we will throw exception based on age validation

public class ThrowInJava {

      public void validateAge(int age){
             if(age<18){
                   throw new ArithmeticException("person age is not valid for voting");
                        }
               else{
                   System.out.println("person is valid for voting);   
            }
}
     public static void main(String[] args) {
                        ThrowInJava obj = new ThrowInJava();
                        obj.validateAge(17);
            }
}

output:
Exception in thread "main" java.lang.ArithmeticException:
 person age is not valid for voting
            at ThrowInJava.validateAge(ThrowInJava.java:6)
            at ThrowInJava.main(ThrowInJava.java:15)

Throws Keyword in Java

The Throws keyword is used in method declaration, in order to explicitly specify the exceptions that a particular method might throw. When a method declaration has one or more exceptions defined using throws clause then the method-call must handle all the defined exceptions.

public class ThrowsInJava {
         public void validateAge(int age) throws ArithmeticException{
                  if(age<18){
                           throw new ArithmeticException("person age is not valid for voting");
                  }
                  else{
                           System.out.println("person is valid for voting");
                  }
         }
}

The above example it will throws ArithmeticException so that whenever we call this method from any class, it will force us to handle the exception

Finally block in Java:

Java Finally blocked will always get executed whether we have handled the exception or not. In This example we are not handling ArithmeticException in catch block, still finally block will get executed.

Finally blocked is used to execute important code like closing DB connection, closing file connection.

public class ThrowInJava {     
public static void main(String[] args) {
            try {
                        int i = 9/0;
            } catch (NullPointerException e) {
                        e.printStackTrace();
            }
            finally{
                        System.out.println(" I am finally");
            }}
}

Output
java.lang.ArithmeticException: / by zero
 I am finally
            at ThrowInJava.main(ThrowInJava.java:6)

Q: Is finally blocked will get executed, if we have return statement in try block.

Answer: - Yes (In general Return statement will be the last line of code after that compile will be returned from method or block).

Collection Framework:

The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures.

Collection framework allow us to manipulate and store group of object.

Collection Interface and classes are present in Java.utill package.

Here Interfaces are

  • Iterable
  • Collection
  • Set
  • Map
  • List
  • Queue

Remaining all are classes

  • Hash Map
  • Linked Hash Map
  • Tree Map
  • Hash Map
  • Linked Hash Map
  • Tree Map
  • Array List
  • Linked List
  • Vector
  • Priority Queue

Array List: -

Array List is class in Java. It allows us to store multiple objects.

Points to Note: -

  • Array list is dynamic array, which means it will grow and shrink automatically.
  • Array list allows us to store duplicate elements.
  • Array list store data based on index.
  • Array list internally usages array.
  • Array list maintains insertion order.
  • Array list are not thread safe (not synchronized).
  • Manipulation is slow because a lot of shifting needs to be occurred if any element is removed from the Array list.
  • Retrievals is fast in Array list.
  • Array list allows us to store any kind of data.

Arrays List Methods

  • void add(int index, Object element): It is used to insert the specified element at the specified position index in a list.
  • boolean addAll(Collection c) : It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.
  • void clear() : It is used to remove all of the elements from this list.
  • int lastIndexOf(Object o) : It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
  • Object[] toArray(): It is used to return an array containing all of the elements in this list in the correct order.
  • Object[] toArray(Object[] a) : It is used to return an array containing all of the elements in this list in the correct order.
  • boolean add(Object o) : It is used to append the specified element to the end of a list.
  • boolean addAll(int index, Collection c) : It is used to insert all of the elements in the specified collection into this list, starting at the specified position.
  • Object clone() : It is used to return a shallow copy of an ArrayList.
  • int indexOf(Object o): It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
  • void trimToSize() : It is used to trim the capacity of this ArrayList instance to be the list's current size.

Array list Example:

In this example we can store any data type

import java.util.*;
public class Example3 {
            public static void main(String[] args) {
                        List list = new ArrayList();
                        list.add(2);
                        list.add("2");
                        list.add("test");
                        list.add(true);
                        list.add('c');
                        list.add(9.80);
                        System.out.println(list);}}

Output: -
      [2, 2, test, true, c, 9.8]

Linked List

Points to Note:

  • Linked List is class, which will allow us to store and manipulate groups of data.
  • It allows us to store duplicate objects
  • It will grow dynamically on run time
  • It maintains insertion order
  • It is not thread safe (non synchronized)
  • It usages node to store the data.
  • Data retrieval is slow in linked list.
  • Manipulation is fast, due to no shifting operation happens.

In this example we can store all objects type

import java.util.*;
public class Example3 {
           public static void main(String[] args) {
                        List list = new LinkedList<>();
                        list.add(1);
                        list.add(10.990);
                        list.add(true);
                        list.add("6");
                        list.add("Test");                 
                        System.out.println(list);
        }}
// Output: -[1, 10.99, true, 6, Test]

|ArrayList|LinkedList|

Vector

Points to Note:

  • Vector is class, which will allow us to store and manipulate groups of data.
  • It allows us to store duplicate objects
  • It will grow dynamically on run time
  • It maintains insertion order
  • It is thread safe (synchronized)

In this example we can store all objects type


import java.util.*;
public class Example3 {
            public static void main(String[] args) {
                        List list = new Vector<>();
                        list.add(1);
                        list.add(10.990);
                        list.add(true);
                        list.add("6");
                        list.add("Test");                 
                        System.out.println(list);
            }
}
// Output: -[1, 10.99, true, 6, Test]

Iterators in Java

  • Iterator is used to iterator over collection of objects.
  • Iterator is interface.
package Test;
import java.util.ArrayList;
import java.util.Iterator;
public class Example2 {         
      /**
     * Returns { true} if the iteration has more elements.
     * (In other words, returns {true} if {next} would
     * return an element rather than throwing an exception.)
     *
     * return {code true} if the iteration has more elements
     */
            public static void main(String[] args) {
                        ArrayList<Integer> array = new ArrayList<Integer>();
                        array.add(3);
                        array.add(4);
                        array.add(5);
                        Iterator<Integer> itr = array.iterator();
                        while(itr.hasNext()){
                                    System.out.println(itr.next());
                        }
            } }

Iterator Methods

  • boolean hasNext();
  • E next ();
  • void remove ();

boolean hasNext()

  • Returns true if the iteration has more elements.

E next ()

  • Returns the next element in the iteration.

void remove ()

  • Removes from the underlying collection the last element returned by this iterator (optional operation).

boolean hasNext()

  • Returns true if the iteration has more elements. (In other words, returns true if next () would return an element rather than throwing an exception.)
  • Returns: true if the iteration has more elements

List Iterator

It is used to Iterator over collection of object.

List Iterator Methods

  • boolean hasNext();
  • E next ();
  • boolean hasPrevious();
  • E previous ();
  • void remove ();
/**
 * Returns the previous element in the list and moves the cursor
 * position backwards.
*/
boolean hasPrevious();
/**
Return the previous element from list
*/
E previous();
/**
 * Returns the next element in the list and advances the cursor position.
 * This method may be called repeatedly to iterate through the list,
 */
boolean hasNext();
/**
 * Return the element for collection objects
 * @return
 */
E next();

void remove();

Set in Java

Points to know:

  • Set will store only unique data
  • Hash Set will not maintain insertion order.
ConstructorDescription
HashSet()It is used to construct a default HashSet.
HashSet(int capacity)It is used to initialize the capacity of the hash set to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet
HashSet(int capacity, float loadFactor)It is used to initialize the capacity of the hash set to the given integer value capacity and the specified load factor.
HashSet(Collection<? extends E> c)It is used to initialize the hash set by using the elements of the collection c.
Return TypeMethodDescription
booleanadd(E e)It is used to add the specified element to this set if it is not already present.void clear() It is used to remove all of the elements from the set.
objectclone()It is used to return a shallow copy of this HashSet instance: the elements themselves are not cloned.
booleancontains(Obje ct o)It is used to return true if this set contains the specified element.
booleanisEmpty()It is used to return true if this set contains no elements.
Iteratoriterator()It is used to return an iterator over the elements in this set.
booleanremove(Objec t o)It is used to remove the specified element from this set if it is present.
intsize()It is used to return the number of elements in the set.
Spliteratorspliterator()It is used to create a late-binding and fail-fast Spliterator over the elements in the set.

Example of Hash Set

package Test;
import java.util.HashSet;
import java.util.Set;
public class ExampleHashSet {

            public static void main(String[] args) {
                        // Hash Set will store Only unique data.
                        Set<Integer> set = new HashSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        // insertion order are not maintained
                        System.out.println(set);
            }
}
//output: [1, 80, 7, 8, 10]

Linked Hash set

Linked Hash set will maintain insertion order.

package Test;
import java.util.LinkedHashSet;
import java.util.Set;
public class ExampleHashSet {
            public static void main(String[] args) {
                        Set<Integer> set = new LinkedHashSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        System.out.println(set);
            }
}
//output: [1, 10, 7, 80, 8]

Tree Set

Tree Set Maintain the data in ascending order.

package Test;
import java.util.Set;
import java.util.TreeSet;
public class ExampleHashSet {

            public static void main(String[] args) {
                        Set<Integer> set = new TreeSet<Integer>();
                        set.add(1);
                        set.add(1);
                        set.add(10);
                        set.add(7);
                        set.add(80);
                        set.add(8);
                        set.add(8);
                        System.out.println(set);
            }
}
//output: [1, 7, 8, 10, 80]

Map in collection

  • Map will not maintain insertion order.
  • Map will store data based on key value pair
  • Map will store only unique data.

Hash Map

  • A Hash Map contains values based on the key.
  • It contains only unique elements.
  • It may have one null key and multiple null values.
  • It maintains no order.
  • Java HashMap class is non synchronized.
public class HashMap<K,V> extends AbstractMap<K,V> 
implements Map<K,V>, Cloneable, Serializable

Constructor and Description

HashMap()

Constructs an empty HashMap with the default initial capacity (16) 
and the default load factor (0.75).

HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity 
and the default load factor (0.75).

HashMap(int initialCapacity, float loadFactor)

Constructs an empty HashMap with the specified initial capacity 
and load factor.

HashMap(Map<? extends K,? extends V> m)
Modifier and TypeMethod and Description
void clear()Removes all of the mappings from this map.
Object clone()Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned.
boolean containsKey(Object key)Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value)Returns true if this map maps one or more keys to the specified value.
Set> entrySet()Returns a Set view of the mappings contained in this map.
V get(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
boolean isEmpty()Returns true if this map contains no key-value mappings.
Set keySet()Returns a Set view of the keys contained in this map.
V put(K key, V value)Associates the specified value with the specified key in this map.
void putAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map.
V remove(Object key)Removes the mapping for the specified key from this map if present.
int size()Returns the number of key-value mappings in this map.
Collection values()Returns a Collection view of the values contained in this map.

Example:

package Test;
import java.util.HashMap;
import java.util.Map;
public class ExampleHashMap {

            public static void main(String[] args) {
                        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(4, 100);
                        System.out.println(map);
            }
}
//output: {1=100, 4=100, 20=100, 30=100}

Hash Map will store one null key.

package Test;
import java.util.HashMap;
import java.util.Map;

public class ExampleHashMap {

            public static void main(String[] args) {
                        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(30, 100);
                        map.put(30, 100);
                        map.put(30, 100);
                        map.put(null, 100);
                        System.out.println(map);
            }
}
//output: {null=100, 1=100, 20=100, 30=100}

LinkedHashMap is a subclass of HashMap. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order.

Example
package Test;
import java.util.LinkedHashMap;
import java.util.Map;

public class ExampleHashMap {

            public static void main(String[] args) {
                        Map<Integer,Integer> map = new LinkedHashMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(4, 100);
                        System.out.println(map);
            }
}
//output: {1=100, 20=100, 30=100, 4=100}

Tree Map will store the data in ascending order

package Test;
import java.util.Map;
import java.util.TreeMap;

public class ExampleHashSet {

            public static void main(String[] args) {
                        Map<Integer,Integer> map = new TreeMap<Integer,Integer>();
                        map.put(1, 100);
                        map.put(20, 100);
                        map.put(30, 100);
                        map.put(4, 100);
                        System.out.println(map);
            }
}
//output: {1=100, 4=100, 20=100, 30=100}

Hash Table

  • Hash Table is thread safe.
  • We cannot store null key in hash table
  • It will not insertion order. Example
package Test;
import java.util.Hashtable;
public class HashTableInJava {

            public static void main(String[] args) {
                        Hashtable<Integer,Integer> obj = new Hashtable<Integer,Integer>();
                        obj.put(1, 900);
                        obj.put(2, 800);
                        obj.put(3, 600);
                        obj.put(4, 400);
                        obj.put(5, 900);
                        System.out.println(obj);
            }
}
// Output: - {5=900, 4=400, 3=600, 2=800, 1=900}

Set entrySet()

It is used to return a set view of the keys contained in this map.

import java.util.HashMap;
import java.util.Map;

public class EntrySetExample {
public static void main(String args[]) {
HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(10, "Sandeep1");
hm.put(11, "Sandeep3");
hm.put(12, "Sandeep2");
for (Map.Entry m : hm.entrySet()) {
System.out.println(m.getKey() + " " + m.getValue());
}
}
}

Output:
10 Sandeep1
11 Sandeep3
12 Sandeep2
public class A {
int id;
String name, author, publisher;
int quantity;

public A(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {    
    //Creating map of A    
    Map<Integer,A> map=new HashMap<Integer,A>();    
    //Creating A    
    A b1=new A(101,"Test1","AAA","BPB",8);    
    A b2=new A(102,"Test2","BBB","yes",4);    
    A b3=new A(103,"Test3","CCC","Wiley",6);    
    //Adding A to map   
    map.put(1,b1);  
    map.put(2,b2);  
    map.put(3,b3);  

    //Traversing map  
    for(Map.Entry<Integer, A> entry:map.entrySet()){    
        int key=entry.getKey();  
        A b=entry.getValue();  
        System.out.println(key+" Details:");  
        System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);   
    }    
}  }

Output:
1 Details:
101 Test1 AAA BPB 8
2 Details:
102 Test2 BBB yes 4
3 Details:
103 Test3 CCC Wiley 6

The keySet() method is used to get a Set view of the keys contained in this map.

import java.util.HashMap;
import java.util.Set;

public class EntrySetDemo {
public static void main(String args[]) {
// create hash map
HashMap newmap = new HashMap();
// populate hash map
newmap.put(1, "Test1");
newmap.put(2, "Test2");
newmap.put(3, "is best");

// get keyset value from map
Set keyset = newmap.keySet();

// check key set values
System.out.println("Key set values are: " + keyset);
}
}

Output
Key set values are: [1, 2, 3]

Java Stack

  • Java Stack is LIFO object. It extends Vector class, but supports only five operations. Java Stack class has only one constructor which is empty or default constructor. So, when we create a Stack, initially it contains no items that means Stack is empty.
  • Stack internally has a pointer: TOP, which refers to the top of the Stack element. If Stack is empty, TOP refers to the before first element location. If Stack is not empty, TOP refers to the top element.

Java Stack Methods

Java Stack extends Vector class with the following five operations only.

E is type of object you are adding like (Integer, String, Custom Object)

  • boolean empty(): Tests if this stack is empty.
  • E peek(): Looks at the object at the top of this stack without removing it from the stack.
  • E pop() : Removes the object at the top of this stack and returns that object as the value of this function.
  • E push(E item) : Pushes an item onto the top of this stack.
  • int search(Object o) : Returns the 1-based position where an object is on this stack.
import java.util.Stack;
public class StackBasicExample {
  public static void main(String a[]){
        Stack<Integer> stack = new Stack<>();
        System.out.println("Empty stack : "  + stack);
        System.out.println("Empty stack : "  + stack.isEmpty());
        // Exception in thread "main" java.util.EmptyStackException
        // System.out.println("Empty stack : Pop Operation : "  + stack.pop());
        stack.push(1001);
        stack.push(1002);
        stack.push(1003);
        stack.push(1004);
        System.out.println("Non-Empty stack : "  + stack);
        System.out.println("Non-Empty stack: Pop Operation : "  + stack.pop());
        System.out.println("Non-Empty stack : After Pop Operation : "  + stack);
        System.out.println("Non-Empty stack : search() Operation : "  + stack.search(1002));
        System.out.println("Non-Empty stack : "  + stack.isEmpty());
    }
}

Output:
Empty stack : []
Empty stack : true
Non-Empty stack : [1001, 1002, 1003, 1004]
Non-Empty stack: Pop Operation : 1004
Non-Empty stack : After Pop Operation : [1001, 1002, 1003]
Non-Empty stack : search() Operation : 2
Non-Empty stack : false

Java Queue Interface

Java Queue interface orders the element in FIFO(First In First Out) manner. In FIFO, first element is removed first and last element is removed at last.

MethodDescription
boolean add(object)It is used to insert the specified element into this queue and return true upon success.
boolean offer(object)It is used to insert the specified element into this queue.
Object remove()It is used to retrieves and removes the head of this queue.
Object poll()It is used to retrieves and removes the head of this queue, or returns null if this queue is empty.
Object element()It is used to retrieves, but does not remove, the head of this queue.
Object peek()It is used to retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

Example

import java.util.Iterator;
import java.util.PriorityQueue;
public class PriorityQueueExample {
public static void main(String args[]){  
PriorityQueue<String> queue=new PriorityQueue<String>();  
queue.add("Test1");  
queue.add("Test2");  
queue.add("Test3");  
queue.add("Test4");  
queue.add("Test5");  
System.out.println("head:"+queue.element());  
System.out.println("head:"+queue.peek());  
System.out.println("iterating the queue elements:");  
Iterator itr=queue.iterator();  
while(itr.hasNext()){  
System.out.println(itr.next());  
}  
queue.remove();  
queue.poll();  
System.out.println("after removing two elements:");  
Iterator<String> itr2=queue.iterator();  
while(itr2.hasNext()){  
System.out.println(itr2.next());  
}  }  }

Output:
head:Test1
head:Test1
iterating the queue elements:
Test1
Test2
Test3
Test4
Test5
after removing two elements:
Test3
Test4
Test5

String In Java

Strings

Strings are a sequence of characters

public class StringDemo {
public static void main(String args[]) {
      char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
      String helloString = new String(helloArray);  
      System.out.println( helloString );
  }
}

Output:
hello.
public class Testimmutablestring {
public static void main(String args[]) {
String s = "Java";
s.concat(" Test");
// concat() method appends the string at the end
System.out.println(s);
// will print Java because strings are immutable objects
}
}

String Methods:

MethodDescription
char charAt(int index)Returns the character at the specified index.
int compareTo(Object o)Compares this String to another Object.
int compareTo(String anotherString)Compares two strings lexicographically.
int compareToIgnoreCase(String str)Compares two strings lexicographically, ignoring case differences.
String concat(String str)Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.
static String copyValueOf(char[] data)Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)Tests if this string ends with the specified suffix.
boolean equals(Object anObject)Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)Compares this String to another String, ignoring case considerations.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)Copies characters from this string into the destination character array.
int hashCode()Returns a hash code for this string.
int indexOf(int ch, int fromIndex)Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str)Returns the index within this string of the first occurrence of the specified substring.
int lastIndexOf(int ch)Returns the index within this string of the last occurrence of the specified character.
int length()Returns the length of this string.
String replace(char oldChar, char newChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement)Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)Replaces the first substring of this string that matches the given regular expression with the given replacement.
String[] split(String regex)Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)Tests if this string starts with the specified prefix beginning a specified index.
String substring(int beginIndex)Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)Returns a new string that is a substring of this string.
char[] toCharArray()Converts this string to a new character array.
String toLowerCase()Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale)Converts all of the characters in this String to lower case using the rules of the given Locale.
String toUpperCase()Converts all of the characters in this String to upper case using the rules of the default locale.
String trim()Returns a copy of the string, with leading and trailing whitespace omitted.

Difference between == and .equals() method in Java

In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:

  • Main difference between .equals() method and == operator is that one is method and other is operator.
  • We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
// Java program to understand 
// the concept of == operator
public class Test {
    public static void main(String[] args)
    {
        String s1 = new String("HELLO");
        String s2 = new String("HELLO");
        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}

Output:
false 
true
class Test {
    public static void main(String[] args)
    {
        // integer-type
        System.out.println(10 == 20);

        // char-type
        System.out.println('a' == 'b');

        // char and double type
        System.out.println('a' == 97.0);

        // boolean type
        System.out.println(true == true);
    }
}

Output:
false 
false 
true 
true

public class Test {
    public static void main(String[] args)
    {
        Thread t1 = new Thread();
        Thread t2 = new Thread();
        Thread t3 = t1;

        String s1 = new String("GEEKS");
        String s2 = new String("GEEKS");

        System.out.println(t1 == t3);
        System.out.println(t1 == t2);

        System.out.println(t1.equals(t2));
        System.out.println(s1.equals(s2));
    }

Output:
true 
false 
false 
true

Java StringBuffer class

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java is same as String class except it is mutable i.e. it can be changed.

class StringBufferExample {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Java");
sb.append("Test");// now original string is changed
System.out.println(sb);
// prints Java Test
}
}

Java StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.

Multithreading in Java

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :

  • Extending the Thread class
  • Implementing the Runnable Interface
public class MultithreadingDemo extends Thread {
public void run() {
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
public static void main(String[] args) {
for (int i = 0; i < 8; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}}}

Output:
Thread 8 is running 
Thread 9 is running 
Thread 10 is running 
Thread 11 is running 
Thread 12 is running 
Thread 13 is running 
Thread 14 is running 
Thread 15 is running
//Java code for thread creation by implementing
//the Runnable Interface
public class MultithreadingDemo implements Runnable {
public void run() {
try {
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId() + " is running");

} catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < 8; i++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}

Lifecycle and States of a Thread in Java

A thread in Java at any point of time exists in any one of the following states. A thread lies only in one of the shown states at any instant:

  • New
  • Runnable
  • Running
  • Non-Runnable (Blocked)
  • Terminated
StateDescription
NewThe thread is in new state if you create an instance of Thread class but before the invocation of start() method.
RunnableThe thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread.
RunningThe thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)This is the state when the thread is still alive, but is currently not eligible to run.
TerminatedA thread is in terminated or dead state when its run() method exits.
MethodDescription
public void run()is used to perform action for a thread.
public void start()starts the execution of the thread.JVM calls the run() method on the thread.
public int getPriority()returns the priority of the thread.
public int setPriority(int priority)changes the priority of the thread.
public String getName()returns the name of the thread.
public void setName(String name)changes the name of the thread.
public void sleep(long miliseconds)Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds.
public void join()waits for a thread to die.
public void join(long miliseconds)waits for a thread to die for the specified miliseconds.
public Thread currentThread()returns the reference of currently executing thread.
public int getId()returns the id of the thread.
public Thread.State getState()returns the state of the thread.
public boolean isAlive()tests if the thread is alive.
public void yield()causes the currently executing thread object to temporarily pause and allow other threads to execute.
public void suspend()is used to suspend the thread(depricated).
public void resume()is used to resume the suspended thread(depricated).
public void stop()is used to stop the thread(depricated).
public boolean isDaemon()tests if the thread is a daemon thread.
public void setDaemon(boolean b)marks the thread as daemon or user thread.
public void interrupt()interrupts the thread.
public boolean isInterrupted()tests if the thread has been interrupted.
public static boolean interrupted()tests if the current thread has been interrupted.

I hope this article helped you to brush up the java fundamental concepts.Also, have a look at my other interesting articles:

Refrences : docs.oracle.com/en/java

If you have any Queries or Suggestions, feel free to reach out to me in the Comments Section below.

Please share and also subscribe to my newsletter to be notified when I post a new subject and also follow on

TWITTER

FACEBOOK

LINKEDIN

TUMBLR

No Comments Yet