Friday 3 February 2017

Java Basic Questions Part 1

1) What is the Difference Between JVM, JDK and JRE ? JVM The Java Virtual machine (JVM) is the virtual machine that run the Java by... thumbnail 1 summary
1) What is the Difference Between JVM, JDK and JRE ?

JVM

The Java Virtual machine (JVM) is the virtual machine that run the Java bytecodes. The JVM doesn't understand Java source code, that's why you compile your *.java files to obtain *.class files that contain the bytecodes understandable by the JVM. It's also the entity that allows Java to be a "portable language" (write once, run anywhere). Indeed there are specific implementations of the JVM for different systems (Windows, Linux, MacOS,....), the aim is that with the same bytecodes they all give the same results.

Java Runtime Environment (JRE)

The Java Runtime Environment (JRE) provides the libraries, the Java Virtual Machine, and other components to run applets and applications written in the Java programming language. In addition, two key deployment technologies are part of the JRE: Java Plug-in, which enables applets to run in popular browsers; and Java Web Start, which deploys standalone applications over a network. It is also the foundation for the technologies in the Java 2 Platform, Enterprise Edition (J2EE) for enterprise software development and deployment. The JRE does not contain tools and utilities such as compilers or debuggers for developing applets and applications.

Java Development Kit (JDK)

The JDK is a superset of the JRE, and contains everything that is in the JRE, plus tools such as the compilers and debuggers necessary for developing applets and applications.


2) How many types of memory areas are allocated by JVM?



Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for methods.

Heap

It is the runtime data area in which objects are allocated.

Stack

Java Stack stores frames.It holds local variables and partial results, and plays a part in method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

Program Counter Register

PC (program counter) register. It contains the address of the Java virtual machine instruction currently being executed.

Native Method Stack

It contains all the native methods used in the application.

3) What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

4) What is classloader in java?

The java.lang.ClassLoader is an abstract class that can be subclassed by applications that need to extend the manner in which the JVM dynamically loads classes. Constructors in java.lang.ClassLoader (and its subclasses) allow you to specify a parent when you instantiate a new class loader. If you don't explicitly specify a parent, the virtual machine's system class loader will be assigned as the default parent. In other words, the ClassLoader class uses a delegation model to search for classes and resources. Therefore, each instance of ClassLoader has an associated parent class loader, so that when requested to find a class or resources, the task is delegated to its parent class loader before attempting to find the class or resource itself. The loadClass() method of the ClassLoader performs the following tasks, in order, when called to load a class:

If a class has already been loaded, it returns it. Otherwise, it delegates the search for the new class to the parent class loader. If the parent class loader doesn't find the class, loadClass() calls the method findClass() to find and load the class. The finalClass() method searches for the class in the current class loader if the class wasn't found by the parent class loader.

5) What is constructor in java?

A constructor in Java is a block of code similar to a method that's called when an instance of an object is created. Here are the key differences between a constructor and a method: A constructor doesn't have a return type. The name of the constructor must be the same as the name of the class.

6) Does constructor return any value?

So when you call the constructor using a new keyword you get an object. Though it doesnt explicitly return something but instead it creates or constructs something which you can use as an instance of a class. yes, it is the current class instance. (We cannot use return type yet it returns a value).

7) What is static variable and static final variables?

Static variable’s value is same for all the object(or instances) of the class or in other words you can say that all instances(objects) of the same class share a single copy of static variables.

class StaticVariable
{
   static int count=0;
   public void increment()
   {
       count++;
   }
   public static void main(String args[])
   {
       StaticVariableobj1=new StaticVariable();
       StaticVariableobj2=new StaticVariable();
       obj1.increment();
       obj2.increment();
       System.out.println("Obj1: count is="+obj1.count);
       System.out.println("Obj2: count is="+obj2.count);
   }
}

Output:
Obj1: count is=2
Obj2: count is=2

As you can see in the above example that both the objects of class, are sharing a same copy of static variable that’s why they displayed the same value of count.

Static variables are initialized when class is loaded.
Static variables in a class are initialized before any object of that class can be created.
Static variables in a class are initialized before any static method of the class runs.

Static final variables are constants.


public class MyClass{
   public static final int MY_VAR=27;
}

The above code will execute as soon as the class MyClass is loaded, before static method is called and even before any static variable can be used.
The above variable MY_VAR is public which means any class can use it. It is a static variable so you won’t need any object of class in order to access it. It’s final so this variable can never be changed in this or in any class.

final variable always needs initialization, if you don’t initialize it would throw a compilation error.

8) What is static method?

It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It can not access non-static data (instance variables)
A static method can call only other static methods and can not call a non-static method from it.
A static method can be accessed directly by the class name and doesn’t need any object
Syntax: <class-name>.<method-name>
A static method cannot refer to this or super keywords in anyway

9) Why main method is static?

This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class. Similarly, we use static sometime for user defined methods so that we need not to make objects. void indicates that the main() method being declared does not return a value.

10) What is static block?

Static block is a set of statements, which will be executed by the JVM before execution of main method.
At the time of class loading if we want to perform any activity we have to define that activity inside static block because this block execute at the time of class loading.
In a class we can take any number of static block but all these blocks will be execute from top to bottom.
Note : In real time application static block can be used whenever we want to execute any instructions or statements before execution of main method.

11) What is difference between static method and instance method?

The main difference is an instance method belongs to an object while a static method belongs to the class.
Which means to access an instance method you need to make an object out of a java class and the object has instance methods and instance variables which are accessible through the object. (object reference)
The static methods and variables do not need an object. They are accessed through the class. (class reference)
public class Student{ 
 private String name;
 
 //instance method to set the name of the student object
 public String setName(String name){
  this.name = name;
 }
 
 //static method to get a student object with the given name
 public static Student getStudent(String name){
  //... code to get the Student with the given name from DB
  return student;
 }
}
 
class StudentDemo{
 public static void main(String args[]){
  //create Student object
  Student student1 = new Student();
  
  //access instance method through the object
  //this will set the name of the Student object we created
  student1.setName("John Doe");
 
  //access static method through the class
  Student.getStudent("Jane Doe");
 }
}

12) What is this in java?

Here is given the 6 usage of java this keyword.

  • this keyword can be used to refer current class instance variable.
  • this() can be used to invoke current class constructor.
  • this keyword can be used to invoke current class method (implicitly)
  • this can be passed as an argument in the method call.
  • this can be passed as argument in the constructor call.
  • this keyword can also be used to return the current class instance.
Note: Call to this() must be the first statement in constructor.


13) What is Inheritance?

Inheritance by definition means to aquire the properties / state and behaviour of an other class.
To achieve Inheritance it is necessary that IS-A relation should be present, because every sub-class IS-A super class. Inheritance can be achieved using keyword extends. Eg: Class B extends Class A //means Class B can show its own behaviour as well as Class A behaviour.

Example:
package com.InterviewGuess

public class Flying

{
 public void wings() //non-static method in class A

{ System.out.println(“Show Wings”);

}
}

public class Landing extends
class Flying

{
 public void wheels() //non-static method in class B

{ System.out.println(“Show Wheels”);

}
 }

 class Run

 {
  public static void main(String[] args)

  {
   Landing objlan = new Landing();

   // object type of Landing class is created (because non-static
   // method cannot be directly called from a static method).

   objlan.wings(); // Executes wings() method

   objlan.wheels(); // Executes wheels() method

  }
}

OUTPUT: Show Wings Show Wheels

Here when Flight is Flying it has got only Wings when it is Landing it shows the behaviour of Flying as well as Landing. ie. When Landing type object is created, it can use both the method - wings() in class Flying as well as wheels() in class Landing, because Class Landing extends Class Flying.

Hence Landing (sub-class) IS-A Flying (super-class) or it can be said that Landing class Inherits everything present within Flying class. This is known as Inheritance.
NOTE: Static Members (Methods/Variables) cannot be inherited because only one copy is present, which is loaded during class loading.
A child-class / sub-class cannot have more than 1 parent-class / super-class). ie Multiple inheritance is not possible in java.
Multilevel inheritance is possible. 1 parent-class can have many child-classes.
If a class is declared as static / final it cannot be inherited by any other class.

14) Which class is the superclass for every class?

java.lang.Object is the superclss of every class.

The Mthod which present in Object class are :

  • public final Class getClass() : returns the Class class object of this object. The Class class can further be used to get the metadata of this class.
  • public int hashCode() : returns the hashcode number for this object.
  • public boolean equals(Object obj) : compares the given object to this object.
  • protected Object clone() throws CloneNotSupportedException : creates and returns the exact copy (clone) of this object.
  • public String toString() : returns the string representation of this object.
  • public final void notify() : wakes up single thread, waiting on this object's monitor.
  • public final void notifyAll() : wakes up all the threads, waiting on this object's monitor.
  • public final void wait(long timeout)throws InterruptedException : causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).
  • public final void wait(long timeout,int nanos)throws InterruptedException : causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).
  • public final void wait()throws InterruptedException : causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).
  • protected void finalize()throws Throwable : is invoked by the garbage collector

15) What is super in java?

It(super) is a keyword.

It is used inside a sub-class method definition to call a method defined in the super class. Private methods of the super-class cannot be called. Only public and protected methods can be called by the super keyword.
Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.

However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.
public class Animal {
   private final String noise;
   protected Animal(String noise) {
      this.noise = noise;
   }

   public void makeNoise() {
      System.out.println(noise);
   }
}

public class Pig extends Animal {
    public Pig() {
       super("Oink");
    }
}

16) Why can't this() and super() both be used together in a constructor?

Because this(...) will call another constructor in the same class whereas super() will call a super constructor. If there is no super() in a constructor the compiler will add one implicitly.
Thus if both were allowed you could end up calling the super constructor twice.

17) What is object cloning?

The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object. The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create.
Read : How does clone method work ?

18) What is method overloading?

Method Overloading is a feature that allows a class to have two or more methods having same name, if their argument lists are different. Constructor overloading that allows a class to have more than one constructors having different argument lists.

  • Argument lists could differ in –
  • Number of parameters.
  • Data type of parameters.
  • Sequence of Data type of parameters.

Method overloading is also known as Static Polymorphism.
Points to Note:

  • Static Polymorphism is also known as compile time binding or early binding.
  • Static binding happens at compile time. Method overloading is an example of static binding where binding of method call to its definition happens at Compile time.

19) Can we overload main() method?

You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example:
public class InterviewGuess{
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}

That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.

You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

20) What is method overriding?

When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.For Example
class Animal
{
 public void eat()
 {
  System.out.println("Generic Animal eating");
 }
}

class Dog extends Animal
{
 public void eat()   //eat() method overriden by Dog class.
 {
  System.out.println("Dog eat meat");
 }
}

As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

21) What is final variable?

In Java, when final keyword is used with a variable of primitive data types (int, float, .. etc), value of the variable cannot be changed.

For example following program gives error because i is final.
public class Test {
    public static void main(String args[]) {
        final int i = 10;
        i = 30; // Error because i is final.
    }
}

When final is used with non-primitive variables (Note that non-primitive variables are always references to objects in Java), the members of the referred object can be changed. final for non-primitive variables just mean that they cannot be changed to refer to any other object 
class Test1 {
   int i = 10;
}
 
public class Test2 {
    public static void main(String args[]) {
      final Test1 t1 = new Test1();
      t1.i = 30;  // Works
    }
}

22) What is final method?

A final method cannot be overridden or hidden by subclasses. This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.

23)What is final class?

Java class with final modifier is called final class in Java. Final class is complete in nature and can not be sub-classed or inherited. Several classes in Java are final e.g. String, Integer and other wrapper classes. Here is an example of final class in java
final class PrivateAccount{

}

class SavingsAccount extends PrivateAccount{  //compilation error: cannot
                                     //inherit from final class
}

24) When is it appropriate to use blank final variables?

This is useful to create immutable objects:
public class InterviewGuess {
    private final Color color;

    public InterviewGuess(Color c) {this.color = c};
}

InterviewGuess is immutable (once created, it can't change because color is final). But you can still create various InterviewGuess's by constructing them with various colors.

25) Can you declare the main method as final?

Sure, it can be declared final! It doesn't matter if it is declared final, the JVM will still find it and run it, and the compiler doesn't care. Yes We can declare main method final. If we make this final it can not be override.Hence we can't use it in its child class.

26) Overriding a method with different return types in java?

You can return a different type, as long as it's compatible with the return type of the overridden method. Compatible means: it's a subclass, sub-interface, or implementation of the class or interface returned by the overridden method.

And that's logical. If a method returns an Animal, and your derived class returns a Cow, you're not breaking the contract of the superclass method, since a Cow is an Animal. If the derived class returns a Banana, that isn't correct anymore, since a Banana is not an Animal.
class ShapeBuilder {
    ...
    public Shape build() {
    ....
}

class CircleBuilder extends ShapeBuilder{
    ...
    @Override
    public Circle build() {
    ....
}

No comments

Post a Comment