Showing posts with label interview question. Show all posts
Showing posts with label interview question. Show all posts

Thursday, 21 June 2018

How HashSet works internally in Java?

As we all know that a Set is a well-defined collection of distinct objects. Each member of a set is called Element of Set. Set contains unique elements.

In Java, Set interface implements classes like HashSet, LinkedHashSet, TreeSet to achieve the uniqueness.

In this post, we will see how HashSet works internally in Java.

HashSet internally uses HashMap to store its object. Whenever we create a HashSet object, one HashMap object associated with it is also created. This HashMap object is used to store the elements we enter in the HashSet. The elements we add into HashSet is store as Keys of the HashMap and the Values associated to those keys will be constant.

Lets look into the HashSet class -


Here we can see constructor of HashSet class is internally creating HashMap object. There are four public constructors available in HashSet class, all the constructors creates HashMap objects internally.


Whenever we add an element to HashSet using add() method, it actually calls put() method on internally created HashMap object with element we have specified as a Key and constant PRESENT as its Value.


And whenever we remove an element from HashSet using remove() method, it actually call remove() method on internally created HashMap object.


So we can say HashSet maintains its uniqueness internally through HashMap.

Thursday, 31 August 2017

How to convert Date and Time between Timezone in Java?

TimeZone represents a time zone offset, and also figures out daylight savings.

Typically, we can get a TimeZone using getDefault() method which creates a TimeZone based on the time zone where the application is running. 

For example, if the application is running in India, getDefault() method creates a TimeZone object based on Indian Standard Time (IST).

We can also get a TimeZone using getTimeZone along with a time zone ID. For instance, the time zone ID for the Indian Standard Time (IST) zone is Asia/Calcutta. So, we can get a IST TimeZone object with:

TimeZone timezone = TimeZone.getTimeZone("Asia/Calcutta");


Lets look into the code -


package com.anjan.timezone;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TimeZoneDemo {

public static String convertDateToTimeZone(Date date, TimeZone timeZoneID, String dateFmt) {

SimpleDateFormat sdf = new SimpleDateFormat(dateFmt);
sdf.setTimeZone(timeZoneID);

return sdf.format(date);

}

public static void main(String arg[]) {

Date date = new Date();

String dt = convertDateToTimeZone(date, TimeZone.getTimeZone("Asia/Calcutta"), "dd-MM-YYYY HH:mm:ss");

System.out.println("Date in Asia/Calcutta : "+dt);
dt = convertDateToTimeZone(date, TimeZone.getTimeZone("America/Los_Angeles"), "dd-MM-YYYY HH:mm:ss");
System.out.println("Date in America/Los_Angeles : "+dt);

}

}

Output -

Date in Asia/Calcutta : 31-08-2017 15:06:30

Date in America/Los_Angeles : 31-08-2017 02:36:30

Sunday, 5 February 2017

How to Clone a Linked List with Next and Random Pointers in Java?

Today we'll see how to clone a linked list with next and random pointers in Java using simple approach.
The problem statement is - "You are given a linked list with two pointers. One pointer will point to the next node and the other pointer will be pointing to the random node i.e any node of the linked list. We have to write a program in O(n) time to clone or duplicate the list"


There are many ways to clone the linked list. But we will use the following method to clone a linked list -

1. We will traverse the linked list and make a copy of data of each node.
2. We will store the Original linked list node as key and Cloned linked list node as value into a HashMap.
3. We will traverse the Original linked list again, and using the HashMap assign the next and random pointers to the cloned linked list.

Now we will look into to program -

package com.anjan.clone;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Node Class
class Node{
int data;
Node next, randPointer;

public Node(int data){
this.data data;
this.next = null;
this.randPointer null;
}
}

// Custom Linked List Class
class MyLinkedList{

private static Node head null;

// Private Constructor for Cloning
private MyLinkedList(Node head){
this.head head;
}

// Public Constructor
public MyLinkedList(){

}

// Inserting Data in Last
public void push(int data){
Node node null;

if(head == null){
head = new Node(data);

}else{
node= new Node(data);
node.next null;
Node temp head;
while(temp.next != null){
temp temp.next;
}
temp.next node;
}
}

// Return Head Address
public Node getHead(){
return head;
}

// Method to display elements of Linked List
public void display(){

Node temp head;

while(temp != null){
System.out.print("Data : "+temp.data+", Node Address : "+temp+", Next Data : ");
if(temp.next != null)
System.out.print(temp.next.data);
else
System.out.print(temp.next);

System.out.print(", Random Data : ");

if(temp.randPointer!= null)
System.out.print(temp.randPointer.data);
else
System.out.print(temp.randPointer);
temp temp.next;
System.out.println("");
}

}

// Method to get Random Numbers between a Range
private int getRandom(int minint max){
return (min + (int)(Math.random() * max));
}

// Method to set Random pointers
public void setRandomPointer(){
Node temp = getHead();

List<Node> list = new ArrayList<Node>();

while(temp != null){
list.add(temp);
temp temp.next;
}

temp = getHead();

while(temp != null){
int n = getRandom(0, list.size()-1);
temp.randPointerlist.get(n);
list.remove(n);
temp = temp.next;
}
}

// Method to clone Linked List
public MyLinkedList clone(){

Node origCur = getHead();
Node cloneCur = null;

Map<Node, Node> map = new HashMap<Node, Node>();

while(origCur != null){
cloneCur = new Node(origCur.data);
map.put(origCur cloneCur);
origCur origCur.next;
}

origCur = getHead();

while(origCur != null){
cloneCur = map.get(origCur);
cloneCur.next map.get(origCur.next);
cloneCur.randPointer = map.get(origCur.randPointer);
origCur = origCur.next;
}
return new MyLinkedList(map.get(getHead()));
}
}

public class CloneLinkedList {

public static void main(String args[]){
System.out.println("** Original Linked List **");
MyLinkedList origList new MyLinkedList();
origList.push(1);
origList.push(2);
origList.push(3);
origList.push(4);
origList.push(5);
origList.setRandomPointer();
origList.display();

System.out.println("** Cloned Linked List **");
MyLinkedList cloneList origList.clone();
cloneList.display();

}

}


Output -


** Original Linked List **

Data : 1, Node Address : com.anjan.clone.Node@7852e922, Next Data : 2, Random Data : 3

Data : 2, Node Address : com.anjan.clone.Node@4e25154f, Next Data : 3, Random Data : 1
Data : 3, Node Address : com.anjan.clone.Node@70dea4e, Next Data : 4, Random Data : 2
Data : 4, Node Address : com.anjan.clone.Node@5c647e05, Next Data : 5, Random Data : 4
Data : 5, Node Address : com.anjan.clone.Node@33909752, Next Data : null, Random Data : 5

** Cloned Linked List **
Data : 1, Node Address : com.anjan.clone.Node@55f96302, Next Data : 2, Random Data : 3
Data : 2, Node Address : com.anjan.clone.Node@3d4eac69, Next Data : 3, Random Data : 1
Data : 3, Node Address : com.anjan.clone.Node@42a57993, Next Data : 4, Random Data : 2
Data : 4, Node Address : com.anjan.clone.Node@75b84c92, Next Data : 5, Random Data : 4
Data : 5, Node Address : com.anjan.clone.Node@6bc7c054, Next Data : null, Random Data : 5

For the above program, the Time Complexity for cloning the Linked list is O(n).

Monday, 26 December 2016

How to write Native methods?

The Java Native method is a great way to gain and merge the power of C or C++ programming into Java.

Writing native methods involves importing C code into Java application. We'll follow few steps to create native methods -
1. Writing and Compiling Java Code
2. Creating C header (.h file)
3. Writing C code
4. Creating shared code library (.dll file) for Windows and (.so file) for Unix
5. Run Application.

In our example, we are using gcc compiler for C and considering path for gcc and java are set in the environment. Here we will create two methods - printMessage() which will print message in the console and printSum() which will print the sum of two numbers.

Project Structure -



Step 1 : Writing and Compiling Java Code

(NativeClass.java )

package com.anjan.api;

public class NativeClass {

static{
System.loadLibrary("nativedemo"); //Load native library at runtime nativedemo.dll (windows) and nativedemo.so (unix)
}

public native void printMessage();
public native int printSum(int a, int b);
}

(MainClass.java)

package com.anjan.main;

import com.anjan.api.NativeClass;

public class MainClass {

public static void main(String args[]){
NativeClass cls = new NativeClass();
cls.printMessage();
System.out.println(cls.printSum(5, 3));
}

}


After writing the Java Code, compile the code. After compiling the code, .class files will be generated in bin folder of the project.

Step 2 : Creating C header file (.h file)

To generate header file, follow the below steps -
(a) Go to the command prompt.
(b) Go to the bin directory of the project
      e.g - cd C:\NativeDemo\bin
(c) We'll use javah command to generate header file. Execute the below command to generate header file (.h file) for NativeClass
      e.g - javah com.anjan.api.NativeClass

A file com_anjan_api_NativeClass.h will be generated in bin folder. Create cfiles directory in the project and copy the header file into it.

(com_anjan_api_NativeClass.h)

Step 3 : Writing C Code

Create NativeClass.c inside cfiles folder and we'll write the logic for printMessage() and printSum() method in C file.

(NativeClass.c)

Step 4 : Creating Shared code library (.dll file)

To generate the shared code library (.dll file), we will go to cfiles directory in command prompt and we execute the below command.

gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o <dll file name> <cfilename>

e.g -
gcc -Wl,--add-stdcall-alias -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" -shared -o nativedemo.dll NativeClass.c

After executing the above command .dll file will be generated inside cfiles directory.
The dll file name should be same as the library name provided to load library in Java class.

Step 5 : Run Application

To execute the application, we will have to set the VM arguments for the application.

To set the VM arguments, follow the below steps -
(a) Right click on the Project and go to Run As -> Run Configurations
(b) In main tab, browse the project and enter the Main class of the project. Click Apply

(c) Go to Arguments tab, and enter the VM arguments and Click Apply and Run
-Djava.library.path=<directory containing dll file>

e.g -
-Djava.library.path=cfiles




Output -

I am Native Method
8

Thursday, 22 December 2016

How to modify the value of final fields in Java?

In JDK 1.1.x, we were not able to modify/access private fields using Reflection in Java. If someone tried to access fields which is inaccessible, the method throws an IllegalAccessException.

In JDK 1.2.x, we could make private fields accessible with setAccessible(true) method. We can even modify the final fields with Reflection.

If we set a final field of primitive type at declaration time, the value will be inlined, if the type is primitive or a String.

Lets see an example to modify final field of primitive integer type, Integer type and String type using Reflection -


import java.lang.reflect.Field;

public class ReflectionDemo {

private final String strVal1;
private final String strVal2 = "Anjan";
private final String strVal3;
private final String strVal4 = "XYZ";
private final Integer wrapperInt = 45;
private final int primInt1;
private final int primInt2 = 11;

public ReflectionDemo() {
primInt1 = 10;
strVal1 = "dummy";
strVal3 = "test";
}

public String toString() {
return "strVal1 : " + strVal1 + "; strVal2 : " + strVal2 + "; strVal3 : " + strVal3 + "; strVal4 : " + strVal4
+ "; wrapperInt : " + wrapperInt + "; primInt1 : " + primInt1
+ "; primInt2 : " + primInt2;
}

public void getMethodParameterValue(Object obj) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Class<?> cls = obj.getClass();

// Changing the value of String type which is initialized at Constructor - strVal1
Field field = String.class.getDeclaredField("value");
field.setAccessible(true);
field.set(strVal1, "new Dummy".toCharArray());

// Changing the value of String type which is declared - strVal2
field = String.class.getDeclaredField("value");
field.setAccessible(true);
field.set(strVal2, "new Anjan".toCharArray());

// Changing the value of String type which is initialized at Constructor - strVal3
field= cls.getDeclaredField("strVal3");
field.setAccessible(true);
field.set(obj, "new Test");

// Changing the value of String type which is declared - strVal4
field = cls.getDeclaredField("strVal4");
field.setAccessible(true);
field.set(obj, "new XYZ");

// Changing the value of Integer type which is declared - wrapperInt
field = Integer.class.getDeclaredField("value");
field.setAccessible(true);
field.set(wrapperInt, 30);

// Changing the value of primitive int type which is initialized at Constructor - primtInt1
field = cls.getDeclaredField("primInt1");
field.setAccessible(true);
field.set(obj, new Integer(48));

// Changing the value of primitive int type which is declared - primInt2
field cls.getDeclaredField("primInt2");
field.setAccessible(true);
field.set(objnew Integer(100));

}

public static void main(String args[]) throws NoSuchFieldException, IllegalAccessException {
ReflectionDemo demo = new ReflectionDemo();
System.out.println(demo);
demo.getMethodParameterValue(demo);
System.out.println(demo);

}
}

Output -

strVal1 : dummy; strVal2 : Anjan; strVal3 : test; strVal4 : XYZ; wrapperInt : 45; primInt1 : 10; primInt2 : 11

strVal1 : new Dummy; strVal2 : new Anjan; strVal3 : new Test; strVal4 : XYZ; wrapperInt : 30; primInt1 : 48; primInt2 : 11


As we discussed earlier that if we set a final field of primitive type and String at declaration time, the value will be inlined. The above highlighted field values are not changed, as strVal4 is String type and primInt2 is primitive type and we have set the values of these fields at declaration time. Hence the field value doesn't get changed.

To modify the value of final primitive type or String type we need to set the value in Constructors.