Java Interview Prep 2

Ace your homework & exams now with Quizwiz!

What is Exception in Java?

Exception is an error event that can happen during the execution of a program and disrupts it's normal flow.

What is an iterator?

Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection

What is Java I/O ?

Java I/O (Input and Output) is used to process the input and produce the output

What is an array?

- An Array stores multiple variables with the same type. It can hold primitive types and object references. - Arrays are always fixed. - An Array is declared similar to how a variable is declared, but you need to add [] after the type. Example: int [] intArray;

What is an interface?

- An interface is a reference type in Java. It is a collection of abstract methods. - An interface cannot be instantiate. - An interface does not contain any constructors. - An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. - An interface is not extended by a class; it is implemented by a class. - An interface can extend multiple interfaces.

Can you tell me the differences between Array and ArrayList?

- Array is static with a fixed size which cannot be changed once delared, while ArrayList is dynamic in size. As elements added to an ArrayList, its capacity or size grows automaticically. - Array contains both primitive data types and objects of a class, while ArrayList does not contain the primitive data types but contains object entries - Array does not have Generics feature, while ArrayList has Generics feature.

What is the difference between an array and a linked list?

- Array requires contiguous memory for its element but linked list elements can be scattered in memory, which means it would be difficult to create a big array but your linked list can grow easily. - An array is good for searching elements if you know the index, but adding and removing elements in an array is expensive as compared to the linked list

What is the difference between an abstract class and interface?

- interfaces can only have abstract methods where as abstract class can have both - interfaces support multiple inheritance wheres as abstract classes do not - interfaces can only have static and final variables - interfaces cant have static methods, main method, or constructors, while abstract classes can

What are the main differences between array and collection?

- Arrays are always of fixed size, but In Collection, size can be changed dynamically as per need. - Arrays can only store homogeneous or similar type objects, but in Collection, heterogeneous objects can be stored. -Arrays cannot provide the ?ready-made? methods for user requirements as sorting, searching, etc. but Collection includes readymade methods to use.

What class add-on allows you to speed up reading / writing by using a buffer?

- BufferedInputStream - BufferedOutputStream - BufferedReader - BufferedWriter

Overloading order of operations:

- Exact match - Conversion -> Primitives/Objects cast themselves to other types. - Boxing -> Primitives/Objects will undergo -Auto Boxing/UnBoxing - Varargs -> arguments wrapped into arrays.

What is the difference between HashMap and TreeMap?

- HashMap maintains no order, but TreeMap maintains ascending order. - HashMap is implemented by hash table whereas TreeMap is implemented by a Tree structure. - HashMap can be sorted by Key or value whereas TreeMap can be sorted by Key. - HashMap may contain a null key with multiple null values whereas TreeMap cannot hold a null key but can have multiple null values.

What is the difference between HashSet and HashMap?

- HashSet contains only values whereas HashMap includes the entry (key, value). - HashSet can be iterated, but HashMap needs to convert into Set to be iterated. -HashSet cannot have any duplicate value whereas HashMap can contain duplicate values with unique keys. -HashSet contains the only single number of null value whereas HashMap can hold a single null key with n number of null values.

What is the difference between HashSet and TreeSet?

- HashSet maintains no order whereas TreeSet maintains ascending order. - HashSet impended by hash table whereas TreeSet implemented by a Tree structure. - HashSet performs faster than TreeSet. - HashSet is backed by HashMap whereas TreeSet is backed by TreeMap.

What is common and how do the following streams differ: InputStream, OutputStream, Reader, Writer?

- InputStream: the base class, read data from source -OutputStream: abstract class that defines stream byte output, write data into destination -Reader class: abstract class that defines character streaming input -Writer class: abstract class that defines character stream output.

What is the difference between Set and Map?

- Set contains values only whereas Map contains key and values both. - Set contains unique values whereas Map can contain unique Keys with duplicate values. - Set holds a single number of null value whereas Map can include a single null key with n number of null values.

What is the difference between Collection and Collections?

- The Collection is an interface whereas Collections is a class. - The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements. - The Collection interface provides the methods that can be used for data structure whereas Collections class provides the static methods which can be used for various operation on a collection.

What is the difference between List and Set?

- The List can contain duplicate elements whereas Set includes unique items. - The List is an ordered collection which maintains the insertion order whereas Set is an unordered collection which does not preserve the insertion order. - The List interface contains a single legacy class which is Vector class whereas Set interface does not have any legacy class. - The List interface can allow n number of null values whereas Set interface only allows a single null value.

What Are Some Advantages of Using Generic Types?

- avoiding casts and provide type safety - avoid code duplication.

What are the Exception Handling Keywords in Java?

- throw: used to throw exception to the runtime to handle it. - throws: use in method signature to let caller program know the exceptions that might be thrown by the method. - try-catch: try is the start of the block and catch is at the end of try block to handle the exceptions. catch block requires a parameter that should be of type Exception. - finally: optional and can be used only with try-catch block. finally block gets executed always, whether exception occurrs or not.

What is the difference between ArrayList and Vector?

1)ArrayList is not synchronized.Vector is synchronized. 2)ArrayList is not a legacy class.Vector is a legacy class. 3)ArrayList increases its size by 50% of the array size.Vector increases its size by doubling the array size. 4)ArrayList is not thread-safe as it is not synchronized.Vector list is thread-safe as its every method is synchronized.

What is the difference between ArrayList and LinkedList?

1)ArrayList uses a dynamic array.LinkedList uses a doubly linked list. 2)ArrayList is not efficient for manipulation because too much is required.LinkedList is efficient for manipulation. 3)ArrayList is better to store and fetch data.LinkedList is better to manipulate data. 4)ArrayList provides random access.LinkedList does not provide random access. 5)ArrayList takes less memory overhead as it stores only objectLinkedList takes more memory overhead, as it stores the object as well as the address of that object.

What is the difference between Comparable and Comparator?

1)Comparable provides only one sort of sequence.The Comparator provides multiple sorts of sequences. 2)It provides one method named compareTo().It provides one method named compare(). 3)It is found in java.lang package.It is located in java.util package. 4)If we implement the Comparable interface, The actual class is modified.The actual class is not changed.

What is abstraction and abstract class in Java?

A class that is declared as abstract is known as abstract class. It needs to be extended and its method implemented. It cannot be instantiated.

What is the difference between StringBuffer and String class ?

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created.

What are Wrapper Classes?

A wrapper class wraps or encloses around a data type to give it an object appearance.

What is abstract method in Java?

An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration. All method declared inside Java Interface are by default abstract.

What is the difference between BufferedReader and FileReader in Java?

BufferedReader is a Decorator that provides buffering for faster IO, while FileReader is used to read data from File.

What is the difference between checked and unchecked exceptions?

Checked Exceptions should be handled in the code using try-catch block or else method should use throws keyword to let the caller know about the checked exceptions that might be thrown from the method. Unchecked Exceptions are not required to be handled in the program or to mention them in throws clause of the method. Exception is the super class of all checked exceptions whereas RuntimeException is the super class of all unchecked exceptions. Note that RuntimeException is the child class of Exception.

What is an error?

Errors are exceptional scenarios that are out of scope of application and it's not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error.

What is a priority queue?

Every item in the queue has a priority, and Higher-priority items are dequeued before lower-priority items.

Explain the scenerios to choose between String , StringBuilder and StringBuffer ?

If the Object value will not change in a scenario use String Class because a String object is immutable. If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized(means faster). If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).

What is difference between Scanner and BufferedReader?

Scanner is used for parsing tokens from the contents of the stream while BufferedReader just reads the stream and does not do any special parsing. Usually we pass a BufferedReader to a scanner as the source of characters to parse.

What is serialization?

Serialization is the process of converting a Serializable Java object to a byte stream; deserialization is the process of restoring an object from these bytes

What is String in Java?

String in immutable and final in Java and JVM uses String Pool to store all the String objects.Some other interesting things about String is the way we can instantiate a String object using double quotes

Difference between StringBuffer and StringBuilder ?

StringBuffer is synchronized whereas StringBuilder is not.

Difference between ArrayList and HashSet in Java?

The main difference is the former is List while the later is Set which means ArrayList allowed duplicates, keeps elements in order while HashSet doesn't allow duplicates and provides no ordering guarantee.

What are the types of I / O streams?

There are two types of I / O streams: byte and character.

Difference between HashMap and ArrayList in Java?

There is a huge difference between HashMap and ArrayList, fundamental is former is a Map data structure which stores key-value pairs while the later stores just an object. HashMap access object using key while ArrayList access elements using an index.

Explain Java Exception Hierarchy?

Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects - Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.

What are the conditions for "successful" serialization of an object?

To be serializable, the class must implement the Serializable interface tag. Also, all attributes and subtypes of the class being serialized must be serializable. If the ancestor class was non-realizable, then this superclass must contain an accessible (public, protected) constructor without parameters to initialize the fields.

What is the use of var args ?

Var args is the feature of Java that allows a method to have variable number of arguments. Var args are used when we are not sure about the number of arguments a method may need. Internally java treats them as array.

How to write custom exception in Java?

We can extend Exception class or any of it's subclasses to create our custom exception class. The custom exception class can have it's own variables and methods that we can use to pass error codes or other exception related information to the exception handler.

Can we have an empty catch block?

We can have an empty catch block but it's the example of worst programming. We should never have empty catch block because if the exception is caught by that block, we will have no information about the exception and it wil be a nightmare to debug it. There should be at least a logging statement to log the exception details in console or log files.

What happens when exception is thrown by main method?

When exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

What is the Collection framework in Java?

a combination of classes and interface, which is used to store and manipulate the data in the form of objects.

What Is a Generic?

a generic type parameter is when a type can be used as a parameter in a class, method or interface declaration. - public interface Consumer<T> { public void consume(T parameter) }

What is Autoboxing and Unboxing?

autoboxing: java automatically converts a primitive into corresponding object wrapper unboxing: oposite

Difference between length() of array and size() of ArrayList in Java?

if you get the backed array and call the length() it will return how many elements you can store in this array, also known as capacity, but if you call the size() function of ArrayList class then it will return a total number of elements currently stored in ArrayList, which is always less than or equal to capacity.

Why you need to close the streams in finally block?

we do this because finally block is always executed irrespective of exception in a try block or not.


Related study sets

Grade 7 Structures And Forces - LA

View Set

Bankruptcy, Closed-end credit, Collateral, Collection agency, Creditor, Credit report, Credit score, Debt, Debtor, Down payment, Installment loan, Open-end credit, Payday loan, Predatory lending, Secured loan, Title loan, Unsecured loan, Wage garnishment

View Set

macro chapter 10, Econ Quiz 8, Money and banking chapter 10, Econ Chapter 10 Macro, ECN Chapter 10, ch 11 econ quiz, ch 10 econ quiz, Macroeconomics Quiz

View Set

Pharm 2. Chapter 43 Drugs Affecting Blood Pressure

View Set

Classification of Deferred Tax Accounts

View Set

Testout 7.0 14.7 Malware Protection

View Set