10 Java Concepts you must know before appearing for technical interviews

10 java programs for technical interview

10 java programs for technical interviewThere are a lot of questions that crawl into our minds a few days before the interviews. You can bet this post will not answer any of those but it will surely help you revise with the 10 java concepts you must know before appearing for a technical interview. The first thing that you must know is that the interviewer is trying to know whether you understand the concepts so mugging up definitions will not help. It is very important to make the interviewer understand that you know how the concepts are inspired by real life so it will be good for you if instead of stating a definition, you provide him with an example and explain the concept in your own words. Even if you are giving him a previously read example, state it as if you are making it up right at that moment. Also, prepare a good programming example with every concept. This way it will help you get a complete grasp of every concept and it will also increase your confidence level as you will be better prepared to answer a lot of follow up questions. Click here if you want to find out the 10 C programs frequently asked in interviews.

#1: Class and Object

Yes, I cheated a bit. There are actually more than 10 concepts but I wrote 10 as it sounded better. Anyway coming back to the topic, you must be knowing what is class and object but don’t hurry to state the definition. Rather pause a bit and start out with an example. All human beings belong to a class Humans. Both me and you are objects of the type Humans. You can shamelessly state this example or give a better example but in either case, don’t let him know that you have previously prepared it. One good thing about this example is that it involves the interviewer. This provides an additional feeling that you made up the example at that moment. It can be best followed up with a small definition such as A Class is a blueprint for an Object. The answer is not yet complete. Follow it up with a program. If you are not provided with a paper, explain the program in your own words. There is a class Dog which has an instance variable name and a method bark(). Now we create an object of the class Dog and assign a name tom to it.

Dog tom = new Dog();

An answer like this will definitely impress any interviewer.

#2: Abstraction and Encapsulation

As I told before start off with an example. I don’t know why I just love the car example from Herbert Schildt so I will give you that example here. Here is what you need to say – you see a car is a complex object with several thousand parts but we ignore the complexity by ignoring the details as to how the car’s internal mechanisms work together. Instead, we know how to handle the steering, brakes, clutch and so on… Even in the java programs, we use several methods which are already defined. We just use them without knowing what they actually do. This is known as abstraction.

Continuing with the car example, as you know the gear shift lever enables us to use the transmission. Now it is a well-defined interface to the transmission. You as a user can affect the transmission only by shifting the gears and not by doing anything else. Also shifting gears will not affect anything else other than the transmission. Even in java programs, a class (containing instance variables and methods) is defined in a way so that they are wrapped or encapsulated. The other classes can access this class only through the methods and so cannot arbitrarily change the value of the instance variables. This is known as encapsulation.

#3: Inheritance

Don’t give the example like you have inherited from your father. This might be true in the real sense but this is not what the interviewer wants to listen from you. Instead, give a better example of a class inheriting from another class. A good example will be that of class Mammal which inherits from the class Animal. The Animal class is the super class and Mammal class is the subclass. Mammals can do all the stuff that an animal can do like eat, sleep and so on. Other than that a mammal can do some extra stuff which an animal might not do like breastfeeding their children. Similarly, class Reptile inherits from class Animal. Reptiles can do all the stuff that the Animal can do. Additionally, it can crawl which an animal can not do. Another class Human inherits from the class Mammal. Therefore Human can do both the Animal stuff as well as the Mammal stuff. The pictorial representation is shown below. 

inheritance Animal - Mammal example

Like the methods, the instance variables are also inherited from the super class to the subclasses. A superclass can have 1 or more subclasses but a subclass can have only one superclass. In Java extends keyword is used to implement inheritance.

#4: Method Overriding

This is a popular follow-up question to inheritance. Again don’t start with the definition. Instead, control your urges and start out with an example. We use the previous example where Humans inherit the eat() from Mammal and also from Animal. You see humans does not eat like other mammals do, they use their hands to eat. So the contents of Human’s eat() will not be the same as Animal’s or Mammal’s eat(). So we can change the contents of eat() in the Human class as per our requirement. This is known as method overriding. Now whenever the eat() is called on a Human object, the newly defined eat() in the Human class will be called not the previously defined Animal’s eat(). If you get a pen and paper write a small program to illustrate it.


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

class Mammal extends Animal {
  public void breastFeeding() {
    System.out.println("Mammals breastfeed");
  }
}

class Human extends Mammal {
  //extends eat() from Animal
  //overridden method
  public void eat() {
    System.out.println("Humans eat with their hands");
  }
}

public class AnimalTest {
  public static void main(String[] args){
    Animal animal = new Animal();
    animal.eat(); //will call the eat() of Animal class
    Human man = new Human();
    man.eat(); //will call the eat() of Human class
  }
}

Output :

Animals eat
Humans eat with their hands

A common follow up question to overriding is Dynamic Method Dispatch. Again no definition only examples. Rewrite the AnimalTest class to:


public class AnimalTest {
 public static void main(String[] args){
   Animal animal = new Animal();
   Mammal mammal = new Mammal();
   Human man = new Human();
   Animal newAnimal = animal;
   newAnimal.eat(); //will call Animal's eat()
   newAnimal = mammal;
   newAnimal.eat(); //will call Animal's eat()
   newAnimal = man;
   newAnimal.eat(); //will call Human's eat()
 }
}

Output:

Animals eat
Animals eat
Humans eat with their hands

In Dynamic method dispatch, Java decides at runtime which method to call depending on the object being referred to and not on the type of the reference variable.

#5: Polymorphism

This is supposed to be the most favourite question of all interviewers. Don’t reply with “many forms” as this will not create a good impression on the interviewer. I’ll continue with the same Animal example. Let say there are two more classes Dog and Cat who overrides the eat().


Animal[] animals = new Animal[3];
animals[0] = new Human();
animals[1] = new Dog();
animals[2] = new Cat();
animals[0].eat(); //will call the Human's eat()
animals[1].eat(); //will call the Dog's eat()
animals[2].eat(); //will call the Cat's eat()

With polymorphism, the reference type can be a superclass of the actual object type. This means the same Animal array can behave as Human, Dog as well as Cat. Now you can state your definition of “many forms” to round it off. The earlier example also serves as an example of polymorphism.

#6: Packages

This is not as frequently asked as the other questions. I remember when I was a kid I used to collect different cards – WWE cards, Pokemon cards and so on… I kept them in separate boxes so that they don’t get mixed up. Similarly, similar classes are grouped together and kept in packages. To define a package you need to write:

package MyNewPackage;

And that is it. Other than grouping, packages also provide with security. We can restrict access to classes from other packages. To import another package in your program you need to write:

import MyNewPackage.*;

#7: Garbage Collection

Each time an object is created, Java allocates memory in a space called the Heap. As the size of the heap is fixed, when more objects are created, free space will be needed to create the new objects. Therefore old and unused objects must be removed from the heap. This process is garbage collection and it is quite similar to the process how we throw away the unused objects that are not used in our houses. But there is a difference between the two. You decide what objects you want to throw out of the house but in this case, Java Virtual Machine decides it for you. When the JVM sees that an object can never be used again then that object is eligible for garbage collection. And then when you are running low on memory, the Garbage Collector will run and remove all those unreachable objects and free up space, so that new objects can be created. For example:

Dog d = new Dog(); //creates a new Dog object (say Object 1)
d = new Dog(); //creates another Dog object (say Object 2)

Now there is no reference variable which is pointing to Object 1. So Object 1 is eligible for garbage collection. When the system will run low on memory, the garbage collector will run and remove Object 1.

#8: Interfaces and Abstract Class

Let’s start with an example. Here again, we consider the Animal example with a few modifications.

abstract class

As we can see that the Bat and Human class are subclasses of Animal. The eat() and sleep() are defined in the Animal class and they are inherited in the Bat and Human class but both the Bat and the Human sleeps in different ways. Bats, unlike Humans, sleeps upside down. So there is no point in defining the sleep() in the Animal class itself. Then we can make the method sleep() abstract. Abstract methods are methods without a body. If a method in a class is abstract then that class should also be made abstract. So the Animal class should also be made abstract along with the eat(). An abstract class can never be instantiated. It means we can not create an object of the class Animal. It makes sense too. We know how a Bat or a Human sleep but how does an Animal sleep?

abstract public class Animal {
  public abstract void sleep();
  public void eat() {
    //eat statements
  }
}

And a 100% abstract class is an Interface. All the methods in an interface are abstract. We could have made the Animal an interface if we made the eat() abstract as well.

public interface Animal {
  public abstract void sleep();
  public abstract void eat();
}

Similarly, you can not instantiate an interface. One major difference between the two is an Abstract class is extended but an interface is implemented. In Java, you can extend from one class but you can implement multiple interfaces. The first non-abstract sub class of the interface or abstract class must implement or override all the abstract methods.

#9: Exception Handling

try catch javaIn real life, there are certain things which have a risk involved with it. We still try those things out even knowing the risk involved with it. In case the risk turns into reality, we must know how to handle the problems. In Java, the problem is the exception and the way we use the try/catch block to handle the exception is Exception Handling.

TRY:
If a code is risky that doesn’t mean you should not try it. Keep the risky code inside the try block and relax.

CATCH:
If an exception is thrown then the exception is caught in the catch block. Usually, the error is printed in the catch block to notify the user about the possible problem. For example, if the file you are trying to access is missing you get a FileNotFoundException, then you might want to notify the user about the problem.

FINALLY:
When an exception is thrown, the lines that follow the statement in the try block is not executed. So in case, we want to execute certain statements whatever the outcome you have to keep it in the finally block. The statements inside the finally block get executed even when a statement in the try block throws an exception.

This example from HeadFirst Java explains the try catch finally block.

try {
  turnOvenOn();
  x.bake();
} catch (BakingException e) {
  e.printStackTrace();
} finally {
  turnOvenOff();
}

You have to turn off the oven even if your cake gets burnt and it throws a BakingException. So you have to keep the turnOvenOff() in the finally block. If the turnOvenOn() throws a BakingException then the statement x.bake() will not get executed. The control will immediately fall to the catch block. Only when no exception is thrown the whole try block gets executed. The finally block always get executed.

#10: Threads

threads java intechgrityAren’t there times when you have a lot of pending work and you wish that you can be in two places at once. Well, Java allows you to be superman. You can actually be in two places at the same time, watch TV while you are reading this article using java. But how? Here is where threads come into the picture. Making a thread is very simple. There is a Java class Thread. Make an object of the Thread class and start the thread. But what will the thread do if you do not mention it? There are multiple ways to make a thread but here we will discuss only one way. There is an interface Runnable which you have to implement in your class and override the run() method.

class MyRunnableClass implements Runnable {
  public void run() {
    //write the thread's job here
    System.out.println("Inside the new thread");
  }
}

The run() must contain the job what you want the thread to do. Then make an object of the Thread class and pass an object of the MyRunnableClass in the Thread’s constructor.

class MyRunnableTest {
  public static void main (String[] args) {
    System.out.println("Inside main thread");
    MyRunnableClass runnable = new MyRunnableClass();
    Thread thread = new Thread(runnable);
    thread.start();
    System.out.println("Inside main thread");
  }
}

Now just start the thread. It is interesting to know that main() is also run on a thread which is started by the JVM. It is the starting point of any Java Application. As you go on introducing more and more threads they will run independently and you can actually be in two places at once.
The reality (as it always is) is much different, only a multiprocessor system can do more than one job at the same time. Java threads actually appear to do several tasks at the same time but actually, the JVM switches the threads so fast that they appear to execute simultaneously. You can extend the answer by defining another method of creating a thread but that is not necessary and most probably the interviewer will move on to the next question by then.

With the 10 concepts in mind and the ways to answer the question, you are armed to crack a Java interview. As much as possible avoid the definitions and go for the examples. Use the E-P-D (Examples-Program-Definition) approach to answer the questions, Definition being the most unimportant of the lot. Coming to the end of a long tutorial there is just one thing to say… good luck for the interview. If any of the suggestions has helped you or you have any suggestions, do mention them in the comments. If you like this post you might also be interested in 10 C programs for technical interview.

8 comments

  1. ikram

    hi sir! can you help me about the codes for a “timer in computer shop” in c++

    it’s an assignment that the program or codes should use the following.
    -the looping statement
    -the functions
    -and the arrays
    -the control structure

    i’m not really sure how and where to start 🙁

  2. Swetha

    Simple neat explanation with realistic examples.
    Thank you very much for you post.

  3. kalansami786

    Thanks arnab for this post .Its really easy and simple to understand .

  4. sglearningforchange

    Very good article that covers the most important concepts. The example used really helped. Thanks!

Comments are closed.