fbpx
1800 274 6001 sara@netconnectglobal.com

Java interview questions with code examples for 3-5 years of experience:

Estimated reading: 2 minutes 196 views

Explain abstraction in Java and provide an example of abstract class:

// Abstract class 
abstract class Shape {
  abstract void draw();
}

//Inheriting abstract class
class Rectangle extends Shape {

  @Override
  void draw() {
    System.out.println("Drawing rectangle..."); 
  }
}

Questions:

  • Why can we not instantiate the Shape class?
  • Can we declare the abstract method as static or final?
  • What is the purpose of abstract classes in Java?

Write a program to demonstrate checked and unchecked exceptions. Handle the exception using try/catch block:

import java.io.*;

class Main {
  public static void main(String[] args) {
    try {
      File file = new File("test.txt");
      FileReader fr = new FileReader(file); 
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    
    String str = null;
    System.out.println(str.length()); //NullPointerException
  }
}

Questions:

  • Which exception is checked and which one is unchecked here?
  • What best practices should be followed for exception handling?
  • Difference between throw and throws?

Explain inheritance in Java with an example:

class Animal {
  void eat() {
    System.out.println("Eating...");
  } 
}

class Dog extends Animal {
  void bark() {
    System.out.println("Barking...");
  }
}

class Main {
  public static void main(String[] args) {
    Dog d = new Dog();
    d.bark();
    d.eat();
  }
}

Questions:

  • Can a class extend multiple classes in Java? Why?
  • What is method overriding in inheritance?
  • Difference between abstract classes and interfaces?
Share this Doc

Java interview questions with code examples for 3-5 years of experience:

Or copy link

CONTENTS