Core Java interview Questions

Oct 13, 2022
100 views
152 questions

Key Features of Java

  Lambda expressions
  Methods references
  Default methods
  Functional interface
  date/time classes
  Stream classes
  Multi-release JARs
  API improvements

Java Interview Questions for Freshers

In Java, Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's properties, events, and methods. The introspection feature enables a java bean to get the properties, methods, and events of other beans at runtime.

In Java, Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's properties, events, and methods. The introspection feature enables a java bean to get the properties, methods, and events of other beans at runtime.

The thread's run() method is invoked after a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.

Autoboxing and Unboxing conversions in Java:

Autoboxing refers to the Automatic Conversions that the JAVA compiler makes primitive data types into their corresponding class object such as int to an integer etc. The compiler of the JAVA applies autoboxing whenever a primitive value is passed as a parameter to a method that expects an object of the corresponding wrapper class or is assigned to a variable of the comparable wrapper class of the program.

Unboxing is the reverse process of Autoboxing that is, conversion of an object of a wrapper type to its corresponding primitive value. The compiler of the JAVA applies unboxing when an object of a wrapper class is passed as a parameter to a method that expects a value of the corresponding primitive type or assigned to a variable of the corresponding primitive type class.

In Java, the String is Immutable because String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all other clients. The immutability guarantees Strings that their value won't change.

Difference between a Process and a Thread

Process: Program in execution is commonly referred to as a process. It consists of multiple threads. It is referred to as a task. It has its own address space.

Thread: A thread is a subset or a portion of the process. It is the smallest part of the process that can execute concurrently with other parts or threads of the process. It is commonly referred to as a lightweight process. It uses the process’s address space and shares it with the other threads of that process.

You can use two techniques to sort a List of Java Bean in Ascending Order. These techniques are as follows:

  • If you have access to your bean class and can modify the class file then by implementing Comparable interface you can perform sorting.
  • If you don't have access to your bean(bind in the jar) and still you want to sort on the specific property then by creating a custom Comparator you can achieve the same.

 

Difference between Java Arrays and Collections

Arrays are fixed in size and can hold only homogeneous elements. It doesn't have readymade or predefined methods. They can hold both primitive as well as wrapper objects. They use more memory but give better performance.

Collections are variable or dynamic in size and can hold both heterogeneous as well as homogeneous elements. They have predesigned data structures and methods. They can hold only objects. They use less memory and they are not good to use with respect to performance.

Collections class provides static methods for sorting the elements of a collection. To sort a collection in Java you can use java.util.Collections.sort() method that is present in java.util.Collections class.

A wrapper class is a kind of class whose objects wraps, encloses or contains a primitive data types like char to character, int to an integer, etc. When we have to use data types in the form of objects we have to use wrapper class. In JAVA, it is mainly an object that makes our code fully object-oriented. While we create an object to a wrapper class, it has a field where we can store primitive data types. Wrapper objects take much memory than primitive types so its beneficial to use wrapper class to get more efficiency.

The differences between Array list and vector in Java can be stated as an ArrayList is neither a legacy class nor synchronized. It is fast and increments 50% of the current array size if the number of elements exceeds its capacity. Whereas a Vector is a legacy class and synchronized. It is slow but increments 100% means double the array size if the total number of elements exceeds its capacity.

The main() method of JAVA is the entry point of any core-level program. It has to be static due to keyword static allows the main to be called without the creation of an object of the class in which the main method is defined. Here the main() method also has to be declared public so that it must be called by code outside of its class when the program has begun. The main() method of JAVA has to be void and if these conditions are not met, it will give an error. The syntax of main() method has to be strictly followed else JVM will be unable to locate it and the program will not run. If it's not declared static then JVM needs to create an instance of main class and as constructor can be overloaded and may have arguments then there would be no certain or consistent way to find it.

In Java, an access modifier specifies which classes can access a given class and its fields, constructors, and methods. It is used to set the accessibility of classes, interfaces, variables, methods, constructors, data members, and the setter methods. Access modifiers can be specified separately for a class, its constructors, fields, and methods.

You can create an immutable class in java by following the given steps:

  • Declare the class as final so it can’t be extended.
  • Make all fields private so that direct access is not allowed.
  • Don’t provide setter methods for variables.
  • Make all mutable fields final so that their value can be assigned only once.
  • Initialize all the fields via a constructor performing deep copy.
  • Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

An ATM Machine is a real-time example of Abstraction. All are performing operations on the ATM machine like cash withdrawal, money transfer, retrieve mini-statemen, etc. but we can't know internal details about ATM. Thus it provides security for the data from unauthorized methods.

In Java, the Dictionary class is an abstract parent of any class or an abstract class, which maps keys to values, such as Hashtable. Every key and every value is an object and in any one Dictionary object, every key is associated with at most one value.

No, you can not create an instance of the interface but you can make the reference of it that refers to the Object of its implementing class. An interface can extend to another interface or more than one interface.

Typecasting in JAVA refers to assigning a value of one type to a variable of another type i.e. converting a primitive or interface or class into another type. Implicit type casting is a property of JAVA where the data types are converted without losing its original meaning. It is necessary when we want to change the data types without changing the significance of the values stored inside the variable. Implicit type casting is also known as Widening casting which is an automatic conversion in JAVA. Here The two types of data types are compatible and the target type data is larger than the source data type. Here, the programmer needs not to intervene for the conversion. The JAVA compiler follows certain rules and uses the built-in library functions to convert the variables to common data type before the evaluation of the expression.

JIT (Just in time) production or just in time manufacturing is a methodology that is targeted to reduce time during the production system along with generating the response from suppliers to customers. It refers to an inventory system that supplies management strategy aligning the raw materials from suppliers to production. It also helps organizations to control variability in their workflow.

In Java, System gc and Runtime gc are two methods to request JVM to run Garbage collector.System gc is a class method whereas Runtime gc is an instance method. Generally, System gc is more convenient than Runtime gc.

The checked exceptions in JAVA are the exceptions that are checked at compile time of the program. If some code within a method throws a checked exception then it must either handle the exception or it must specify the exception by using the throws keywords or try-catch block.SQLException,IOException,ClassNotFoundException etc. are some examples.

Unchecked exceptions are the ones that are not checked at the compile time. Here the program will not give a compilation error even if we did not declare that exception. It is upon the programmer to decide the conditions in advance that cause such exceptions and handle them appropriately and carefully. They are the direct subclasses of RuntimeException class.NullPointerException,ArrayIndexOutOfBoundsException,ArithmeticException etc.Are examples of Unchecked Exceptions.

In Java, the default access modifier is also called package-private, which means that all members are visible within the same package but aren't accessible from other packages: package com.

In Java, an Iterator is an interface, not a class. An Iterator interface is used in place of Enumeration and allows the caller to remove elements from the given collection during iterating over the elements.

Garbage collector in JAVA is a program that helps in the management of memory automatically. It is referred to as a process of reclaiming the runtime unused memory in an automatic manner. The deallocation of objects in the JAVA program is handled and maintained by JAVA rather than the programmer. The dynamic allocation of objects is done by using the new operators. The object created occupies some memory and it holds it as long as there are references for the use of the object. But if there are no references to an object, it is assumed to be that it is not required, and the memory has to be reclaimed. If it doesn't happen, the memory will not left and the program will suffer memory leaks.

In Java, the transient keyword is a variables modifier used in serialization. It is used to avoid serialization that means if any object of a data structure is defined as a transient, then it will not be serialized. Serialization is the ​process of converting an object into a byte stream. When JVM comes across a transient keyword, it ignores the original value of the variable and saves the default value of that variable data type.

You can use the suspend() function to explicitly pause the execution or suspend a thread. The suspend() method of thread class puts the thread from running to waiting for state and allows a thread to temporarily cease execution.

A deadlock is a situation where a set of processes are blocked because each process is holding a resource and waiting for another resource. It is said to occur when two or more processes are waiting for each other to release a resource. You can prevent it by preventing at least one of the four required conditions that are:

Mutual Exclusion - At least one resource must be held in a non-sharable mode.

Hold and Wait - A process must be simultaneously holding at least one resource and waiting for at least one resource that is currently being held by some other process.

No preemption - Once a process is holding a resource, then that resource cannot be taken away from that process until the process voluntarily releases it.

Circular Wait - A set of processes { P0, P1, P2, . . ., PN } must exist such that every P[ i ] is waiting for P[ ( i + 1 ) % ( N + 1 ) ]. 

 

NullPointerException in Java is a RuntimeException which represents a special value that can be assigned to an object reference. This value is thrown when an application tries to use the object reference which has null value it includes the calling an instance method over the object referred by null reference. These values are modified in the instance field of the object where the reference type is array or subtype of throwable.

The removal of the elements in JAVA while transversing the collection is the main point of difference between the iterator and enumeration in JAVA. The former can remove the element during the transversal of collection due to the presence of remove() method. Iterator is the interface that is found in the java. util()package.It is useful for the transversal of Hashmap, LinkedList, TreeSet, etc. It can be done by three methods using hasNext(),next() and remove(). Enumeration is also one of the interfaces (legacy interface for transversing Vector, Hastagable) found in the java.util() package. It is useful in passing through a collection which is usually of unknown size. Its methods consist of hasMoreElements() and nextElements().

There are two ways in which a thread can be created in Java. These ways are as follows:

  • The first way to create a thread is to declare a class to be a subclass of Thread.
  • The second way to create a thread is to declare a class that implements the Runnable interface.

 

The splitting of stream or strings into meaningful independent words is termed as tokenization. It is a usual practice for tool developers. The stream tokenizer class in JAVA takes an input stream and parses it into some tokens allowing them to be read one at a time. Here, the source is a string. The process of parsing is controlled by a table and a number of flags that can be set to different states. The stream tokenizer can be used to recognize identifiers, quoted strings, numbers, and various other comment styles.

You can convert a string to long in Java by observing the given code:

public class StringToLongExample{
public static void main(String args[]){
String s="interviewmocks.com";
long l=Long.parseLong(s);
System.out.println(l);
}}

You can add nodes in Jtree by:

import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTree tree = new JTree();
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

    TreePath path = tree.getSelectionPath();
    MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();

    MutableTreeNode newNode = new DefaultMutableTreeNode("green");

    model.insertNodeInto(newNode, node, node.getChildCount());

  }
}

You can remove nodes in Jtree by:

import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTree tree = new JTree();
    DefaultTreeModel model = (DefaultTreeModel) tree.getModel();

    TreePath path = tree.getSelectionPath();
    MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();

    model.removeNodeFromParent(node);

    model.setRoot(null);

  }
}

To break out of nested loops in Java, you must put your label before the loop and you need a colon after the label as well. When you use that label after the break, control will jump outside of the labeled loop. This means if you have 10 levels of a nested loop, you can break from all of them by just calling break and label of the first loop.

You can calculate the difference between two dates in Java with the help of the following methods:

  • By using the SimpleDateFormat and Date classes

- Create an object

- Parse date

- Using getTime() method

- Use the mathematical formula

- Print result

  • By using the TimeUnit class
  • By using the Period class

 

The consecutive curly braces{} in JAVA is used to denote a double brace initialization. It is applied for the combination of two separate processes. The first brace is applied to create an anonymous inner class and the second one is used for the initialization block. Whenever we use the initialization block for an anonymous inner class it is done for the JAVA double brace initialization. The created inner class will have a reference to the enclosing outer class which can be applied using the 'this' pointer. It is used when there is no standard way of creating and initializing collection at the same time in JAVA. Advantages include less line of codes and creating as well as initializing in the same expression. The disadvantages is that it is obscure, cost an extra class every time we use it and hold a hidden reference to the enclosing instance leading to memory leaks.

In Java, we need the constructor is to initialize the object of a class while the purpose of a method is to perform a task by executing java code. Constructors cannot be abstract, final, static, and synchronized as well as Constructors do not have return types while methods do.

There are five different ways in which you can create an object in Java:

Java new Operator - While we create an object it occupies space in the heap.

Java Class.newInstance() method - It returns the newly created instance of the class.

Java newInstance() method of constructor - The method returns a new object created by calling the constructor.

Java Object.clone() method -  It returns clone of this instance. 

Java Object Serialization and Deserialization -  It does not use any constructor to create an object.

 

In Java, to create a custom class loader, we will create a class that will extend ClassLoader. After this, the method findClass() is overridden. Now, Create a method that will load your given class from the classpath.

Difference between ArrayList and Vector:

Array list - It is not synchronized and increments almost half of the current arise if the number in any elements exceeds the capacity. Array list does not represent 'not a legacy' class which is introduced in JDK 1.2

Vector list - It is synchronized and increments completely double the array size of the total number of elements exceeding the capacity. It is a legacy class and it is also slow as it synchronizes.

You can give a name to a thread by using the setName() method of the Thread class. You can also retrieve the name of a thread using the getName() method of a Thread class. These two methods are public and final.

Yes, there is a slight difference between a=a+b and a+=b in Java. The main difference is the accuracy of the calculation, of course -=, *=, /=, %= is also a truth. It needs to be clear that the "+=" operator is an operator in Java, not two.

Raw types refer to using a generic type or interface without the specification of type parameters or arguments in JAVA. It can be a reference type that is formed by taking the name of a generic type declaration without including the type argument list. It can also be a no static member type of a raw type R which is not inherited from a super interface or superclass of R. Necessarily they behave just like they were before generics were introduced in JAVA. It is used only for the concession to the compatibility of legacy codes. Migration compatibility is the only reason to use them.

With the help of the File exists() method you can check if a file exists or not in Java. It determines whether the is a file or directory denoted by the abstract filename exists or not. The function returns true if the abstract file path exists or else returns false. Syntax - file.exists()

You can print nodes of a Binary tree in Java by following the steps mentioned below:

  • Create a Stack and push the root node.
  • Loop until Stack is not empty.
  • Call Stack.pop() to get the last element and store its left and right child if they are not null.
  • if both left and right child of the last node is null then it's a leaf node, print its value.

 

Inner class in JAVA denotes that there is one class that is a member of another class. It is also referred to as the Nested class as it is completely declared within the body of another class or interface. It is not like a subclass. We use them to logically group interfaces or group classes in a single place in order to make it more readable and maintainable. It provides a facility to access all the members of outer class which consists of private data members and methods. It requires fewer lines of code makes it more beneficial to use. They can be declared public, private, protected or with default access. It leads to encapsulation.

In Java sizeof() is a function that returns how much memory a particular data type takes and this method does exactly that. ​x. /** 2. * Java Program to print size of primitive data types e.g. byte, int, short, double, float.

The term Connection pooling means that connections are reused rather than created each time a connection is requested. To facilitate connection reuse, a memory cache of database connections, called a connection pool, is maintained by a connection pooling module as a layer on top of any standard JDBC driver product.

The default initialized value of a String in Java is initialized with null. It means that the null value is the default value for a string in Java.

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

The difference between sleep and suspend can be determined as sleep() is a static method that is used to send the calling thread into a non-runnable state for the given duration of time. Whereas suspend() method has been deprecated, as it is inherently deadlock-prone. It suspends the thread on which it is invoked. If the target thread holds a lock on the monitor protecting a critical system resource when it is suspended, no thread can access this resource until the target thread is resumed.

JAR is basically known as the Java Archive. Basically, this contains certain class associated files in a compressed manner. It contains different codes, images and metadata, and other resources. These files can be used or supplied during the Java programming platform. This file format is almost similar to the Tape archive (TAR) file format which was used in Unix. These files can be really referred for their security abilities and these files can be used as the building blocks in the Java application.

In Java, the super keyword is used as a reference variable that is used to refer super class or parent class objects. You can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields. The most common use of the super keyword is to eliminate the confusion between superclasses and subclasses that have methods with the same name.

They really perform an important operation in loading the class files into the Java Virtual Machine. What happens here is that there is a Java runtime and at that point in time they just have no idea about the files and their systems because of the presence of the classloaders. So the classes in Java are not mounted all at once into the memory. But when required in an application at that point in time it the JRE gives the command to the classloaders that mount the class into the memory.

Final - Final is a keyword that is used to apply restrictions on class, method, and variable.

Finally - Finally is a block that is used to place important code, it will be executed whether an exception is handled or not.

Finalize - Finalize is a method that is used to perform clean-up processing just before an object is a garbage collected.

In Java, an Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. The externalizable interface is not a marker interface and thus it defines two methods writeExternal() and readExternal().Externalizable interface contains two methods: writeExternal() and readExternal().

Difference between JVM and JRE

JVM stands for JAVA Virtual Machine which is an abstract machine. It is used to provide a runtime environment where java bytecode can be executed. They are available for many software and hardware platforms. It creates five similar runtime areas for the execution of class members. The Java compiler generates the bytecode which is in JVM understandable format. It is the heart of the Java programming language and is used for providing an independent environment. It is an essential part of JRE and JDKas it is inbuilt in both of them.

JRE stands for Java Runtime Environment and is useful for providing a runtime environment. It is for the implementation of JVM It consists of a set of libraries and other files that JVM uses at runtime. It can also be denoted by Java RTE. It gives information about the minimum requirements for the execution of a Java application. It is only used by the end-users of the systems.

To interrupt a thread explicitly you can use the interrupt() method. A thread can send an interrupt by invoking an interrupt on the Thread object for the thread to be interrupted therefore if any thread is in a sleeping or waiting for state then using the interrupt() method, we can interrupt the execution of that thread by showing InterruptedException.

DTO - DTO stands for Data transfer objects that can be spread between different layers of the software architecture.

VO - VO stands for Value Object that contains an object, such as Integer, Money, etc.

POJO - POJO stands for Plain Old Java Object, which is an ordinary Java object, not bound by any special restriction.

JavaBeans - JavaBeans are classes that encapsulate many objects into a single object known as a bean. It is a platform-independent component that allows us to reuse the class object in our Java code.

JNDI stands for Java Naming and Directory Interface which is an API that enables JMS clients to look up configured JMS objects. By delegating all the provider-specific work to administrative tasks for creating and configuring these objects, the clients can be completely portable between environments.

The types of data passing mechanisms are as follows:

  • Call-by-value.
  • Call-by-reference.
  • Call-by-copy-restore.

You can implement RMI in Java with the help of the steps mentioned below:

  • Create the remote interface.
  • Provide the implementation of the remote interface.
  • Compile the implementation class and create the stub and skeleton objects using the rmic tool.
  • Start the registry service with rmiregistry tool.
  • Create and start the remote application.
  • Create and start the client application.

Semaphore is used for signaling from one task to another. It is basically an abstract data type used to control access to a common resource by multiple processes and avoid critical section problems in a concurrent system for process synchronization. A Semaphore in Java controls access to a shared resource through a counter.

The difference between core Java and Java EE can be stated as Core Java is used for developing a desktop-based application. It is basically a programming language used to develop general java applications. Whereas The Java EE platform is built on top of the SE platform, used especially for large-scale applications. Java EE is a computing platform that consists of core java with a powerful set of libraries that provides an API and runtime environment for developing and running large-scale applications which are used for Enterprise development.

In Java, Runnable is an interface that is to be implemented by a class whose instances are intended to be executed by a thread. It is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread. This can be done by overriding only the run() method.

In Java, the Thread Deadlock is a situation that occurs where two or more threads are blocked forever, waiting for each other. Deadlock occurs when multiple threads need the same locks but obtain them in a different order. it can be resolved by taking the following measures:

  • Avoid Unnecessary Locks
  • Avoid Nested Locks
  • Using Thread.join() Method
  • Use Lock Ordering
  • Lock Time-out

The difference between a StringBuffer and String in Java can be stated as the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read-only and immutable. Whereas the StringBuffer class is used to represent characters that can be modified. A StringBuffer class is a thread-safe, mutable sequence of characters.

The differences between C++ and Java can be stated as C++ is derived from C and has the features of both procedural and object-oriented programming languages. C++ was designed for application and System development. Whereas Java is built upon a virtual machine that is very secure and highly portable in nature. It is grouped with a comprehensive library to provide support for the abstraction of the existing platform.

The difference between the Abstract class and Final class in JAVA can be stated as the abstract class is a class with abstract and non-abstract methods and allows accomplishing abstraction. The only way to use an abstract method is by overriding it. Whereas the final class is a class that restricts the other classes from accessing its data and methods. The final method is regarded as complete and can't be overridden.

Java doesn't support multiple inheritance because it leads to a deadly diamond problem.Java doesn't allow multiple inheritance to avoid the ambiguity caused by it. But if you still want to implement it in JAVA then you can do it with the help of interfaces.

You can design and implement a garbage collector by following the given steps:

  • Make sure you can collate the global roots. These are the local and global variables that contain references into the heap. For local variables, push them onto a shadow stack for the duration of their scope.
  • Make sure you can traverse the heap, e.g. every value in the heap is an object that implements a Visit method that returns all of the references from that object.
  • Keep the set of all allocated values.
  • Allocate by calling malloc and inserting the pointer into the set of all allocated values.
  • When the total size of all allocated values exceeds a quota, kick off the mark and then sweep phases. This recursively traverses the heap accumulating the set of all reachable values.
  • The set difference of the allocated values minus the reachable values is the set of unreachable values. Iterate over them calling free and removing them from the set of allocated values.
  • Set the quota to twice the total size of all allocated values.

 

No, Java does not support pointers in order to make it more secure because the pointers point to a memory location or are used for memory management that loses the security as we use them directly. It can create a security issue as if anyone gets the address of any variable then they could access it anywhere from the program without any restriction even variable is private.

In Java, multithreading can be implemented with the help of the following steps:

  • Thread creation by extending the Thread class. We create a class that extends java. lang. Thread class. 
  • Thread creation by implementing the Runnable Interface. We create a new class that implements java. lang. Runnable interface and override run() method. 
  • Thread Class vs Runnable Interface.

 

JRE stands for Java Runtime Environment, which is a software bundle that allows Java programs to run. JRE contains class libraries and other supporting files. Whereas JVM stands for Java Virtual Machine which is an environment for executing bytecode. It is an abstract computing machine with its own instruction set and manipulates various memory areas at runtime.

Call by value - It is a parameter passing method in which the values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. Therefore any changes made inside functions are not reflected in actual parameters of the caller.

Call by reference - It is a parameter passing method in which both the actual and formal parameters refer to the same locations, so any changes made inside the function are actually reflected in actual parameters of the caller.

Final - Final is a keyword that is used to apply restrictions on class, method, and variable.

Finally - Finally is a block that is used to place important code, it will be executed whether an exception is handled or not.

Finalize - Finalize is a method that is used to perform clean-up processing just before an object is garbage collected.

JDK stands for Java Development Kit which is basically a software development kit that provides a development environment for building applications, applets, and components using the Java programming language. Whereas JVM stands for Java Virtual Machine which is an environment for executing bytecode. It is an abstract computing machine with its own instruction set and manipulates various memory areas at runtime.

Overloading - It is a method used in JAVA to increase the readability of the program. It occurs when two or more methods in one class have the same method name but different parameters. It is an example of compile time polymorphism.

Overriding - It is a method used in JAVA to provide the specific implementation of the method that is already provided by its super class. It occurs when two methods have the same method name and parameters. One of the methods is in the parent class, and the other is in the child class. It is an example of run time polymorphism.

ENUM in Java is used to classify a certain set of values in just one word. It is and should only be done when you know that the set of variables will not be changed and it has a known exact value (days, months, a deck of cards). At that point in time, you can use the Enumerations or Enum. Like for example, you have certain names like the Blue, orange, red, green; here you can simply use the Enum as Colours.

In Java, instanceof is a keyword that is used for checking if a reference variable is containing a given type of object reference or not. It is a binary operator used to test if an object is a subtype of a given Type and returns either true or false.

Final is a keyword that is used to apply restrictions on class, method, and variable. Therefore when a method is declared with the final keyword, it is called a final method. Once a final method is declared it cannot be overridden.

A blank final variable is a local variable or a final variable in Java that is not initialized during declaration. If you want to create a variable that is initialized at the time of creating an object and once initialized may not be changed, it is useful.

In java, the transient variable is a variables modifier used in serialization. It is used to indicate that a field should not be part of the serialization process. The modifier Transient can be applied to member variables of a class to turn off serialization on these member variables.

When a thread blocks on I/O, it enters into the waiting state.

"%" operator is used as an Arithmetic operator known as modulo in JAVA. It is used to find the modulus or remainder of the given variable.

In Java, immutable classes define objects which, once created, never change their value. It can be only changed by re-assigning to that variable. Immutable classes make concurrent programming easier and also make sure that values are not changed in the middle of an operation without using synchronized.

The difference between HashMap and HashTable can be stated as HashMap is non-synchronized and can’t be shared between many threads without a proper synchronization code. It allows one null key and multiple null values and it is generally preferred if thread synchronization is not needed. Whereas Hashtable is synchronized, thread-safe, and can be shared with many threads. It doesn’t allow any null key or value.

In Java, the intern() method is used for getting the string from the memory as it returns a canonical representation for the string object. It ensures that all the same strings share the same memory therefore while executing it checks whether the String equals to this String Object or not.

JCA stands for Java EE Connector Architecture and J2EE Connector Architecture, which is a Java-based tool for connecting application servers by connecting enterprise information systems. This interface can be used with minor changes to communicate with any enterprise information system.

JPA stands for Java Persistence API, which is the standard API for persistence and object/relational mapping for the Java EE platform, provides several advantages to Java developers for data-binding purposes.It is used to persist data between Java object and relational database.

In JAVA, OutOfMemoryError is an exception that is typically thrown because the amount of live data barely fits into the Java heap having little free space for new allocations. You can solve OutOfMemoryError by increasing the maximum heap size with the help of JVM options -Xmx512M, this will immediately solve the OutOfMemoryError problem.

The maximum Heap Size of 32 bit JVM is 2^32 bit i.e. 4 GB whereas for 64-bit JVM is 2^64 bit i.e. 16 Exabytes in Windows and Linux operating systems.

The difference between JDBC and JNDI can be stated as JDBC stands for Java Database Connectivity API which is consists of a set of classes and interfaces that Java application developers use to access the database and execute SQL statements.JDBC is used to connect to the database and execute SQL statements. Whereas JNDI stands for Java Naming and Directory Interface API which is a unique identifier for all resources managed by the current application server, including Databases, web pages, files, connection pools, etc. It provides a unified way to find and access services on the network.

The JAVA_HOME environment variable is an operating system that can optionally be set after either the Java Development Kit - JDK or the Java Runtime Environment - JRE is installed. The main purpose of the JAVA_HOME environment variable is to point to where Java is installed.

Yes, we can override the toString() method for Enum as the toString() method of Enum class returns the name of this enum constant, as the declaration contains.

In Java, the ordinal() method belongs to the Enum class that returns the order of an enum instance. It represents the sequence in the enum declaration, where the initial constant is assigned an ordinal of '0'. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.

To convert a String to Enum in Java, you can simply use the static method Enum. It can be done by using Enum.valueOf() method.

No, it is not possible to have multiple public classes in Java. As if you have more than one public class in a single file a compile-time error will be generated.

 The difference between notify and notify All methods can be stated as:

  • notify() method is used if all your waiting threads are interchangeable or if you only ever have one waiting thread. In this method, the notification is sent to a single thread among the multiple waiting threads so it is sure that which of those waiting threads is going to receive the lock.
  • notifyAll() method is used for other cases where the waiting threads may have different purposes and should be able to run concurrently. In this method, the notification is sent to all waiting threads instead of a single thread.

In Java, the Iterator interface is an interface that allows us to access elements of the collection and is used to iterate over the elements in the collection such as Map, List, or Set. The main purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container.

Null interface and marker interface are same i.e. null interface is another name for marker interface which is basically empty, means without any method declarations. In Java, the null interface is an interface that has no methods or constants inside it and provides run-time type information about objects, so the compiler and JVM have additional information about the object.

In Java, a jagged array is an array of arrays such that member arrays can be of different sizes and therefore sometimes it is called an array of arrays. They used to store rows of data of varying lengths to improve performance when working with multi-dimensional arrays.

In Java, the Runtime class allows the application to interface with the environment in which the application is running. Runtime class is used to interact with the java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory, etc. There is only one instance of java.

Yes, we can cast double to a byte in Java with the help of a cast operator. But we can't convert it implicitly as double is a higher data type compared to byte.

The advantage of thread yielding is that using the yield() method you can get a chance to execute other waiting threads so if our current thread takes more time to execute and allocate processor to other threads.

In Java, a collections API is a unified framework for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. The Java Collections API provides a set of classes and interfaces that makes it easier to work with collections of objects, e.g. lists, maps, stacks, etc.

In Java, the Vector class implements a growable array of objects that can be accessed using an integer index. One of its main advantages is that the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.

An Anonymous Class is an inner class without a name and for which only a single object is created such that it can be used while making an instance of an object with certain extras such as overloading methods of a class or interface, without having to actually subclass a class.

Preemptive scheduling allocates the task in such a way that the CPU is allocated to the processes for a specific time period. It is used when a process switches from running state to ready state or from waiting for the state to ready state.

JDK stands for Java Development Kit which is basically a software development kit that provides a development environment for building applications, applets, and components using the Java programming language.

JRE stands for Java Runtime Environment, which is a software bundle that allows Java programs to run. JRE contains class libraries and other supporting files.

JVM stands for Java Virtual Machine which is an environment for executing bytecode. It is an abstract computing machine with its own instruction set and manipulates various memory areas at runtime.

There are five types of memory areas that are allocated by JVM. These areas are as follows:

  • Class Area or Method Area 
  • Heap
  • Stack
  • Program Counter Register
  • Native Method Stack.

JIT or Just-In-Time compiler is a compiler that helps in improving the performance of Java programs by compiling bytecodes into native machine code at run time. It is a part of the Java Runtime Environment that compiles bytecodes into native machine codes at run time. It is also known for run-time compilations.

In Java, Write once, run anywhere or WORA is used to refer to the Ability of JAVA applications that are developed on one system but can be deployed and run on other systems. It simply states that we can write our code in one platform once and we can run the code anywhere.

The answer to this question i.e. "If I do not provide any arguments on the command line, then the String array of main() method will be empty or null" is empty.

In Java, there is no default value for local variables i.e. local variables are not initialized to any default values, therefore the local variables should be declared and an initial value should be assigned before using it.

In Java, the initial or default value of an object reference which is defined as an instance variable defers according to their types. For numbers, the default value is 0, for Booleans it is false, and for object references it is null.

In Java, a constructor is a method that is called when an instance of an object is created or initialized. The main purpose of a constructor in Java is to initialize the newly created object before it is used.

The Rules to define a constructor are as follows:

  • A constructor must have the same name as that of the Class. 
  • Constructors cannot be marked static. 
  • A constructor cannot be marked abstract. 
  • A Constructor cannot be overridden. 
  • A Constructor cannot be final.

 

In java, a default constructor refers to a constructor that is automatically generated by the compiler such that it can initialize any uninitialized instance variables with default values if no constructors have been defined for the class. It has no parameters, or if it has parameters, all the parameters have default values.

No, Constructors are not inherited as in subclasses it has a different name.

No, you can not make a constructor final in JAVA and it is actually one of the important properties of a java constructor is that it can not be final.

In Java, Static variables are the variables that are stored in the static memory. Static variables are created when the program starts and destroyed when the program stops and can be used to refer to the common property of all objects.

In Java, Static variables can be used to refer to the common property of all objects. It can be used with variables, methods, blocks, and nested classes. It is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

A static block is a set of instructions that are run only once when a class is loaded into memory. This block gets executed when the class is loaded in the memory.

Yes, we can execute a program without a main() method. It can be executed with the help of a static block but after its execution, you will get an error saying no main method found.

The difference between the static (class) method and the instance method can be stated as the Instance method is a method that requires an object of its class to be created before it can be called. You have to create an object to access the instance variable or method. Whereas Static methods are the methods in Java that can be called without creating an object of the class.

Method overloading is a method used in JAVA to increase the readability of the program. It occurs when two or more methods in one class have the same method name but different parameters. It is an example of compile-time polymorphism.

In Java,"this" is a keyword that refers to the current object in a method or constructor. It is used to eliminate the confusion between class attributes and parameters with the same name.

In java, Inheritance is an important concept of OOPs. It is a mechanism that acquires the properties from one class to another class. It can be explained as like a child inherits the traits of their parents, with inheritance, we can reuse the fields and methods of the existing class.

Java doesn't support multiple inheritance because it leads to a deadly diamond problem.Java doesn't allow multiple inheritance to avoid the ambiguity caused by it. But if you still want to implement it in JAVA then you can do it with the help of interfaces.

In Java, the composition is a concept in object-oriented programming. It describes a class that references one or more objects of other classes in instance variables. It allows us to reuse the code.

In Java, object cloning refers to the creation of an exact copy of an object. By using the clone() method of the Object class you can create a new instance of the class of the current object and initializes all its fields with exactly the contents of the corresponding fields of this object.

No, we can not override the static methods as the static methods are bonded at compile time using static binding therefore we cannot override static methods in Java.

Method Overloading - It is a method used in JAVA to increase the readability of the program. It occurs when two or more methods in one class have the same method name but different parameters. It is an example of compile-time polymorphism.

Method Overriding - It is a method used in JAVA to provide the specific implementation of the method that is already provided by its superclass. It occurs when two methods have the same method name and parameters. One of the methods is in the parent class, and the other is in the child class. It is an example of run time polymorphism.

Exception Handling is a method that refers to the way that a program handles exceptional circumstances. It ensures that the continuity of the program doesn't break when an exception occurs. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.

The final variable is the variable in which the value cannot change after it has been initialized. A Java method with the final keyword is called a final method and it can not be overridden in the subclass. Whereas the final methods are the methods that cannot be overridden by subclasses.

In Java, the term polymorphism is the method in an object-oriented programming language that states the ability of a programming language to present the same interface for several different underlying data types.

Run-Time Polymorphism can be defined as whenever an object is bound with the functionality at run time, this is known as runtime polymorphism. It can be achieved by method overriding where a subclass overrides a method with the same signature as that of in its superclass.

Dynamic binding is also known as late binding the method to invoke at runtime instead of at compile time. It is the mechanism a computer program waits until runtime to bind the name of a method called to an actual subroutine.

Abstraction is a concept of OOPs that is used for hiding the important parts of a program. In java, abstraction is achieved by interfaces and abstract classes and it is used to show only functionality to the user.

Abstraction is a concept of OOPs that is used for hiding the important parts of a program. In java, abstraction is achieved by interfaces and abstract classes and it is used to show only functionality to the user. Whereas the Encapsulation can be implemented using by access modifier i.e. private, protected, and public. It hides the code and data into a single entity or unit so that the data can be protected from the outside world.

The difference between Checked Exception and Unchecked Exception can be stated as Checked Exceptions are checked at runtime of the program whereas the Unchecked Exceptions are checked at the compile time of the program.

In Java, an exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, when an exception happens, Propagation is a process in which the exception is being dropped from to the top to the bottom of the stack.

Nested Classes in Java states that a class can be defined within another class and will enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and creates more readable and maintainable code.

The purpose of the toString() method in java is to return the value given to it in string format. Therefore whenever on any object this method is applied, will then be returned as a string object.

In Java, garbage collection is the process by which Java programs perform automatic memory management. It is basically a task to automatically determine what memory is no longer being used by a Java application and to recycle this memory for other uses.

In java, Finalize() method is a method that is used to perform clean-up processing just before an object is a garbage collected.

Final - Final is a keyword that is used to apply restrictions on class, method, and variable.

Finally - Finally is a block that is used to place important code, it will be executed whether an exception is handled or not.

Finalize - Finalize is a method that is used to perform clean-up processing just before an object is garbage collected.

In Java, a stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.

In Java, Serialization is a mechanism of converting the state of an object into a byte stream. It allows us to convert an Object to a stream that we can send over the network or save it as a file or store it in DB for later usage.

In Java, the Socket class is a class that represents client sockets and is a communication channel between two TCP communications ports belonging to one or two machines.

A thread is a subset or a portion of the process. It is the smallest part of the process that can execute concurrently with other parts or threads of the process. It is commonly referred to as a lightweight process. It uses the process’s address space and shares it with the other threads of that process.

A collection is an object that represents a group of objects in Java whereas a collections framework in java is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.

Pass by Value - In Pass by Value, the parameter value copies to another variable. It means that the value of a variable is passed to the function.

Pass by Reference - In Pass by Reference, the actual parameter passes to the function. It means that the memory address of the variable is passed to the function.

Share this post