Latest

Friday 11 November 2016

critical java interview qustions

critical java interview qustions

  

 How can you determine if JVM is 32-bit or 64-bit from Java Program?
    Can you create an Immutable object that contains a mutable object?
    How can you mark an array volatile in Java?
    What will this return 5*0.1 == 0.5? true or false?
    What is the right data type to represent Money (like Dollar/Pound) in Java
    Is ++ operation thread-safe in Java?
    In Java, can we store a double value in a long variable without explicit casting?
    How can you do constructor chaining in Java?
    How can we find the memory usage of JVM from Java code?
    Can you catch an exception thrown by another thread in Java?
    How can you check if a String is a number by using regular expression?

Thursday 10 November 2016

Most frequently asked java interview questions

Most frequently asked java interview questions

comment your answer or questions
1.Difference between Abstract Class an Interface
2.Why we are using interface in java
3.Why we are using Abstract Class in java
4.Explain static Keyword.
5.Final,Finally, Finalize Keyword in java
6.What is meant by Abstraction
7.Given an example of Encapsulation
8.Difference & and && operators
9.Explain Assertion Keyword in java
10.What is mean serialization.
11.Default object of class in java
12.Default methods in java
13.Default Interfaces in java
14.What is the difference between String and String buffer
15.What is the difference between String Buffer and String Builder
16.what is meant String Tokenizer
17.Difference between Exception and Error with Example
18.Explain Exception Hirearchy
19.Difference between Checked and unchecked Exception with Example
20.Difference between ArrayList and vector
21.Difference between ArrayList and Array
22.Difference between ArrayList and Linked List
23.Define List, Map , Set
24.Difference between HashSet and TreeSet
25.Difference between HashMap and HashTable
26.Difference between HashMap and TreeMap
27.Difference between Comparable and Comparator
28.Difference collection and Collections
29.Explain Hashing alrogithm
30.Why we are using generic in java
31.Why we are using transien varaible in java
32.what is meant String literals in java
33.Difference between throw and throws keyword in java
34.Difference between Aggressition and composition in java
35.List and Map are synchronized in java explain with example
36.Why we are using arraylist in java
37.Why we are using Vector in java
38.Why we are using Linked List in java
39.What is meant fail fast in java
40.What is meant Singleton in java with example
41.Difference between static variable and instance variable
42.Difference between method overloading and overiding
43.Define this and Super keyword in java
44.Define Enum in java
45.Difference between List Iterator and Iterator
46.What is meant by Autoboxing
47.Difference between equals() and hashcode() method in java
48.Explain function of garbage collection in java
49.Difference between List and Set in java
50.Explain feature of Java 5 and Java 6 and Java 7

By:Vimal Kumar V(sr.software engineer,java)
Java Programming and Coding Questions

Java Programming and Coding Questions


1)    How to check if a String contains only numeric digits? (solution)

If you'll be processing the number as text, then change:
if (text.contains("[a-zA-Z]+") == false && text.length() > 2){
to:
if (text.matches("[0-9]+") && text.length() > 2) {
Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.
If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


2) How to write LRU cache in Java using Generics? (answer)

We need to keep a pointer to the LRU and MRU items. The entries' values will be stored in the list and when we we query the HashMap, we will get a pointer to the list. On get(), we need to put the item at the right-most side of the list. On put(key,value), if the cache is full, we need to remove the item at the left-most side of the list from both the list and the HashMap.
import java.util.LinkedHashMap;
import java.util.Iterator;

public class LRUCache {

    private int capacity;
    private LinkedHashMap<Integer,Integer> map;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.map = new LinkedHashMap<>();
    }

    public int get(int key) {
        Integer value = this.map.get(key);
        if (value == null) {
            value = -1;
        } else {
            this.set(key, value);
        }
        return value;
    }

    public void set(int key, int value) {
        if (this.map.containsKey(key)) {
            this.map.remove(key);
        } else if (this.map.size() == this.capacity) {
            Iterator<Integer> it = this.map.keySet().iterator();
            it.next();
            it.remove();
        }
        map.put(key, value);
    }
}


3) Write a Java program to convert bytes to long? (answer)

public byte[] longToBytes(long x) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.putLong(x);
    return buffer.array();
}

public long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.put(bytes);
    buffer.flip();//need flip
    return buffer.getLong();
}

4) How to reverse a String in Java without using StringBuffer? (solution)

public class ReverseString {

private static String hello = "Hello World";

public static void main(String[] args)
{
System.out.println(reverseString(hello));
}

public static String reverseString(String s) {
char c[] = s.toCharArray();
int i = 0, j = c.length - 1;
while (i < j) {
char tmp = c[i];
c[i] = c[j];
c[j] = tmp;
i++;
j--;
}
return new String(c);
}

5) How to find the word with the highest frequency from a file in Java? (solution)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Pattern;
/**
 * Java program to find count of repeated words in a file.
 *
 * @author
 */
public class Problem {

    public static void main(String args[]) {
        Map<String, Integer> wordMap = buildWordMap("C:/temp/words.txt");
        List<Entry<String, Integer>> list = sortByValueInDecreasingOrder(wordMap);
        System.out.println("List of repeated word from file and their count");
        for (Map.Entry<String, Integer> entry : list) {
            if (entry.getValue() > 1) {
                System.out.println(entry.getKey() + " => " + entry.getValue());
            }
        }
    }

    public static Map<String, Integer> buildWordMap(String fileName) {
        // Using diamond operator for clean code
        Map<String, Integer> wordMap = new HashMap<>();
        // Using try-with-resource statement for automatic resource management
        try (FileInputStream fis = new FileInputStream(fileName);
                DataInputStream dis = new DataInputStream(fis);
                BufferedReader br = new BufferedReader(new InputStreamReader(dis))) {
            // words are separated by whitespace
            Pattern pattern = Pattern.compile("\\s+");
            String line = null;
            while ((line = br.readLine()) != null) {
                // do this if case sensitivity is not required i.e. Java = java
                line = line.toLowerCase();
                String[] words = pattern.split(line);
                for (String word : words) {
                    if (wordMap.containsKey(word)) {
                        wordMap.put(word, (wordMap.get(word) + 1));
                    } else {
                        wordMap.put(word, 1);
                    }
                }
            }
        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
        return wordMap;
    }

    public static List<Entry<String, Integer>> sortByValueInDecreasingOrder(Map<String, Integer> wordMap) {
        Set<Entry<String, Integer>> entries = wordMap.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<>(entries);
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return (o2.getValue()).compareTo(o1.getValue());
            }
        });
        return list;
    }
}

Output:
List of repeated word from file and their count
its => 2
of => 2
programming => 2
java => 2
language => 2


6) How do you check if two given String are anagrams? (solution)

package miscellaneous;

/*
 * We increment the count of each character in the first array and
 * decrement the count of each character in the second array.
 *
 * If the resulting counts array is full of zeros, then strings are anagrams otherwise not.
 */
public class Find2StringAreAnagramsOfEachOther {

 public static void main(String[] args) {
  String str1 = "abc";
  String str2 = "abc";
  System.out.println("Anagram?? :"+isAnagram(str1, str2));
 }

 private static boolean isAnagram(String a, String b){
 
  //if both string is null, then considering it as anagram.
  if(a==b){
   return true;
  }

  //if any one string is null, then they are not anagram.
  if(a==null || b==null)
   return false;
 
  //If length of both strings are not same then obviously they are not anagrams.
  if(a.length()!=b.length())
   return false;
 
  char[] aArr = a.toLowerCase().toCharArray();
  char[] bArr = b.toLowerCase().toCharArray();
 
  // An array to hold the number of occurrences of each character
  int[] counts = new int[26];
 
  for (int i = 0; i < aArr.length; i++){
   counts[aArr[i]-97]++;  // Increment the count of the character at respective position
   counts[bArr[i]-97]--;  // Decrement the count of the character at respective position
  }
 
  // If the strings are anagrams, then counts array will be full of zeros not otherwise
  for (int i = 0; i<26; i++){
   if (counts[i] != 0)
    return false;
  }
 
  return true;
 }
}


7) How to print all permutation of a String in Java? (solution)

package com.journaldev.string.permutation;

import java.util.HashSet;
import java.util.Set;

/**
 * Java Program to find all permutations of a String
 * @author pankaj
 *
 */
public class StringHelper {
    public static Set<String> permutationFinder(String str) {
        Set<String> perm = new HashSet<String>();
        //Handling error scenarios
        if (str == null) {
            return null;
        } else if (str.length() == 0) {
            perm.add("");
            return perm;
        }
        char initial = str.charAt(0); // first character
        String rem = str.substring(1); // Full string without first character
        Set<String> words = permutationFinder(rem);
        for (String strNew : words) {
            for (int i = 0;i<=strNew.length();i++){
                perm.add(charInsert(strNew, initial, i));
            }
        }
        return perm;
    }

    public static String charInsert(String str, char c, int j) {
        String begin = str.substring(0, j);
        String end = str.substring(j);
        return begin + c + end;
    }

    public static void main(String[] args) {
        String s = "AAC";
        String s1 = "ABC";
        String s2 = "ABCD";
        System.out.println("\nPermutations for " + s + " are: \n" + permutationFinder(s));
        System.out.println("\nPermutations for " + s1 + " are: \n" + permutationFinder(s1));
        System.out.println("\nPermutations for " + s2 + " are: \n" + permutationFinder(s2));
    }
}


8 How do you print duplicate elements from an array in Java? (solution)

public class DuplicatesInArray
{  
    public static void main(String[] args)
    {
        String[] strArray = {"abc", "def", "mno", "xyz", "pqr", "xyz", "def"};

        for (int i = 0; i < strArray.length-1; i++)
        {
            for (int j = i+1; j < strArray.length; j++)
            {
                if( (strArray[i].equals(strArray[j])) && (i != j) )
                {
                    System.out.println("Duplicate Element is : "+strArray[j]);
                }
            }
        }
    }   
}


9) How to convert String to int in Java? (solution)

Integer x = Integer.valueOf(str);
// or
int y = Integer.parseInt(str);

There is a slight difference between these methods:
•    valueOf returns a new or cached instance of java.lang.Integer
•    parseInt returns primitive int.
The same is for all cases: Short.valueOf/parseShort, Long.valueOf/parseLong, etc.


10) How to swap two integers without using temp variable? (solution)


a = a + b;
b = a - b;
a = a - b;

For strings (by using a temporary variable for the length):
 int len1 = s1.length();
s1 = s1 + s2;
 s2 = s1.substring(0, len1);
s1 = s1.substring(len1);




JVM Internals and Garbage Collection Interview Questions

JVM Internals and Garbage Collection Interview Questions

Q1.  When are static variables loaded in memory ?

Ans. They are loaded at runtime when the respective Class is loaded. 

Q2.  What is a String Pool ?

Ans. String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.

Q3.  how many objects are created with this code ?

String s =new String("abc"); 

Ans. Two objects will be created here. One object creates memory in heap with new operator and second in stack constant pool with "abc".

Q4.  Which are the different segments of memory ?

Ans. 

1. Stack Segment - contains local variables and Reference variables(variables that hold the address of an object in the heap)

2. Heap Segment - contains all created objects in runtime, objects only plus their object attributes (instance variables)

3. Code Segment -  The segment where the actual compiled Java bytecodes resides when loaded

Q5.  Which memory segment loads the java code ?

Ans. Code segment.

Q6.  Does garbage collection guarantee that a program will not run out of memory?

Ans. Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection

Q7.  Describe what happens when an object is created in Java ?

Ans. 

1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implemenation-specific data includes pointers to class and method data.

2. The instance variables of the objects are initialized to their default values.

3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its superclasses. This process continues until the constructor for java.lang.Object is called,
as java.lang.Object is the base class for all objects in java.

4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.

Q8.  Describe, in general, how java's garbage collector works ?

Ans. The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java's dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected.

Q9.  Can I import same package/class twice? Will the JVM load the package twice at runtime?

Ans. One can import the same package or same class multiple times. Neither compiler nor JVM complains wil complain about it. And the JVM will internally load the class only once no matter how many times you import the same class.

Q10.  Different types of memory used by JVM ?

Ans. Class , Heap , Stack , Register , Native Method Stack.

Q11.  What is a class loader ? What are the different class loaders used by JVM ?

Ans. Part of JVM which is used to load classes and interfaces.

Bootstrap , Extension and System are the class loaders used by JVM.

Q12.  Explain java.lang.OutOfMemoryError ?

Ans. This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

Q13.  Is JVM, a compiler or interpretor ?

Ans. Its an interpretor.

Q14.  Difference between loadClass and Class.forName ?

Ans. loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize the object after loading it.

Q15.  Should we override finalize method ?

Ans. Finalize is used by Java for Garbage collection. It should not be done as we should leave the Garbage Collection to Java itself.

Q16.  Which kind of memory is used for storing object member variables and function local variables ?

Ans. Local variables are stored in stack whereas object variables are stored in heap.

Q17.  Why do member variables have default values whereas local variables don't have any default value ?

Ans. member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

Q18.  Why Java don't use pointers ?

Ans. Pointers are vulnerable and slight carelessness in their use may result in memory problems and hence Java intrinsically manage their use. 

Q19.  What are various types of Class loaders used by JVM ?

Ans. 

Bootstrap - Loads JDK internal classes, java.* packages.

Extensions - Loads jar files from JDK extensions directory - usually lib/ext directory of the JRE

System  - Loads classes from system classpath. 

Q20.  How are classes loaded by JVM ?

Ans. Class loaders are hierarchical. The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running.

Wednesday 9 November 2016

Data types and Basic Java Interview Questions

Data types and Basic Java Interview Questions


1) What is the right data type to represent a price in Java? (answer)
BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision.


2) How do you convert bytes to String? (answer)
you can convert bytes to the string using string constructor which accepts
byte[], just make sure that right character encoding otherwise platform's default character encoding will be used which may or may not be same.


3) How do you convert bytes to long in Java? (answer)
This questions if for you to answer :-)


4) Can we cast an int value into byte variable? what will happen if the value of
int is larger than byte?
Yes, we can cast but int is 32 bit long in java while byte is 8 bit long in java so when you cast an int to byte higher 24 bits are lost and a byte can only hold a value from -128 to 128.


5) There are two classes B extends A and C extends B, Can we cast B into C e.g. C = (C) B; (answer)


6) Which class contains clone method? Cloneable or Object? (answer)
java.lang.Cloneable is marker interface and doesn't contain any method clone method is defined in the object class. It is also knowing that clone() is a native method means it's implemented in C or C++ or any other native language.


7) Is ++ operator is thread-safe in Java? (answer)
 No it's not a thread safe operator because its involve multiple instructions like reading a value, incriminating it and storing it back into memory which can be overlapped between multiple threads.


8) Difference between a = a + b and a += b ? (answer)
The += operator implicitly cast the result of addition into the type of variable used to hold the result. When you add two integral variable e.g. variable of type byte, short, or int then they are first promoted to int and them addition happens. If result of addition is more than maximum value of a then a + b will give compile time error but a += b will be ok as shown below


byte a = 127;
byte b = 127;
b = a + b; // error : cannot convert from int to byte
b += a; // ok


9) Can I store a double value in a long variable without casting? (answer)
No, you cannot store a double value into a long variable without casting because the range of double is more  that long and you we need to type cast. It's not dificult to answer this question but many develoepr get it wrong due to confusion on which one is bigger between double and long in Java.


10) What will this return 3*0.1 == 0.3? true or false? (answer)
This is one of the really tricky questions. Out of 100, only 5 developers answered this question and only of them have explained the concept correctly. The short answer is false because some floating point numbers can not be represented exactly.


11) Which one will take more memory, an int or Integer? (answer)
An Integer object will take more memory an Integer is the an object and it  store meta data overhead about the object and int is primitive type so its takes less space.


12) Why is String Immutable in Java? (answer)
One of my favorite Java interview question. The String is Immutable in java because java designer thought that string will be heavily used and making it immutable allow some optimization easy sharing same String object between multiple clients. See the link for the more detailed answer. This is a great question for Java programmers with less experience as it gives them food for thought, to think about how things works in Java, what Jave designers might have thought when they created String class etc.

13) Can we use String in the switch case? (answer)
Yes from Java 7 onward we can use String in switch case but it is just syntactic sugar. Internally string hash code is used for the switch. See the detaiedl answer for more explanation and discussion.

14) What is constructor chaining in Java? (answer)
When you call one constructor from other than it's known as constructor chaining in Java. This happens when you have multiple, overloaded constructor in the class.
Top 20 Spring Interview Questions Answers 2016

Top 20 Spring Interview Questions Answers 2016

Spring MVC Request flow


1) What is spring framework? Why Java programmer should use Spring framework
Very common Spring interview question, Spring is a framework which helps Java programmer in development. Spring provides dependency Injection and IOC container, Spring MVC flow and several useful API for Java programmer.

2) What is default scope of bean in Spring framework ?
The default scope of a Spring bean is Singleton scope, you can read this article which explains about all possible scope of a spring bean : What is bean scope in Spring


3) Does Spring singleton beans are thread-safe ?
No, Spring singleton beans are not thread-safe. Singleton doesn't mean bean would be thread-safe.


4) What is dependency Injection?
Dependency Injection is one of the design pattern, which allows injecting dependency on Object, instead of object resolving the dependency.

5. What are benefits of Spring Framework?

  • Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.
  • Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
  • Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
  • Container: Spring contains and manages the life cycle and configuration of application objects.
  • MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.
  • Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
  • Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

6) What is Spring MVC ? Can you explain How one request is processed ?

7) How to you create a controller in Spring ?



8) What is view Resolver pattern ? how it work in Spring MVC

View Resolver pattern is a J2EE pattern which allows a web application to dynamically choose it's view technology e.g. HTML, JSP, Tapestry, JSF, XSLT or any other view technology. In this pattern, View resolver holds mapping of different views, controller return name of the view, which is then passed to View Resolver for selecting an appropriate view.
 Spring MVC framework supplies inbuilt view resolver for selecting views.

9) What is Spring Security ?
Spring security is a project under spring framework umbrella, which provides support for security requirements of enterprise Java projects. Spring Security formerly known as aegis security provides out of box support for creating login screen, remember me cookie support, securing URL, authentication provider to authenticate the user from the database, LDAP and in memory, concurrent active session management support and much more. In order to use Spring security in a Spring MVC based project, you need to include spring-security.jar and configure it in application-Context-security.XML file, you can name it whatever you want, but make sure to supply this to ContextLoaderListener, which is responsible for creating Spring context and initializing dispatcher servlet. You can see Pro Spring Security by Carlo Scarioni to learn more about Spring Security.

10) How do you control concurrent Session on Java web application using Spring Security?
You can use Spring Security to control a number of active session in Java web application. Spring security framework provides this feature out of the box and when enabled , a user can only have one active session at a time. See this Spring Security example to learn more about How to control concurrent user session using Spring security
11) What types of dependency injection is supported by Spring Framework? When do you use Setter and Constructor Injection, pros and cons?
There are 2 types of dependency injection supported by Spring, constructor based injection, and setter-based injection. Both types have their own advantages and disadvantages, you should use Constructor injection when object's dependencies are not optional and they must be initialized with their dependencies. Also use constructor injection if the order of initialization or dependency matters because in Setter based injection you cannot impose any order. Use setter injection when dependencies are optional. See the difference between setter and constructor injection in Spring for more detailed answer.

12) If a user checked in CheckBox and got a validation error in other fields and then he unchecked the CheckBox, what would be selection status in command object in Spring MVC ? How do you fix this issue?
Since during HTTP post, if the checkbox is unchecked than HTTP does include a request parameter for checkbox, which means updated selection won't be picked up. you can use hidden form field, starting with _ to fix this in Spring MVC. quite a tricky question to answer if you are not aware of HTTP POST behavior and Spring MVC.

13) What are different implementations of View interface you have used in Spring MVC?
ULBased View e.g. JSP , JSTLView.
12) What is the difference between ApplicationContext and BeanFactory in Spring framework?

13) How do you call stored procedure by using Spring framework?

14) What does JdbcTemplate and JmsTemplate class offer in Spring?


15) Explain Spring MVC flow with a simple example e.g. starting from Container receives a request and forward to your Java application ?

16) What is the difference in Spring MVC and Spring core?

17) Can you use Spring MVC framework along with Struts ? I have an existing Java MVC application which is based in Struts, Can I migrate that to use Spring MVC ? How ?

18) What is the advantage of Spring MVC framework over Struts 1.0 or Struts 2.0 ? is it worth to convert an existing Struts application to Spring MVC ?

19) How do Spring resolves view returned by ModelAndView class ?


20. What are inner beans in Spring?

When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of <bean/> element inside the <property/> or <constructor-arg/> elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.