Showing posts with label Java Interview QA. Show all posts
Showing posts with label Java Interview QA. Show all posts

Java Map Comparison- hashmap, linkedhashmap, treemap


Java Map Comparison :
  • HashMap is the fastest map with O(1) search and insertion times.
  • LinkedHashMap is a little slower for inserts, but maintains the insertion order.
  • TreeMap is the slowest map, but lets you iterate over the keys in a sorted order.

Java iterate through map, hashmap - working source code

Iterating through Map in Java - working efficient source code 

Map<String, Object> map = ...;

The solution uses map.keySet(), map.values(), and map.entrySet().

Top Java Interview Question : reverse a string using recursion

Best Answer using Recursion :

  public String reverse(String str) {
     if ((null == str) || (str.length()  <= 1)) {
        return str;
      }
    return reverse(str.substring(1)) + str.charAt(0);
   }


Less Best Answer :
public class JdkReverser implements Reverser {
  public String reverse(String str) {
     if ((null == str) || (str.length() <= 1)) {
         return str;
      }
     return new StringBuffer(str).reverse().toString();
  }
}

Call one constructor from another in Java

Is this possible to call one constructor from another in Java ?

Yes, it is possible:

public class Foo
{
    private int x;

    public Foo()
    {
        this(1);//calling constructor -->> public Foo(int x)
    }

    public Foo(int x)
    {
        this.x = x;
    }
}

Scenarios in which Serialization cannot happen

What are the special cases in which serialization cannot happen?
-> There are following scenarios in which serialization cannot happen:
a. Variables are transient.
b. Variables are static.
c. Base class variables are serialized if class itself is serializable.

redirect message to IO stream

How could Java classes direct program messages to the system console, but error messages, say to a file?
The class System has a variable out that represents the standard output, and the variable err that represents the standard error device. By default, they both point at the system console. This how the standard output could be re-directed:

Stream st = new Stream(new FileOutputStream("output.txt")); 
System.setErr(st);
System.setOut(st);

How to serialize variables selectively

In a Java class, one has 10 variables. One wants to serialize only 3 variables,how can this be achieved?
->Make variables as 'transient' which are not to be serialized.

The usage of Java packages.


Explain the usage of Java packages.

A. This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. 
Packages access level also allows you to protect data from being used by the non-authorized classes.

Java: difference between private, protected, and public?

These keywords are for allowing privileges to components such as java methods and variables.
Public: accessible to all classes
Private: accessible only to the class to which they belong
Protected: accessible to the class to which they belong and any subclasses.

Access specifiers are keywords that determines the type of access to the member of a class. These are:
* Public
* Protected
* Private
* Defaults

Order of catching exception in java

Does it matter in what order catch statements for FileNotFoundException and IOExceptipon are written?

A. Yes, it does. The FileNotFoundException is inherited from the IOException. 
Exception's subclasses have to be caught first.

Exception
^
|
IOException
^
|
FileNotFoundException 
So while catching exceptions, we must catch the low level exception first - here : FileNotFoundException .


#The hierarchy in Java Exception framework :





wrapper classes in Java

Describe the wrapper classes in Java.Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:
Primitive - Wrapper
boolean  - java.lang.Boolean

byte - java.lang.Byte
char - java.lang.Character
double - java.lang.Double
float - java.lang.Float
int - java.lang.Integer
long - java.lang.Long
short - java.lang.Short
void - java.lang.Void

Java Class as Applet as well as Application

Can you write a Java class that could be used both as an applet as well as an application?
A. Yes. Add a main() method to the applet.

Redirect Standard System Output and Error Message to PrintStream in Java

In a Java program, how can you divert standard system output or error messages, say to a file?
->We can achieve this by using
public static void setErr(PrintStream err)
and public static void setOut(PrintStream out) methods.
By default, they both point at the system console. The following example redirects Out and Err messages to 'error.txt'  file

Stream stream = new Stream(new FileOutputStream("error.txt"));
System.setErr(stream);
System.setOut(stream);

You can redirect the Err and Out stream to any PrintStream object.

difference between an interface and an abstract class

What's the difference between an interface and an abstract class? Also discuss the similarities. (Very Important)
Abstract class is a class which contain one or more abstract methods, which has to be implemented by sub classes. Interface is a Java Object containing method declaration and doesn't contain implementation. The classes which have implementing the Interfaces must provide the method definition for all the methods
Abstract class is a Class prefix with a abstract keyword followed by Class definition. Interface is a Interface which starts with interface keyword.
Abstract class contains one or more abstract methods. where as Interface contains all abstract methods and final declarations
Abstract classes are useful in a situation that Some general methods should be implemented and specialization behavior should be implemented by child classes. Interfaces are useful in a situation that all properties should be implemented.

Differences are as follows:
* Interfaces provide a form of multiple inheritance. A class can extend only one other class.
* Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
* A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
* Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

* Neither Abstract classes or Interface can be instantiated.


How to define an Abstract class?
A class containing abstract method is called Abstract class. An Abstract class can't be instantiated.
Example of Abstract class:

abstract class testAbstractClass { 
    protected String myString; 
    public String getMyString() { 
    return myString; 

public abstract string anyAbstractFunction();
}

How to define an Interface?Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Example of Interface:

public interface sampleInterface {
    public void functionOne();
    public long CONSTANT_ONE = 1000;
}