Java interview questions

We have collected huge set of java interview questions with answers that will be very fruitful for beginners as well as experienced programmers who want to face a java interview.

Instead of keeping answers sort, I've prefered it to explain so that you can answer in better way. Our collection contains java interview questions, OOPs interview questions, String Handling interview questions, Multithreading interview questions, collection interview questions, JDBC interview questions etc.

1. What is the difference between an inner class and a sub class?

An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.

A sub class is a class which inherits from another class called super class. Sub class can access all public and protected methods and fields of its super class.

2. What are the various access specifiers in java?

In Java, access specifiers are the keywords used before a class name, method name, variable name which defines the access scope. The types of access specifiers in java are:

  • Public access specifier: Classes, methods, and fields declared as public can be accessed from any class in the Java program, whether these classes are in the same package or in another package.
  • Private access specifier: methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
  • Protected access specifier: Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within the package of the protected members' class. The protected access specifier cannot be applied to class and interfaces.
  • Default access specifier: When you don't set access specifier for the element, it will follow the default accessibility level. There is no default specifier keyword. Classes, variables, and methods can be default accessed.Using default specifier we can access class, method, or field which belongs to same package,but not from outside this package.

3. What is static keyword in java?

The static keyword is used in java mainly for memory management. It is used with variables, methods, blocks and nested class. It is a keyword that are used for share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class.

Static variables or static methods can be access without creating instance of that class, just put the class name before the static variable or method to use them.

Static method can not call non-static method.

4. Explain data encapsulation and its significance?

Encapsulation is one of the four fundamental OOP concepts.Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.

5. What is the difference between continue and break statement?

Continue statement: The continue statement skips the current iteration of a for, while , or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop.

A labeled continue statement skips the current iteration of an outer loop marked with the given label.

Break statement: The break statement has two forms: labeled and unlabeled. You can also use an unlabeled break to terminate a for, while, or do-while loop.

An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

6. What is the difference between double and float variables in Java?

In java, float takes 4 bytes in memory while double takes 8 bytes in memory. Float is single precision floating point decimal number while Double is double precision decimal number.

7. What is final Keyword in Java?

Final class: A class that is declared as final, it cannot be subclassed. Example String,Integer and other wrapper classes.

Final method: A method that is declared as final, can't be overridden by the subclasses of that class where final method is declared.

Final variable: The value of a variable that is declared as final, can't be changed.

8. What is ternary operator? Give an example.

Ternary operator , also called conditional operator is used to decide which value to assign to a variable based on a Boolean value evaluation. It’s denoted as ?

9. How can you generate random numbers in Java?

Using Math.random() we can generate random numbers in the range of 0.1 to 1.0

Random class is in package java.util

10. What is default switch case? Give example.

In a switch statement, default case is executed when no other switch condition matches. Default case is an optional case.

11. What is the base class in Java from which all classes are derived?

java.lang.Object

12. What is package in java?

In Java, package is a collection of classes and interfaces which are bundled together as they are related to each other. Use of packages helps developers to modularize the code and group the code for proper reuse. Once code has been packaged in Packages, it can be imported in other classes and used.

13. Can we declare a class as abstract without having any abstract method?

Yes we can.

Also, if a class has atleast one abstract method, then, the class must be declared as abstract otherwise it will give compile time error.

14. What are the difference between an abstract class and and an interface in Java?

Key difference between an Abstract class and an Interface are:

  • In an abstract class we can declare a variable or method public, private, protected or default but an interface can declare only public variables and methods
  • An abstract class can provide concreate implementation of a method where an Interface can't.
  • A class that implements an interface, must implements all its method where a class that extends an abstract class, doesn't require to implements all its methods.
  • A class can extends only 1 abstract class where a class can implements multiple interfaces.

15. What are the performance implications of Interfaces over abstract classes?

Interfaces are slower in performance as compared to abstract classes as extra indirections are required for interfaces. Another key factor for developers to take into consideration is that any class can extend only one abstract class while a class can implement many interfaces.

Anytime an interface is implemented in a class; developer is forced to implement each and every method of interface.

16. Does importing a package imports its sub-packages as well in Java?

In java, when a package is imported, its sub-packages aren’t imported and developer needs to import them separately if required.

17. Can we declare the main method of our class as private?

In java, main method must be public static in order to run any application correctly. If main method is declared as private, developer won’t get any compilation error however, it will not get executed and will give a runtime error.

18. Can we pass argument to a function by reference instead of pass by value?

In java, we can pass argument to a function only by value and not by reference.

19. What is difference between JDK, JRE and JVM?

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

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.

JDK: Java Development Kit 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.

20. What is JIT compiler?

In java, a just-in-time (JIT) compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor.

21. What is platform?

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

22. 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:

  • Runtime Environment
  • API(Application Programming Interface)

23. What is classloader?

All JVM has atleast one class loader. The classloader are responsible of loading classes and interfaces.

There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

24. What are different oops concept in java?

OOPs stands for Object Oriented Programming. The concepts of oops in java are:

  • Abstraction
  • Encapsulation
  • Association
  • Aggregation
  • Composition
  • Polymorphism
  • Inheritance

25. What is abstraction?

In object oriented programming, abstraction is one of the three central principles (along with encapsulation and inheritance). Through the process of abstraction, a programmer hides all but the relevant data about an object in order to reduce complexity and increase efficiency.

26. What is Encapsulation?

Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as as single unit. In encapsulation the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class, therefore it is also known as data hiding.

27. What is Association?

Association establish relationship between any two objects. It can be defined as the multiplicity between any objects so you must know about the one to one, many to one, one to many and many to many as all these are the association between objects.

Association: A uses B, A is related to B

28. What is Aggregation?

Aggregation is one of the special case of Association. The directional association present in between the objects can also be determined. When a single object ‘has-a’ another object and you will get the aggregation. The directions between the object will be specified with the object containing other object. Aggregation can also be called as “Has-a” relationship. For example, Employee "Has a" address.

29. What is Composition?

Java composition is a design correlation between two classes that is based on the “has-a” and “whole/part” association or aggregation relationship. Composition takes the relationship one step further by ensuring that the containing object is responsible for the lifetime of the object it holds. If Object B is contained within Object A, then Object A is responsible for the creation and destruction of Object B. Unlike aggregation, Object B cannot exist without Object A.

30. What is Polymorphism?

Polymorphism is the ability of a class instance to behave as if it were an instance of another class in its inheritance tree, most often one of its ancestor classes. For example, in Java all classes inherit from Object. Therefore, you can create a variable of type Object and assign to it an instance of any class.

The best way to express polymorphism is via an abstract base class (or interface). Consider, a Human abstract class with an abstract method goPee(). This method is abstract because it can't be defined for human but can be defined for Male and Female.

Now, consider the implementation of Male and Female class.

And Female class is

Now, we can tell an entire room full of Humans to go pee.

31. What is Inheritance?

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

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, and you can add new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

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

String array will be emply not null

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

In java, there is no default values for local variables either it is primitive or object reference.

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

Ordering of static, public will not affect the result.

35. What is difference between object oriented programming language and object based programming language?

Object oriented programming language: Object oriented programming supports all features of oops and it doesn't has in built object. Object oriented programming languages are C++, C#, Java etc.

Object based programming language: doesn't support all the features of OOPs like Polymorphism and Inheritance. It has in built object like javascript has window object. Object based languages are Javascript, VB etc.

36. What will be the initial value of an object reference which is defined as an instance variable?

Most of the beginners get confused with this question. Lets look 2 code samples very closely:

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them, so it will give compile time error.

In the second code sample, a is class member variable, hence it will be initialized to default value that is 0

So, answer of the question is null

37. What is constructor?

Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation.

The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class

Rules

  • Constructor name must be same as its class name
  • Constructor must have no explicit return type

Features/Characteristic

  • Constructor return its current state
  • Constructor can't be inherited.
  • Constructor can't be final.

38. Why main method is static?

Main method is static because object is not required to call static method if It were non static method, jvm creates object first then call main() method that will lead to the problem of extra memory allocation.

39. What is static block?

  • Static block is used to initialize the static data member.
  • Static block is excuted before main method at the time of classloading.

40. Can we execute a program without main() method?

Yes, we can execute a program by using static block

41. What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

42. What is this in java?

It is a java keyword that points to the current object.

43. What is multiple inheritance? Is multiple inheritance supported in java?

If a class can inherit properties of many parent then process is called multiple inheritance.

To reduce complexity, Java doesn't support multiple inheritance.

44. What is difference between aggregation and composition?

Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).

45. Why Java does not support pointers?

Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.

46. Can you use this() and super() both in a constructor?

Both this() and super() are constructor calls, and constructor call must be the first (and only first) call in a constructor. Otherwise, the Object constructor will be called more than once when instantiating a single object. So, we can't use this() and super() both in a constructor.

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

48. What is method overloading?

Method overloading in Java occurs when two or more methods shares same name and fulfill at least one of the following condition:

  • Have different number of arguments.
  • Have same number of arguments but their types are different.
  • Have both different numbers of arguments with a difference in their types.

49. Can we overload main() method?

Yes, we can have many main() methods in a class by overloading the main method.

50. Can we overload main() method?

Yes, we can have many main() methods in a class by overloading the main method.

Share & Like

About ApnaTutorials.com

ApnaTutorials.com is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.