Category Archives: JAVA

JAVA

String having unique characters


public class IsStringHavingUniqueChar {

	public static void main(String[] args) {
		System.out.println("isStringHavingUniqueCharacters: "+isStringHavingUniqueCharacters("Raaaahul"));
	}
	
	private static boolean isStringHavingUniqueCharacters(String str){
		
		boolean[] asciiArray = new boolean[256];
		for (int i = 0; i < str.length(); i++) {
			int charAscii = str.charAt(i);
			if(asciiArray[charAscii])
				return false;
			asciiArray[charAscii] = true;
		}
		
		return true;
	}
	
}

Collection Sorting using Comparator Interface

package com.orange.mail.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

public class EmployeeComparatorSorting implements Comparator {

	public static void main(String[] args) {

		Employee employee1 = new Employee(1, "Rahul");
		Employee employee2 = new Employee(5, "Mehul");
		Employee employee3 = new Employee(3, "Manisha");
		Employee employee4 = new Employee(6, "Shahnahwaz");
		Employee employee5 = new Employee(2, "Hitesh");
		
		List<Employee> employees = new ArrayList<Employee>();
		employees.add(employee1);
		employees.add(employee2);
		employees.add(employee3);
		employees.add(employee4);
		employees.add(employee5);
		
	    System.out.println("Before Sorting");
	    for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmp_Id() + ", "+employee.getEmp_name());
		}
		
	    System.out.println("After Sorting using Comparable");
	    Collections.sort(employees, new EmployeeComparatorSorting());
	    System.out.println("Before Sorting");
	    for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmp_Id() + ", "+employee.getEmp_name());
		}
	    
	}

	public int compare(Object o1, Object o2) {
		Employee employee1 = (Employee)o1;
		Employee employee2 = (Employee)o2;
		return (employee1.getEmp_Id() < employee2.getEmp_Id()) ? -1 : (employee1.getEmp_Id() > employee2.getEmp_Id()) ? 1 :0;
	}
}

package com.orange.mail.controller;
public class Employee {
	private int emp_Id;
	private String emp_name;

	public Employee(int id, String name ) {
		super();
		this.emp_Id = id;
		this.emp_name = name;
	}
	
	/*public int compareTo(Object obj) {
		Employee employee = (Employee)obj;
		
		return (this.emp_Id < employee.emp_Id) ? -1 : (this.emp_Id > employee.emp_Id) ? 1 :0;
	}*/
	
	public int getEmp_Id() {
		return emp_Id;
	}
	public void setEmp_Id(int emp_Id) {
		this.emp_Id = emp_Id;
	}
	public String getEmp_name() {
		return emp_name;
	}
	public void setEmp_name(String emp_name) {
		this.emp_name = emp_name;
	}
	
}

Output:
Before Sorting
1, Rahul
5, Mehul
3, Manisha
6, Shahnahwaz
2, Hitesh
After Sorting using Comparator
1, Rahul
2, Hitesh
3, Manisha
5, Mehul
6, Shahnahwaz

Collection Sort using Comparable Interface

package com.orange.mail.controller;
public class Employee implements Comparable {

	private int emp_Id;
	private String emp_name;
	
	public Employee(int id, String name ) {
		super();
		this.emp_Id = id;
		this.emp_name = name;
	}
	
	public int compareTo(Object obj) {
		Employee employee = (Employee)obj;
		
		return (this.emp_Id < employee.emp_Id) ? -1 : (this.emp_Id > employee.emp_Id) ? 1 :0;
	}
	
	public int getEmp_Id() {
		return emp_Id;
	}
	public void setEmp_Id(int emp_Id) {
		this.emp_Id = emp_Id;
	}
	public String getEmp_name() {
		return emp_name;
	}
	public void setEmp_name(String emp_name) {
		this.emp_name = emp_name;
	}
	
}

package com.orange.mail.controller;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class EmployeeComparableSorting {
	public static void main(String[] args) {
		Employee employee1 = new Employee(1, "Rahul");
		Employee employee2 = new Employee(5, "Mehul");
		Employee employee3 = new Employee(3, "Manisha");
		Employee employee4 = new Employee(6, "Shahnahwaz");
		Employee employee5 = new Employee(2, "Hitesh");
		
		List<Employee> employees = new ArrayList<Employee>();
		employees.add(employee1);
		employees.add(employee2);
		employees.add(employee3);
		employees.add(employee4);
		employees.add(employee5);
		
	    System.out.println("Before Sorting");
	    for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmp_Id() + ", "+employee.getEmp_name());
		}
		
	    System.out.println("After Sorting using Comparable");
	    Collections.sort(employees);
	    for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
			Employee employee = (Employee) iterator.next();
			System.out.println(employee.getEmp_Id() + ", "+employee.getEmp_name());
		}	    
	}
}

Output:
Before Sorting
1, Rahul
5, Mehul
3, Manisha
6, Shahnahwaz
2, Hitesh
After Sorting
1, Rahul
2, Hitesh
3, Manisha
5, Mehul
6, Shahnahwaz

EnumMap vs HashMap

Both implement Map interface.
1. EnumMap is optimized for enums to store in a map. EnumMap internally uses array and provide constant time performance for common methods like get() and put().
2. You can only use Enum as a key in EnumMap whereas in HashMap you can use any object including Enum
3. As EnumMap is optimized for enum keys , so it’s performance is better than HashMap when use Enum key as object
4. One more difference is that Enummap dont use hascode() method to store the keys and values so there is no collision.

Stackoverflow vs Outofmemory error

JVM divides its memory into two parts Heap memory and Stack : heap memory is used to store the instance objects whereas stack memory is used to store the calling hirarchy of the methods as well as the local variables of the method.
OutOfMemoryError is related to Heap. If you have large object which is refrenced and not eligible for garbage collection, and you are going to create new objects for which memory is not availbale , it will throw OutOfMemory error.
Solution : Always free your objects from reference so that objects will be eligible for GC.

StackOverflowError is related to stack. All your local variables and methods calls related data will be on stack. There is a single stack frame for every method call and all the data related to local variable and methods wiil be stored inside the stack frame. Stack frame is removed once execution is completed.
Solution: Avoid recursion for large iterations.

Thread Dump

How to take Thread Dump:
1. Get the process Id of the process
ps -aef | grep java

2. Get the Thread dump for all the threads within a process
jstack {pid} > dump.log

Load file data using class loader in java

public class PublicServicesSkeleton{
    	static final ClassLoader loader = PublicServicesSkeleton.class.getClassLoader();
    	private static List<String> cuidList;
    	static {
    		try {
		InputStream inputStream = loader.getResourceAsStream("USER_GASSI_KO.txt");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				
		cuidList = new ArrayList<String>();
		String strLine;
				
		// Read file line by line
		while ((strLine = bufferedReader.readLine())!=null) {
			cuidList.add(strLine);
		}		
		bufferedReader.close();
		inputStream.close();
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    }
}

Immutable Objects in java

If we can not modify the object after creation that object is called Immutable object.
String is the best example for Immutable Object.
Rules for making the objects Immutable:

  1. Class should be final.
  2. Class members should be final.
  3. If we have any mutable object in our class then return the copy of that object through the getter of that class member.

We can create our own immutable objects like as follows:

import java.util.Date;
public final class Employee implements Cloneable
{
   private final String name;
   private final String id;
   Date date;	
   public Employee(String name, String id, Date date)
   {
	this.name = name;
	this.id = id;
	this.date = date;
   }	
   public String getName() 
   {
	return name;
   }
   public String getId() 
   {
	return id;
   }
   public Date getDate() 
   {
	return (Date)date.clone();
   }
}


In the above example we have one class Employee which have three members , two are String which are already immutable and one is Date which is mmutable , so we need to take care one thing that we should return copy of the mutable member instead of the original object.
We can say that one use of cloning is to make an object Immutable.

Note: Main benefit of immutable object is that multiple threads can access the immutable object outside the synchronization block , it improves the performance.

Facade Design Pattern

Facade pattern hides the complexities of the system and provide the interface to use that system.
Here we are going to create a shape interface that will be provided to client for using the Shape Maker.

facade.jpg

Step-1 Create an interface Shape

interface Shape
{
 public void draw();
}

class Circle implements Shape
{
  public void draw()
  {
     system.out.println("Hi, this is circle");
  }
}

class Rectangle implements Shape
{
  public void draw()
  {
     system.out.println("Hi, this is rectangle");
  }
}

class Square implements Shape
{
   public void draw()
   {
     system.out.println("Hi, this is square");
   }
}

class ShapeMaker 
{
   Shape circle;
   Shape rectangle;
   Shape square;
   ShapeMaker(Shape shape)
    {
	circle = new Circle();
	rectangle = new Rectangle();
        square = new Square();
    }

   public void drawCircle()
   {
	circle.draw();
   }

  public void drawRectangle()
  {
	rectangle.draw();
  }

  public void drawSquare()
  {
  	square.draw();
  }
}

public class FacadeDemo
{
 ShapeMaker shapeMaker = new ShapeMaker();	
 public static void main(String[] arg)
 {
  shapeMaker.drawCircle();
  shapeMaker.drawRectangle();
  shapeMaker.drawSquare();
 }
}


Output:
Hi, this is circle
Hi, this is rectangle
Hi, this is square