Java Interview Questions-Core Faq - 2

How to get current time in milli seconds?

long timeInMillis = Calendar.getInstance().getTimeInMillis();

Difference between a static and a non-static inner class?

Nested classes are divided into two categories: static and non-static . Nested classes that are declared static are simply called static nested classes . Non-static nested classes are called inner classes. A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance , so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

Difference between a break statement and a continue statement?

Break statement: If a particular condition is satisfied then break statement exits you out from a particular loop or switch case etc. Continue statement: When the continue statement is encountered in a code, all the actions up till this statement are executed again without execution of any statement after the continue statement.

Difference between a while statement and a do while statement?

A while loop will check the condition first before executing the content.
while(true){ //loop code }
Before entering inside the while loop , while loop check the condition first and then execute the code inside the loop code

The do while loop executes the content of the loop once before checking the condition of the while.

do{ //loop code }while(condition)
In do..while loop, your condition is at the end of the loop block , and makes sure to execute the loop code at least one time.

Difference between an if statement and a switch statement?

The if statement is used to select among two alternatives only. It uses a boolean expression to decide which alternative should be executed. While the switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed. We can't operate float or double values using switch case, but we can do using if else statements. A switch statement works much faster than equivalent if-else ladder . It is because compiler generates a jump table for a switch during compilation. Consequently, during execution, instead of checking which case is satisfied, it only decides which case has to be executed.

Difference between Executor.submit() and Executer.execute() method ?

The main difference between a factory method and an "abstract factory" is that the factory method is a single method, and an abstract factory is an object. That means, Factory Method is used to create one product only but Abstract Factory is about creating families of related or dependent products. Both the Abstract Factory Pattern and the Factory Method Pattern decouples the client system from the actual implementation classes through the abstract types and factories. The Factory Method creates objects through inheritance where the Abstract Factory creates objects through composition. Factory Method pattern hides the construction of single object whereas Abstract factory method hides the construction of a family of related objects.

Difference between the prefix and postfix forms of the ++ operator?

Prefix: increments the current value and then passes it to the function. example
i = 5; System.out.println(++i);

Above code return 6 because the value of i is incremented, and the value of the expression is the new value of i.

Postfix: passes the current value of i to the function and then increments it.

i = 6; System.out.println(i++);

Above code return 6 because the value of i is incremented, but the value of the expression is the original value of i

Which class is super class of all classes in Java?

The java.lang.Object is a super class of any class by default. Also Object class is a superclass for all interfaces by default.

The following methods are inherited from Object in every class.

  1. equals(Object o)
  2. getClass()
  3. hashCode()
  4. notify()
  5. notifyAll()
  6. toString()
  7. wait()
  8. wait(long millis, int nanos)
  9. wait(long millis)

What is object cloning?

The object cloning is a way to create exact copy of an object. The clone() method provides this functionality. Every object has also a clone method which can be used to copy the object . For this purpose, clone() method of Object class is used to clone an object .

Do I need to import java.lang package any time? Why ?

No. It is by default loaded internally by the Java Virtual Machine . You can use it without fully qualified names. For example, System.out.println() method . System is really the java.lang.System class. This class has a public static field called "out" which is an instance of the class. So when we write System.out.println() , we're really calling the println() method of the out field of the java.lang.System class.

What is a native method?

Native methods allow you to use code from other languages such as C or C++ in your java code. That is, code that does not run in the JVM . They are usually used to interface with system calls or libraries written in other programming languages .

Native code features:

  1. Hardware access and control.
  2. Use of legacy software that hasn't or cannot be ported to Java.
  3. Using native code to perform time-critical tasks.

Is there any difference between nested classes and inner classes?

Nested classes that are declared static are simply called static nested classes . Non-static nested classes are called inner classes.

What is Locale?

A Locale object represents a specific geographical , political, or cultural region. A locale object may includes user's language, country, and any special variant preferences that user needs.

Locale Class Declaration:

public final class Locale extends Object implements Cloneable, Serializable

Can an Interface implement another Interface?

The word implements means implementation , when interface is meant to declare just to provide interface not for implementation. Only a class can do this. You can't implement an interface from another interface . It specifies what needs to be implemented. But interfaces use inheritance, so you can extend an interface and define a subinterface that can require additional methods.

Can a Class extend more than one Class?

In Java multiple inheritance is not permitted. You can only extend a single class. It was excluded from the language as a design decision, primarily to avoid circular dependencies . You can achieve it with the help of interface but not with class. More about.... Why Java doesn’t support multiple inheritance?

Can a class be defined inside an Interface?

Yes, you can have classes inside interfaces . Specifying a class inside an interface ties that class directly to that interface. Users which use that interface will have access to that class and all the functionality that it provides.

Can an Interface be defined inside a class?

Java programming language allows defining inner classes and interfaces . This is typically useful if you want to limit visibility of this class or interface by scope of current outer class . If there is a situation, inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface .

Can we define private and protected modifiers for variables in interfaces?

Interface is like a blueprint of any class, where you declare your members. Any class that implement that interface is responsible for its definition. Having private or protected members in an interface doesn't make sense conceptually. Only public members matter to the code consuming the interface. The public access specifier indicates that the interface can be used by any class in any package.

When does the compiler supply a default constructor for a class?

The compiler provides a default constructor if no other constructors are available in the class which initialises all the instance variables to their default values. This default constructor will call the no-argument constructor of the superclass.

What are the various access specifiers for Java classes?

There are 4 types of java access modifiers . The access specifiers are listed according to their restrictiveness order.
  1. private
  2. default (when no access specifier is specified)
  3. protected
  4. public
More about.... Access Modifiers in Java

How can we make copy of a java object?

There are two popular approaches. One is to provide a clone method Or a copy factory .

How destructors are defined in Java?

In Java, there are no destructors also there is no syntax for destructors in java. Objects are destructed but there is no destructor. The Java Virtual Machine handles that for you. Java garbage collector takes care of collecting garbage which is what a destructor is basically in languages like C++. We cannot predict when an object is destroyed. There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector .

Where does class, object, reference variable get stored in java?

Runtime data area in JVM can be divided as follow:

  1. Method Area : Storage area for compiled class files.
  2. Heap : Storage area for Objects.
  3. Java stack: Storage are for local variables, results of intermediate operations.
  4. PC Register : Stores the address of the next instruction to be executed if the next instruction is native method then the value in pc register will be undefined.
  5. Native method stacks : Helps in executing native methods( methods written in languages other than java).

What is the difference between == and quals() in comparing Java String objects?

The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. More about..... String comparison in Java

Can we create abstract classes without any abstract methods?

Yes, you can. An Abstract class means the definition of the class is not complete and hence cannot be instantiated. Even though it does not have abstract method, it is an indicator that the class is available for inheritance . Also, declaring a method abstract means that subclasses have to provide an implementation for that method.

Can we have static methods in interface?

Before the release of Java 8 , by default, all methods in an interface are declared as public, abstract. It will never be static. With Java 8, interfaces can have static methods . They can also have concrete instance methods, but not instance fields.

Can you override a private or static method in Java?

No, you cannot override private method , because the method is called private so that no class extending from that class has any access to the private method . Private methods are not visible to sub classes. Overriding depends on having an instance of a class . A static method is not associated with any instance of a class so the concept is not applicable. You however can declare same static method with same signature in child classes, but that would not be considered as runtime polymorphism (override of methods).

What is an efficient way to implement a singleton pattern in Java?

Since java5 the best way to do it is to use an enum:
enum Singleton { INSTANCE }
More about....... Singleton in Java

What is the best way to determine the size of an object?

The java.lang.instrument.Instrumentation class provides a nice way to get the size of a Java Object, but it requires you to define a premain and run your program with a java agent .

How do I test a class that has private methods, fields or inner classes?

The best way to test private methods is to use reflection. The following patterns will let you do pretty much anything related to the private methods. It is important to know that you can't change private static final variables through reflection. Syntax
public Method getDeclaredMethod(String name,parameterTypes)
The java.lang.Class.getDeclaredMethod() method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object . Example
Method method = targetClass.getDeclaredMethod(methodName, argClasses); method.setAccessible(true); return method.invoke(targetObject, argObjects);

Can a Byte object be cast to a double value?

You cannot cast from a double to byte because the byte has a range smaller than the double and it does not contain decimals like a double does. More about..... Boxing and Unboxing

What is the purpose of Process class in Java?

It's an object-based representation of a process. Similar to the Thread class, which represents a thread.

What is hashCode?

The hashCode method returns a hash code value for the object. The hashCode() method should ideally return the same int for any two objects that compare equal and a different int for any two objects that don't compare equal. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. More about..... Why do I need to override the equals and hashCode methods in Java?

What is the difference between super() and this()?

super() is used to call super class constructor , whereas this() used to call constructors in the same class. Interesting thing about this and super is that, they can be used as both method and variable.

What is Class.forName()?

The java.lang.Class.forName(String className) method returns the Class object associated with the class or interface with the given string name . It is used to load the class and it also provides a new way for creating the instance of a class without using the "new" operator. Also, we can use newInstance() to get the instance.

How to prevent a method from being overridden?

You can use final keyword to the method for avoid overriding in a subcalss. Similarly one can use final at class level to prevent creating subclasses . Apart from final methods there are two more techniques which you can use to prevent a method from being overridden in Java. Private and Static modifier in Java, then you may be knowing that private method is not accessible in subclass, which means they cannot be overridden as well, because overriding happens at child class .