Most Asked Java Viva / Interview Questions with Answers






 Q. Why is Java a platform independent language?

Ans : Java language was developed in such a way that it does not depend on any hardware or software due to the fact that the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems.

The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.




Q. Why is Java not a pure object oriented language?

Ans : Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object-oriented language.


Q. Pointers are used in C/ C++. Why does Java not make use of pointers?

Ans : Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers.

Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.



Q. What do you understand by an instance variable and a local variable?

Ans : Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost

All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected.

Example:

class Athlete {

public String athleteName;

public double athleteSpeed;

public int athleteAge;

}

Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don’t have any knowledge about the local variable.




Q. What is Java?

Ans : Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.



Q. List the features of Java Programming language.

Ans :There are the following features in Java Programming Language.

Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.

Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.

Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.

Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.

Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.

Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.

Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.

Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.

High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).

Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.

Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.

Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.


Q.What do you understand by Java virtual machine?

Ans : Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.


 

Q. What is the difference between JDK, JRE, and JVM?

Ans : JVM

JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.

JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.

JRE

JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.

JDK

JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

Standard Edition Java Platform

Enterprise Edition Java Platform

Micro Edition Java Platform

More Details.



Q.How many types of memory areas are allocated by JVM?

Ans : Many types:

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

Heap: It is the runtime data area in which the memory is allocated to the objects

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 the 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 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.

More Details.



Q. What is JIT compiler?

Ans : Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode 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.




Q. What is the platform?

Ans :A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.



Q.What are the main differences between the Java platform and other platforms?

Ans : There are the following differences between the Java platform and other platforms.

Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.

Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.



Q.What gives Java its 'write once and run anywhere' nature?

Ans : The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.




Q.What is classloader?

Ans : Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.

Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.

Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.

System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.



Q.Is delete, next, main, exit or null keyword in java?

Ans : No.




Q. If I don't provide any arguments on the command line, then what will the value stored in the String array passed into the main() method, empty or NULL?

Ans : It is empty, but not null.




Q.  What if I write static public void instead of public static void?

Ans : The program compiles and runs correctly because the order of specifiers doesn't matter in Java.



Q.  What is the default value of the local variables?

Ans : The local variables are not initialized to any default value, neither primitives nor object references.



Q. What are the various access specifiers in Java?

Ans : In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.

Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.

Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.

Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.

Private The private class, methods, or variables defined as private can be accessed within the class only.



Q.  What is the purpose of static methods and variables?

Ans : The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.

For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static.



Q. What are the advantages of Packages in Java?

Ans :There are various advantages of defining packages in Java.

Packages avoid the name clashes.

The Package provides easier access control.

We can also have the hidden classes that are not visible outside and used by the package.

It is easier to locate the related classes.




Q. What is the output of the following Java program?

Ans : class Test   

{  

    public static void main (String args[])   

    {  

        System.out.println(10 + 20 + "Java");   

        System.out.println("Java" + 10 + 20);  

    }  

}  

The output of the above code will be


Java

Java1020

Explanation


In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.

In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020.




Q.  What is the output of the following Java program?

Ans : class Test   

{  

    public static void main (String args[])   

    {  

        System.out.println(10 * 20 + "Java");   

        System.out.println("Java" + 10 * 20);  

    }  

}  

The output of the above code will be


200Java

Java200

Explanation


In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint.

In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpointto produce the output as Javatpoint200.


Q. What is the output of the following Java program?

Ans : class Test   

{  

    public static void main (String args[])   

    {  

        for(int i=0; 0; i++)   

        {  

            System.out.println("Hello Java");  

        }  

    }  

}  

The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.



Q. Explain public static void main(String args[]) in Java.

Ans : main() in Java is the entry point for any Java program. It is always written as public static void main(String[] args).

public: Public is an access modifier, which is used to specify who can access this method. Public means that this Method will be accessible by any Class.

static: It is a keyword in java which identifies it is class-based. main() is made static in Java so that it can be accessed without creating the instance of a Class. In case, main is not made static then the compiler will throw an error as main() is called by the JVM before any objects are made and only static methods can be directly invoked via the class. 

void: It is the return type of the method. Void defines the method which will not return any value.

main: It is the name of the method which is searched by JVM as a starting point for an application with a particular signature only. It is the method where the main execution occurs.

String args[]: It is the parameter passed to the main method.




Q. Why Java is platform independent?

Ans : Java is called platform independent because of its byte codes which can run on any system irrespective of its underlying operating system.




Q. Why Java is not 100% Object-oriented?

Ans : Java is not 100% Object-oriented because it makes use of eight primitive data types such as boolean, byte, char, int, float, double, long, short which are not objects.



Q. What are wrapper classes in Java?

Ans :Wrapper classes convert the Java primitives into the reference types (objects). Every primitive data type has a class dedicated to it. These are known as wrapper classes because they “wrap” the primitive data type into an object of that class. Refer to the below image which displays different primitive type, wrapper class and constructor argument.



Q. What are constructors in Java?

Ans : In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.

There are two types of constructors:


Default Constructor: In Java, a default constructor is the one which does not take any inputs. In other words, default constructors are the no argument constructors which will be created by default in case you no other constructor is defined by the user. Its main purpose is to initialize the instance variables with the default values. Also, it is majorly used for object creation. 

Parameterized Constructor: The parameterized constructor in Java, is the constructor which is capable of initializing the instance variables with the provided values. In other words, the constructors which take the arguments are called parameterized constructors.


Q. What is singleton class in Java and how can we make a class singleton?

Ans : Singleton class is a class whose only one instance can be created at any given time, in one JVM. A class can be made singleton by making its constructor private.



Q. Why pointers are not used in Java?

Ans : Java doesn’t use pointers because they are unsafe and increases the complexity of the program. Since, Java is known for its simplicity of code, adding the concept of pointers will be contradicting. Moreover, since JVM is responsible for implicit memory allocation, thus in order to avoid direct access to memory by the user,  pointers are discouraged in Java.


Q. What is JIT compiler in Java?

Ans : JIT stands for Just-In-Time compiler in Java. It is a program that helps in converting the Java bytecode into instructions that are sent directly to the processor. By default, the JIT compiler is enabled in Java and is activated whenever a Java method is invoked. The JIT compiler then compiles the bytecode of the invoked method into native machine code, compiling it “just in time” to execute. Once the method has been compiled, the JVM summons the compiled code of that method directly rather than interpreting it. This is why it is often responsible for the performance optimization of Java applications at the run time.



Q. What is an object in Java and how is it created?

Ans : An object is a real-world entity that has a state and behavior. An object has three characteristics:

State

Behavior

Identity

An object is created using the ‘new’ keyword. For example:


ClassName obj = new ClassName();



Q. What is Object Oriented Programming?

Ans : Object-oriented programming or popularly known as OOPs is a programming model or approach where the programs are organized around objects rather than logic and functions. In other words, OOP mainly focuses on the objects that are required to be manipulated instead of logic. This approach is ideal for the programs large and complex codes and needs to be actively updated or maintained.



Q. What are the main concepts of OOPs in Java?

Ans : Object-Oriented Programming or OOPs is a programming style that is associated with concepts like:

Inheritance: Inheritance is a process where one class acquires the properties of another.

Encapsulation: Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.

Abstraction: Abstraction is the methodology of hiding the implementation details from the user and only providing the functionality to the users. 

Polymorphism: Polymorphism is the ability of a variable, function or object to take multiple forms.



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

Ans : In Java, a local variable is typically used inside a method, constructor, or a block and has only local scope. Thus, this variable can be used only within the scope of a block. The best benefit of having a local variable is that other methods in the class won’t be even aware of that variable.

Example

if(x > 100)

{

String test = "ka";

}

 

Whereas, an instance variable in Java, is a variable which is bounded to its object itself. These variables are declared within a class, but outside a method. Every object of that class will create it’s own copy of the variable while using it. Thus, any changes made to the variable won’t reflect in any other instances of that class and will be bound to that particular instance only.

class Test{

public String EmpName;

public int empAge;

}





Q. What is Polymorphism?

Ans : Polymorphism is briefly described as “one interface, many implementations”. Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow an entity such as a variable, a function, or an object to have more than one form. There are two types of polymorphism:

Compile time polymorphism

Run time polymorphism

Compile time polymorphism is method overloading whereas Runtime time polymorphism is done using inheritance and interface.



Q. What is runtime polymorphism or dynamic method dispatch?

Ans : In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. Let’s take a look at the example below to understand it better.


class Car {

void run()

{

System.out.println(“car is running”); 

}

}

class Audi extends Car {

void run()

{

System.out.prinltn(“Audi is running safely with 100km”);

}

public static void main(String args[])

{

Car b= new Audi();    //upcasting

b.run();

}

}



Q. What is abstraction in Java?

Ans : Abstraction refers to the quality of dealing with ideas rather than events. It basically deals with hiding the details and showing the essential things to the user. Thus you can say that abstraction in Java is the process of hiding the implementation details from the user and revealing only the functionality to them. Abstraction can be achieved in two ways:

Abstract Classes (0-100% of abstraction can be achieved)

Interfaces (100% of abstraction can be achieved)



Q. What do you mean by an interface in Java?

Ans : An interface in Java is a blueprint of a class or you can say it is a collection of abstract methods and static constants. In an interface, each method is public and abstract but it does not contain any constructor. Thus, interface basically is a group of related methods with empty bodies. 

Example:

public interface Animal {

  public void eat();

  public void sleep();

  public void run();

}




Q. What is inheritance in Java?

Ans : Inheritance in Java is the concept where the properties of one class can be inherited by the other. It helps to reuse the code and establish a relationship between different classes. Inheritance is performed between two types of classes:

Parent class (Super or Base class)

Child class (Subclass or Derived class)

A class which inherits the properties is known as Child Class whereas a class whose properties are inherited is known as Parent class.



Q. What are the different types of inheritance in Java?

Ans : Java supports four types of inheritance which are:

Single Inheritance: In single inheritance, one class inherits the properties of another i.e there will be only one parent as well as one child class.

Multilevel Inheritance: When a class is derived from a class which is also derived from another class, i.e. a class having more than one parent class but at different levels, such type of inheritance is called Multilevel Inheritance.

Hierarchical Inheritance: When a class has more than one child classes (subclasses) or in other words, more than one child classes have the same parent class, then such kind of inheritance is known as hierarchical.

Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.



Q. What is method overloading and method overriding?

Ans : Method Overloading :

In Method Overloading, Methods of the same class shares the same name but each method must have a different number of parameters or parameters having different types and order.

Method Overloading is to “add” or “extend” more to the method’s behavior.

It is a compile-time polymorphism.

The methods must have a different signature.

It may or may not need inheritance in Method Overloading.

Let’s take a look at the example below to understand it better.


class Adder {

Static int add(int a, int b)

{

return a+b;

}

Static double add( double a, double b)

{

return a+b;

}

public static void main(String args[])

{

System.out.println(Adder.add(11,11));

System.out.println(Adder.add(12.3,12.6));

}}

Method Overriding:  

In Method Overriding, the subclass has the same method with the same name and exactly the same number and type of parameters and same return type as a superclass.

Method Overriding is to “Change” existing behavior of the method.

It is a run time polymorphism.

The methods must have the same signature.

It always requires inheritance in Method Overriding.




Q. What is encapsulation in Java?

Ans : Encapsulation is a mechanism where you bind your data(variables) and code(methods) together as a single unit. Here, the data is hidden from the outer world and can be accessed only via current class methods. This helps in protecting the data from any unnecessary modification. We can achieve encapsulation in Java by:

Declaring the variables of a class as private.

Providing public setter and getter methods to modify and view the values of the variables.



Q. What is an association?

Ans : Association is a relationship where all object have their own lifecycle and there is no owner. Let’s take the example of Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers but there is no ownership between the objects and both have their own lifecycle. These relationships can be one to one, one to many, many to one and many to many.



Q. What do you mean by aggregation?

Ans : An aggregation is a specialized form of Association where all object has their own lifecycle but there is ownership and child object can not belong to another parent object. Let’s take an example of Department and teacher. A single teacher can not belong to multiple departments, but if we delete the department teacher object will not destroy. 



Q. What is composition in Java?

Ans : Composition is again a specialized form of Aggregation and we can call this as a “death” relationship. It is a strong type of Aggregation. Child object does not have their lifecycle and if parent object deletes all child object will also be deleted. Let’s take again an example of a relationship between House and rooms. House can contain multiple rooms there is no independent life of room and any room can not belongs to two different houses if we delete the house room will automatically delete.



Q. What is a marker interface?

Ans : A Marker interface can be defined as the interface having no data member and member functions. In simpler terms, an empty interface is called the Marker interface. The most common examples of Marker interface in Java are Serializable, Cloneable etc. The marker interface can be declared as follows.

public interface Serializable{

}



Q. What is object cloning in Java?

Ans : Object cloning in Java is the process of creating an exact copy of an object. It basically means the ability to create an object with a similar state as the original object. To achieve this, Java provides a method clone() to make use of this functionality. This method creates a new instance of the class of the current object and then initializes all its fields with the exact same contents of corresponding fields. To object clone(), the marker interface java.lang.Cloneable must be implemented to avoid any runtime exceptions. One thing you must note is Object clone() is a protected method, thus you need to override it.




Q. What is a copy constructor in Java?

Ans : Copy constructor is a member function that is used to initialize an object using another object of the same class. Though there is no need for copy constructor in Java since all objects are passed by reference. Moreover, Java does not even support automatic pass-by-value.





Q. What's the purpose of Static methods and static variables?

Ans: When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.



Q. What is data encapsulation and what's its significance?

Ans: Encapsulation is a concept in Object Oriented Programming for combining properties and methods in a single unit.

Encapsulation helps programmers to follow a modular approach for software development as each object has its own set of methods and variables and serves its functions independent of other objects. Encapsulation also serves data hiding purpose.



Q. What is a singleton class? Give a practical example of its usage.

Ans : A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for the situations when there is a need to limit the number of objects for a class.

The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues.



Q. What are Loops in Java? What are three types of loops?

Ans: Looping is used in programming to execute a statement or a block of statement repeatedly. There are three types of loops in Java:

1) For Loops

For loops are used in java to execute statements repeatedly for a given number of times. For loops are used when number of times to execute the statements is known to programmer.

2) While Loops

While loop is used when certain statements need to be executed repeatedly until a condition is fulfilled. In while loops, condition is checked first before execution of statements.

3) Do While Loops

Do While Loop is same as While loop with only difference that condition is checked after execution of block of statements. Hence in case of do while loop, statements are executed at least once.

Post a Comment

0 Comments