Intermediate java Flashcards
How would you iterate over a Map?
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
Are Maps in the Collections API?
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.
What is the difference between ArrayList and LinkedList?
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.
What are generics?
What is the diamond operator (<>)?
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.
What is the difference between a Set and a List?
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.
What is the difference between a Array and an ArrayList (or any List)
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.
What are collections in Java?
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.
throw vs throws vs Throwable?
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.
Do you need a catch block? Can have more than 1? Order of them?
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.
What are the different ways of handling checked exceptions?
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.
Difference between checked and unchecked exceptions?
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.
List some checked and unchecked exceptions?
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.
What is base class of all exceptions? What interface do they all implement?
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.
Can you overload / override a main method?
1. static method?
2. a private method?
3. a default method?
4. a protected method?
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.
What is the difference between static and final variables?
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.