Selenium with Java Interview Questions and Answers

Java Interview Questions and Answers

Last updated on 04th Oct 2020, Blog, Interview Question

About author

Ramesh (Sr Project Manager )

Highly Expertise in Respective Industry Domain with 7+ Years of Experience Also, He is a Technical Blog Writer for Past 4 Years to Renders A Kind Of Informative Knowledge for JOB Seeker

(5.0) | 16547 Ratings 1621

It’s a no-brainer that Java is one of the leading programming options for bagging a lucrative job. After all, the class-based, general-purpose, object-oriented programming language, is one of the most widely used programming languages in the world.

With a plethora of great features, the programming language is preferred not only by the seasoned experts but also pursued by those new to the programming world. So, here are top Java interview questions and answers that will help you bag a Java job, or, at the very least, enhance your learning. The Java interview questions are recommended for both beginners and professionals as well as for Software Developers and Android Applications Developers. 

Given below is a comprehensive list of the most important and commonly asked basic and advanced Java programming interview questions with detailed answers.

1. Is Java platform independent?

Ans:

Yes. Java is a platform independent language. We can write java code on one platform and run it on another platform. For e.g. we can write and compile the code on windows and can run the generated bytecode on Linux or any other supported platform. This is one of the main features of java.

2. What all memory areas are allocated by JVM?

Ans:

Classloader, Class area, Heap, Stack, Program Counter Register and Native Method Stack

3. Java vs. C ++?

Ans:

Here are the few differences between Java and C++:

  • Platform dependency – C++ is platform dependent while java is platform independent
  • No goto support – Java doesn’t support goto statement while C++ does.
  • Multiple inheritance – C++ supports multiple inheritance while java does not.
  • Multithreading – C++ does not have in-build thread support, on the other hand java supports multithreading
  • Virtual keyword – C++ has virtual keyword, it determines if a member function of a class can be overridden in its child class. In java there is no concept of virtual keyword.

4.Explain public static void main(String args[])

Ans:

Here public is an access modifier, which means that this method is accessible by any class.

static – static keyword tells that this method can be accessed without creating the instance of the class. Refer: Static keyword in java

void – this main method returns no value.

main – It is the name of the method.

String args[] – The args is an array of String type. This contains the command line arguments that we can pass while running the program.

5. What is javac ?

Ans:

The javac is a compiler that compiles the source code of your program and generates bytecode. In simple words javac produces the java byte code from the source code written

  • *.java file

JVM executes the bytecode to run the program.

6. What is class?

Ans:

A class is a blueprint or template or prototype from which you can create the object of that class. A class has a set of properties and methods that are common to its objects.

7. What is the base class of all classes?

Ans:

java.lang.Object is the base class (super class) of all classes in java.

8. What is a wrapper class in Java?

Ans:

A wrapper class converts the primitive data type such as int, byte, char, boolean etc. to the objects of their respective classes such as Integer, Byte, Character, Boolean etc. 

9. What is a path and classPath in Java?

Ans:

Path specifies the location of .exe files. Classpath specifies the location of bytecode (.class files).

10. Different Data types in Java.

Ans:

byte – 8 bit

short – 16 bit

char – 16 bit Unicode

int – 32 bit (whole number)

float – 32 bit (real number)

long – 64 bit (Single precision)

double – 64 bit (double precision)

11. What is Unicode?

Ans:

Java uses Unicode to represent the characters. Unicode defines a fully international character set that can represent all of the characters found in human languages.

12. What are Literals?

Ans:

Any constant value that is assigned to a variable is called literal in Java. For example –

  • // Here 101 is a literal
  • int num = 101
Subscribe For Free Demo

Error: Contact form not found.

13. Dynamic Initialization?

Ans:

Dynamic initialization is a process in which initialization value of a variable isn’t known at compile-time. It’s computed at runtime to initialize the variable.

14. What is Type casting in Java?

Ans:

When we assign a value of one data type to the different data type then these two data types may not be compatible and need a conversion. If the data types are compatible (for example assigning int value to long) then java does automatic conversion and does not require casting. However if the data types are not compatible then they need to be casted for conversion.

For example:

  • //here in the brackets we have mentioned long keyword, this is casting
  • double num = 10001.99;
  • long num2 = (long)num;

15. What is an Array?

Ans:

An array is a collection (group) of a fixed number of items. Array is a homogeneous data structure which means we can store multiple values of the same type in an array but it can’t contain multiple values of different types. For example an array of int type can only hold integer values.

16. What is a BREAK statement in java?

Ans:

The break statement is used to break the flow sequence in Java.

break statement is generally used with switch case data structure to come out of the statement once a case is executed.

It can be used to come out of the loop in Java

17.Arrays can be defined in different ways. Write them down.

Ans:

  • int arr[];
  • int[] arr;

18. Four main principles of OOPS Concepts?

Ans:

  • Inheritance
  • Polymorphism
  • Data Encapsulation
  • Abstraction

19. What is inheritance?

Ans:

The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance brings reusability of code in a java application. 

20. Does Java support Multiple Inheritance?

Ans:

When a class extends more than one class then it is called multiple inheritance. Java doesn’t support multiple inheritance whereas C++ supports it, this is one of the differences between java and C++.  

21. What is Polymorphism and what are the types of it?

Ans:

Polymorphism is the ability of an object to take many forms. The most common use of polymorphism in OOPs is to have more than one method with the same name in a single class. There are two types of polymorphism: static polymorphism and dynamic polymorphism. 

22. What is method overriding in Java?

Ans:

When a subclass (child class) overrides the method of super class(parent class) then it is called overriding. To override a method, the signature of method in child class must match with the method signature in parent class.

23. Can we override a static method?

Ans:

No, we cannot override a static method in Java.

24. What is method overloading?

Ans:

When a class has more than one methods with the same name but different number, sequence or types of arguments then it is known as method overloading.

25. Does Java support operator overloading?

Ans:

Operator overloading is not supported in Java.

26. Can we overload a method by just changing the return type and without changing the signature of method?

Ans:

No, We cannot do this. To overload a method, the method signature must be different, return type doesn’t play any role in method overloading.

27. Is it possible to overload the main() method of a class?

Ans:

Yes, we can overload the main() method in Java.

28. What is static and dynamic binding in Java?

Ans:

Binding refers to the linking of method call to its body. A binding that happens at compile time is known as static binding while binding at runtime is known as dynamic binding. 

29. What is Encapsulation?

Ans:

Wrapping of the data and code together is known as encapsulation.

30. What is an abstract class in Java?

Ans:

An abstract class is a class which can’t be instantiated (we cannot create the object of abstract class), we can only extend such classes. It provides the generalised form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. We can achieve partial abstraction using abstract classes, to achieve full abstraction we use interfaces.

31. What is Interface in java?

Ans:

An interface is used for achieving full abstraction. A class implements an interface, thereby inheriting the abstract methods of the interface. 

32. What is the difference between abstract class and interface?

Ans:

1) abstract class can have abstract and non-abstract methods. An interface can only have abstract methods.

2) An abstract class can have static methods but an interface cannot have static methods.

3) abstract classes can have constructors but an interface cannot have constructors.

33. Name the access modifiers that can be applied to the inner classes?

Ans:

public ,private , abstract, final, protected.

34. What is a constructor in Java?

Ans:

Constructor is used for creating an instance of a class, they are invoked when an instance of class gets created. Constructor name and class name should be the same and it doesn’t have a return type. 

35. Can we inherit the constructors?

Ans:

No, we cannot inherit constructors.

Course Curriculum

Get Hands-On Learning on Java Training and Master Your Skills

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

36. Can we mark constructors final?

Ans:

No, Constructor cannot be declared final.

37. What are default and parameterized constructors?

Ans:

Default: Constructors with no arguments are known as default constructors, when you don’t declare any constructor in a class, the compiler creates a default one automatically.

Parameterized: Constructor with arguments are known as parameterized constructors.

38. Can a constructor call another constructor?

Ans:

Yes. A constructor can call another constructor of the same class using this keyword. For e.g. this() calls the default constructor.

Note: this() must be the first statement in the calling constructor.

39. Can a constructor call the constructor of parent class?

Ans:

Yes. In fact it happens by default. A child class constructor always calls the parent class constructor. However we can still call it using super keywords. For e.g. super() can be used for calling super class default constructor.

Note: super() must be the first statement in a constructor.

40.THIS keyword?

Ans:

This keyword is a reference to the current object.

41. Can this keyword be assigned null value?

Ans:

No, this keyword cannot have null values assigned to it.

42. Explain ways to pass the arguments in Java?

Ans:

In java, arguments can be passed as call by value – Java only supports call by value, there is no concept of call by reference in Java.

43. What is a static variable in java?

Ans:

Static variables are also known as class level variables. A static variable is the same for all the objects of that particular class in which it is declared.

44. What is a static block?

Ans:

A static block gets executed at the time of class loading. They are used for initializing static variables.

45. What is a static method?

Ans:

Static methods can be called directly without creating the instance (Object) of the class. A static method can access all the static variables of a class directly but it cannot access non-static variables without creating an instance of the class.

46. Explain super keywords in Java?

Ans:

super keyword references to the parent class. There are several uses of super keyword:

It can be used to call the superclass(Parent class) constructor.

It can be used to access a method of the superclass that has been hidden by subclass (Calling parent class version, In case of method overriding).

To call the constructor of parent class.

47. Use of the final keyword in Java?

Ans:

Final methods – These methods cannot be overridden by any other method.

Final variable – Constants, the value of these variables can’t be changed, it’s fixed.

Final class – Such classes cannot be inherited by other classes. These types of classes will be used when applications require security or someone doesn’t want that particular class. Final Keyword in Java.

48. What is an Object class?

Ans:

This is a special class defined by java; all other classes are subclasses of object class. Object class is a superclass of all other classes. Object class has the following methods

objectClone () – to create a new object that is the same as the object being cloned.

boolean equals(Object obj) – determines whether one object is equal to another.

finalize() – Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup.

toString () – Returns a string representation of the object.

49. What are Packages in Java?

Ans:

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations). Refer: Package in Java.

50.What is the difference between import java.util.Date and java.util.* ?

Ans:

The star form (java.util.* ) includes all the classes of that package and that may increase the compilation time – especially if you import several packages. However it doesn’t have any effect on run-time performance.

51.What is the purpose of composition?

Ans:

You can use composition to hold the reference of one class within another class, and in this case, the contained object cannot exist without the class containing it. It is a type of aggregation.

52. Garbage collection in java?

Ans:

Since objects are dynamically allocated by using the new operator, java handles the deallocation of the memory automatically, when no references to an object exist for a long time. This whole process is called garbage collection. The whole purpose of Garbage collection is efficient memory management.

53. Use of finalize() method in java?

Ans:

finalize() method is used to free the allocated resource.

54. How many times does the garbage collector call the finalize() method for an object?

Ans:

The garbage collector calls the finalize() method only once for an object.

55. What are two different ways to call a garbage collector?

Ans:

  • System.gc() OR Runtime.getRuntime().gc().
Course Curriculum

Enroll in Java Certification Course with In-Depth Modules By Certified Experts

Weekday / Weekend BatchesSee Batch Details

56. Can the Garbage Collection be forced by any means?

Ans:

No, it’s not possible. you cannot force garbage collection. you can call system.gc() methods for garbage collection but it does not guarantee that garbage collection would be done.

57. What is an exception?

Ans:

Exceptions are abnormal conditions that arise during execution of the program. It may occur due to wrong user input or wrong logic written by the programmer.

58. Exceptions are defined in which java package? OR which package has definitions for all the exception classes?

Ans:

  • Java.lang.Exception

This package contains definitions for Exceptions.

59. What are the types of exceptions?

Ans:

There are two types of exceptions: checked and unchecked exceptions.

Checked exceptions: These exceptions must be handled by the programmer otherwise the program would throw a compilation error.

Unchecked exceptions: It is up to the programmer to write the code in such a way to avoid unchecked exceptions. You would not get a compilation error if you do not handle these exceptions. These exceptions occur at runtime.

60. What is the difference between Error and Exception?

Ans:

Error: Mostly a system issue. It always occurs at run time and must be resolved in order to proceed further.

Exception: Mostly an input data issue or wrong logic in code. Can occur at compile time or run time.

61. What is the throw keyword in exception handling?

Ans:

The throw keyword is used for throwing user defined or predefined exceptions.

62. What is the keyword?

Ans:

If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method’s signature.

63. Can static blocks throw exceptions?

Ans:

Yes, A static block can throw exceptions. It has its own limitations: It can throw only Runtime exceptions (Unchecked exceptions), In order to throw checked exceptions you can use a try-catch block inside it.

64. What is finally blocked?

Ans:

Finally block is a block of code that always executes, whether an exception occurs or not. Finally block follows try block or try-catch block.

65. ClassNotFoundException vs NoClassDefFoundError?

Ans:

1) ClassNotFoundException occurs when the loader could not find the required class in the classpath.

2) NoClassDefFoundError occurs when a class is loaded in classpath, but one or more of the classes which are required by another class, are removed or failed to load by the compiler.

66. Can we have a try block without catch or finally block?

Ans:

No, we cannot have a try block without a catch or finally block. We must have either one of them or both.

67. Can we have multiple catch blocks following a single try block?

Ans:

Yes we can have multiple catch blocks in order to handle more than one exception.

68. Is it possible to finally block without a catch block?

Ans:

Yes, we can have try blocks followed by finally blocks without even using catch blocks in between.

69.When a finally block does not get executed?

Ans:

The only time finally won’t be called is if you call System.exit() or if the JVM crashes first.

70. Can we handle more than one exception in a single catch block?

Ans:

Yes we can do that using if-else statements but it is not considered as a good practice. We should have one catch block for one exception.

71. What is a Java Bean?

Ans:

A JavaBean is a Java class that follows some simple conventions including conventions on the names of certain methods to get and set state called Introspection. Because it follows conventions, it can easily be processed by a software tool that connects Beans together at runtime. JavaBeans are reusable software components.

72. What is Multithreading?

Ans:

It is a process of executing two or more parts of a program simultaneously. Each of these parts is known as threads. In short the process of executing multiple threads simultaneously is known as multithreading.

73. What is the main purpose of having a multi-threaded environment?

Ans:

Maximizing CPU usage and reducing CPU idle time

74. What are the main differences between Process and thread? Explain in brief.

Ans:

1)  One process can have multiple threads. A thread is a smaller part of a process.

2)  Every process has its own memory space, executable code and a unique process identifier (PID) while every thread has its own stack in Java but it uses process main memory and shares it with other threads.

3) Threads of the same process can communicate with each other using keywords like wait and notify etc. This process is known as inter process communication.

java Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

75. How can we create a thread in java?

Ans:

There are following two ways of creating a thread:

1)  By Implementing Runnable interface.

2)  By Extending Thread class.

76. Explain yield and sleep?

Ans:

yield() – It causes the currently executing thread object to temporarily pause and allow other threads to execute.

sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock.

77. What is the difference between sleep() and wait()?

Ans:

sleep() – It causes the current thread to suspend execution for a specified period. When a thread goes into sleep state it doesn’t release the lock

wait() – It causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object, or a specified amount of time has elapsed.

78. What is a daemon thread?

Ans:

A daemon thread is a thread that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection.

79. What does join( ) method do?

Ans:

if you use join() ,it makes sure that as soon as a thread calls join,the current thread(yes,currently running thread) will not execute unless the thread you have called join is finished.

80. Preemptive scheduling vs. time slicing?

Ans:

1) The preemptive scheduling is prioritized. The highest priority process should always be the process that is currently utilized.

2) Time slicing means a task executes for a defined slice/ period of time and then enters the pool of ready states. The scheduler then determines which task executes next based on priority or other factor.

81. Can we call the run() method of a Thread class?

Ans:

Yes, we can call the run() method of a Thread class but then it will behave like a normal method. To actually execute it in a Thread, you should call Thread.start() method to start it.

82. What is Starvation?

Ans:

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

83. What is the deadlock?

Ans:

Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.

84. What is Serialization and deserialization?

Ans:

Serialization is a process of converting an object and its attributes to the stream of bytes. De-serialization is recreating the object from a stream of bytes; it is just a reverse process of serialization. To know more about serialization with an example program, refer to this article.

85.Do we need to implement any method of Serializable interface to make an object serializable?

Ans:

No. In order to make an object serializable we just need to implement the interface Serializable. We don’t need to implement any methods.

86. What is a transient variable?

Ans:

1) transient variables are not included in the process of serialization.

2) They are not the part of the object’s serialized state.

3) Variables which we don’t want to include in serialization are declared as transient.

87. A string class is immutable or mutable?

Ans:

String class is immutable. That’s the reason once its object gets created, it cannot be changed further.

88. Difference between StringBuffer and StringBuilder class?

Ans:

1) StringBuffer is thread-safe but StringBuilder is not thread safe.

2) StringBuilder is faster than StringBuffer.

3) StringBuffer is synchronized whereas StringBuilder is not synchronized.

89. What is toString() method in Java?

Ans:

The toString() method returns the string representation of any object.

90. What is a List?

Ans:

Elements can be inserted or accessed by their position in the list, using a zero-based index.

A list may contain duplicate elements.

91. What is a Map?

Ans:

Map interface maps unique keys to values. A key is an object that we use to retrieve a value later. A map cannot contain duplicate keys: Each key can map to at most one value.

92. What is Set?

Ans:

A Set is a Collection that cannot contain duplicate elements.

93. Why is ArrayList better than Arrays?

Ans:

Arrays can hold a fixed number of elements. ArrayList can grow dynamically.

94. What is the difference between ArrayList and LinkedList?

Ans:

1) LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array.

2) LinkedList is preferred for add and update operations while ArrayList is a good choice for search operations. Read more here.

95. For addition and deletion. Which one is most preferred: ArrayList or LinkedList?

Ans:

LinkedList. Because deleting or adding a node in LinkedList is faster than ArrayList.

96.For searches. Which one is most preferred: ArrayList or LinkedList?

Ans:

ArrayList. Searching an element is faster in ArrayList compared to LinkedList.

97. What is the difference between ArrayList and Vector?

Ans:

1) Vector is synchronized while ArrayList is not synchronized.

2) By default, Vector doubles the size of its array when it is resized internally. ArrayList increases by half of its size when it is resized. More details.

98. What is the difference between Iterator and ListIterator?

Ans:

Following are the major differences between them:

1) Iterators can be used for traversing Set, List and Map. ListIterator can only be used for traversing a List.

2) We can traverse only in forward direction using an Iterator. ListIterator can be used for traversing in both the directions(forward and backward). Read more at: ListIterator vs Iterator.

99.  What is aggregation?

Ans:

It is a type of weak relation you can create between two classes, where one contains references to another class contained within it.

Are you looking training with Right Jobs?

Contact Us

Popular Courses