Java

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What is the 'IS-A ' relationship in OOPs java?

'IS-A' relationship is another name for inheritance. When we inherit the base class from the derived class, then it forms a relationship between the classes. So that relationship is termed an 'IS-A' Relationship.

When an object has its own lifecycle and its child object cant belong to another parent object, what is it called? Association Aggregation Composition Encapsulation

Aggregation

What are the differences between HashMap and HashTable in Java?

HashMap HashMap is not synchronized thereby making it better for non-threaded applications. Allows only one null key but any number of null in the values.Supports order of insertion by making use of its subclass LinkedHashMap. HashTable HashTable is synchronized and hence it is suitable for threaded applications. This does not allow null in both keys or values. Order of insertion is not guaranteed in HashTable.

What part of memory - Stack or Heap - is cleaned in garbage collection process?

Heap.

How is an infinite loop declared in Java?

for (;;) {} while(true) do { }while(true);

How to not allow serialization of attributes of a class in Java?

the attribute can be declared along with the usage of transient keyword.

How do exceptions affect the program if it doesn't handle them?

Exceptions are runtime errors. Suppose we are making an android application with java. And it all works fine but there is an exceptional case when the application tries to get the file from storage and the file doesn't exist (This is the case of exception in java). And if this case is not handled properly then the application will crash. This will be a bad experience for users. This is the type of error that cannot be controlled by the programmer. But programmers can take some steps to avoid this so that the application won't crash. The proper action can be taken at this step.

Do final, finally and finalize keywords have the same function?

Final: If any restriction is required for classes, variables, or methods, the final keyword comes in handy. Inheritance of a final class and overriding of a final method is restricted by the use of the final keyword. The variable value becomes fixed after incorporating the final keyword. Example: final int a=100; a = 0; // error The second statement will throw an error. Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Example: try { int variable = 5; } catch (Exception exception) { System.out.println("Exception occurred"); } finally { System.out.println("Execution of finally block"); } Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented. Example: public static void main(String[] args) { String example = new String("InterviewBit"); example = null; System.gc(); // Garbage collector called } public void finalize() { // Finalize called }

Is it mandatory for a catch block to be followed after a try block?

No, it is not necessary for a catch block to be present after a try block. - A try block should be followed either by a catch block or by a finally block. If the exceptions likelihood is more, then they should be declared using the throws clause of the method.

What are the possible ways of making object eligible for garbage collection (GC) in Java?

Set the object references to null, point the reference variable to another object, or when 2 reference variables pointing to instances of the same class, and these variables refer to only each other and the objects pointed by these 2 variables don't have any other references, then it is said to have formed an "Island of Isolation" and these 2 objects are eligible for GC.

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

Using relevant properties highlight the differences between interfaces and abstract classes.

Availability of methods: Only abstract methods are available in interfaces, whereas non-abstract methods can be present along with abstract methods in abstract classes. Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances.

How is Java different from C++?

C++ is only a compiled language, whereas Java is compiled as well as an interpreted language. Java programs are machine-independent whereas a c++ program can run only in the machine in which it is compiled. C++ allows users to use pointers in the program. Whereas java doesn't allow it. Java internally uses pointers. C++ supports the concept of Multiple inheritances whereas Java doesn't support this. And it is due to avoiding the complexity of name ambiguity that causes the diamond problem.

What is a singleton class in Java? And How to implement a singleton class?

A Singleton class is a class that can only have one object at a time. To implement: Declare all constructors of the class to be private. Provide a static method that creates an instance. The instance is stored as a private static variable.

What is the difference between the program and the process?

A program can be defined as a line of code written in order to accomplish a particular task. Whereas the process can be defined as the programs which are under execution. A program doesn't execute directly by the CPU. First, the resources are allocated to the program and when it is ready for execution then it is a process.

How we can set the spring bean scope. And what supported scopes does it have?

A scope can be set by an annotation such as the @Scope annotation or the "scope" attribute in an XML configuration file. Spring Bean supports the following five scopes: Singleton Prototype Request Session Global-session

How is the 'new' operator different from the 'newInstance()' operator in java?

Both 'new' and 'newInstance()' operators are used to creating objects. The difference is- that when we already know the class name for which we have to create the object then we use a new operator. But suppose we don't know the class name for which we need to create the object, Or we get the class name from the command line argument, or the database, or the file. Then in that case we use the 'newInstance()' operator. The 'newInstance()' keyword throws an exception that we need to handle. It is because there are chances that the class definition doesn't exist, and we get the class name from runtime. So it will throw an exception.

What is a Comparator in java?

Comparator is the interface in java that contains the compare method and is used to order objects. Consider the example where we have an ArrayList of employees like( EId, Ename, Salary), etc. If we want to sort this list of employees based on the names of employees we use the comparator with the Collections.sort() method.

What are Composition and Aggregation? State the difference.

Composition, and Aggregation help to build (Has - A - Relationship) between classes and objects. But both are not the same in the end. Let's understand with the help of an example. Consider the University as a class that has some departments in it. So the university will be the container object. And departments in it will contain objects. Now in this case, if the container object destroys then the contained objects will also get destroyed automatically. So here we can say that there is a strong association between the objects. So this Strong Association is called Composition. Now consider one more example. Suppose we have a class department and there are several professors' objects there in the department. Now if the department class is destroyed then the professor's object will become free to bind with other objects. Because container objects (Department) only hold the references of contained objects (Professor's). So here is the weak association between the objects. And this weak association is called Aggregation.

What are the differences between constructor and method of a class in Java?

Constructor Constructor is used for initializing the object state. Constructor has no return type. Constructor gets invoked implicitly. If the constructor is not defined, then a default constructor is provided by the java compiler. The constructor name should be equal to the class name. A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here. Final variable instantiations are possible inside a constructor and the scope of this applies to the whole class and its objects. Method is used for exposing the object's behavior. Method should have a return type. Even if it does not return anything, return type is void. Method has to be invoked on the object explicitly. If a method is not defined, then the compiler does not provide it. The name of the method can have any name or have a class name too. A method can be defined as final but it cannot be overridden in its subclasses. A final variable if initialised inside a method ensures that the variable cant be changed only within the scope of that method.

Briefly explain the concept of constructor overloading

Constructor overloading is the process of creating multiple constructors in the class consisting of the same name with a difference in the constructor parameters. Depending upon the number of parameters and their corresponding types, distinguishing of the different types of constructors is done by the compiler.

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. class InterviewBit{ String department; String service; InterviewBit(InterviewBit ib){ this.departments = ib.departments; this.services = ib.services; } } Here we are initializing the new object value from the old object value in the constructor. Although, this can also be achieved with the help of object cloning.

What is a CountDownLatch?

CountDownLatch is used to make sure that a task waits for other threads before it starts.

What do you mean by data encapsulation?

Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviours in a single unit. It helps developers to follow modularity while developing software by ensuring that each object is independent of other objects by having its own methods, attributes, and functionalities. It is used for the security of the private properties of an object and hence serves the purpose of data hiding.

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 method overloading and method overriding? Give examples.

In Java, method overloading is made possible by introducing different methods in the same class consisting of the same name. Still, all the functions differ in the number or type of parameters. It takes place inside a class and enhances program readability. Method overriding is the concept in which two methods having the same method signature are present in two different classes in which an inheritance relationship is present. A particular method implementation (already present in the base class) is possible for the derived class by using method overriding.

Explain the use of final keyword in variable, method and class.

In Java, the final keyword is used as defining something as constant /final and represents the non-access modifier. final variable:When a variable is declared as final in Java, the value can't be modified once it has been assigned.If any value has not been assigned to that variable, then it can be assigned only by the constructor of the class. final method:A method declared as final cannot be overridden by its children's classes.A constructor cannot be marked as final because whenever a class is inherited, the constructors are not inherited. Hence, marking it final doesn't make sense. Java throws compilation error saying - modifier final not allowed here final class:No classes can be inherited from the class declared as final. But that final class can extend other classes for its usage.

Can we make the main() thread a daemon thread?

In java multithreading, the main() threads are always non-daemon threads. And there is no way we can change the nature of the non-daemon thread to the daemon thread.

Contiguous memory locations are usually used for storing actual values in an array but not in ArrayList. Explain.

In the case of ArrayList, data storing in the form of primitive data types (like int, float, etc.) is not possible. The data members/objects present in the ArrayList have references to the objects which are located at various sites in the memory. Thus, storing of actual objects or non-primitive data types (like Integer, Double, etc.) takes place in various memory locations. However, the same does not apply to the arrays. Object or primitive type values can be stored in arrays in contiguous memory locations, hence every element does not require any reference to the next element.

Why is the remove method faster in the linked list than in an array?

In the linked list, we only need to adjust the references when we want to delete the element from either end or the front of the linked list. But in the array, indexes are used. So to manage proper indexing, we need to adjust the values from the array So this adjustment of value is costlier than the adjustment of references.

Although inheritance is a popular OOPs concept, it is less advantageous than composition. Explain.

Inheritance lags behind composition in the following scenarios: Multiple-inheritance is not possible in Java. Classes can only extend from one superclass. In cases where multiple functionalities are required, for example - to read and write information into the file, the pattern of composition is preferred. The writer, as well as reader functionalities, can be made use of by considering them as the private members. Composition assists in attaining high flexibility and prevents breaking of encapsulation. Unit testing is possible with composition and not inheritance. When a developer wants to test a class composing a different class, then Mock Object can be created for signifying the composed class to facilitate testing. This technique is not possible with the help of inheritance as the derived class cannot be tested without the help of the superclass in inheritance. The loosely coupled nature of composition is preferable over the tightly coupled nature of inheritance. Let's take an example: package comparison; public class Top { public int start() { return 0; } } class Bottom extends Top { public int stop() { return 0; } } In the above example, inheritance is followed. Now, some modifications are done to the Top class like this: public class Top { public int start() { return 0; } public void stop() { } } If the new implementation of the Top class is followed, a compile-time error is bound to occur in the Bottom class. Incompatible return type is there for the Top.stop() function. Changes have to be made to either the Top or the Bottom class to ensure compatibility. However, the composition technique can be utilized to solve the given problem: class Bottom { Top par = new Top(); public int stop() { par.start(); par.stop(); return 0; } }

Java works as "pass by value" or "pass by reference" phenomenon?

Java always works as a "pass by value". There is nothing called a "pass by reference" in Java. However, when the object is passed in any method, the address of the value is passed due to the nature of object handling in Java. When an object is passed, a copy of the reference is created by Java and that is passed to the method. The objects point to the same memory location.

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.

What is the functionality of Class.getInstance()? It invokes the constructor. It has the same functionality of new operator. It creates object if the class does not have constructor defined. None of the above.

It creates object if the class does not have constructor defined.

Why does the java array index start with 0?

It is because the 0 index array avoids the extra arithmetic operation to calculate the memory address. It is more efficient this way.

Is it possible to import the same class or package twice in Java and what happens to it during runtime?

It is possible to import a class or package more than once, however, it is redundant because the JVM internally loads the package or class only once.

What do you understand by Object Cloning and how do you achieve it in Java?

It is the process of creating an exact copy of any object. In order to support this, a java class has to implement the Cloneable interface of java.lang package and override the clone() method provided by the Object class the syntax of which is: protected Object clone() throws CloneNotSupportedException{ return (Object)super.clone(); } In case the Cloneable interface is not implemented and just the method is overridden, it results in CloneNotSupportedException in Java.

What is the volatile keyword?

It means that multiple threads can modify the value of a variable at the same time. It is also used to make classes thread safe.

Which of the following is the functionality of the java interpreter? Interpretor is nothing but the JIT compiler. It acts as medium between JVM and JIT. It does the conversion of byte code to machine code. It reads the high level code and executes them.

It reads the high level code and executes them.

What is the component used for compiling, debugging, and executing java programs? JDK JVM JRE JIT

JDK

What are the differences between JVM, JRE and JDK in Java?

JDK is a complete software development kit for developing Java applications. It comprises JRE, JavaDoc, compiler, debuggers, etc. JRE is a software package providing Java class libraries, JVM and all the required components to run the Java applications. JVM is a platform-dependent, abstract machine comprising of 3 specifications - document describing the JVM implementation requirements, computer program meeting the JVM requirements and instance object for executing the Java byte code and provide the runtime environment for execution. JDK is mainly used for code development and execution. JRE is mainly used for environment creation to execute the code .JVM provides specifications for all the implementations to JRE. JDK provides tools like compiler, debuggers, etc for code development. JRE provides libraries and classes required by JVM to run the program. JVM does not include any tools, but instead, it provides the specification for implementation. Summary: JDK = (JRE) + Development tools; JRE = (JVM) + Libraries to execute the application; JVM = Runtime environment to execute Java byte code.

Tell us something about JIT compiler.

JIT stands for Just-In-Time and it is used for improving the performance during run time. It does the task of compiling parts of byte code having similar functionality at the same time thereby reducing the amount of compilation time for the code to run. The compiler is nothing but a translator of source code to machine-executable code. But what is special about the JIT compiler? Let us see how it works:First, the Java source code (.java) conversion to byte code (.class) occurs with the help of the javac compiler.Then, the .class files are loaded at run time by JVM and with the help of an interpreter, these are converted to machine understandable code.JIT compiler is a part of JVM. When the JIT compiler is enabled, the JVM analyzes the method calls in the .class files and compiles them to get more efficient and native code. It also ensures that the prioritized method calls are optimized.Once the above step is done, the JVM executes the optimized code directly instead of interpreting the code again. This increases the performance and speed of the execution.

What component does the task of bytecode to machine code conversion? JDK JVM JRE JIT

JVM

What is a ClassLoader?

Java Classloader is the program that belongs to JRE (Java Runtime Environment). The task of ClassLoader is to load the required classes and interfaces to the JVM when required. Example- To get input from the console, we require the scanner class. And the Scanner class is loaded by the ClassLoader.

Pointers are used in C/ C++. Why does Java not make use of pointers?

Java doesn't need pointers for several reasons: Memory access via pointers - Fundamentally unsafe, Java does not include them to improve security. No need for manual memory management - Java has its own automatic garbage collection Indexed array access - No need for pointer offsets to access array indices.

Why is the main method static in Java?

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

Why is Java not a pure object oriented language?

Java supports primitive data types - byte, boolean, char, short, int, float, long, and double and hence it is not a pure object oriented language.

Can you explain the Java thread lifecycle?

Java thread life cycle is as follows: New - When the instance of the thread is created and the start() method has not been invoked, the thread is considered to be alive and hence in the NEW state. Runnable - Once the start() method is invoked, before the run() method is called by JVM, the thread is said to be in RUNNABLE (ready to run) state. This state can also be entered from the Waiting or Sleeping state of the thread. Running - When the run() method has been invoked and the thread starts its execution, the thread is said to be in a RUNNING state. Non-Runnable (Blocked/Waiting) - When the thread is not able to run despite the fact of its aliveness, the thread is said to be in a NON-RUNNABLE state. Ideally, after some time of its aliveness, the thread should go to a runnable state.A thread is said to be in a Blocked state if it wants to enter synchronized code but it is unable to as another thread is operating in that synchronized block on the same object. The first thread has to wait until the other thread exits the synchronized block.A thread is said to be in a Waiting state if it is waiting for the signal to execute from another thread, i.e it waits for work until the signal is received. Terminated - Once the run() method execution is completed, the thread is said to enter the TERMINATED step and is considered to not be alive.

What are the different types of Thread Priorities in Java? And what is the default priority of a thread assigned by JVM?

MIN_PRIORITY: It has an integer value assigned with 1. MAX_PRIORITY: It has an integer value assigned with 10. NORM_PRIORITY: It has an integer value assigned with 5. In Java, Thread with MAX_PRIORITY gets the first chance to execute. But the default priority for any thread is NORM_PRIORITY assigned by JVM.

What do you understand by marker interfaces in Java?

Marker interfaces, also known as tagging interfaces are those interfaces that have no methods and constants defined in them. They are there for helping the compiler and JVM to get run time-related information regarding the objects.

Will the finally block be executed if the code System.exit(0) is written at the end of try block?

NO. The control of the program post System.exit(0) is immediately gone and the program gets terminated which is why the finally block never gets executed.

Can the static methods be overridden?

Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.

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

Stack memory is the fixed amount of memory provided for every program. 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. For example, 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.

Difference between static methods, static variables, and static classes in java.

Static Methods and Static variables are those methods and variables that belong to the class of the java program, not to the object of the class. This gets memory where the class is loaded. And these can directly be called with the help of class names.For example - We have used mathematical functions in the java program like - max(), min(), sqrt(), pow(), etc. And if we notice that, then we will find that we call it directly with the class name. Like - Math.max(), Math.min(), etc. So that is a static method. And Similarly static variables we have used like (length) for the array to get the length. So that is the static method. Static classes - A class in the java program cannot be static except if it is the inner class. A static nested class may be instantiated without instantiating its outer class. Inner classes can access both static and non-static members of the outer class. A static class can access only the static members of the outer class.

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.

Apart from the security aspect, what are the reasons behind making strings immutable in Java?

String Pool: The String pool cannot be possible if String is not immutable in Java. A lot of heap space is saved by JRE. The same string variable can be referred to by more than one string variable in the pool. Multithreading: The String is safe for multithreading because of its immutableness. Different threads can access a single "String instance". It removes the synchronization for thread safety because we make strings thread-safe implicitly.

Which among String or String Buffer should be preferred when there are lot of updates required to be done in the data?

StringBuffer is mutable and dynamic in nature whereas String is immutable. Every updation / modification of String creates a new String thereby overloading the string pool with unnecessary objects. Hence, in the cases of a lot of updates, it is always preferred to use StringBuffer as it will reduce the overhead of the creation of multiple String objects in the string pool.

Define System.out.println().

System.out.println() is used to print the message on the console. System - It is a class present in java.lang package. Out is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class. So if we justify the statement, then we can say that if we want to print anything on the console then we need to call the println() method that was present in PrintStream class. And we can call this using the output object that is present in the System class.

What is the difference between the 'throw' and 'throws' keyword in java?

The 'throw' keyword is used to manually throw the exception to the calling method. And the 'throws' keyword is used in the function definition to inform the calling method that this method throws the exception. So if you are calling, then you have to handle the exception.

What is a Memory Leak? Discuss some common causes of it.

The Java Garbage Collector (GC) typically removes unused objects when they are no longer required, but when they are still referenced, the unused objects cannot be removed. So this causes the memory leak problem. Some common causes of Memory leaks are - When there are Unbounded caches. Excessive page swapping is done by the operating system. Improper written custom data structures. Inserting into a collection object without first deleting it.etc

Why is Java a platform independent language?

The compiler compiles the code and then converts it to byte code which can be executed by the JVM. Although the JVM you have is platform dependent, all JVMs will execute the byte code to give the same desired output.

Why is it said that the length() method of String class doesn't return accurate results?

The length method returns the number of Unicode units of the String. Let's understand what Unicode units are and what is the confusion below. We know that Java uses UTF-16 for String representation. With this Unicode, we need to understand the below two Unicode related terms:Code Point: This represents an integer denoting a character in the code space.Code Unit: This is a bit sequence used for encoding the code points. In order to do this, one or more units might be required for representing a code point. Under the UTF-16 scheme, the code points were divided logically into 17 planes and the first plane was called the Basic Multilingual Plane (BMP). The BMP has classic characters - U+0000 to U+FFFF. The rest of the characters- U+10000 to U+10FFFF were termed as the supplementary characters as they were contained in the remaining planes.The code points from the first plane are encoded using one 16-bit code unitThe code points from the remaining planes are encoded using two code units. Now if a string contained supplementary characters, the length function would count that as 2 units and the result of the length() function would not be as per what is expected. In other words, if there is 1 supplementary character of 2 units, the length of that SINGLE character is considered to be TWO - Notice the inaccuracy here? As per the java documentation, it is expected, but as per the real logic, it is inaccurate.

What could be the tradeoff between the usage of an unordered array versus the usage of an ordered array?

The main advantage of having an ordered array is the reduced search time complexity of O(log n) whereas the time complexity in an unordered array is O(n). The main drawback of the ordered array is its increased insertion time which is O(n) due to the fact that its element has to reordered to maintain the order of array during every insertion whereas the time complexity in the unordered array is only O(1). Considering the above 2 key points and depending on what kind of scenario a developer requires, the appropriate data structure can be used for implementation.

What is the main objective of garbage collection?

The main objective of this process is to free up the memory space occupied by the unnecessary and unreachable objects during the Java program execution by deleting those unreachable objects. This ensures that the memory resource is used efficiently, but it provides no guarantee that there would be sufficient memory for the program execution.

What happens if there are multiple main methods inside one class in Java?

The program can't compile as the compiler says that the method has been already defined inside the class.

What are shallow copy and deep copy in java?

The shallow copy only creates a new reference and points to the same memory location. In a deep copy, we create a new object and copy the old object value to the new object. You can use the clone() method to deep copy.

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.

When can you use super keyword?

The super keyword is used to access hidden fields and overridden methods or attributes of the parent class. Following are the cases when this keyword can be used:Accessing data members of parent class when the member names of the class and its child subclasses are same.To call the default and parameterized constructor of the parent class inside the child class.Accessing the parent class methods when the child classes have overridden them.

What are the default values assigned to variables and instances in java?

There are no default values assigned to the variables in java. We need to initialize the value before using it. Otherwise, it will throw a compilation error of (Variable might not be initialized). But for instance, if we create the object, then the default value will be initialized by the default constructor depending on the data type. If it is a reference, then it will be assigned to null. If it is numeric, then it will assign to 0. If it is a boolean, then it will be assigned to false. Etc.

What is the best way to inject dependency? Also, state the reason.

There is no boundation for using a particular dependency injection. But the recommended approach is - Setters are mostly recommended for optional dependencies injection, and constructor arguments are recommended for mandatory ones. This is because constructor injection enables the injection of values into immutable fields and enables reading them more easily.

What happens if the static modifier is not included in the main method signature in Java?

There wouldn't be any compilation error. But then the program is run, since the JVM cant map the main method signature, the code throws "NoSuchMethodError" error at the runtime.

What is the difference between '>>' and '>>>' operators in java?

These 2 are the bitwise right shift operators. Although both operators look similar. But there is a minimal difference between these two right shift operators. '>>' Bitwise Right Shift Operator- This operator shifts each bit to its right position. And this maintains the signed bit. '>>>' Bitwise Right Shift Operator with trailing zero- This operator also shifts each bit to its right. But this doesn't maintain the signed bit. This operator makes the Most significant bit to 0.

In case a package has sub packages, will it suffice to import only the main package? e.g. Does importing of com.myMainPackage.* also import com.myMainPackage.mySubPackage.*?

This is a big NO. We need to understand that the importing of the sub-packages of a package needs to be done explicitly. Importing the parent package only results in the import of the classes within it and not the contents of its child/sub-packages.

Explain the term "Double Brace Initialisation" in Java?

This is a convenient means of initializing any collections in Java. Consider the below example. import java.util.HashSet; import java.util.Set; public class IBDoubleBraceDemo{ public static void main(String[] args){ Set<String> stringSets = new HashSet<String>() { { add("set1"); add("set2"); add("set3"); } }; doSomething(stringSets); } private static void doSomething(Set<String> stringSets){ System.out.println(stringSets); } } In the above example, we see that the stringSets were initialized by using double braces. The first brace does the task of creating an anonymous inner class that has the capability of accessing the parent class's behavior. In our example, we are creating the subclass of HashSet so that it can use the add() method of HashSet. The second braces do the task of initializing the instances. Care should be taken while initializing through this method as the method involves the creation of anonymous inner classes which can cause problems during the garbage collection or serialization processes and may also result in memory leaks.

Which of the following happens when the garbage collection process kicks off during the execution of the thread? Garbage collection does not happen during thread execution. Thread pauses while the garbage collection process runs. Both the process takes place simultaneously and does not interfere its execution. Nothing happens, the thread proceeds with execution.

Thread pauses while the garbage collection process runs.

How is the creation of a String using new() different from that of a literal?

When a String is formed as a literal with the assistance of an assignment operator, it makes its way into the String constant pool so that String Interning can take place. This same object in the heap will be referenced by a different String if the content is the same for both of them. Conversely, when a String formation takes place with the help of a new() operator, interning does not take place. The object gets created in the heap memory even if the same content object is present.

How does an exception propagate in the code?

When an exception occurs, first it searches to locate the matching catch block. In case, the matching catch block is located, then that block would be executed. Else, the exception propagates through the method call stack and goes into the caller method where the process of matching the catch block is performed. This propagation happens until the matching catch block is found. If the match is not found, then the program gets terminated in the main method.

Can the static methods be overloaded?

Yes! There can be two or more static methods in a class with the same name but differing input parameters.

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)

Is exceeding the memory limit possible in a program despite having a garbage collector?

Yes, it is possible for the program to go out of memory in spite of the presence of a garbage collector. Garbage collection assists in recognizing and eliminating those objects which are not required in the program anymore, in order to free up the resources used by them. In a program, if an object is unreachable, then the execution of garbage collection takes place with respect to that object. If the amount of memory required for creating a new object is not sufficient, then memory is released for those objects which are no longer in the scope with the help of a garbage collector. The memory limit is exceeded for the program when the memory released is not enough for creating new objects. Moreover, exhaustion of the heap memory takes place if objects are created in such a manner that they remain in the scope and consume memory. The developer should make sure to dereference the object after its work is accomplished. Although the garbage collector endeavors its level best to reclaim memory as much as possible, memory limits can still be exceeded.

A single try block and multiple catch blocks can co-exist in a Java Program. Explain.

Yes, multiple catch blocks can exist but specific approaches should come prior to the general approach because only the first catch block satisfying the catch condition is executed. The given code illustrates the same: public class MultipleCatch { public static void main(String args[]) { try { int n = 1000, x = 0; int arr[] = new int[n]; for (int i = 0; i <= n; i++) { arr[i] = i / x; } } catch (ArrayIndexOutOfBoundsException exception) { System.out.println("1st block = ArrayIndexOutOfBoundsException"); } catch (ArithmeticException exception) { System.out.println("2nd block = ArithmeticException"); } catch (Exception exception) { System.out.println("3rd block = Exception"); } } } Here, the second catch block will be executed because of division by 0 (i / x). In case x was greater than 0 then the first catch block will execute because for loop runs till i = n and array index are till n-1.

Can you call a constructor of a class inside another constructor?

Yes, the concept can be termed as constructor chaining and can be achieved using this()

Is it possible that the 'finally' block will not be executed? If yes then list the case.

Yes. It is possible that the 'finally' block will not be executed. The cases are- Suppose we use System.exit() in the above statement. If there are fatal errors like Stack overflow, Memory access error, etc.

Can you tell the difference between equals() method and equality operator (==) in Java?

equals() is used for checking the equality of contents between two objects as per the specified business logic. == is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.

What are the different ways of threads usage?

extending the Thread class or implementing the Runnable interface. Implementing a thread using the method of Runnable interface is more preferred and advantageous as Java does not have support for multiple inheritances of classes. start() method is used for creating a separate call stack for the thread execution. Once the call stack is created, JVM calls the run() method for executing the thread in that call stack.

What is the output of the below code? class InterviewBit{ public static void main(String args[]) { String obj = "Hello"; String obj1 = "InterviewBit"; String obj2 = "Hello"; System.out.println(obj.equals(obj1) + " " + obj.equals(obj2)); } } false false true true true false false true

false true


Ensembles d'études connexes

chpt 28-Managements of Patients With Structural, Infectious and Inflammatory Cardiac Disorders

View Set

Principles Quiz 3 (Ch. 20,21,43,46,31,36)

View Set

Testing and Remediation Advanced Test

View Set

HESI practice notes - nursings sciences

View Set

Psychology of workforce diversity UWF Exam 1

View Set

FNAN 320: Chapter 11 - The economics of financial intermediation

View Set

Government Regulation of The Economy

View Set

Chapter 25 & 26 (Vision and Hearing and Endocrine Function)

View Set