Showing posts with label Java interview Questions. Show all posts
Showing posts with label Java interview Questions. Show all posts
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?
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.
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.