LATEST UPDATES

Friday 18 November 2016

What is the difference between continue and break statement?



Break and continue are two important keywords used in Loops. When a break keyword is used in a loop, loop is broken instantly while when continue keyword is used, current iteration is broken and loop continues with next iteration.

In below example, Loop is broken when counter reaches 4.



for (counter=0;counter
System.out.println(counter);
 
if (counter==4) {
 
break;}
 
}



In the below example when counter reaches 4, loop jumps tonext iteration and any statements after the continue keyword are skipped for current iteration.



for (counter=0;counter
System.out.println(counter);
 
if (counter==4) {
 
continue;
 
}
 
System.outprintln("This will not get printed when counter is 4");
 
}
Java

1

for (counter=0;counter

What is a singleton class? Give a practical example of its usage.

A singleton class in java can have only one instance and hence all its methods and variables belong to just one instance. Singleton class concept is useful for the situations when there is a need to limit the number of objects for a class.
The best example of singleton usage scenario is when there is a limit of having only one connection to a database due to some driver limitations or because of any licensing issues.

What’s the purpose of Static methods and static variables?

When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.

What are the various access specifiers for Java classes?

1. Public : Class,Method,Field is accessible from anywhere.
2. Protected:Method,Field can be accessed from the same class to which they belong or from the sub-classes,and from the class of same package,but not from outside.
3. Default: Method,Field,class can be accessed only from the same package and not from outside of it’s native package.
4. Private: Method,Field can be accessed from the same class to which they belong.

What is the difference between an Inner Class and a Sub-Class?

An Inner class is a class which is nested within another class. An Inner class has access rights for the class which is nesting it and it can access all variables and methods defined in the outer class.
A sub-class is a class which inherits from another class called super class. Sub-class can access all public and protected methods and fields of its super class.

What is the difference between throw and throws ?

The throw keyword is used to explicitly raise a exception within the program.

The throws clause is used to indicate those exceptions that are not handled by a method.

Each method must explicitly specify which exceptions does not handle, so the callers of that method can guard against possible exceptions. 

Finally, multiple exceptions are separated by a comma.

What is the difference between HashSet and TreeSet ?


  • The HashSet is Implemented using a hash table.
  • Its elements are not ordered. 
  • The add, remove, and contains methods of a HashSet.
  • Time  complexity O(1). 



  •  TreeSet is implemented using a tree structure. 
  • The elements in a TreeSet are sorted.
  • The add, remove, and contains methods.
  • Time complexity  O(logn).

What is Comparable and Comparator interface ? List their differences.

Java provides the Comparableinterface, --> which contains only one method, called compareTo

  1. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object. 



Java provides the Comparator interface, --> which contains two methods, called compare and equals


  1. The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. 
  2. The second method requires an object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator.

What is difference between ArrayList and LinkedList ?


1) ArrayList internally uses dynamic array to store the elements.
LinkedList internally uses doubly linked list to store the elements.

2) Manipulation with ArrayList is slow because it internally uses array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses doubly linked list so no bit shifting is required in memory.

3) ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.


4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.

What is difference between Array and ArrayList ? When will you use Array over ArrayList ?

  • Arrays can contain primitive or objects, while an ArrayList can contain only objects.
  • Arrays have fixed size, while an ArrayList is dynamic.
  • An ArrayListprovides more methods and features, such as addAllremoveAlliterator, etc.
  • For a list of primitive data types, the collections use autoboxing to reduce the coding effort. However, this approach makes them slower when working on fixed size primitive data types.

Array
ArrayList
Arrays are data structures that can store elements of similar data type.
ArrayList is a collection that can store elements of similar data type as well as elements of different data type.
Along with objects, Arrays can also store elements of primitive data type.
ArrayList cannot store elements of primitive data type. ArrayList can store only objects.
Array size is fixed.
ArrayList is resizable. Its size is not fixed.
While declaring and creating the Array, the size is specified in square brackets []. For example,
int[] intArray = new int[10]
The above statement creates an integer array of size 10. After creating it, its size cannot be changed. It cannot hold more than 10 elements.
ArrayList has a special parameter called initialCapacity using which the initial size of the ArrayList is specified. Later on, the ArrayList can be resized.
Array cannot automatically grow or shrink in size.
ArrayList has the capability to automatically grow and shrink in size. When an element is removed from the ArrayList, its size is reduced by 1. When an element is added to the ArrayList and if its initial capacity is reached then the size is automatically increased by 1.
Array is not part of collection framework. Arrays are directly defined in java language as a basic data structure.
ArrayList is part of Collection framework.
Arrays inherit from java.lang.Object.
ArrayList implements List interface and inherits AbstractList class.
Generics cannot be used along with Arrays.
When elements of similar data type have to be stored in an ArrayList then the ArrayList will use generics.
Arrays can be single dimensional or multi dimensional.
ArrayList can only be single dimensional.
Arrays are present in java.lang package. However a customized array class is present in java.util package. This java.util.Arrays has the capability to perform binary search, copy of another array, fill, sort and much more using its predefined methods.
ArrayList is present in java.util package. ArrayList also has rich predefined methods such as add, addAll, remove, toArray, iterator, listiterator, sort, reverse and much more.
Arrays can be iterated through a simple for loop by iterating over its index.
ArrayList can be iterated using Iterator or ListIterator.
Arrays cannot be synchronized.
ArrayList can be synchronized.
Array elements are accessed using its index. The index ranges from 0 to array length-1.
ArrayList elements are accessed using get() and other specialized methods.

What differences exist between HashMap and Hashtable ?


    1. HashMap allows the existence of null keys and values, 
    2. Hashtable doesn’t allow neither null keys, nor null values.

    1. Hashtable is synchronized.
    2. while a HashMap is not.

    1.  HashMap is preferred in single-threaded environments.
    2.  Hashtable is suitable for multi-threaded environments.

    1. HashMap provides its set of keys and a Java application can iterate over them.
    2. Hashtable provides an Enumeration of its keys.

What is the importance of hashCode() and equals() methods ?


  • In Java, a HashMap uses the hashCode and equals methods to determine the index of the key-value pair and to detect duplicates.
  • More specifically, the hashCodemethod is used in order to determine where the specified key will be stored. 
  • Since different keys may produce the same hash value, the equals method is used, in order to determine whether the specified key actually exists in the collection or not.
  • Therefore, the implementation of both methods is crucial to the accuracy and efficiency of the HashMap.

How HashMap works in Java ?


  • The HashMap requires a hash function and uses hashCode and equals methods, in order to put and retrieve elements to and from the collection respectively. 
  • When the put method is invoked, the HashMap calculates the hash value of the key and stores the pair in the appropriate index inside the collection. 
  • If the key exists, its value is updated with the new value. 
  • Some important characteristics of a HashMap are its capacity, its load factor and the threshold resizing.

Java Collections

Java Collections Framework provides a well designed set of interfaces and classes that support operations on a collections of objects. The most basic interfaces that reside in the Java Collections Framework are:
  • Collection, which represents a group of objects known as its elements.
  • Set, which is a collection that cannot contain duplicate elements.
  • List, which is an ordered collection and can contain duplicate elements.
  • Map, which is an object that maps keys to values and cannot contain duplicate keys.

What is the difference between a synchronized method and a synchronized block ?

In Java programming, each object has a lock. 
A thread can acquire the lock for an object by using the synchronized keyword. 
The synchronized keyword can be applied in a method level  or block level of code.

Explain the available thread states in a high-level.

  • NEW: The thread becomes ready to run, but does not necessarily start running immediately.
  • RUNNABLE: The Java Virtual Machine (JVM) is actively executing the thread’s code.
  • BLOCKED: The thread is in a blocked state while waiting for a monitor lock.
  • WAITING: The thread waits for another thread to perform a particular action.
  • TIMED_WAITING: The thread waits for another thread to perform a particular action up to a specified waiting time.
  • TERMINATED: The thread has finished its execution.

Explain different ways of creating a thread. Which one would you prefer and why ?

There are three ways that can be used in order for a Thread to be created:
  • A class may extend the Thread class.
  • A class may implement the Runnable interface.
  • An application can use the Executor framework, in order to create a thread pool.
The Runnable interface is preferred, as it does not require an object to inherit the Thread class. 

What is the difference between an Interface and an Abstract class ?

Interface  v/s  Abstract class


  • All methods in an interface are implicitly abstract
  • Abstract class may contain both abstract and non-abstract methods.

  • A class may implement a number of Interfaces
  • Abstract class can extend only one abstract class


  • In order for a class to implement an interface, it must implement all its declared methods. However, a class may not implement all declared methods of an abstract class. Though, in this case, the sub-class must also be declared as abstract.
  • Abstract classes can implement interfaces without even providing the implementation of interface methods.

  • Variables declared in a Java interface is by default final.
  • An abstract class may contain non-final variables.

  • Members of a Java interface are public by default.
  • A member of an abstract class can either be private, protected or public.

Does Java support multiple inheritance ?

No, Java does not support multiple inheritance. Each class is able to extend only on one class, but is able to implement more than one interfaces.

Can you access non static variable in static context ?


  • A static variable in Java belongs to its class and its value remains the same for all its instances.
  • A static variable is initialized when the class is loaded by the JVM.
  • If your code tries to access a non-static variable, without any instance, the compiler will complain, because those variables are not created yet and they are not associated with any instance.

What does the “static” keyword mean ? Can you override private or static method in Java ?

The static keyword denotes that a member variable or method can be accessed, without requiring an instantiation of the class.


  • User cannot override static methods in Javabecause method overriding is based upon dynamic binding at run time.
  • Static methods are statically binded at compile time
  • A static method is not associated with any instance of a class so the concept is not applicable.

What is the Difference between JDK and JRE ?


  • The Java Runtime Environment (JRE) is
    •  Basically the Java Virtual Machine (JVM) 
    • Where your Java programs are being executed. 
    • It also includes browser plugins for applet execution. 
  • The Java Development Kit (JDK) is 
    • The full featured Software Development Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java Debugger), in order for a user to develop, compile and execute Java applications.


Designed By Blogger Templates