Sunday 13 August 2017

Java popular Q&A

Can you override a private or static method in Java?

 you can not override a private or static method in Java, if you create a similar method with same return type and same method arguments in child class then it will hide the superclass method, this is known as method hiding.
Though you can declare a method with same name and method signature in sub class which does look like you can override static method in Java but in reality that is method hiding.

If you use Java IDE like Eclipse or Netbeans, they will show warning that static method should be called using class name and not by using object becaues static method can not be overridden in Java.
 

Can you access a non-static variable in the static context?

No, you can not access a non-static variable from the static context in Java. If you try, it will give compile time error.

Difference between ArrayList and LinkedList in Java?
In short, ArrayList is backed by array in Java, while LinkedList is just collection of nodes, similar to linked list data structure. ArrayList also provides random search if you know the index, while LinkedList only allows sequential search. On other hand, adding and removing element from middle is efficient in LinkedList as compared to ArrayList because it only require to modify links and no other element is rearranged.

How do you sort ArrayList in descending order?
You can use Collections.sort() method with reverse Comparator, which can sort elements in the reverse order of their natural order e.g.

List listOfString = Arrays.asList("London", "Tokyo", "NewYork");
Collections.sort(listOfString, Collections.reverseOrder());
System.out.println(listOfString); //[Tokyo, NewYork, London]

What is difference between PATH and CLASSPATH in Java?
PATH is an environment variable which points to Java binary which is used to run Java programs. CLASSPATH is another environment variable which points to Java class files or JAR files. If a class is not found in CLASSPATH then Java throws ClassNotFoundException.



What is the difference between creating String as new() and literal?  


When we create the string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself.

String s = "Test" that Java automatically puts that into the String pool.
Which two methods you need to implement to use an Object as key in HashMap?
In order to use any object as Key in HashMap or Hashtable, it must implement equals and hash-code methods in Java. 

Why String is Immutable or Final in Java
The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client


Why character array is better than String for Storing password in Java
Since Strings are immutable in Java if you store password as plain text it will be available in memory until Garbage collector clears it and since String are used in String pool for reusability there is pretty high chance that it will be remain in memory for long duration, which pose a security threat. 

Since any one who has access to memory dump can find the password in clear text and that's another reason you should always used an encrypted password than plain text.
String strPassword="Unknown";
char[] charPassword= new char[]{'U','n','k','w','o','n'};
System.out.println("String password: " + strPassword);
System.out.println("Character password: " + charPassword);

String password: Unknown
Character password: [C@110b053


How Deadlock happen and how to resolve it?


 
If you have looked above  carefully then you may have figured out that real reason for deadlock is not multiple threads but the way they are requesting lock , if you provide an ordered access then problem will be resolved , here is my fixed version, which avoids deadlock by avoiding circular wait with no preemption.
 
 What is Synchronization in Java
Synchronization in Java is possible by using Java keywords "synchronized" and "volatile”.
If your code is executing in a multi-threaded environment, you need synchronization for objects, which are shared among multiple threads, to avoid any corruption of state or any kind of unexpected behavior.

public class Counter{  
private static int count = 0;  
public static synchronized int getCount(){ 
 return count; }  
public synchoronized setCount(int count){ 
 this.count = count;
 } }
 
Important method related to synchronization in Java are wait(), notify() and notifyAll() which is defined in Object class
 
Using synchronized block in java is also similar to using synchronized keyword in methods.
 
How to determine if a string has all unique characters in Java?
 
solve this problem is by using a Set data structure. A Set is an unordered collection which doesn't allow duplicates. The JDK provides several Set implementations e.g. HashSet, TreeSet or LinkedHashSet but to solve this problem we can use general purpose HashSet. The add() method is used to insert an element into Set and this method returns true if an element is successfully inserted otherwise it returns false i.e. when an element is already present in the Set.
 
Can you make a class Static in Java?
A class is said to be top level if it is not inside any other class and a class which is inside another class is known as nested class. You can create nested class inside another top level or another nested class in Java. This is the class which can be static in Java.
a static keyword can be used with a class, method or variable in Java and anything static belongs to the class, which means a static method can be accessed and called just by using class name i.e. you don't need to create an instance of the class to call this method because it belongs to class.
 
class Top{ 
 static class Nested
{ ...... }
 }  
class Test{ 
 public static void main(String args[]){ 
Top.Nested n = new Top.Nested(); // ok 
 } }


Difference between Heap and Stack Memory in Java JVM
 
 Heap memory is shared by all threads of Java application but Stack memory is local to each thread. Objects are created in heap memory but method frames are stored in Stack memory, and size of heap space is much bigger than the small size of Stack in Java.
 
 
.
 

Difference between Iterator and ListIterator in Java?

The Iterator is the standard way to traverse a collection in Java. You can use Iterator to traverse a List, Set, Map, Stack, Queue or any Collection, but you might not know that there is another way to traverse over List in Java? Yes, it's called the ListIterator. There are many differences between Iterator and ListIterator in Java, but the most significant of them is that Iterator only allows you to traverse in one direction i.e. forward, you have just got a next() method to get the next element, there is no previous() method to get the previous element. On the other hand, ListIterator allows you to traverse the list in both directions i.e. forward and backward. It has got both next() and previous() method to access the next and previous element from List.
 

Difference between final vs finally and finalize in Java?

 final keyword with a class it becomes a final class and no one can extend this
 e.g. String is final in Java. 
When you use the final modifier with method than it cannot be overridden in subclass, 
and when you use the final keyword with variable, it become a constant i.e. its value
 cannot be changed once assigned. 
finally is a keyword related to exception handling in Java.
 It's often used with try block and it's part of try, catch and finally 
 A finally block can be used with or without catch block in Java and its guaranteed to be always executed
, irrespective of what happens inside try block. This is the reason finally block is used to do cleanup and free resources.

finalize() is a method in java.lang.Object class and part of Java's garbage collection process. A garbage collector is supposed to call the finalize() method before reclaiming memory from a dead object in Java.
 
 Difference between BufferedReader and Scanner class in Java 
 both BufferedReader and Scanner can read a file or user input from command prompt.
BufferedRedaer can only read String but Scanner can read both String and other data types like int, float, long, double, float etc.
 
Difference between static and nonstatic member variables in Java
As with static methods, a static member variable belongs to a class and a non-static member variable belongs to an instance. This means, the value of a static variable will be same for all instances, but the value of a non-static variable will be different for different objects. That is also referred as the state of objects. The value of nonstatic member variable actually defines the state of objects.
 

HashSet vs TreeSet in Java?

HashSet and TreeSet both implement same interface i.e  java.util.Set interface and 
they possess the quality of Set interface means duplicate elements are not allowed. 
Both HashSet and TreeSet are used for to store unique elements, but HashSet doesn't care
about any order and TreeSet keeps a thing in order. Ordering or sorting on TreeSet can be customized by
 using Comparator interface, by default TreeSet uses elements natural order for sorting, 
which is defined by compareTo() method of java.lang.Comparable interface.
 Right way to Compare String in Java
 either use equals(), equalsIgnoreCase(), or compareTo() method. 
You should use equals() method to check if two String contains exactly same characters in same order.
 It returns true if two String are equal or false if unequal. This happens because String class overrides equals() method from Object class,
==operator compares references i.e. if two reference variable points to the same object in the heap then it returns true, otherwise, it returns false.
it will return true if you compare String literals but return false if you compare String object to a literal or two String object, even if they have same characters.
 Always remember, == operator returns true only if both variables points to the same object in the heap.

 So, Better to use default always equals() method instead on == operator.

By the way, if you want to compare multiple String objects in alphabetical order then you should use compareTo() method
which is especially for deciding the order of multiple String.
 
What is ClassLoader in Java
 ClassLoader in Java is a class which is used to load class files in Java. Java code is compiled into class file by javac compiler and JVM  
executes Java program, by executing byte codes written in class file. ClassLoader is responsible for loading class files from file system, network or any other source.
 There are three default class loader used in Java, Bootstrap , Extension and System or Application class loader

Every class loader has a predefined location, from where they loads class files.
 Bootstrap ClassLoader is responsible for loading standard JDK class files from rt.jar and it is parent of all class loaders in Java.
 Bootstrap class loader don't have any parents, if you call String.class.getClassLoader() it will return null and any code based on that may 
throw NullPointerException in Java. Bootstrap class loader is also known as Primordial ClassLoader in Java.  
 
Extension ClassLoader delegates class loading request to its parent, Bootstrap and if unsuccessful, loads class form jre/lib/ext directory or any other directory
 pointed by java.ext.dirs system property. Extension ClassLoader in JVM is implemented by  sun.misc.Launcher$ExtClassLoader. 

Third default class loader used by JVM to load Java classes is called System or Application class loader and it is responsible for loading application specific
 classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.
 Application class loader is a child of Extension ClassLoader and its implemented by sun.misc.Launcher$AppClassLoader class. 
Also, except Bootstrap class loader, which is implemented in native language mostly in C,  all  Java class loaders are implemented using java.lang.ClassLoader.

Difference between ArrayList and HashSet in Java?
  • ArrayList implements List interface while HashSet implements Set interface in Java.
  • ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn't maintain any order.
  • ArrayList allow duplicates while HashSet doesn't allow duplicates.
  • When to use transient variable in Java? 
    Transient in Java is  used to indicate that the variable should not be serialized. 
    Serialization is a process of saving an object's state in Java. When we want to persist and object's state by default all instance variables in the object is stored.
     In some cases, if you want to avoid persisting some variables because we don’t have the necessity to transfer across the network. So, declare those variables as transient.
     If the variable is declared as transient, then it will not be persisted. 

    Difference between transient and volatile variable in Java?
    transient keyword is used with those instance variable which will not participate in serialization process.we cannot use static with transient variable as they are part of instance variable.
    Volatile variable : volatile keyword is used with only variable  in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache,
     it can be static.

    Difference between Hashtable and HashMap in Java?

  • Hashtable is thread-safe and can be shared between multiple threads whereas HashMap cannot be shared between multiple threads without proper synchronization.
  • You can also make your HashMap thread-safe by using Collections.synchronizedMap() method. It's performance is similar to Hashtable.

    Difference between Comparator and Comparable

    It is used to compare two objects in Java. 
     The main usage of java.lang.Comparable and java.util.Comparator interface is for sorting a list of objects in Java. 
    For example to sort a list of Employee by their Id, we can use Comparable interface and provide additional sorting capability,
     we can define multiple comparators e.g. AgeComparator to compare the age of the employee, SalaryComparator to compare the salary of employees etc
     

  • No comments:

    Post a Comment