Intermediate java Flashcards

1
Q

How would you iterate over a Map?

A

To iterate over a Map in most programming languages, you can use a for loop or an iterator. Here’s an example in Java:
Map<String, Integer> map = new HashMap<>();
map.put(“apple”, 1);
map.put(“banana”, 2);
map.put(“cherry”, 3);

// Iterate using a for-each loop
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + “ = “ + value);
}

// Iterate using an iterator
Iterator<Map.Entry<String, Integer» iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + “ = “ + value);
}
In the above code, we first create a Map and add some key-value pairs to it. We then iterate over the Map using both a for-each loop and an iterator. In both cases, we use the entrySet() method to obtain a set of key-value pairs, and then iterate over that set using the for loop or while loop. For each key-value pair, we extract the key and value using the getKey() and getValue() methods of the Map.Entry class, respectively. Finally, we print out each key-value pair to the consol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Are Maps in the Collections API?

A

Yes, Maps are part of the Collections API in most programming languages, including Java. The Collections API provides a set of interfaces and classes to represent and manipulate collections of objects. The Map interface is a part of this API, which represents a collection of key-value pairs.

In Java, the java.util.Map interface provides the methods to access, add, remove, and manipulate key-value pairs in a Map. There are also several concrete implementations of the Map interface provided by the Collections API, such as HashMap, TreeMap, and LinkedHashMap. These classes provide different performance characteristics and ordering guarantees, and can be chosen based on the specific use case.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the difference between ArrayList and LinkedList?

A

ArrayList and LinkedList are both data structures in Java that are used to store and manipulate collections of elements. However, there are some key differences between them that are important to understand.

Internal Data Structure:
An ArrayList is implemented as an array, where elements are stored in contiguous memory locations. A LinkedList, on the other hand, is implemented as a linked list, where elements are stored in nodes that are connected by pointers.

Insertion and Deletion:
Insertion and deletion operations in ArrayList are slower because they require shifting elements to maintain contiguous memory. In LinkedList, these operations are faster because only the pointers need to be updated.

Random Access:
Random access (accessing elements at a particular index) is faster in ArrayList because it allows direct access to the elements via their index. In LinkedList, random access requires traversing the list from the beginning or end until the desired element is found.

Memory Efficiency:
ArrayList is more memory-efficient than LinkedList for storing large lists of primitive data types. However, for storing large lists of complex objects, LinkedList can be more memory-efficient because it doesn’t require contiguous memory allocation.

Usage:
ArrayList is generally used when there is a need for frequent access to elements and for iterating over the list, while LinkedList is preferred when there is a need for frequent insertion and deletion operations.

In summary, the main difference between ArrayList and LinkedList is their internal data structure, which affects their performance in terms of insertion, deletion, random access, and memory usage. The choice between the two depends on the specific requirements of the program or application being developed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What are generics?
What is the diamond operator (<>)?

A

Generics:
Generics is a feature in Java that allows the creation of parameterized types or classes. Generics are used to ensure type safety at compile-time, by enabling the specification of the type of data that will be stored in a collection or returned by a method. Generics make the code more reusable and flexible, as they allow the creation of generic classes and methods that can work with different types of data.

Diamond Operator:
The diamond operator or angle bracket (<>) is a shorthand notation introduced in Java 7 to simplify the use of generics. The diamond operator is used to represent the type argument in a generic class, and it can be used in cases where the type argument can be inferred from the context.

For example, instead of writing:

List<String> myList = new ArrayList<String>();
we can write:</String></String>

List<String> myList = new ArrayList<>();</String>

In the second example, the type argument “String” is inferred from the declaration of the variable “myList”, making the code more concise and readable. The diamond operator is especially useful when working with complex generic types, as it eliminates the need to write the type argument twice, reducing the chance of errors and making the code more maintainable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between a Set and a List?

A

In Java, both Set and List are interfaces that represent collections of objects, but there are several key differences between them.

Duplicates:
A List can contain duplicate elements, whereas a Set cannot. In a List, elements are ordered by their index position, while in a Set, elements are unordered and cannot be accessed by index.

Ordering:
Lists maintain the order in which elements were added, whereas Sets do not have a defined order. In other words, Lists have a sequential ordering, while Sets do not.

Retrieval:
In a List, elements can be retrieved by their index position, whereas in a Set, elements can be retrieved by iterating over the Set.

Performance:
Lists are generally faster when accessing elements by index position, whereas Sets are faster when checking whether an element is contained in the collection.

Usage:
Lists are typically used when there is a need to maintain a specific order of elements, and when there may be duplicates. Sets are typically used when there is a need to store unique elements and order is not important.

In summary, the main difference between Set and List is that Sets cannot contain duplicates and do not have a defined order, whereas Lists can contain duplicates and maintain the order of elements. The choice between the two depends on the specific requirements of the program or application being developed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the difference between a Array and an ArrayList (or any List)

A

Arrays and Lists are both used to store collections of elements, but they have some key differences.

An array is a fixed-size collection of elements that are stored in contiguous memory locations. Once the size of an array is defined, it cannot be changed. Elements in an array can be accessed using an index that starts from 0. Arrays are generally faster than Lists when it comes to accessing elements by index position.

A List, on the other hand, is a dynamic collection of elements that can grow or shrink in size as needed. Unlike an array, the size of a List can be changed at runtime. There are several types of Lists in Java, such as ArrayList, LinkedList, and Vector. Lists are generally slower than arrays when it comes to accessing elements by index position, but they are more flexible and provide more features such as adding, removing, and searching elements.

ArrayList is a specific type of List in Java that is implemented using an array. The ArrayList class provides methods to add, remove, and retrieve elements from the list. It can grow or shrink in size dynamically, and it is usually faster than LinkedList when it comes to accessing elements by index position. However, ArrayList may not be the best choice when it comes to frequent additions or deletions from the middle of the list, as it can be slow and inefficient.

In summary, the main difference between an array and a List (such as ArrayList) is that arrays have a fixed size and are faster when accessing elements by index position, while Lists are dynamic and provide more features such as adding, removing, and searching elements. The choice between the two depends on the specific requirements of the program or application being developed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are collections in Java?

A

Collections in Java are used to store and manipulate groups of objects. They are implemented using various interfaces and classes that are part of the Java Collection Framework.

The Java Collection Framework provides a set of standard interfaces and classes that define the behavior of collections and provide implementations of various collection types. These interfaces include List, Set, Map, Queue, Deque, and their subtypes.

List and Set are both used to store collections of objects. List maintains the order in which elements are added, while Set does not allow duplicates. Map is used to store key-value pairs, where each key is associated with a value. Queue and Deque are used to store elements in a specific order, such as first-in-first-out (FIFO) or last-in-first-out (LIFO).

Collections in Java provide several benefits, such as increased efficiency and code reusability. They provide a standardized way of manipulating groups of objects, making it easier to read and write code. Collections also provide various methods for adding, removing, and manipulating elements, making it easier to work with groups of objects in a program.

In summary, collections in Java are a set of interfaces and classes that are used to store and manipulate groups of objects. They provide a standardized way of working with groups of objects and provide several benefits such as increased efficiency and code reusability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

throw vs throws vs Throwable?

A

throw is a keyword in Java that is used to explicitly throw an exception. When an exceptional condition occurs in a program, such as a divide-by-zero error or an invalid argument, an exception can be thrown using the throw keyword. This exception can be caught and handled by the calling method or propagated up the call stack.

throws is a keyword in Java that is used in method signatures to indicate that the method can potentially throw one or more exceptions. When a method is declared with the throws keyword, it means that the method can throw an exception, but it does not handle it. The exception must be caught and handled by the calling method or propagated up the call stack.

Throwable is the superclass of all exceptions and errors in Java. It is the root of the exception hierarchy in Java. All exceptions and errors in Java extend from the Throwable class. When an exceptional condition occurs in a program, an exception object is created that represents the exceptional condition. This exception object can be thrown using the throw keyword, and it can be caught and handled by the calling method or propagated up the call stack.

In summary, throw is used to explicitly throw an exception, throws is used to indicate that a method can potentially throw an exception, and Throwable is the superclass of all exceptions and errors in Java. These concepts are all related to exception handling in Java and are used to indicate, propagate, and handle exceptions in a program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Do you need a catch block? Can have more than 1? Order of them?

A

Yes, in Java, if you are using a try block, then you must have at least one catch block or a finally block, or both. The catch block is used to handle any exceptions that are thrown by the code inside the try block.

Yes, you can have more than one catch block in Java, and the order of the catch blocks matters. When an exception is thrown inside the try block, Java will try to match the type of the exception to the types of exceptions that are listed in each catch block, in the order in which they appear.

If an exception matches the type of an exception that is listed in a catch block, then the code inside that catch block will be executed. If the exception does not match the type of any of the catch blocks, then the exception will be propagated up the call stack until it is caught by a catch block that matches the type of the exception.

In general, it is best practice to order catch blocks from most specific to least specific. This means that catch blocks for more specific exceptions should come before catch blocks for more general exceptions. This is because if a more general catch block comes before a more specific catch block, it will catch exceptions that could have been handled by the more specific catch block.

In summary, a catch block is required if a try block is used in Java. Multiple catch blocks can be used, and the order of the catch blocks matters. The best practice is to order catch blocks from most specific to least specific.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are the different ways of handling checked exceptions?

A

Sure, there are several ways to handle checked exceptions in Java.

The first way is to use a try-catch block to catch the exception and handle it. In this approach, we wrap the code that could potentially throw an exception in a try block and use a catch block to handle the exception if it is thrown.

Another way to handle checked exceptions is to use the throws keyword in the method signature. This approach involves declaring the exception that the method could potentially throw using the throws keyword. The calling method is then responsible for handling the exception.

A third way to handle checked exceptions is to use the finally block. The finally block is executed whether an exception is thrown or not, making it useful for cleaning up resources or performing other necessary actions regardless of the outcome of the code.

A fourth way to handle checked exceptions is to use the try-with-resources statement. This approach is used when working with resources that implement the AutoCloseable interface. The try-with-resources statement automatically closes the resource after the try block, even if an exception is thrown.

In summary, the different ways of handling checked exceptions in Java include using try-catch blocks, using the throws keyword in the method signature, using the finally block, and using the try-with-resources statement. Each approach has its advantages and disadvantages and is used in different situations depending on the requirements of the code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Difference between checked and unchecked exceptions?

A

Yes, in Java, there are two types of exceptions: checked and unchecked exceptions.

Checked exceptions are exceptions that are checked at compile-time. This means that the compiler will check to see if the exception is handled or declared to be thrown in the method signature. If the exception is not handled or declared to be thrown, the code will not compile. Examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.

On the other hand, unchecked exceptions are exceptions that are not checked at compile-time. This means that the compiler does not force you to catch or declare them in the method signature. Unchecked exceptions are typically caused by programming errors, such as NullPointerException or ArrayIndexOutOfBoundsException. These types of exceptions can be caught and handled, but they do not need to be declared in the method signature.

The main difference between checked and unchecked exceptions is that checked exceptions are checked at compile-time, while unchecked exceptions are not. Checked exceptions must be handled or declared to be thrown, while unchecked exceptions do not need to be handled or declared. Because of this, checked exceptions are usually used for exceptional conditions that can be reasonably expected to occur, such as file I/O errors, while unchecked exceptions are used for programming errors or other unexpected conditions.

In summary, checked exceptions are checked at compile-time and must be handled or declared to be thrown, while unchecked exceptions are not checked at compile-time and do not need to be handled or declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

List some checked and unchecked exceptions?

A

Can you provide some examples of checked and unchecked exceptions in Java?

Me: Sure, here are some examples of both checked and unchecked exceptions in Java:

Checked exceptions:

IOException: This exception is thrown when an I/O operation fails or is interrupted, such as when reading from or writing to a file.
SQLException: This exception is thrown when there is an error accessing a database or executing a SQL statement.
ClassNotFoundException: This exception is thrown when the Java Virtual Machine (JVM) cannot find a class at runtime that was previously available.
Unchecked exceptions:

NullPointerException: This exception is thrown when an application attempts to use null in a case where an object is required.
ArrayIndexOutOfBoundsException: This exception is thrown when an array index is out of bounds.
ArithmeticException: This exception is thrown when an arithmetic operation results in an error, such as division by zero.
In general, checked exceptions are used for exceptional conditions that can be reasonably expected to occur, while unchecked exceptions are used for programming errors or other unexpected conditions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is base class of all exceptions? What interface do they all implement?

A

In Java, the base class of all exceptions is java.lang.Throwable. All exceptions, both checked and unchecked, inherit from this class.

The Throwable class implements the java.lang.Serializable interface, which allows objects to be serialized and deserialized. It also provides two important methods that are commonly used in exception handling:

getMessage(): Returns a detailed message about the exception.

printStackTrace(): Prints the stack trace of the exception, including the method calls that led to the exception being thrown.

By implementing the Throwable class, all exceptions in Java have access to these methods and can use them to provide useful information to developers and users when errors occur.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Can you overload / override a main method?
1. static method?
2. a private method?
3. a default method?
4. a protected method?

A

Can you overload/override a main method?
Yes, you can overload the main method in Java, but you cannot override it. Overloading means creating a method with the same name but different parameters in the same class. This can be useful if you want to have multiple entry points to your application.

For example, you can have a main method that takes no arguments, and another main method that takes a String array as an argument:

public class MyClass {
public static void main(String[] args) {
System.out.println(“Main method with String[] argument”);
}

public static void main() {
    System.out.println("Main method with no arguments");
} }

Can you overload/override a static method?
Yes, you can overload and override a static method in Java. Overloading a static method means creating a method with the same name but different parameters in the same class. Overriding a static method means creating a method with the same name and signature in a subclass.

However, it is important to note that when you call a static method, the method that is invoked is determined at compile time based on the type of the reference variable, not the type of the object. This means that if you override a static method in a subclass, the subclass method will not be called if you call the method using a reference variable of the superclass type.

Can you overload/override a private method?
You can overload a private method in Java, but you cannot override it. Overloading a private method means creating a method with the same name but different parameters in the same class. However, since a private method is not accessible outside of the class in which it is declared, it cannot be overridden by a subclass.

Can you overload/override a default method?
Yes, you can overload and override a default method in Java. Default methods were introduced in Java 8 to allow for the addition of new methods to an interface without breaking existing code. Overloading a default method means creating a method with the same name but different parameters in the same interface. Overriding a default method means creating a method with the same name and signature in a class that implements the interface.

Can you overload/override a protected method?
Yes, you can overload and override a protected method in Java. Overloading a protected method means creating a method with the same name but different parameters in the same class or a subclass. Overriding a protected method means creating a method with the same name and signature in a subclass. A protected method is accessible within the same package and in subclasses, but not outside the package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between static and final variables?

A

Static and final are both keywords in Java that are used to modify variables, but they have different meanings.

A static variable is a variable that belongs to the class itself rather than to any particular instance of the class. This means that there is only one copy of the variable, regardless of how many instances of the class are created. Static variables are often used to store data that is shared across all instances of the class.

A final variable, on the other hand, is a variable whose value cannot be changed once it has been initialized. This means that the variable is effectively a constant. Final variables are often used to store values that are used throughout the program and should not be changed.

Here are some key differences between static and final variables:

Initialization: A static variable can be initialized either when it is declared or in a static block of code, while a final variable must be initialized when it is declared.

Memory allocation: Static variables are allocated memory only once, at the time the class is loaded, while final variables are allocated memory each time an instance of the class is created.

Value modification: A static variable can be modified throughout the lifetime of the program, while a final variable cannot be modified after it has been initialized.

Access: Static variables can be accessed using the class name, while final variables are accessed using the instance of the class.

In summary, static variables are used to store data that is shared across all instances of the class, while final variables are used to store values that should not be changed throughout the program.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between == and .equals()?

A

In Java, == and .equals() are both used for comparison, but they have different meanings.

The == operator compares two objects to see if they are the same object in memory. It checks if the two object references point to the same memory location. It is a binary operator that can be used to compare two primitive data types or two object references.

For example:

int a = 5;
int b = 5;
System.out.println(a == b); // true

String s1 = “Hello”;
String s2 = “Hello”;
String s3 = new String(“Hello”);
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false

In this example, the first == comparison returns true because a and b both have the same value of 5. The second == comparison returns true because s1 and s2 both refer to the same String object in memory, which is created by the compiler. The third == comparison returns false because s1 and s3 refer to different String objects in memory.

The .equals() method, on the other hand, compares the values of two objects to see if they are equal. It checks if the two objects have the same state, i.e., if their member variables have the same values. It is a method that is defined in the Object class and can be overridden by subclasses to provide a more specific implementation.

For example:

String s1 = “Hello”;
String s2 = “Hello”;
String s3 = new String(“Hello”);
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true

In this example, both .equals() comparisons return true because the String objects have the same value, even though they are different objects in memory.

In summary, == compares object references to see if they are the same object in memory, while .equals() compares the values of two objects to see if they are equal. It is important to use the correct comparison method depending on what you are trying to achieve in your code.

17
Q

How can you force garbage collection in Java?

A

n Java, you cannot force the garbage collector to run, as it is up to the JVM to decide when to run it. However, you can suggest to the JVM that it should run the garbage collector by calling the System.gc() method.

The System.gc() method suggests that the JVM should run the garbage collector. However, there is no guarantee that the garbage collector will actually run. The JVM may choose to ignore the suggestion if it believes that it is not necessary.

Here is an example of how to call System.gc():

// Create some objects
Object obj1 = new Object();
Object obj2 = new Object();

// Set the objects to null, making them eligible for garbage collection
obj1 = null;
obj2 = null;

// Suggest to the JVM that it should run the garbage collector
System.gc();

In this example, we create two objects and then set their references to null, making them eligible for garbage collection. We then call System.gc() to suggest to the JVM that it should run the garbage collector.

Note that it is generally not recommended to call System.gc() explicitly, as it can have a negative impact on performance. The garbage collector is designed to run automatically and is usually very good at managing memory efficiently without external intervention.

18
Q

What is autoboxing / unboxing?

A

Autoboxing and unboxing are features introduced in Java 5 that provide a way to convert between primitive types and their corresponding object wrapper classes automatically.

Autoboxing is the process of converting a primitive data type (such as int, float, or double) to its corresponding object wrapper class (such as Integer, Float, or Double) automatically, without the need for explicit conversion. Autoboxing is done by the compiler behind the scenes.

For example, instead of writing:

int num = 10;
Integer numObj = new Integer(num);
You can simply write:

int num = 10;
Integer numObj = num;

The second line is an example of autoboxing. The compiler automatically converts the int value 10 to an Integer object.

Unboxing is the reverse process of autoboxing. It is the process of converting an object of a wrapper class back to its corresponding primitive data type automatically.

For example, instead of writing:

Integer numObj = new Integer(10);
int num = numObj.intValue();
You can simply write:

Integer numObj = new Integer(10);
int num = numObj;
The second line is an example of unboxing. The compiler automatically converts the Integer object numObj to an int value.

Autoboxing and unboxing can simplify code and make it more readable by eliminating the need for explicit conversions between primitive data types and their corresponding object wrapper classes. However, it is important to note that autoboxing and unboxing can have performance implications, as they involve the creation of additional objects, so they should be used judiciously in performance-critical code.

19
Q

Explain stack vs heap?

A

In Java, memory is divided into two areas: the stack and the heap.

The stack is a region of memory used to store data that is local to a function or method. Each thread in a Java application has its own stack. When a method is called, a new block of memory is created on the stack to hold the method’s local variables and parameters. When the method returns, the memory is automatically freed. This is why the stack is often referred to as “automatic memory”.

The stack is fast and efficient because it is managed by the system and does not require garbage collection. However, the amount of memory available on the stack is limited, and if the stack overflows, it can cause a stack overflow error.

The heap, on the other hand, is a region of memory used to store objects. When an object is created in Java, it is allocated on the heap. The heap is much larger than the stack and is shared by all threads in an application.

The heap is managed by the garbage collector, which periodically frees memory that is no longer being used by the program. Because the garbage collector needs to traverse the entire heap to determine which objects are still in use, garbage collection can be a time-consuming process, especially for large applications.

In general, objects that are short-lived or have a well-defined lifespan are usually allocated on the stack, while objects that need to persist beyond the lifespan of a method or function are allocated on the heap.

It’s important to note that Java programmers do not have direct control over the stack or the heap. Java manages memory allocation and deallocation automatically through its built-in memory management system.

20
Q

If two objects are equal, do they have the same hashcode? If not equal?

A

If two objects are equal, they should have the same hashcode, but it is possible for two unequal objects to have the same hashcode.

In Java, the Object class has two methods that are used for comparing objects: equals() and hashCode(). The equals() method is used to compare the contents of two objects to determine if they are equal, while the hashCode() method returns an integer value that represents the object’s hash code.

By convention, if two objects are equal according to the equals() method, they should have the same hashcode. This means that if you override the equals() method for a class, you should also override the hashCode() method to ensure that equal objects have the same hashcode.

However, it is possible for two unequal objects to have the same hashcode. This is known as a hash collision. A hash collision can occur when two different objects have the same hashcode value. When this happens, the objects are placed in the same bucket of a hash table, and their equality is determined by the equals() method.

To minimize the likelihood of hash collisions, it is important to implement a good hash function that distributes hashcodes evenly across the range of possible hashcode values. A good hash function should produce different hashcodes for different objects, while still producing the same hashcode for equal objects.

21
Q

What is the root class from which every class extends?

A

In Java, the java.lang.Object class is the root class from which every class in Java extends. This means that every class in Java is a subclass of Object, either directly or indirectly.

The Object class provides a number of important methods that are inherited by all classes, including the equals(), hashCode(), and toString() methods, among others. These methods provide a common interface for working with objects in Java and are essential for writing robust and reliable Java code.