31st
Dec
Core Java interview questions

Java Interview Questions

  • Tony Thomas
  • 31st Dec, 2020
  • 943 Followers

About Java

Java is a programming language used in building applications. It's a class-based, object-oriented programming language that functions on the "write one time, run anywhere principle". The java coding once done can run on any platform and doesn't require recompilation. It is currently the most popular programming language and therefore, one can fairly guess the demand that these professionals enjoy.Java was first introduced by Sun Microsystem in 1995. It was developed to run most independently with few implementation dependencies. It has adopted most of its syntax from C and C++, which is often regarded as the basics of programming language.

Core Java interview questions

1) What is Java?

Java is a general-purpose programming language that is class-based, object-oriented, and designed to have as few implementation dependencies as possible. It supports Static, strong, safe, nominative, and manifest typing discipline. Java was designed by James Gosling and released on May 23, 1995.

2) Outline the major features of Java?

Major features of Java are:

  • Object-Oriented
  • Platform Independent
  • Simple and Secure
  • Portable
  • Multithreaded
  • Architectural Neutral
  • High Performance and Dynamic

3) What do you mean by platform independence of Java?

The meaning of platform-independent is that the java compiled code(byte code) can run on all operating systems.JAVA is platform-independent because it having its own JVM so that it can run on any platform.

4) What is the difference between JDK, JRE, and JVM?

It is important to understand the difference between JDK, JRE, and JVM in Java.

JVM (Java Virtual Machine):

Java virtual machine is actually an abstract machine that provides a runtime environment in which the java bytecode gets executed. A JVM performs some main tasks such as- loading, verifying and executing the code. It also provides a runtime environment.

JRE (Java Runtime Environment):

The Java runtime environment is used to provide a runtime environment. It is implemented by JVM. It consists of certain libraries that are used by JVM at runtime.

JDK (Java Development Kit):

The Java development kit consists of JRE and all the development tools which are necessary for compiling a program.

5) What is JVM and is it platform independent?

Java Virtual Machine (JVM) is the heart of java programming language. JVM is responsible for converting byte code into machine-readable code. JVM is not platform-independent, that's why you have different JVM for different operating systems. We can customize JVM with Java Options, such as allocating minimum and maximum memory to JVM. It's called virtual because it provides an interface that doesn't depend on the underlying OS.

6) Java Compiler is stored in JDK, JRE or JVM?

The task of java compiler is to convert java program into bytecode, we have javac executable for that. So it must be stored in JDK, we don't need it in JRE and JVM is just the specs.

7) Why Java is not pure Object Oriented language?

Java is not fully object-oriented because it supports primitive data types like int, byte, long, etc., which are not objects. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:

  1. Encapsulation/Data Hiding
  2. Inheritance
  3. Polymorphism
  4. Abstraction
  5. All predefined types are objects
  6. All user-defined types are objects
  7. All operations performed on objects must be only through methods exposed to the objects.

8) What do you mean by an object in java?

A Java object is a combination of data and procedures working on the available data. An object has a state and behavior.

The state of an object is stored in fields (variables), while methods (functions) display the object's behavior. Objects are created from templates known as classes. In Java, an object is created using the keyword "new".

User u = new User();

9) Does Java supports pointers?

Yes, but only internally, we cannot use pointers directly in JAVA. Java doesn't support pointers. Java uses reference types instead of pointers.

10) What is purpose of super keyword in Java?

Super keyword in Java is a reference variable which is used to refer immediate parent class object. Whenever you create the instance of a subclass, an instance of the parent class is created implicitly which is referred by a super reference variable.

11) What is difference between path and classpath variables in Java?

PATH and CLASSPATH are the two most common environment variables you will deal with while configuring java environment.

  • PATH is an environment variable that is used by the Operating System to locate the exe files (.exe) or java binaries ( java or javac command).

    Command to set PATH

    set PATH=%PATH%;C:\Program Files\Java\JDK1.8.20\bin
  • CLASSPATH is also an environment variable which is used by Application ClassLoader to locate and load the .class files. CLASSPATH setting is done to locate the .class files found in another directory.

    Command to set CLASSPATH

    set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\JDK1.8.20\lib

12) Differentiate call by value and call by reference?

In Java functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.

The parameters passed to function are called actual parameters whereas the parameters received by the function are called formal parameters.

  • Call By Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of the caller.
  • Call by Reference: Both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in the actual parameters of the caller.

13) What are the various access specifiers in Java?

Access Specifiers in Java are also known as Visibility Specifiers are used to regulating access to classes, fields, and methods in Java. These Specifiers determine whether a field or method in a class can be used or invoked by another method in another class or sub-class.

14) What is the difference between Array list and vector in Java?

Vector and ArrayList both use Array internally as a data structure. They are dynamically resizable. The difference is in the way they are internally resized. By default, Vector doubles the size of its array when its size is increased. But, ArrayList increases by half of its size when its size is increased.

Therefore as per Java API, the only main difference is, Vector’s methods are synchronized and ArrayList’s methods are not synchronized.

15) What is main method in Java? Why it public static and void?

Java main() method is always static, so that compiler can call it without the creation of an object or before the creation of an object of the class.

  • In any Java program, the main() method is the starting point from where compiler starts program execution. So, the compiler needs to call the main() method.
  • If the main() is allowed to be non-static, then while calling the main() method JVM has to instantiate its class.
  • While instantiating it has to call the constructor of that class, there will be ambiguity if the constructor of that class takes an argument.
  • The static method of a class can be called by using the class name only without creating an object of a class.
  • The main() method in Java must be declared public, static and void. If any of these are missing, the Java program will compile but a runtime error will be thrown.

16) What is a Class in Java?

A Class is like an object constructor or a "blueprint" for creating objects.class the keyword is used to create a class in Java.

Syntax

public class MyClass {
  int x = 5;
}

17) What is SerialVersionUID?

serialVersionUID is a unique identifier for Serializable classes. It is used during the deserialization of an object, to ensure that a loaded class is compatible with the serialized object. If no matching class is found, an InvalidClassException is thrown.

18) What do you understand by immutable object?

Immutable objects are objects that don't change. You can create them, but you can't change them. A Java immutable object must have all its fields be internal, private final fields. It must not implement any setters. It needs a constructor that takes a value for every single field.

19) What is constructor in Java?

Constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in java but it's not a method as it doesn't have a return type. A Constructor has the same name as the class and looks like this in java code.

Example

class MyClass
{   
  // A Constructor
  MyClass(){
    System.out.println("Constructor called");
  }

}

20) What is an Exception in Java? List types?

Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).

In Java, an exception is an object that wraps an error event that occurred within a method and contains:

  • Information about the error including its type
  • The state of the program when the error occurred
  • Optionally, other custom information

21) What is use of Final Keyword in Java?

Final Keyword in Java is used to finalize the value of a variable, class or method in the entire program. It stores the initialized value in the memory which will never change at any condition.

22) What is early binding and late binding in Java?

Static or early binding: The binding which can be resolved at compile time by the compiler is known as static or early binding. Binding of all the static, private and final methods is done at compile-time.

Late binding or dynamic binding: In the late binding or dynamic binding, the compiler doesn't decide the method to be called. Overriding is a perfect example of dynamic binding. In overriding both parent and child classes have the same method.

23) What is message passing in java?

Message passing in Java is like sending an object i.e. message from one thread to another thread. It is used when threads do not have shared memory and are unable to share monitors or semaphores or any other shared variables to communicate.

24) What is an Anonymous Class?

In Java, a class can contain another class known as nested class. It's possible to create a nested class without giving any name. A nested class that doesn't have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class.

25) What is the difference between == and .equals() method in Java?

Both equals() method and the == operator is used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in the heap, whether they point to the same location or not.

Whenever we create an object using the operator new it will create a new memory location for that object. So we use == operator to check memory location or address of two objects are the same or not.

When we talk about the equals() method the main purpose is to compare the state of two objects or contents of the object.

26) What is difference between overloading and overriding?

Few differences between overloading and overriding are

OVERLOADING OVERRIDING
It is performed at compile time. It is performed at runtime.
It is carried out within a class. It is carried out with two classes having an IS-A relationship between them.
Parameters do not remain the same in case of overloading. The parameter must remain the same in case of overriding.
You can perform overloading on static methods. You cannot perform overriding on static methods.
Overloaded methods use static binding. Overridden methods use dynamic binding.

27) What is an Abstract Class?

A class that is declared with the abstract keyword is known as an abstract class in Java. An Abstract class can have both abstract and non-abstract methods (method with the body).

28) What is a design Pattern. Tell me some design patterns you have used?

In software engineering, a software design pattern is a general, reusable solution to a commonly occurring problem within a given context in software design. It is not a finished design that can be transformed directly into a source or machine code.

Few Design Patterns

  • Structural Design Pattern: Composite Pattern, Decorator Pattern, Adapter Pattern, Bridge Pattern, Proxy Pattern, Facade Pattern, Flyweight Pattern.
  • Creational Design Pattern: Singleton Pattern, Prototype Pattern, Factory Pattern, Abstract Factory Pattern, Builder Pattern.
  • Behavioural Design Pattern: Interpreter Pattern, Iterator Pattern, Chain Of Responsibility Pattern, Observer Pattern, State Pattern, Command Pattern, Mediator Pattern, Memento Pattern, Strategy Pattern, Visitor Pattern, Template Pattern

29) What is Hashing in Java?

Hashing is a way to assign a unique code for any variable/object after applying any function/algorithm on its properties. A true Hashing function must follow this rule: Hash function should return the same hash code each and every time when the function is applied on the same or equal objects.

30) What are Mutable Classes?

A mutable class is one that can change its internal state after it is created. Generally speaking, a class is mutable unless special effort is made to make it immutable. To create a mutable class in Java you have to make sure the following requirements are satisfied:

  • Provide a method to modify the field values
  • Getter and Setter method

Example

package interviewMocks;
 
public class example {
	private String coursename;
	example(String coursename) {
		this.coursename = coursename;
	}
	public String getName() {
		return coursename;
	}
	public void setName(String coursename) {
		this.coursename = coursename;
	}
	public static void main(String[] args) {
		example obj = new example("Machine Learning");
		System.out.println(obj.getName());
		 
		// update the name, this object is mutable
		obj.setName("Machine Learning Masters");
		System.out.println(obj.getName());
	 
	}
}

31) What Is a Package? Which package is imported by default?

A package in Java is used to group related classes. Think of it as a folder in a file directory. We use packages to avoid name conflicts and to write better maintainable code. Packages are divided into two categories:

  • Built-in Packages (packages from the Java API)
  • User-defined Packages (create your own packages)

The java.lang package is always imported by default as it is loaded internally by the JVM.

32) What is inheritance? List types of inheritance supported by Java?

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a 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 the parent class.

Below are the different types of inheritance which are supported by Java.

  • Single Inheritance
  • Multiple Inheritance (Through Interface)
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance (Through Interface)

33) Is multiple inheritance is supported by Java?

Java doesn't support multiple inheritance to avoid the ambiguity caused by it. One of the examples of such a problem is the diamond problem that occurs in multiple inheritance.

34) What is the default JVM heap size?

The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes (MB) and otherwise one-fourth of the physical memory up to a physical memory size of 1 gigabyte (GB).

35) What is Singleton design pattern?

Singleton pattern is a design pattern that restricts a class to instantiate its multiple objects. It is nothing but a way of defining a class. Class is defined in such a way that only one instance of the class is created in the complete execution of a program or project. It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn’t have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.

36) Explain Dependency Injection and its types?

Dependency injection is a way to pass one object dependencies to another object. It is a broader form of inversion of control (IOC).

There are basically 3 types of dependency injection:

  • constructor injection
  • setter injection
  • Interface injection

37) What is this keyword?

The this keyword refers to the current object in a method or constructor. The most common use of this keyword is to eliminate the confusion between class attributes and parameters with the same name.

this can also be used to

  • Invoke current class constructor
  • Invoke the current class method
  • Return the current class object
  • Pass an argument in the method call
  • Pass an argument in the constructor call

38) What is Garbage Collection in Java?

Java garbage collection is the process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.

39) What is byte code in Java?

Java bytecode is the instruction set for the Java Virtual Machine. It acts similarly to an assembler which is an alias representation of C++ code. As soon as a java program is compiled, java bytecode is generated.

40) What are wrapper classes in Java?

Wrapper classes in Java are classes that provide a way to use primitive data types ( int, boolean, etc..) as objects. Examples of Wrapper classes in Character, Byte, Short, Integer, Float, Double, Boolean.

41) What are 4 pillers of object oriented programming?

The four pillars of the object-oriented programming are: 

  • Abstraction: Abstraction is basically used to separate unwanted things from the essential ones. Only important properties.
  • Encapsulation: The encapsulation process consists of certain methods and properties of the abstraction process. It also protects these methods from any interference or tampering.
  • Inheritance: Inheritance is of two types basically: single inheritance & multiple inheritances. It is how a class is derived from the other class.
  • Polymorphism: Here in polymorphism, you can name it all the same for the different actions of an object of different data types.

42) What is an interface?

An interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

43) What is the use of System class in Java?

The System Class is one of the core classes in Java and belongs to the java.lang package. The System class is a final class and does not provide any public constructors. Because of this all of the members and methods contained in this class are static in nature.

44) What is use of instanceof keyword?

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false.

45) What is Marker interface in Java?

Marker interface in Java is an empty interface (no field or methods). Examples of marker interface are Serializable, Clonnable and Remote interface.

Syntax

public interface Serializable 
{
  // nothing here
}

46) List types of storage classes in Java?

There are basically four types of storage classes in Java:

  • Automatic storage class: When a variable that is used in the coding is defined within a function and that also with the auto specifier then it simply belongs to this storage class.
  • Register storage class: Those variables in the coding which are declared by the register specifier then it belongs to this storage class.
  • Static storage class: It has a function to declare the variable with the help of the static specifier and that is how it belongs to the static storage class.
  • External storage class: The main objective with this is that the variable which is being declared consists of external linkage.

47) What is difference between throw and throws?

Major differences between throw and throws are given below:

throw throws
Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception.
Checked exceptions cannot be propagated using throw only. Checked exception can be propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException, SQLException.

48) What is composition in java?

Composition is the design technique to implement a has-a relationships in classes. We can use java inheritance or Object composition for code reuse. Java composition is achieved by using instance variables that refer to other objects.

49) What is static block in Java?

In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block.

Example

public class StaticBlockClass {
static {
  //static block
  System.out.println("Hi, I'm a Static Block!");
  }
}

50) What are structs in Java?

Structs is a framework in Java. The use of this framework is for the development of the Java enterprise edition purpose. It is an open-source framework. This is a very reliable and efficient working framework. In order to introduce the MVC which is known as the model view controller, it makes use of the Java servlet API and also it extends its functions for more results. It later became one of the best frameworks that were designed in the Apache project.

51) What is exception chaining in Java?

Exception chaining, or exception wrapping, is an object-oriented programming technique of handling exceptions by re-throwing a caught exception after wrapping it inside a new exception. The original exception is saved as a property (such as to cause) of the new exception.

52) What is OutOfMemoryError in Java?

In Java, all objects are stored in the heap. They are allocated using the new operator. The OutOfMemoryError Exception in Java looks like this:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

Usually, this error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

53) What are meta-annotations in Java?

In Java annotations that are used to annotate other annotations are known as "Meta Annotation".

There are four annotation types in the "java.lang.annotation" package:

  • @Documented
  • @Inherited
  • @Retention
  • @Target

54) What String.intern() function do in Java?

The java String.intern() method returns the interned string. It returns the canonical representation of the string. It can be used to return a string from memory if it is created by new keyword. It creates an exact copy of the heap string object in a string constant pool.

55) What is Spliterator in Java?

Spliterator is a Java Iterator, which is used to iterate elements one-by-one from a List implemented object. It is a special type of Iterator to traverse and partition the elements of a source in Java. A source can be a collection, an IO channel or a generator function. A Spliterator may traverse elements individually or sequentially in bulk.

56) What is StringJoiner in Java?

StringJoiner is a class in java.util package which is used to construct a sequence of characters(strings) separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

57) What is fail fast iterator in Java?

Fail Fast Iterators in java are used to iterate over the Collection objects. Fail-Fast iterators immediately throw ConcurrentModificationException if there is a structural modification of the collection.

58) Are Arrays of Primitive Data Type in Java?

No, arrays are not primitive datatypes in Java. They are container objects which are created dynamically. All methods of class Object may be invoked on an array. They were considered as reference data types.

59) What is use of finalize in Java?

Finalize is a method that the Garbage Collector always calls just before the deletion/destroying the object which is eligible for Garbage Collection, so as to perform clean-up activity. Clean-up activity means closing the resources associated with that object like Database Connection, Network Connection or we can say resource de-allocation. Remember it is not a reserved keyword. Once the finalize method completes immediately Garbage Collector destroys that object.

60) What is use of transient keyword in Java?

Transient variable in Java is a variable whose value is not serialized during Serialization and which is initialized by its default value during de-serialization, for example for object transient variable it would be null.

61) What is semaphore in Java?

A semaphore in Java controls access to a shared resource through the use of a counter. If the counter is greater than zero, then access is allowed. If it is zero, then access is denied. What the counter is counting are permits that allow access to the shared resource. Thus, to access the resource, a thread must be granted a permit from the semaphore.

It is a thread synchronization construct that can be used either to send signals between threads to avoid missed signals, or to guard a critical section like you would with a lock.

62) What is the difference between Error and Exception?

Major differences between Error and Exception in Java

Basis for Comparison Error Exception
Basic An error is caused due to lack of system resources. An exception is caused because of the code.
Recovery An error is irrecoverable. An exception is recoverable.
Keywords There is no means to handle an error by the program code. Exceptions are handled using three keywords "try", "catch", and "throw".
Consequences As the error is detected the program will terminated abnormally. As an exception is detected, it is thrown and caught by the "throw" and "catch" keywords correspondingly.
Types Errors are classified as unchecked type. Exceptions are classified as checked or unchecked type.
Package In Java, errors are defined "java.lang.Error" package. In Java, an exceptions are defined in"java.lang.Exception".
Example OutOfMemory, StackOverFlow. Checked Exceptions : NoSuchMethod, ClassNotFound.
Unchecked Exceptions : NullPointer, IndexOutOfBounds.

63) What is synchronization?

Synchronization in java is the capability to control the access of multiple threads to any shared resource. Java Synchronization is a better option where we want to allow only one thread to access the shared resource.

64) What is Runtime Polymorphism?

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass.

65) What is Heap and Stack Memory?

Heap memory is the run time data area from which the memory for all java class instances and arrays is allocated. The heap is created when the JVM starts up and may increase or decrease in size while the application runs.

Stack in java is a section of memory that contains methods, local variables, and reference variables. Stack memory is always referenced in the Last-In-First-Out order. Local variables are created in the stack.

66) What is classloader?

Java ClassLoader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually, classes are only loaded on demand. The Java run time system does not need to know about files and file systems because of classloaders.

67) What is varargs in Java?

Varargs is a short name for variable arguments. In Java, an argument of a method can accept arbitrary number of values. This argument that can accept variable number of values.

68) What is NullPointerException?

NullPointerException is a RuntimeException . In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference that has the null value.

69) Why string is immutable in java?

A string is immutable in Java for several reasons, here is a summary:

  • Security: parameters are typically represented as String in-network connections, database connection URLs, usernames/passwords, etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread-safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it seems that if two objects have the same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in the wrong class being loaded (because mutable objects change their state).

70) What is default access modifier in Java?

The default access modifier in Java is the package level modifier. If no modifier is specified that it is considered default by default.

71) What is JDBC Driver?

A JDBC driver is a software component enabling a Java application to interact with a database. JDBC drivers are analogous to ODBC drivers, ADO.NET data providers, and OLE DB providers. To connect with individual databases, JDBC requires drivers for each database.

72) What is Reflection in Java?

Reflection is an API that is used to examine or modify the behavior of methods, classes, interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package.

73) When to use Runnable interface in Java?

java.lang.Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. There are two ways to start a new Thread – Subclass Thread and implement Runnable. There is no need for subclassing Thread when a task can be done by overriding only run() method of Runnable.

74) What is the default size of load factor in hashing based collection?

The Load factor is a measure that decides when to increase the HashMap capacity to maintain the get() and put() operation complexity of O(1). The default load factor of HashMap is 0.75f (75% of the map size).

75) What is JIT compiler?

The Just-In-Time (JIT) compiler is a component of the runtime environment that improves the performance of Java™ applications by compiling bytecodes to native machine code at run time.

76) What are the advantages of Packages in Java?

Advantages of using packages in Java:

  • Programmers can define their own packages to bundle a group of classes/interfaces, etc. 
  • It is a good practice to group related classes implemented by you so that a programmer can easily determine that the classes, interfaces, enumerations, and annotations are related. 
  • Since the package creates a new namespace there won't be any name conflicts with names in other packages.
  • Using packages, it is easier to provide access control 
  • It is also easier to locate related classes.

77) What is aggregation in Java?

Aggregation in Java is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship.The aggregate class contains a reference to another class and is said to have ownership of that class. Each class referenced is considered to be part-of the aggregate class.

78) What is object cloning?

Object cloning is a way to create an exact copy of an object. The 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.

79) What is the Executor Design pattern?

Executor Design pattern can be defined as a particular type of design pattern that serves the purpose of decoupling the execution of a task from the real task taken by the user with the help of executors. Executors are specially designed to provide factory methods.

80) What is covariant return type?

The covariant return type in java allows narrowing down the return type of the overridden method. This feature will help to avoid downcasting on the client-side. It allows the programmer to program without the need for type checking and downcasting. The covariant return type always works only for non-primitive return types.

81) What is exception propagation?

Exception propagation in Java occurs when an exception thrown from the top of the stack. When it is not caught, the exception drops down the call stack of the preceding method. If it is not caught there, it further drops down to the previous method. This continues until the method reaches the bottom of the call stack or is caught somewhere in between.

82) What is String Pool?

String Pool is a storage area in Java heap. Each time a string literal is created, the JVM checks the string literal pool first. If the string already exists in the string pool, a reference to the pooled instance returns.

83) What is Autoboxing in Java?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

84) What is a nested class?

A nested class is a class that is declared in another enclosing class. A nested class is a member and as such has the same access rights as any other member. The members of an enclosing class have no special access to members of a nested class; the usual access rules shall be obeyed.

Syntax

class OuterClass
{

    class NestedClass
    {
        ...
    }
}

85) What is jframe?

JFrame class is a type of container which inherits the java. JFrame works like the main window where components like labels, buttons, text fields are added to create a GUI. Unlike Frame, JFrame has the option to hide or close the window with the help of the setDefaultCloseOperation(int) method.

86) What is EnumSet?

An EnumSet in Java is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet.

87) What is use of gc()?

gc() is a function that is used to invoke the garbage collector and on invocation, the garbage collector will run to reclaim the unused memory space. It will attempt to free the memory that are occupied by the discarded objects.

88) List modifiers available in Java?

Access specifiers in java are the keywords which define the access scope of the function. It can be used before a class or a method. There are basically 4 types of access specifiers in java:

  • Public: – class, methods, and fields are accessible from anywhere.
  • Protected: – methods and fields are accessed from the same class to which they belong. Even from the subclass and class from the same package. Any outside class cannot access the methods and fields.
  • Default: – only from the same package, the methods and fields be accessed and not from the outside package.
  • Private: – the methods and fields can be only accessed from the same class to which they belong.

89) What are Comparable and Comparator Interfaces?

Comparable interface: It is used to order the objects of the user-defined class. This interface is found in java.lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only.

Comparator interface: This interface is used to order the objects of a user-defined class. This interface is found in java. util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

90) What is an Enum in Java?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum, use the enum keyword (instead of class or interface), and separate the constants with a comma.

Example

enum Level { LOW, MEDIUM, HIGH }

91) What is an externalizable interface?

Externalizable interface enables you to define custom rules and your own mechanism for serialization.Externalizable extends Serializable and implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.

92) What is a JAR?

A JAR is a package file format typically used to aggregate many Java class files and associated metadata and resources into one file for distribution. JAR files are archive files that include a Java-specific manifest file. They are built on the ZIP format and typically have a .jar file extension.

93) What is Nashorn in Java?

Nashorn is a JavaScript engine developed in the Java programming language by Oracle. It is based on the Da Vinci Machine and has been released with Java 8.

94) What is multi-catch block in java?

Multi-catch block in Java is a catch block that handles multiple exception types creates no duplication in the bytecode generated by the compiler, that is, the bytecode has no replication of exception handlers.

95) What is jfreechart?

JFreeChart is an open-source framework for the programming language Java, which allows the creation of a wide variety of both interactive and non-interactive charts. JFreeChart supports a number of various charts, including combined charts: X-Y charts.

96) What is a daemon thread in Java?

Daemon thread in Java is a low priority thread that runs in the background to perform tasks such as garbage collection.

97) What are annotations in Java?

Java Annotation is a tag that represents the metadata i.e. attached with class, interface, methods or fields to indicate some additional information that can be used by java compiler and JVM.

Annotations in Java are used to provide additional information, so it is an alternative option for XML and Java marker interfaces.

98) What are different types of classloaders?

Java ClassLoader is an abstract class. It belongs to a java.lang package. It loads classes from different resources. Java ClassLoader is used to load the classes at run time.

Different types of ClassLoaders in Java

  • Bootstrap Class Loader
  • Extensions Class Loader
  • System Class Loader

99) How to convert string to byte array in java?

To convert from string to byte array, use String.getBytes() method can be used. This method uses the platform’s default charset.

Example

String string = "hello world"; 
//Convert string to byte[]
byte[] bytes = string.getBytes();

100) What is maximum heap size of 32-bit and 64-bit JVM?

Memory is nothing to do with a signed or unsigned bit as there is no negative memory address. So the theoretical limit for maximum heap size on 32 bit JVM is 4GB and for 64 bit JVM its 2^64.

2 comment(s) :

  •   Reply
    img

    Janvi Jaiswal

    13th Apr, 2020
    "Great set of interview Questions and answers on Core Java for Beginners and Expert Java Programmer. Must Read.
  •   Reply
    img

    Vanga anil

    04th Sep, 2020
    "As of now ok but require more questions from collections frame work

Leave A Comment :

Valid name is required.

Valid name is required.

Valid email id is required.