Sunday, 29 April 2018

Java Coding Interview Question

1)Write a program for non repeating Characters?

  class Char
              {
                   public static void  main(String arsg[])
                    {
                           public static char FirstNonRepatingChar(String word)
                              {


                                Set<characters>nonrepeating = new HashSet<>();
                                List<characters>nonrepeating = new ArrayList<>();
                                   for(int i=0; i<word.length();i++)
                                         {
                                            char letter = word.charAt(i); 
                                              if(repeating.contains(letter))
                                                      {
                                                         continue;
                                                     }
                                 if(nonrepeating.conntains(letter))
                                    {
                                      nonrepeating.remove((character)letter);
                                      repeating.add(letter);
                                   }
                             else
                              {
                                  nonrepeating.add(letter);
                            }
                 }
    return nonrepeating.get(0);
     }
  }
}


2) Write a program to insert string object into the Treeset reverse of alphabetical order



package treeset;

import java.util.TreeSet;



public class TreeSetDemo
{
public static void main(String args[])
{
TreeSet t= new TreeSet(new MyComparator());
t.add("Rajesh");
System.out.println(t);

class MyComparator implements comparator
{
public int compare (Object obj1, object obj2)
{
String s1= obj1.toString();
String s2=(String)obj2;
return-s1.CompareTo(s2);
}
}

}


Frequently asked java and j2ee questions and answer

1)What is abstraction?

     Showing the essential and hiding the nonEssential is known as Abstraction.

2)Define Encapsulation?

  The Wrapping up of data and functions into a single unit is known as Encapsulation. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessed via the reference of the object.

3)Define Inheritance?

 It is the Process by which the Obj of one class acquires the properties of Obj’s another Class.  Inheritance is the method of creating the new class based on already existing class, the new class derived is called Sub class which has all the features of existing class and its own, i.e sub class.
 Advantage of the inheritance:
     *Reusability of code 
      *accessibility of variables and methods of the Base class by the Derived class.

4)Define Polymorphism?

   The ability to take more that one form, it supports Method Overloading & Method Overriding.

 5)Define Method overloading?

  When a method in a class having the same method name with different arguments (diff Parameters or Signatures) is said to be Method Overloading. This is Compile time Polymorphism. Using one identifier to refer to multiple items in the same scope. 

6) Define Method Overriding? 

          When a method in a Class having same method name with same arguments is said to be Method overriding. This is Run time Polymorphism. Providing a different implementation of a method in a subclass of the class that originally defined the method. 

7)Difference between overloading and overriding?

 1. In Over loading there is a relationship between the methods available in the same class, where as in Over riding there is relationship between the Super class method and Sub class method.

2. Overloading does not block the Inheritance from the Super class , Where as in Overriding blocks Inheritance from the Super Class. 

3. In Overloading separate methods share the same name, where as in Overriding Sub class method replaces the Super Class. 

4. Overloading must have different method Signatures , Signatures. 

8)What is Dynamic dispatch? 

         It is a mechanism by which a call to Overridden function is resolved at runtime rather than at Compile time , and this is how Java implements Run time Polymorphism. 

9)What is a Dynamic Binding?

           Dynamic Binding Means the code associated with the given procedure call is not known until the time of call the call at run time. (it is associated with Inheritance & Polymorphism). 

10)What is interface?

*A class can implement more than one Interface.
*  An Interface can extend one or more interfaces, by using the keyword extends. 
*All the data members in the interface are public, static and Final by default. 
*An Interface method can have only Public, default and Abstract modifiers. 
*An Interface is loaded in memory only when it is needed for the first time. 
* A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface. 

11)what is a Marker Interfaces?

A method which has a no name is Marker Interface.
 Serializable, Clonable, Remote, EventListener.

12)Define Abstract Class?

Abstract classes can be used to implement the inheritance relationship between the classes that belongs same hierarchy.
 *Classes and methods can be declared as abstract. 
* Abstract class can extend only one Class. 


13)Difference Between Interfaces And Abstract class?


o All the methods declared in the Interface are Abstract, where as abstract class must have atleast one abstract method and others may be concrete.
 o In abstract class keyword abstract must be used for method, where as in Interface we need not use the keyword for methods.
 o Abstract class must have Sub class, where as Interface can’t have sub classes.

14)Define Final variable?

 All the Variables, methods and classes can be declared as Final. Classes declared as final class can’t be sub classed. Method ‘s declared as final can’t be over ridden. If a Variable is declared as final, the value contained in the Variable can’t be changed. Static final variable must be assigned in to a value in static initialized block.  


15)What is Transient Keyword?

Transient can be applied only to class level variables. Local variables can’t be declared as transient. During serialization, Object’s transient variables are not serialized.

11 Java interview Question and answer


1: What’s wrong using HashMap in the multi-threaded environment? When does the get() method go to an infinite loop? 
For example, if you initialize the HashMap just by one thread and then all threads are only reading from it, then it’s perfectly fine. One example of this is a Map which contains configuration properties.
The real problem starts when at-least one of that thread is updating HashMap i.e. adding, changing or removing any key value pair. Since put() operation can cause re-sizing and which can further lead to infinite loop, that’s why either you should use Hashtable or ConcurrentHashMap, later is better.
 2. Does overriding the hashCode() method have any performance implication? 
This is a good question and open to all, as per my knowledge a poor hash code function will result in the frequent collision in HashMap which eventually increases the time for adding an object into Hash Map.
From Java 8 onwards though, collision will not impact performance as much as it does in earlier versions, because after a threshold the linked list will be replaced by the binary tree, which will give you O(logN) performance in the worst case, as compared to O(n) of linked list.
 3) Do all properties of an Immutable Object need to be final? 
Not necessarily, as stated above you can achieve same functionality by making the member non-final but private and not modifying them except in a constructor. Don’t provide setter methods for them and if it is a mutable object, then don’t ever leak any reference for that member.
 4) How does the substring() method inside String works? 
 I think the answer is not sufficient, but here it is “Substring creates a new object out of source string by taking a portion of original string”.
This question was mainly asked to see if the developer is familiar with the risk of memory leaks, which a sub-string can create. Until Java 1.7, substring holds the reference of the original character array, which means even a sub-string of 5 character long, can prevent 1GB character array from garbage collection, by holding a strong reference.This issue is fixed in Java 1.7, where the original character array is not referenced anymore, but that change also made the creation of substring a bit more costly in terms of time. Earlier it was on the range of O(1), which could be O(n) in worst case on Java 7.
5) Can you write a critical section code for the singleton?
This core Java question is a followup of the previous question and expecting the candidate to write Java singleton using double checked locking. Remember to use the volatile variable to make Singleton thread-safe.
 6: How do you handle error condition while writing stored procedure or accessing stored procedure from java?
This is one of the tough Java interview questions and its open for all, my friend didn’t know the answer so he didn’t mind telling me. My take is that stored procedure should return an error code if some operation fails but if stored procedure itself fails than catching SQLException is the only choice.
7) What is difference between Executor.submit() and Executer.execute() methods ? 
This question is from my list of Top 15 Java multi-threading question answers. It’s getting popular day by day because of huge demand of Java developers with good concurrency skills. The answer is that former returns an object of Future which can be used to find result from worker thread.
There is a difference when looking at exception handling. If your tasks throw an exception and if it was submitted with executing this exception will go to the uncaught exception handler (when you don’t have provided one explicitly, the default one will just print the stack trace to System.err).
If you submitted the task with submit any thrown exception, checked exception or not, is then part of the task’s return status. For a task that was submitted with submitting and that terminates with an exception, the Future.get() will re-throw this exception, wrapped in an ExecutionException.
 8)What is the difference between factory and abstract factory pattern?
Abstract Factory provides one more level of abstraction. Consider different factories each extended from an Abstract Factory and responsible for the creation of different hierarchies of objects based on the type of factory. E.g. AbstractFactory extended by AutomobileFactoryUserFactoryRoleFactory etc. Each individual factory would be responsible for the creation of objects in that genre. Here is UML diagram of factory and abstract factory pattern:
9) What is a Singleton? Is it better to make the whole method synchronized or only critical section synchronized? 
Singleton in Java is a class with just one instance in the whole Java application, for example, java.lang.Runtime is a Singleton class. Creating Singleton was tricky prior Java 4 but once Java 5 introduced Enum its very easy.
10:  Can you write code for iterating over HashMap in Java 4 and Java 5?
Tricky one but he managed to write using while and a for loop. Actually there are four ways to iterate over any Map in Java, one involves using keySet() and iterating over key and then using get() method to retrieve values, which is bit expensive.
 11) When do you override hashCode() and equals()? 
Whenever necessary, especially if you want to do equality check based upon business logic rather than object equality, e.g. two employee objects are equal if they have the same emp_id, despite the fact that they are two different objects, created by different part of the code.
Also overriding both these methods are must if you want to use them as key in HashMap. Now as part of the equals-hashcode contract in Java, when you override equals, you must override hashcode as well, otherwise your object will not break invariant of classes e.g. Set, Map which relies on equals() method for functioning properly.

Saturday, 28 April 2018

Interview Questions on Core Java:


  1)Why main method is static? Can we execute a program without main() method? If yes, how?

          Yes u can run java without main method , but make sure that your JDK is below 1.7. and   above 1.7 it will not be supported.

        *Static means it shared all the instance from the class and belong to the object type and not actual objects. 

2)How Weak hashmap Works?

     Weak hasmap operates like a normal hashmap but use weak reference for key. suppose if the key object doesn't device any reference then both key/value mapping will become appropriate for a garbage value.


3) how a.hascode() used for? how it is related to a.equals(b)?


          
           hashcode() methods returns an int hash value corresponding to an object. It is used in hash based based collection classes. eg Hashtable, Hashmap.
        According to the java specification, two objects which are identical to each other using equals() method needs to have same hashcode.


4)what is compile constant in java?


   public static final variable are known as compile time constant.


5)How do you print array in java?


    you can print an array by using the Arrays.toString() and Arrays.deeptoString() method. since Array does not implemented to String() by itself, just passing an array to the System.out .println() will not print its content but Array.to.String will print each element.

6)

Commonly asked program in the Interview

Commonly asked program in the Interview

1)Write a program to sort a array?


  package sort;

import java.util.Scanner;
public class Sortarray 
{
public static void main(String args[])
{
int n, temp;
Scanner s = new Scanner(System.in);  
System.out.println("Enter no of the elements:");
n =s.nextInt();                                                      //getting input from the user 
int a[] = new int[n];
System.out.println("Enter all the elements:");
for(int i=0; i<n;i++)
{
a[i]=s.nextInt();
}
for(int i=0;i<n;i++)
{
for(int j=i+1; j<n; j++)                             //passing and assigning the values
{
if(a[i]>a[j])
{
temp =a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Ascending order");
for(int i=0; i<n-1; i++)
{
System.out.println(a[i]+",");
}
System.out.println(a[n-1]);
}
}


2) Program for Arraylist and Linkedlist and HashSet

          import java.util.*;

public class Array{

   public static void main(String[] args) {
      //ArrayList 
      List a1 = new ArrayList();
      a1.add("Zara");
      a1.add("Mahnaz");
      a1.add("Ayan");
      System.out.println(" ArrayList Elements");
      System.out.print("\t" + a1);

      //LinkedList
      List l1 = new LinkedList();
      l1.add("Zara");
      l1.add("Mahnaz");
      l1.add("Ayan");
      System.out.println();
      System.out.println(" LinkedList Elements");
      System.out.print("\t" + l1);

      //HashSet
      Set s1 = new HashSet(); 
      s1.add("Zara");
      s1.add("Mahnaz");
      s1.add("Ayan");
      System.out.println();
      System.out.println(" Set Elements");
      System.out.print("\t" + s1);

      //HashMap
      Map m1 = new HashMap(); 
      m1.put("Zara", "8");
      m1.put("Mahnaz", "31");
      m1.put("Ayan", "12");
      m1.put("Daisy", "14");
      System.out.println();
      System.out.println(" Map Elements");
      System.out.print("\t" + m1);
   }
}
  

4) Program for the LinkedList ()


    import java.util.*; 
import java.util.Iterator;
public class LinkList
{  
 public static void main(String args[])
 {  
   
  LinkedList al=new LinkedList(); 
  LinkedList<String> a2=new LinkedList<String>();
  LinkedList<Character> a3=new LinkedList<Character>();
  
  
  al.add("Ravi");  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add("Ajay"); 
  /*al.add(10);
  al.add(15);
  al.add(10);
  al.add(56);
  al.add("e");  */
  al.get(2);
  al.set(2, "hashed");
  System.out.println(al  );
  Iterator it = al.iterator();
 // it = al.iterator();
  while(it.hasNext()) 
  {
      Object element = it.next();
      System.out.print(element + " ");
  }
  //System.out.println(it.previous());
  
  System.out.println(" ");
 }
}
  

5)Program for to find a Largest  file in Java?

    import java.io.BufferedReader;
class Largestfile
{
 public static void main(String args[])
 {
  findMethod("My name is H GANESHKUMAR");
 }
 static public void findMethod(String s)
 {
  String str = s + " ";
  char ch = ' ';
  int len = str.length(), l = 0;
  int min = len, max = 0;
  String shortest_word = "", longest_word = "", word = "";
  for (int i = 0; i < len; i++)
  {
   ch = str.charAt(i);
   if (ch != ' ')
   {
    word += ch;
   }                                     //if ends
   else
   {
    l = word.length();
    if (l < min)
   
    {
     min = l;
     shortest_word = word;
    }                                     //if ends
    if (l > max)
    {
     max = l;
     longest_word = word;
    }
    word = "";
   }
  }
  System.out.println("Shortest word = " + shortest_word + " with length " + min);
  System.out.println("Longest word = " + longest_word + " with length " + max);
 }
}




Java Interview Question for Experienced Candidates:


1)What are the Java 8 Features in java?

      *For Each() method in Iterable Interface.
      *Default and Static methods in interface.
      *Functional Interface and Lambada Expression.
      *Collection API Improvements.

 NOTE: We can use default and static keyword to create Interface with Implementation.

2)Define a Concrete Class?

    *used for Specific Requirement.
    *Object of Concrete Class can be created directly
   *Containing fully defined methods or implementation methods.

3)Steps for remove duplicates elements in java?

    public class RemoveDuplicates
       
           {
                ArrayList<object> a1= new ArrayList<object>();
                al.add("JAVA"); //you can add any number of the data you want
             
                     System.out.println("the elements are:" +a1);
                   
                       for(int i=0; i<a1.size(); i++)
                             {
                                  if(a1.get(i).equals(a1.get(j)))
                                    {
                                        a1.remove(j);
                                        j--;
                                     } 
                                 }
                         }
           System.out.println("After Removing the duplicates elements:" +a1 );

      }
}


4) Define halt() function?
         public void halt(int staus):
                           Forcibly terminates the currrently running JVM.
                           This method never returns normally.
                         
5) exit() function;
            public void exit(int status):
                           This method terminates the currently running Java Virtual Machine.
                     java.lang.sysyem.exit();