Java Interview Questions 1

¡Supera tus tareas y exámenes ahora con Quizwiz!

What are the differences between interfaces and abstract classes?

- Abstract class can have both abstract and concrete methods but interface can only have abstract methods (Java 8 onward, it can have default and static methods as well); - Abstract class methods can have access modifiers other than public but interface methods are implicitly public and abstract; - Abstract class can have final, non-final, static and non-static variables but interface variables are only static and final; - A subclass can extend only one abstract class but it can implement multiple interfaces; - An Abstract class can extend one other class and can implement multiple interfaces but an interface can only extend other interfaces, which means an interface cannot extend an abstract class.

Difference between Comparable and Comparator?

- Comparable interface can be used to provide single way of sorng whereas Comparator interface is used to provide mulple ways of sorng - Comparable interface is present in 'java.lang' package whereas Comparator interface is present in 'java.ul' package - For using Comparable, the class needs to implement Comparable interface whereas for using Comparator, there is no need to make changes in the class - Comparable provides compareTo() method to sort elements, whereas Comparator provides compare() method to sort elements - We can sort the list elements of Comparable type by using Collecons.sort(listObj) method, whereas to sort the list elements of Comparator type, we have to provide a Comparator object like, Collecons.sort(listObj, Comparator) At mes, when you are using any third-party classes or the classes where you are not the author of the class, then in that case Comparator is the only choice to sort those objects

Difference between Serializable and Externalizable

- Serializable is a marker interface which means it does not contain any method whereas Externalizable is a child interface of Serializable and it contains two methods writeExternal() and readExternal() - When using Serializable, JVM takes full responsibility for serializing the class object but in case of Externalizable, the programmer has full control over serializaon logic - Serializable interface is a beer fit when we want to serialize the enre object whereas Externalizable is beer suited for custom serializaon - Default serializaon is easy to implement but it comes with some issues and performance cost whereas in case of Externalizable, the programmer has to provide the complete serializaon logic which is a lile hard but results in beer performance - Default serializaon does not call any constructor whereas a public no-arg constructor is needed when using Externalizable interface - When a class implements Serializable interface, it gets ed with default serializaon which can easily break if structure of the class changes like adding/removing any variable whereas using Externalizable, you can create your own binary format for your object

Explain System.out.println() statement

- System is a class in java.lang package - out is a stac member of System class and is an instance of java.io.PrintStream - println() is a method of PrintStream class

Which one to choose, an interface or an abstract class?

- When you want to provide default implementation to some of the common methods that can be used directly by the subclasses then you can use abstract class because it can have concrete methods also, this is not the case with Interface because the child classes that are implementing this interface will have to provide implementation for all the methods that are declared in the interface; - If your contract keeps on changing then Interface will create problems because then you will have to provide implementation of those new methods in all the implementing classes, whereas with abstract class you can provide one default implementation to the new methods and only change those implementing classes that are actually going to use these new methods

What is init block?

- init block is used to initialize the instance data members - init block runs each time when object of the class is created - init block runs in the order they appear in the program - compiler replaces the init block in each constructor after the super() statement - init block is different from static block which runs at the time of class loading

Can the static methods be overridden?

-No! Declaration of static methods having the same signature can be done in the subclass but run time polymorphism can not take place in such cases. -Overriding or dynamic polymorphism occurs during the runtime, but the static methods are loaded and looked up at the compile time statically. Hence, these methods cant be overridden.

What is the ASCII value of null?

0x00

What are the three principles of class loader?

1. Delegaon principle: It forwards the request for class loading to its parent class loader. It only loads the class if the parent does not find or load the class. 2. Visibility principle: According to Visibility principle, the child ClassLoader can see all the classes loaded by parent ClassLoader. But the parent class loader cannot see classes loaded by the child class loader. 3. Uniqueness principle: According to this principle, a class loaded by Parent should not be loaded by Child ClassLoader again. It is achieved by delegaon principle.

What are local inner classes in Java?

A class i.e., created inside a method, is called local inner class in java. Local Inner Classes are the inner classes that are defined inside a block.

What is an abstract class?

A class that is declared using "abstract" keyword is known as abstract class. It can have abstract methods (methods without body) as well as concrete methods (methods with body).

What is a constant and how we create constants in Java?

A constant is a variable whose value cannot change once it has been assigned. To make any variable a constant, we can use 'stac' and 'final' modifier like below: public stac final TYPE NAME_OF_CONSTANT_VARIABLE = VALUE; We can also use "enum" to define constants.

Is a finally block executed when an exception is thrown from a try block that does not have a catch block, and if so, when?

A finally block is executed even if an exception is thrown or propagated to the calling code block.

What is a patch file?

A patch file is a text file that consists of a list of differences between the original file and the modified file. It is the best and easiest way to share changes to a document with friends and colleagues, without having to send repetitive information.

What is Abstraction in OOP?

Abstraction is a process of hiding the implementation details and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.

What makes a HashSet different from a TreeSet?

Although both HashSet and TreeSet are not synchronized and ensure that duplicates are not present, there are certain properties that distinguish a HashSet from a TreeSet. Implementation: For a HashSet, the hash table is utilized for storing the elements in an unordered manner. However, TreeSet makes use of the red-black tree to store the elements in a sorted manner. Complexity/ Performance: For adding, retrieving, and deleting elements, the time amortized complexity is O(1) for a HashSet. The time complexity for performing the same operations is a bit higher for TreeSet and is equal to O(log n). Overall, the performance of HashSet is faster in comparison to TreeSet. Methods: hashCode() and equals() are the methods utilized by HashSet for making comparisons between the objects. Conversely, compareTo() and compare() methods are utilized by TreeSet to facilitate object comparisons. Objects type: Heterogeneous and null objects can be stored with the help of HashSet. In the case of a TreeSet, runtime exception occurs while inserting heterogeneous objects or null objects

What is an algorithm?

An algorithm is a set of instructions for accomplishing a task.

What is exception and exception handling?

An exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime, so exception handling is a mechanism by which normal flow of the program is maintained.

Why interface is used?

An interface is designed to achieve full abstraction. It specifies what a class does, but it doesn't know how to do it.

What is String Pool?

As the name suggests, String Pool in java is a pool of Strings stored in Java Heap Memory. We know that String is a special class in java and we can create String objects using a new operator as well as providing values in double-quotes.

What does the equals() method of String class do?

As we know, Object class is the parent of all classes, and Object class has a equals() method that compares the reference of two objects, but String class has overridden this method, and String class's equals() method compares the contents of two strings.

How to make a class Immutable?

As we know, String is an Immutable class in Java, i.e. once inialized its value never change. We can also make our own custom Immutable class, where the class object's state will not change once it is inialized. Benefits of Immutable class: - Thread-safe: With immutable classes, we don't have to worry about the thread-safety in case of mul-threaded environment as these classes are inherently thread-safe - Cacheable: An immutable class is good for Caching because while we don't have to worry about the value changes How to create an Immutable class in java: - Declare the class as final so that it cannot be extended - Make all fields as private so that direct access to them is not allowed - Make all fields as final so that its value can be assigned only once - Don't provide 'seer' methods for variables - When the class contains a mutable object reference, 1. While inializing the field in constructor, perform a deep copy 2. While returning the object from its geer method, make sure to return a copy rather than the actual object reference

What is association in Java?

Association, in general terms, refers to the relationship between any two entities. Association in java is the relationship that can be established between any two classes. (one-to-one, many-to-many, etc.)

What does batch processing stand for?

Batch processing is the process by which a computer completes batches of jobs, often simultaneously, in non-stop, sequential order. It's also a command that ensures large jobs are computed in small parts for efficiency during the debugging process

What is Comparable and Comparator?

Both Comparable and Comparator interfaces are used to sort the collecon of objects. These interfaces should be implemented by your custom classes, if you want to use Arrays/Collecons class sorng methods. Comparable interface has compareTo(Obj) method, you can override this method in your class, and you can write your own logic to sort the collecon. General rule to sort a collecon of objects is: If 'this' object is less than passed object, return negave integer. If 'this' object is greater than passed object, return posive integer. If 'this' object is equal to the passed object, return zero.

What are the differences between StringBuffer and StringBuilder?

Both StringBuffer and StringBuilder classes are used for String manipulation. These are mutable objects. But StringBuffer provides threadsafety as all its methods are synchronized, this makes performance of StringBuffer slower as compared to StringBuilder. StringBuffer class is present from Java 1.0, but due to its slower performance, StringBuilder class was introduced in Java 1.5. If you are in a single-threaded environment or don't care about thread safety, you should use StringBuilder. Otherwise, use StringBuffer for thread-safe operations.

How to create a thread in Java?

By extending Thread class. By implementing Runnable interface.

What are the different types of exceptions?

Checked exceptions: All exceptions other than RunTimeException and Error are known as Checked Exceptions. These exceptions are checked by the compiler at the compile time itself. E.g. When you are trying to read from a file, then compiler forces us to handle the FileNotFoundException because it is possible that the file may not be present. Unchecked exceptions: Runtime Exceptions are known as Unchecked exceptions. Compiler doesn't force us to handle this type of exceptions, rather we developers should handle them logically by ourselves.

Explain Class loaders in Java

ClassLoader is a java class which is used to load .class files in memory. When we compile a java class, JVM creates a bytecode which is plaorm independent. The bytecode is present in .class file. When we try to use a class, then classloader loads it into memory. There are 3 types of built-in class loaders in java: 1. Bootstrap class loader : it loads JDK class files from jre/lib/rt.jar and other core classes. It is the parent of all class loaders, it is also called Primordial classloader. 2. Extensions class loader : it loads classes from JDK extensions directory, it delegates class loading request to its parent, Bootstrap and if the loading of class is unsuccessful, it loads classes from jre/lib/ext directory or any other directory pointed by java.ext.dirs system property. 3. System class loader : It loads applicaon specific classes from the CLASSPATH. We can set classpath while invoking the program using -cp or classpath command line opons. It is a child of Extension ClassLoader.

What is Cloneable?

Cloneable is an interface in Java which needs to be implemented by a class to allow its objects to be cloned. A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-forfield copy of instances of that class. If you try to Clone an object which doesn't implement the Cloneable interface, it will throw CloneNotSupportedExcepon.

Why Java 8 has introduced static methods?

Consider an example where you want to define a utility class, what you usually do is you define a class which contains static methods and then you call these methods using class name. Now, Java 8 onward you can do the same thing using an Interface by giving only static methods inside your interface. This way of using Interface for defining utility classes is better as it helps in performance also, because using a class is more expensive operation than using an interface.

What is called first, constructor or init block?

Constructor is invoked first. Compiler copies all the code of instance inializer block into the constructor aer first statement super().

Define Copy constructor in java.

Copy Constructor is the constructor used when we want to initialize the value to the new object from the old object of the same class.

Explain enum

ENUM in java is a data type which contains a fixed set of constants. In ENUM, we can also add variables, methods and constructors. Some common examples of enums are: days of week, colors, excel report columns etc. Some points to remember: - enum constants are stac and final implicitly - enum improves type safety - enum can be declared inside or outside of a class - enum can have fields, constructors (private) and methods - enum cannot extend any class because it already extends Enum class implicitly but it can implement many interfaces - We can use enum in switch statement - We can have main() method inside an enum - enum has values(), ordinal() and valueOf() methods. values() return an array containing all values present inside enum, ordinal() method returns the index of given enum value and valueOf() method returns the value of given constant enum - enum can be traversed - enum can have abstract methods - enum cannot be instanated because it contains private constructor only - The constructor is executed for each enum constant at the me of enum class loading - While defining enum, constants should be declared first, prior to any fields or methods, or else compile me error will come

What is the difference between errors and exceptions?

Errors in a program are irrecoverable, they indicate that something severe has gone wrong in the applicaon and the program gets terminated in case of error occurrence e.g. running out of memory: OutOfMemoryError , making too many recursive calls: StackOverflowError etc. Exceptions on the other hand are something that we can recover from by handling them properly e.g.: trying to access a property/method from a null object: NullPointerException, dividing an integer by zero: ArithmeticException etc.

What is Encapsulation in OOP?

Formally, encapsulation is simply combining data and behavior in one package and hiding the implementation details from the users of the object. The bits of data in an object are called its instance fields, and the procedures that operate on the data are called its methods. A specific object that is an instance of a class will have specific values of its instance fields. The set of those values is the current state of the object. Whenever you invoke a method on an object, its state may change. Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. Benefits of Encapsulation The fields of a class can be made read-only or write-only. A class can have total control over what is stored in its fields.

What does full-duplex mean?

Full-duplex data transmission means that data can be transmitted in both directions on a signal carrier at the same time.

What does half-duplex mean?

Half-duplex data transmission means that data can be transmitted in both directions on a signal carrier, but not at the same time.

Exception handling and method overriding

If the parent class method does not declare an exception then child class overridden method cannot declare checked exceptions but it can declare unchecked exceptions - If the parent class method declares an exception, then child class overridden method - can declare no exception - can declare same exception - can declare a narrower exception (more broader exception declaration than parent one is not allowed)

What is final keyword and where it can be used?

If you use final with a primitive type variable, then its value cannot be changed once assigned. If you use final with a method, then you cannot override it in the subclass. If you use final with class, then that class cannot be extended. If you use final with an object type, then that object cannot be referenced again

Which way of creating threads is better: Thread class or Runnable interface

Implemenng Runnable is always the preferred choice, see the reasons below: - As you know, Java does not allow mulple inheritance through classes (because of Diamond problem discussed in ueson 9), so if you are creang threads by extending Thread class then you will not be able to extend any other class. - When we are working with mul-threading, we are not looking to overwrite any exisng funconality of Thread class, we just want to execute the code with mulple threads, so in that way also, Runnable is a good choice. - One more reason to choose Runnable is that, most people don't work with just Raw Threads, they use the Executor framework that is provided from Java 5, that separates the task from its execuon and we can execute Runnables using execute(Runnable Task) method of Executor interface .

Explain Auto-boxing and Un-boxing?

In Java 1.5, the concepts of Auto-boxing and Un-boxing were introduced to automacally convert primive type to object and viceversa. When Java automacally converts a primive type, like int into its corresponding wrapper class object i.e. Integer, then this is called Autoboxing. While the opposite of this is called Un-boxing, where an Integer object is converted into primive type int.

Why would it be more secure to store sensitive data (such as a password, social security number, etc.) in a character array rather than in a String?

In Java, Strings are immutable and are stored in the String pool. What this means is that, once a String is created, it stays in the pool in memory until being garbage collected. Therefore, even after you're done processing the string value (e.g., the password), it remains available in memory for an indeterminate period of time thereafter (again, until being garbage collected) which you have no real control over. Therefore, anyone having access to a memory dump can potentially extract the sensitive data and exploit it. In contrast, if you use a mutable object like a character array, for example, to store the value, you can set it to blank once you are done with it with confidence that it will no longer be retained in memory.

Explain static keyword in Java

In Java, a stac member is a member of a class that isn't associated with an instance of a class. Instead, the member belongs to the class itself. In Java, Stac is applicable for the following: - Variable - Method - Block - Nested class

Why is the character array preferred over string for storing confidential information?

In Java, a string is basically immutable i.e. it cannot be modified. After its declaration, it continues to stay in the string pool as long as it is not removed in the form of garbage. In other words, a string resides in the heap section of the memory for an unregulated and unspecified time interval after string value processing is executed. As a result, vital information can be stolen for pursuing harmful activities by hackers if a memory dump is illegally accessed by them. Such risks can be eliminated by using mutable objects or structures like character arrays for storing any variable. After the work of the character array variable is done, the variable can be configured to blank at the same instant. Consequently, it helps in saving heap memory and also gives no chance to the hackers to extract vital data.

What is the volatile keyword? How and why would you use it?

In Java, each thread has its own stack, including its own copy of variables it can access. When the thread is created, it copies the value of all accessible variables into its own stack. The volatile keyword basically says to the JVM "Warning, this variable may be modified in another Thread". In all versions of Java, the volatile keyword guarantees global ordering on reads and writes to a variable. This implies that every thread accessing a volatile field will read the variable's current value instead of (potentially) using a cached value. In Java 5 or later, volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex. Using volatile may be faster than a lock, but it will not work in some situations. The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly. The volatile keyword is also useful for 64-bit types like long and double since they are written in two operations. Without the volatile keyword you risk stale or invalid values. One common example for using volatile is for a flag to terminate a thread. If you've started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag (i.e., to stop it, set the flag to true). By making the flag volatile, you can ensure that the thread that is checking its value will see that it has been set to true without even having to use a synchronized block.

What is an Inner Class in Java, how it can be instantiated and what are the types of Inner Classes?

In Java, when you define one non-stac class within another class, it is called Inner Class/Nested Class. Inner class enables you to logically group classes that are only used in one place, thus, this increases the use of encapsulaon and creates more readable and maintainable code. Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can't have any stac variables in them. The object of java inner class is part of the outer class object and to create an instance of the inner class, we first need to create an instance of outer class. Java Inner classes can be instanated like below: OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass();

What is eager initialization?

In eager inializaon, the instance of Singleton Class is created at the me of class loading, this is the easiest method to create a singleton class but it has a drawback that instance is created even though client applicaon might not even use it.

What is the difference between procedural and object oriented programming?

In procedural programming, the program is divided into small parts called functions. In object-oriented programming, the program is divided into small parts called objects

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

Instance variables are those variables that are accessible by all the methods in the class. They are declared outside the methods and inside the class. These variables describe the properties of an object and remain bound to it at any cost. All the objects of the class will have their copy of the variables for utilization. If any modification is done on these variables, then only that instance will be impacted by it, and all other class instances continue to remain unaffected. Local variables are those variables present within a block, function, or constructor and can be accessed only inside them. The utilization of the variable is restricted to the block scope. Whenever a local variable is declared inside a method, the other class methods don't have any knowledge about the local variable.

Explain Generics in Java

Java Generics provides a way to reuse the same code with different inputs. Generics provide compile-me type safety that allows programmers to catch invalid types at compile me. When using Generics, there is no need of type-casng. By using generics, programmers can implement generic algorithms that work on collecons of different types, can be customized and are type safe and easier to read.

What is Java?

Java is the high-level programming language that was developed by James Gosling in the year 1982. It is based on the principles of object-oriented programming and can be used to develop large-scale applications.

Local inner class

Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop , or an if clause. Local Inner classes are not a member of any enclosing classes. They belong to the block in which they are defined in, due to which local inner classes cannot have any access modifiers associated with them. However, they can be marked as final or abstract. These classes have access to the fields of the class enclosing it. Local inner class must be instantiated in the block they are defined in. Points to remember: - local inner class cannot be instanated from outside of the block where they are defined - local inner class has access to the members of the enclosing class - ll Java 1.7, local inner class can access only final local variable of the enclosing block where they are defined. But from Java 1.8 onwards, it is possible to access the non-final local variable of the enclosing block - the scope of local inner class is restricted to the block where they are defined - A local inner class can extend an abstract class or can implement an interface

What is Multi-threading?

Multithreading is a programming concept in which the application can create a small unit of tasks to execute in parallel. If you are working on a computer, it runs multiple applications and allocates processing power to them. A simple program runs in sequence and the code statements execute one by one. This is a single-threaded application. But, if the programming language supports creating multiple threads and passes them to the operating system to run in parallel, it's called multithreading.

Can private methods or constructors be overridden?

No

Can we override final methods?

No, final methods cannot be overridden.

Can you instantiate an abstract class?

No, it has no use unless it is extended.

Can you pass primitive long value in switch statement?

No, switch works only with 4 primives and their wrappers, as well as with the enum type and String class: - byte and Byte - short and Short - char and Character - int and Integer - enum - String

Once a thread has been started can it be started again

No. A thread can be started only once in its lifeme. If you try to start a thread which has already been started, an IllegalThreadStateExcepTion is thrown, which is a runtime exception. A thread in runnable state or a dead thread cannot be restarted.

ArrayList, LinkedList, and Vector are all implementations of the List interface. Which of them is most efficient for adding and removing elements from the list? Explain your answer, including any other alternatives you may be aware of

Of the three, LinkedList is generally going to give you the best performance. Here's why: ArrayList and Vector each use an array to store the elements of the list. As a result, when an element is inserted into (or removed from) the middle of the list, the elements that follow must all be shifted accordingly. Vector is synchronized, so if a thread-safe implementation is not needed, it is recommended to use ArrayList rather than Vector. LinkedList, on the other hand, is implemented using a doubly linked list. As a result, an inserting or removing an element only requires updating the links that immediately precede and follow the element being inserted or removed. However, it is worth noting that if performance is that critical, it's better to just use an array and manage it yourself, or use one of the high performance 3rd party packages such as Trove or HPPC.

Why is String Immutable?

One of the reasons is related to String pools. - String parameters are used in network connections, database URL's, username and passwords etc. Because String is immutable, these values can't be changed. Otherwise any hacker could change the referenced values which will cause severe security issues in the application. - Since String is immutable, it is safe for multithreading. A single String instance can be shared across different threads. This avoids the use of synchronization for thread safety. Strings are implicitly thread-safe. The hashcode of string is frequently used in Java. Since string is immutable, the hashcode will remain the same, so it can be cached without worrying about the changes. This makes it a great candidate for using it as a Key in Map. - Strings are used in Java ClassLoaders and since String is made immutable, it provides security that correct class is being loaded.

What is overriding?

Overriding means when we have two methods with same name and same parameters in parent and child class. Through overriding, child class can provide specific implementation for the method which is already defined in the parent class.

What is Polymorphism in OOP?

Poly means many and Morph means forms. Polymorphism is the process in which an object or function takes different forms.

What are the different ways in which a Singleton Design pattern can break and how to prevent that from happening?

Reflecon API in java is used to change the runme behavior of a class. Hibernate, Spring's Dependency injecon also uses Reflecon. So, even though in the above singleton implementaons, we have defined the constructor as private, but using Reflecon, even private constructor can be accessed, so Reflecon can be used to break the singleton property of a class. Our Singleton class may implement Serializable interface so that the object's state can be saved and at a later point in me, it can be accessed back using Deserializaon, now the problem here is, when we deserialize the object, a new instance of the class will be created, thus breaking the singleton paern.

What is Shallow Copy and Deep Copy?

Shallow Copy: When we use the default implementaon of clone() method, a shallow copy of object is returned, meaning if the object that we are trying to clone contains both primive variables and nonprimitive or reference type variable, then only the object's reference is copied not the enre object itself. Consider this with the example: Employee object is having Company object as a reference, now when we perform cloning on Employee object, then for primive type variables, cloning will be done i.e. new instances will be created and copied to the cloned object but for non-primive i.e. Company object, only the object's reference will be copied to the cloned object. It simply means Company object will be same in both original and cloned object, changing the value in one will change the value in other and vice-versa. Now, if you want to clone the Company object also, so that your original and cloned Employee object will be independent of each other, then you have to perform Deep Copy. Deep Copy: in Deep copy, the non-primive types are also cloned to make the original and cloned object fully independent of each other.

If one class has an abstract method, should you change the class to an abstract one?

Simply yes.

What is Singleton Design Pattern?

Singleton design paern comes under Creaonal Design Paerns category and this paern ensures that only one instance of class exists in the JVM. Singleton paern is used in: - logging, caching, thread pool etc. - other design paerns like Builder, Prototype, Abstract Factory etc. - core java classes like java.lang.Runme etc.

Difference between Heap and Stack Memory in java. And how java utilizes this.

Stack memory is the portion of memory that was assigned to every individual program. And it was fixed. On the other hand, Heap memory is the portion that was not allocated to the java program but it will be available for use by the java program when it is required, mostly during the runtime of the program. When we write a java program then all the variables, methods, etc are stored in the stack memory. And when we create any object in the java program then that object was created in the heap memory. And it was referenced from the stack memory.

Explain static blocks

Static block gets executed exactly once when the class is first loaded, use static block to initialize the static variables.

Explain static nested classes

Static nested classes are a type of inner class in java where the inner class is static. Static nested classes can access only the static members of the outer class. The advantage of using static nested classes is that it makes the code more readable and maintainable. In the case of normal inner class, you cannot create inner class object without first creating the outer class object, but in the case of static inner class, there can be a static inner class object without the outer class object. How to create object of static inner class: OuterClass.StacNestedClass nestedClassObject = new OuterClass.StacNestedClass();

How would you differentiate between a String, StringBuffer, and a StringBuilder?

Storage area: In string, the String pool serves as the storage area. For StringBuilder and StringBuffer, heap memory is the storage area. Mutability: A String is immutable, whereas both the StringBuilder and StringBuffer are mutable. Efficiency: It is quite slow to work with a String. However, StringBuilder is the fastest in performing operations. The speed of a StringBuffer is more than a String and less than a StringBuilder. (For example appending a character is fastest in StringBuilder and very slow in String because a new memory is required for the new String with appended character.) Thread-safe: In the case of a threaded environment, StringBuilder and StringBuffer are used whereas a String is not used. However, StringBuilder is suitable for an environment with a single thread, and a StringBuffer is suitable for multiple threads.Syntax:

What is a TCP connection?

TCP stands for Transmission Control Protocol a communications standard that enables application programs and computing devices to exchange messages over a network. It is designed to send packets across the internet and ensure the successful delivery of data and messages over networks.

What is the Java Classloader? List and explain the purpose of the three types of class loaders.

The Java Classloader is the part of the Java runtime environment that loads classes on demand (lazy loading) into the JVM (Java Virtual Machine). Classes may be loaded from the local file system, a remote file system, or even the web. When the JVM is started, three class loaders are used: 1. Bootstrap Classloader: Loads core java API file rt.jar from folder. 2. Extension Classloader: Loads jar files from folder. 3. System/Application Classloader: Loads jar files from path specified in the CLASSPATH environment variable.

What is the method equals()?

The equals method in the Object class tests whether one object is considered equal to another. The equals method, as implemented in the Object class, determines whether two object references are identical. This is a pretty reasonable default—if two objects are identical, they should certainly be equal. For quite a few classes, nothing else is required.

Describe and compare fail-fast and fail-safe iterators

The main distinction between fail-fast and fail-safe iterators is whether or not the collection can be modified while it is being iterated. Fail-safe iterators allow this; fail-fast iterators do not. -Fail-fast iterators operate directly on the collection itself. During iteration, fail-fast iterators fail as soon as they realize that the collection has been modified (i.e., upon realizing that a member has been added, modified, or removed) and will throw a ConcurrentModificationException. Some examples include ArrayList, HashSet, and HashMap (most JDK1.4 collections are implemented to be fail-fast). -Fail-safe iterates operate on a cloned copy of the collection and therefore do not throw an exception if the collection is modified during iteration. Examples would include iterators returned by ConcurrentHashMap or CopyOnWriteArrayList.

Why is the main method static in Java?

The main method is always static because static members are those methods that belong to the classes, not to an individual object. So if the main method will not be static then for every object, It is available. And that is not acceptable by JVM. JVM calls the main method based on the class name itself. Not by creating the object. Because there must be only 1 main method in the java program as the execution starts from the main method. So for this reason the main method is static.

What is load factor in java?

The measure that decided when to increase the capacity of some collection types (List, Map, etc.);

In Java, static as well as private method overriding is possible. Comment on the statement.

The statement in the context is completely False. The static methods have no relevance with the objects, and these methods are of the class level. In the case of a child class, a static method with a method signature exactly like that of the parent class can exist without even throwing any compilation error. The phenomenon mentioned here is popularly known as method hiding, and overriding is certainly not possible. Private method overriding is unimaginable because the visibility of the private method is restricted to the parent class only. As a result, only hiding can be facilitated and not overriding.

Difference between throw and throws keyword?

The throw and throws is the concept of exception handling where the throw keyword throw the exception explicitly from a method or a block of code whereas the throws keyword is used in signature of the method.

Are StringBuilders and StringBuffers mutable or immutable?

They are immutable objects;

How can you catch an exception thrown by another thread in Java?

This can be done using Thread.UncaughtExceptionHandler.

Why wait, notify and notifyAll methods are defined in the Object class instead of Thread class

This is another very famous mul-threading interview queson. The methods wait, nofy and nofyAll are present in the Object class, that means they are available to all class objects, as Object class is the parent of all classes. wait() method - it tells the current thread to release the lock and go to sleep unl some other thread enters the same monitor and calls nofy() nofy() method - wakes up the single thread that is waing on the same object's monitor nofyAll() method - wakes up all the threads that called wait() on the same object if these methods were in Thread class, then thread T1 must know that another thread T2 is waing for this parcular resource, so T2 can be nofied by something like T2.nofy() But in java, the object itself is shared among all the threads, so one thread acquires the lock on this object's monitor, runs the code and while releasing the lock, it calls the nofy or nofyAll method on the object itself, so that any other thread which was waing on the same object's monitor will be nofied that now the shared resource is available. That is why these methods are defined in the Object class. Threads have no specific knowledge of each other. They can run asynchronously and are independent. They do not need to know about the status of other threads. They just need to call nofy method on an object, so whichever thread is waing on that resource will be nofied. Let's consider this with a real-life example: Suppose there is a petrol pump and it has a single washroom, the key of which is kept at the service desk. This washroom is a shared resource for all. To use this shared resource, the user must acquire the key to the washroom lock. So, the user goes to service desk, acquires the key, opens the door, locks it from the inside and use the facility. Meanwhile if another user arrives at the petrol pump and wants to use the washroom, he goes to the washroom and found that it is locked. He goes to the service desk and the key is not there because it is with the current user. When the current user finishes, he unlocks the door and returns the key to the service desk. He does not bother about the waing users. The service desk gives the key to waing user. If there are more than one user waing to use the facility, then they must form a queue. Now, apply this analogy to Java, one user is one thread and the washroom is the shared resource which the threads wish to execute. The key will be synchronized keyword provided by Java, through which thread acquires a lock for the code it wants to execute and making other threads wait unl the current thread finishes. Java will not be as fair as the service staon, because any of the waing threads may get a chance to acquire the lock, regardless of the order in which the threads came. The only guarantee is that all the waing threads will get to use the shared resource sooner or later. In this example, the lock can be acquired on the key object or the service desk and none of them is a thread. These are the objects that decide whether the washroom is locked or not.

Why Java 8 has introduced default methods?

To extend the capability of an already existing interface, default methods are introduced in Java 8. Let's understand this by one example: Consider there are 100 classes that are implementing one interface. Now you want to define one new method inside your interface. In this case you will have to change all the implementation classes to fulfill the interface contract. So, Java introduced default methods, here you can provide default implementation of that new method inside your interface and as it is not mandatory to provide implementation of default methods by the implementing classes, all the 100 classes can use the default implementation or if they want they can provide their own implementation by overriding the default method.

How to implement Singleton Pattern?

To implement a Singleton paern, we have different approaches but all of them have the below common concepts: - private constructor to restrict instanaon of the class from other classes. - private stac variable of the same class that is the only instance of the class. - public stac method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

What is overloading?

Two or more methods in one class have the same method name but different arguments. It is called as Compile time polymorphism because it is decided at compile time which overloaded method will be called.

What is Inheritance in OOP?

Using inheritance means defining a parent-child relationship between classes, by doing so, you can reuse the code that is already defined in the parent class. Code reusability is the biggest advantage of Inheritance.

What is lazy initialization?

Using this way of creating Singleton class, the object will not get created unless someone asks for it. Here we will create the class instance inside the global access method.

What is Variable shadowing and Variable hiding in Java?

Variable shadowing: When a local variable inside a method has the same name as one of the instance variables, the local variable shadows the instance variable inside the method block. Variable Hiding : When the child and parent classes both have a variable with the same name, the child class variable hides the parent class variable.

Explain Volatile keyword in java.

Volale is a keyword in java, that can be applied only to variables. You cannot apply volale keyword to classes and methods. Applying volale to a shared variable that is accessed in a mul-threaded environment ensures that threads will read this variable from the main memory instead of their own local cache. 1: class Test { static int var=5; } In the above example, assume that two threads are working on the same class. Both threads run on different processors where each thread has its local copy of var. If any thread modifies its value, the change will not reflect in the original one in the main memory. It leads to data inconsistency because the other thread is not aware of the modified value. 2: class Test { static volatile int var =5; } In the above example, static variables are class members that are shared among all objects. There is only one copy in the main memory. The value of a volatile variable will never be stored in the cache. All read and write will be done from and to the main memory

When finally block will not get executed?

When System.exit() is called. When JVM crashes.

Explain static methods

When a method is declared with static keyword then it is known as static method. These methods belong to the class rather than the object of the class. As a result, a static method can be directly accessed using class name without the need of creating an object. One of the basic rules of working with static methods is that you can't access a non-static method or field from a static method because the static method doesn't have an instance of the class to use to reference instance methods or fields. Another restriction is, 'this' and 'super' cannot be used in static context. For example: main() method is static, Java Runtime uses this method to start an application without creating an object.

What happens when you throw an exception from finally block?

When exception is thrown from finally block, then it takes precedence over the exceptions that are thrown from try/catch block;

What is Exception Propagation?

When method m1( ) calls method m2() which calls method m3(), a stack is formed which gets unfold from the top, so if method m3() throws an exception and it is not handled there, it will drop down the call stack to method m2(), if it is not handled there, it will drop down the call stack to method m1(), this happens until we reach the bottom of the stack or until the exception is caught. This is called Exception Propagation in java.

Can the main method be Overloaded?

Yes, It is possible to overload the main method. We can create as many overloaded main methods we want. However, JVM has a predefined calling method that JVM will only call the main method with the definition of - public static void main(string[] args)

Does an abstract class have constructor?

Yes, it has. If you don't create an constructor, the default one is provided per se. When you instantiate the child class, it will refer to the super class constructor as well.

Can we declare static and default methods inside interfaces?

Yes, since java 8, it has been added.

Do you have to implement abstract methods in the child class?

Yes, you have to override it.

Can we write a try block without a catch block?

Yes. As long as we can use a finally block.

When to use volatile variables in Java?

You can use a volatile variable if you want to read and write long and double variable automatically. It can be used as an alternative way of achieving synchronization in Java. All reader threads will see the updated value of the volatile variable after completing the write operation. If you are not using the volatile keyword, different reader thread may see different values. It is used to inform the compiler that multiple threads will access a particular statement. It prevents the compiler from doing any reordering or any optimization. If you do not use volatile variable compiler can reorder the code, free to write in cache value of volatile variable instead of reading from the main memory.

When to use String/StringBuffer/StringBuilder?

You should use String class if you require immutability, use StringBuffer if you require mutability + Thread safety and use StringBuilder if you require mutability and no thread safety.

Explain static variables

if any variable is declared as static, then it is known as 'static variable'. Only single copy of the variable gets created and all instances of the class share same static variable. The static variable gets memory only once in the class area at the me of class loading. When to use static variable: static variables should be used to declare common property of all objects as only single copy is created and shared among all class objects, for example, the company name of employees etc.

What will happen if I directly call the run() method and not the start() method to execute a thread?

if run() method is called directly, then a new thread will not be created instead the code will run on the current thread which is main thread. Calling run() method directly will make it behave as any other normal method call. Only a call to start() method creates separate thread.

Why Java does not allow multiple inheritance?

let us consider there are 2 parent classes having a method named hello() with same signature and one child class is extending these 2 classes, if you call this hello() method which is same in both parents, which parent class method will get executed - it results into an ambiguous situation, this is also called Diamond Problem.

Compare the sleep() and wait() methods in Java, including when and why you would use one vs. the other.

sleep() is a blocking operation that keeps a hold on the monitor / lock of the shared object for the specified number of milliseconds. wait(), on the other hand, simply pauses the thread until either (a) the specified number of milliseconds have elapsed or (b) it receives a desired notification from another thread (whichever is first), without keeping a hold on the monitor/lock of the shared object. sleep() is most commonly used for polling, or to check for certain results, at a regular interval. wait() is generally used in multithreaded applications, in conjunction with notify() / notifyAll(), to achieve synchronization and avoid race conditions.

What is Constructor chaining?

when one constructor calls another constructor, it is known as constructor chaining. This can be done in two ways: - this() : it is used to call the same class constructor - super() : it is used to call the parent class constructor - this() can call same class constructor only - super() can call immediate super class constructor only - this() and super() call must be the first statement, because of this reason both cannot be used at the same time - you must use super() to call the parent class constructor but if you do not provide a super() call, JVM will put it automacally


Conjuntos de estudio relacionados

HK: Motor Learning and Performance (Chapter 11)

View Set

PHYS 1260 Exam 2 Conceptual Review (DeWitt)

View Set

SCM301: Chapter 7 Inventory Management

View Set