Java Questions For Selenium Interview1

1) What is difference between JDK,JRE and JVM?

JVM is responsible to converting Byte code to the machine specific code. JVM is also platform dependent and provides core java functions like memory management, garbage collection, security etc.

The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.

JRE is the implementation of JVM, it provides platform to execute java programs. JRE consists of JVM and java binaries and other classes to execute any program successfully. JRE doesn’t contain any development tools like java compiler, debugger etc. If you want to execute any java program, you should have JRE installed but we don’t need JDK for running any java program.



JDK (Java Development Kit) consists of JRE along with the development tools required to write and execute a program.

How many types of memory areas are allocated by JVM?Many types:




1.Class(Method) Area
2. Heap
3. Stack
4. Program Counter Register
5. Native Method Stack

1) Classloader

Classloader is a subsystem of JVM that is used to load class files.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, fields and method data, the code for methods.
3) Heap
Java Heap space is used by java runtime to allocate memory to Objects and JRE classes. Whenever we create any object, it’s always created in the Heap space.
Garbage Collection runs on the heap memory to free the memory used by objects that doesn’t have any reference. Any object created in the heap space has global access and can be referenced from anywhere of the application.
4) Stack:
Java Stack memory is used for execution of a thread. They contain method specific values that are short-lived and references to other objects in the heap that are getting referred from the method.
Stack memory is always referenced in LIFO (Last-In-First-Out) order. Whenever a method is invoked, a new block is created in the stack memory for the method to hold local primitive values and reference to other objects in the method.

As soon as method ends, the block becomes unused and become available for next method..Stack memory size is very less compared to Heap memory.


5) Program Counter Register
  PC (program counter) register. It contains the address of the Java virtual  machine instruction currently being executed.
6) Native Method Stack
It contains all the native methods used in the application.
7) Execution Engine
It contains:
  1) A virtual processor
  2) Interpreter: Read bytecode stream then execute the instructions.

 3) 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.

What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components:

1. Runtime Environment   
2.API(Application Programming Interface)

Java Platform Hirarchy: Java Program -Java Platform(JRE/JAVA API) - Operating System - HardWare

Other Platform Hirarchy:
Software/App Program <- Operating System <-Hardware

What gives java platform independent feature meaning Write once execute any where feature:

bytecode:
Once user compile java program it generates class file uses bytecode that can be executed in any plotform

What is classloader?
The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

1.Bootstrap Class Loader:

Bootstrap class loader loads java’s core classes like java.lang, java.util etc. These are classes that are part of java runtime environment. Bootstrap class loader is native implementation and so they may differ across different JVMs.

2.Extensions Class Loader:

JAVA_HOME/jre/lib/ext contains jar packages that are extensions of standard core java classes. Extensions class loader loads classes from this ext folder. Using the system environment propery java.ext.dirs you can add ‘ext’ folders and jar files to be loaded using extensions class loader.
3.System Class Loader:
Java classes that are available in the java classpath are loaded using System class loader.



Is Empty .java file name a valid source file name?
Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname Let's take a simple example:

//save by .java only  
class A{  
public static void main(String args[]){  
System.out.println("Hello java");  
}  
}  
//compile by javac .java  
//run by     java A  
compile it by javac .java
run it by java A

If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?
It is empty. But not null.

What is the default value of the local variables?
The local variables are not initialized to any default values. We should
not use local variables with out initialization. Even the java compiler
throws error
Access Modifiers can not be used for local variable

Default Value of Data Types in Java







What is the difference between a local variable and an instance variable?

Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and it will be destroyed when the method has completed. Instance variables are variables within a class but outside any method


What is the difference between a class variable and an instance variable?

Static(Classvariables and instance variables both are member variablesbecause they are both associated with a specific class, but the difference betweenthem is Class variables only have one copy that is shared by all the different objects of a class, whereas every object has it's own personal copy of an instance

Can we declare a local variable as static?
static variable is common property of all objects of a class so the scope of static variable is global but the scope local variable is local to the method or block where it is defined
So we should not declare local variables as static 

What is the difference between notify and Notifyall in Java?
notifyAll() : The notifyAll() method wakes up all the threads waiting for the lock; the JVM selects one of the threads from the list of threads waiting for the lock and wakes that thread up. In the case of a single thread waiting for a lock, there is no significant difference between notify() and notifyAll() 

What is the difference between a constructor and a method?

1.Constructor are used to initialize the state of object,where as method is expose the behaviour of object. 
2.Constructor must not have return type where as method must have return type. 3.Constructor name same as the class name where as method may or may not the same class name

Can we have private constructors ?
As you can easily guess, like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class

Do we need such ‘private constructors ‘ ?
There are various scenarios where we can use private constructors. The major ones are
  1. Internal Constructor chaining
  2. Singleton class design pattern

What is a Singleton class?
As the name implies, a class is said to be singleton if it limits the number of objects of that class to one.We can’t have more than a single object for such classes.
Singleton classes are employed extensively in concepts like Networking and Database Connectivity.

Java Singleton Class Example Using Private Constructor

  • We can make constructor as private. So that We can not create an object outside of the class.
  • This property is useful to create singleton class in java.
  • Singleton pattern helps us to keep only one instance of a class at any time.
  • The purpose of singleton is to control object creation by keeping private constructor.
public class MySingleTon { private static MySingleTon myObj; /** * Create private constructor */ private MySingleTon(){ } /** * Create a static method to get instance. */ public static MySingleTon getInstance(){ if(myObj == null){ myObj = new MySingleTon(); } return myObj; } public void getSomeThing(){ // do something here System.out.println("I am here...."); } public static void main(String a[]){ MySingleTon st = MySingleTon.getInstance(); st.getSomeThing(); }}
Can we have multiple public classes in a java source file?
We can’t have more than one public class in a single java source file. A single source file can have multiple classes that are not public. Error:The public type <classname> must be defined in its own file
Can we declare a class as static?
We can’t declare a top-level class as static however an inner class can be declared as static. If inner class is declared as static, it’s called static nested class.
Static nested class is same as any other top-level class and is nested for only packaging convenience.
Error : illegal modifier for the class :only public abstract and final are permitted
What is try-with-resources in java?
One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished.
What is static block?
Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class. Mostly it’s used to create static resources when class is loaded. 
What is difference between object oriented programming language and object based programming language? Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc. What will be the initial value of an object reference which is defined as an instance variable? The object references are all initialized to null in Java.
What is constructor?
Constructor gets invoked when a new object is created. Every class has a constructor. If we do not explicitly write a constructor for a class the java compiler builds a default constructor for that class.
What is the purpose of default constructor?
The default constructor assigns the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class or T
he default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values
Does constructor return any value?
yes, that is current instance (You cannot use return type yet it returns a 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) can constructor perform any other tasks other than Initialization? Yes. In addition to initializing the state of an object, construct may initialize threads, invoke methods etc. Constructor exhibits behaviour as same as any Java method in terms of activities that it can perform Is constructor inherited? No, constructor is not inherited. Unlike fields, methods, and nested classes ,Constructors are not class members. A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass


Constructors are special and have same name as class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have same name as class name. For example see the below code:
For Example

class Parent {
    public Parent()
    {
    }
   public void print()
    {
    }
}
 
public class Child extends Parent {
    public Parent() - Error:Return type for Method missing
    {
    }
    public void print()
    {
    }
  public static void main(String[] args)
    {
        Child c1 = new Child(); // allowed
        Child c2 = new Parent(); // not allowed
    }
}

Can you make a constructor final?
No, constructor can't be final. So making a constructor final is not required, so it is not used with constructor. When you set a method as final, it means : "You don't want any class override it", but constructor by JLS definition can't overridden,so it is clean. We can't make constructor to be final because constructor is never inherited. public class Sample
{
final Sample() - Illegal modifier for constructor in type Parent only public private and protected are permitted
{
}
}
What is static variable?
static variable is used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
static variable gets memory only once in class area at the time of class loading.
Java static property is shared to all objects.
What is static method?
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.
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
What is static block? Is used to initialize the static data member.
It is excuted before main method at the time of classloading.
Static block is mostly used for changing the default values of static variables.Thisblock gets executed when the class is loaded in the memory. A class can have multiple Static blocks, which will execute in the same sequence in which they have been written into the program. Can we execute a program without main() method? Ans) Yes, one of the way is static block but from Java7 it throws below error with out main method
Error: Main method not found in class Parent, please define the main method as:
   public static void main(String[] args)
What if the static modifier is removed from the signature of the main method? Program compiles. But at runtime throws an error "NoSuchMethodError".
Error: Main method is not static in class Parent, please define the main method as:
   public static void main(String[] args)
What is difference between static (class) method and instance method?
static or class method
instance method
1)A method i.e. declared as static is known as static method.
A method i.e. not declared as static is known as instance method.
2)Object is not required to call static method.
Object is required to call instance methods.
3)Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly.

Error :can not make a static reference to non static method
change method to static 
static and non-static variables both can be accessed in instance methods.
4)For example: public static int cube(int n){ return n*n*n;}
For example: public void msg(){...}.
What is this keyword in java?
It is a keyword that that refers to the current object
6 usages of this Keyword
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 argument in the constructor call.
this can be used to return the current class instance from the method.
What is Inheritance?
Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding. The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship, also known as parent-child relationship.
 
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.
Note: Multiple Inheritance is not supported in Java
Which class is the superclass for every class.
Object class is the super class for every class in java
Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class
We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited method and they provide their own implementation. Now D inherits from both B and C doing multiple inheritance. D should inherit that overridden method, which overridden method will be used? Will it be from B or C? Here we have an ambiguity. What is composition?
Holding the reference of the other class within some other class is known as composition.
Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.
It represents part-of relationship. In composition, both the entities are dependent on each other. When there is a composition between two entities, the composed object cannot exist without the other entity Example : a library can have no. of books on same or different subjects. So, If Library gets destroyed then All books within that particular library will be destroyed. i.e. book can not exist without library. That’s why it is composition. private String role; private long salary; private int id; public String getRole() { return role; } public void setRole(String role) { this.role = role; } public long getSalary() { return salary; } public void setSalary(long salary) { this.salary = salary; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public class Person { //composition has-a relationship private Job job; public Person(){ this.job=new Job(); job.setSalary(1000L); } public long getSalary() { return job.getSalary(); } } public class TestPerson { public static void main(String[] args) { Person person = new Person(); long salary = person.getSalary(); } }

What is Aggregation? It is a special form of Association where: It represents Has-A relationship. It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice versa is not possible and thus unidirectional in nature. In Aggregation, both the entries can survive individually which means ending one entity will not effect the other entity
Aggregation vs Composition
Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human
Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
Type of association: Composition is a strong Association whereas Aggregation is a weak Assocation.
Why method overloading is not possible by changing the return type in java?
Can we overload main() method?
Yes, You can have many main() methods in a class by overloading the main method.
Can we overload static methods?
Yes’. We can have two ore more static methods with same name, but differences in input parameters.
For example, consider the following Java program.
// filename Test.java public class Test { public static void foo() { System.out.println("Test.foo() called "); } public static void foo(int a) { System.out.println("Test.foo(int) called "); } public static void main(String args[]) { Test.foo(); Test.foo(10); } }
Can we overload methods that differ only by static keyword? We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is same). See following Java program for example.
// filename Test.java public class Test { public static void foo() { System.out.println("Test.foo() called "); } public void foo() { // Compiler Error: cannot redefine foo() System.out.println("Test.foo(int) called "); } public static void main(String args[]) { Test.foo(); } }
Output: Compiler Error, cannot redefine foo()




Comments

Popular Posts