Java

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

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.

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. The following example demonstrates all 3 cases when a super keyword is used.

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.

Explain the term "Double Brace Initialisation" in Java? Set<String> stringSets = new HashSet<String>() { { add("set1"); add("set2"); add("set3"); } };

This is a convenient means of initializing any collections in Java 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.

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

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

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

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

All three keywords have their own utility while programming. 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. Finally: It is the block present in a program where all the codes written inside it get executed irrespective of handling of exceptions. Finalize: Prior to the garbage collection of an object, the finalize method is called so that the clean-up activity is implemented.

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.

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. Variable types: Static and final variables can only be declared in the case of interfaces, whereas abstract classes can also have non-static and non-final variables. Inheritance: Multiple inheritances are facilitated by interfaces, whereas abstract classes do not promote multiple inheritances. Data member accessibility: By default, the class data members of interfaces are of the public- type. Conversely, the class members for an abstract class can be protected or private also. Implementation: With the help of an abstract class, the implementation of an interface is easily possible. However, the converse is not true;

Why is synchronization necessary? Explain with the help of a relevant example.

Concurrent execution of different processes is made possible by synchronization. When a particular resource is shared between many threads, situations may arise in which multiple threads require the same shared resource. Synchronization assists in resolving the issue and the resource is shared by a single thread at a time. Let's take an example to understand it more clearly. For example, you have a URL and you have to find out the number of requests made to it. Two simultaneous requests can make the count erratic.

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

Constructor - used for initializing the object state., no return type., invoked implicitly., default constructor is provided by the java compiler., name should be equal to the class name., 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 method - used for exposing the object's behavior, should have a return type. Even if it does not return anything, return type is void., has to be invoked on the object explicitly., name of the method can have any name or have a class name too., can be defined as final but it cannot be overridden in its subclasses, 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.

What do you mean by data encapsulation?

Data Encapsulation is an Object-Oriented Programming concept of hiding the data attributes and their behaviors 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.

differences between HashMap and HashTable in Java?

HashMap - 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 - synchronized and hence it is suitable for threaded applications., 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

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.

Comment on method overloading and overriding by citing relevant 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. The only difference in the return type of the method does not promote method overloading. The following example will furnish you with a clear picture of it. 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.Let's give a look at this example:

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

In order to achieve this, the attribute can be declared along with the usage of transient keywORD: private transient String someInfo;

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.

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. Example: class Athlete { public String athleteName; public double athleteSpeed; public int athleteAge; } 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. Example: public void athlete() { String athleteName; double athleteSpeed; int athleteAge; }

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:

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.

differences between JVM, JRE and JDK in Java?

Java Development Kit - JDK is mainly used for code development and execution. Java Runtime Environment - JRE is mainly used for environment creation to execute the code. Java Virtual Machine - JVM provides specifications for all the implementations to JRE.

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

Why is Java a platform independent language?

Java language was developed in such a way that it does not depend on any hardware or software due to the fact that the compiler compiles the code and then converts it to platform-independent byte code which can be run on multiple systems. The only condition to run that byte code is for the machine to have a runtime environment (JRE) installed in it.

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

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.

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

Pointers are quite complicated and unsafe to use by beginner programmers. Java focuses on code simplicity, and the usage of pointers can make it challenging. Pointer utilization can also cause potential errors. Moreover, security is also compromised if pointers are used because the users can directly access memory with the help of pointers. Thus, a certain level of abstraction is furnished by not including pointers in Java. Moreover, the usage of pointers can make the procedure of garbage collection quite slow and erroneous. Java makes use of references as these cannot be manipulated, unlike pointers.

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.

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.

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 you tell the difference between equals() method and equality operator (==) in Java?

equals() This is a method defined in the Object class. This method is used for checking the equality of contents between two objects as per the specified business logic. == It is a binary operator in Java. This operator is used for comparing addresses (or references), i.e checks if both the objects are pointing to the same memory location.

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

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.

Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below? public int someMethod(int i){ try{ //some statement return 1; }catch(Exception e){ //some statement return 999; }finally{ //finally block statements } }

finally block will be executed irrespective of the exception or not. The only case where finally block is not executed is when it encounters 'System.exit()' method anywhere in try/catch block.

How is an infinite loop declared in Java?

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


Conjuntos de estudio relacionados

MGMT 495 Nordin Final Study Guide

View Set

Practice test for Cardiovascular System

View Set

Bab 1: Pengenalan kepada Biologi dan Peraturan Makmal

View Set

Real estate practice vocab quiz 2

View Set

Developmental Concepts - OB Module 2

View Set

Chapter 22- Assessment of Integumentary System

View Set

NU660 Prep Week Practice Questions

View Set

Multiplication Facts 10's & 11's

View Set

Fiscal Policy Question Bank and Explanations for some

View Set

Smooth Muscle (Non-striated, Involuntary)

View Set