Reverse LinkedList

Reverse Linkedlist using java code

This is one of the interview question which asked in recent interview like need to create a LinkedList and need to reverse those values in same linkedList without using addition list. We can make use of List implementation class LinkedList to achieve this. There are couple of ways we can achieve this in java by using Collection utility function reverse() and without reverse() function also. 
Lets see both the implementation in below examples. First lets see how to reverse LinkedList by using reverse() function. 


import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class LinkedListReverse {

 public static void main(String[] args) {
  
  List<Integer> list = new LinkedList<Integer>();
  list.add(3);
  list.add(6);
  list.add(7);
  list.add(0);
  list.add(1);
  list.add(4);
  list.add(9);
  list.add(5);
  
  System.out.println("Before Reverse : "+list.toString());
  
  Collections.reverse(list);
  
  System.out.println("After Reverse : "+list.toString());  
 }
}

OUTPUT:


Before Reverse : [3, 6, 7, 0, 1, 4, 9, 5]
After Reverse : [5, 9, 4, 1, 0, 7, 6, 3]

Next we will see how to reverse linkedlist without using reverse() function.


import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class LinkedListReverse {

 public static void main(String[] args) {
  
  List<Integer> list = new LinkedList<Integer>();
  list.add(3);
  list.add(6);
  list.add(7);
  list.add(0);
  list.add(1);
  list.add(4);
  list.add(9);
  list.add(5);
  
  System.out.println("Before Reverse : "+list.toString());
  
  ListIterator<Integer> itrFirst = list.listIterator();
  ListIterator<Integer> itrLast = list.listIterator();
  
  while (itrLast.hasNext()) {
   itrLast.next();   
  }
  
  for(int i = (list.size()/2)-1;itrFirst.hasNext() && itrLast.hasPrevious() && i>=0;i--){
   int first = itrFirst.next();
   int last = itrLast.previous();
   itrFirst.set(last);
   itrLast.set(first);
  }
  
  System.out.println("After Reverse : "+list.toString());  
 }
}

OUTPUT:


Before Reverse : [3, 6, 7, 0, 1, 4, 9, 5]
After Reverse : [5, 9, 4, 1, 0, 7, 6, 3]


How to convert Java Properties file to XML file

 
Convert Java Properties file to XML file

In our earlier tutorial we have seen how to convert XML file to properties file. As a vice verse we will see how to convert XML file to java properties file in this tutorial. Lets consider there are property key with designation, city, state and country as same as previous tutorial example. Lets try to create same XML file using java properties file in below example code,


import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Properties;

public class PropertyToXML {
 
 public static void main(String[] args) {
  try{
   Properties property = new Properties();
   property.setProperty("designation", "APAC Manager");
   property.setProperty("city", "Bangalore");
   property.setProperty("state", "Karnataka");
   property.setProperty("country", "India");
  
   // XML file path to save 
   OutputStream os = new FileOutputStream("D://propertiesToXML.xml");
    
   // Write properties into XML
      property.storeToXML (os, "Details");
      
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
}


OUTPUT:





How to convert XML file to Java Properties file

 
Convert XML file to Java Properties file
In one of our earlier tutorial we have seen how to use Properties class in Java to read property file. Basically property file hold key and corresponding  value part and by just loading those property files we can read application or project related properties which we have configured and also easy to modify those values. 
Same way by using Properties class we can convert XML file to Properties file and also vice-verse (Properties file to XML file). In this tutorial we will see about how to convert XML file to Java Properties file.

Input XML File:


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

<properties>
 <entry key="designation">Software Engineer</entry>
 <entry key="city">Bangalore</entry>
 <entry key="state">Karnataka</entry>
 <entry key="country">India</entry>
</properties>


Java Code to convert XML file to Java Properties file:


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class XMLToProperties {
 
 public static void main(String[] args) {
  try{
   Properties property = new Properties();
   InputStream is = new FileInputStream(new File("D://myproperties.xml"));
   property.loadFromXML(is);
   
   String designation = property.getProperty("designation");
   String city = property.getProperty("city");
   String state = property.getProperty("state");
   String country = property.getProperty("country");
   
   System.out.println(designation);
   System.out.println(city);
   System.out.println(state);
   System.out.println(country);
   
  }catch (Exception e) {
   e.printStackTrace();
  }
 } 
}


OUTPUT:


Software Engineer
Bangalore
Karnataka
India


In XML file <properties> and <entry> tag name must be same along with "key" attribute in entry tag which will be identified as key and value properties.  




Character Frequency in String

 
Character Frequency in String

This is one of the easy interview programming question under 3 years experience. Lets assume given a lengthy string and asked you to find each character frequency. For example the given string is "hello java discover". In this string 'h'=1 , 'o'=2 etc., need to find each character occurred counts need to printed. 
We can achieve this by many ways like converting to character array and then manipulating each character or in looping count each character occurrence and store in any Collection object etc., In our below example we will use HashMap to store characters as key and their counts in value part.


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class CharFreq {

 public static void main(String[] args) {

  String str = "hello javadiscover";

  Map<Character, Integer> map = new HashMap<Character, Integer>();

  for (int i = 0; i < str.length(); i++) {
   char ch = str.charAt(i);
   if (map.get(ch) != null) {
    map.put(ch, (map.get(ch) + 1));
   } else {
    map.put(ch, 1);
   }
  }

  Set<Character> set = map.keySet();
  for (Character character : set) {
   System.out.println(character + " : " + map.get(character));
  }
 }
}


OUTPUT:


  : 1 // space character 
d : 1
e : 2
c : 1
a : 2
o : 2
l : 2
j : 1
h : 1
i : 1
v : 2
s : 1
r : 1



Array with Even and Odd numbers

Array with Even and Odd numbers

This is one of the interesting interview question which asked about integer array. Before going into direct question please refer to other tutorial about Java Array which we discussed earlier. 

There is an integer array with combination of Even and Odd numbers. Numbers are un-ordered and need to arrange all even numbers left and all odd numbers at right side with ascending order respectively ie., all even numbers at left side and all odd numbers at right should to sorted separately. For example if the input array is {4,6,1,5,8,3,2,7,9}, then output should be {2,4,6,8,1,3,5,7,9}
The constraints are 
  • Should not use any additional array
  • Should not use any collection API
Need to arrange and sort integers in same array. Lets see Java solution for this program by sorting and arranging integers.


public class EvenOddArray {

 public static void main(String[] args) {

  int[] array = new int[] {31, 30, 4, 6, 8, 3, 2, 7, 9, 12, 34, 11 };

  int evenPnt = 0;
  
  // Arranging Even and Odd numbers
  for (int i = 0; i < array.length; i++) {
   if (array[i] % 2 == 0) {
    swap(array, evenPnt, i);
    evenPnt++;
   }
  }
  
  // Sorting even numbers
  sort(array, 0, evenPnt);
  
  // Sorting Odd numbers 
  sort(array, evenPnt, array.length);

  for (int i : array) {
   System.out.print(i+", ");
  } 
 }

 public static void sort(int[] arr, int min, int max) {
  for (int i = min; i < (max - 1); i++) {
   for (int j = i + 1; j < max; j++) {
    if (arr[i] > arr[j]) {
     swap(arr, i, j);
    }
   }
  }
 }

 public static void swap(int[] arr, int i, int j) {
  int tmp = arr[i];
  arr[i] = arr[j];
  arr[j] = tmp;
 }
}


OUTPUT:


2, 4, 6, 8, 12, 30, 34, 3, 7, 9, 11, 31, 

Case Insensitive HashMap

 
Array with Even and Odd numbers

This is one of the programming interview questions which asked in recent interview. Need to implement HashMap which will take case insensitive keys. Here we should not confuse with case sensitive, since HashMap by default will hold keys with case sensitive. But as an alternate we need to implement HashMap with Case Insensitive. 
For example: We need to store "abc" and "ABc" in key. Default HashMap will have 2 entries since its case sensitive, where as we need to store only 1 key and value with "abc" with case insensitive. 

So how we can define HashMap with case insensitive? 

We can implement in various ways like implementing Map interface or extending HashMap class etc., In below example we will see about implementing Case Insensitive HashMap by extending HashMap class.


import java.util.HashMap;
import java.util.Map;

public class HashMapCaseInsensitive extends HashMap<String, String>{
 
 @Override
 public String put(String key, String value) {
  return super.put(key.toLowerCase(), value);
 }

 @Override
 public String get(Object key) {
  return super.get(key.toString().toLowerCase());
 }
 
 public static void main(String[] args) {
  
  Map<String, String> hm = new HashMapCaseInsensitive();
  
  hm.put("abc", "one");
  hm.put("ABc", "two");
  hm.put("aBc", "three");
  
  System.out.println("HASHMAP SIZE  : "+hm.size());
  
  System.out.println("GET ABC VALUE : "+hm.get("ABC"));
 }
}


OUTPUT:


HASHMAP SIZE  : 1
GET ABC VALUE : three









Java String

 
Java String

We all know String class in Java is immutable and the value once stored in String Object can't be modified. Also we have discussed about this in our earlier tutorials like difference between String, StringBuffer and StringBuilder and how to create user defined immutable class in Java. We will see how "==" equals operator works on String Object. 

We know that when we apply "==" equals operator on Object it will check only the Object reference rather than values stored in the Object. So using "==" on string Object will result incorrect output and advised to use equals() method which internally overrides hashcode() which will check the values in the Objects using hashing algorithm and gives the correct output.

In this tutorial we will see about how "==" equals operator works internally on string Object with different scenarios. 

Program : 1


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "javadiscover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see in above disassembled code from Java class file, both String references are same. So when we compare these string Objects with "==" operator we will get true. 


Program : 2


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java" + "discover";
  System.out.println(str1 == str2);
 }
}

OUTPUT:


true



We can see both the string Objects are referred by same reference. So we are getting true when we compare by "==" operator. 


Program : 3


public class StringTest {
 
 public static void main(String[] args) {
  String str1 = "javadiscover";
  String str2 = "java";
  String str3 = "discover";
  String str4 = str2 + str3;
  System.out.println(str1 == str4);
 }
}

OUTPUT:


false



From above code we can clearly see first 3 string objects are having different references. But 4th "Str4" String in java file contains same value of 1st String "str1" but JDK has created StringBuilder class instead of String with different reference. Hence we are getting false when we compare "str1" and "str4" with "==" operator. 



Grayscale image

 
In our earlier tutorials we have seen about re-sizing image, drawing image border. On same way we will see about how to convert RGB image to Grayscale image using java code. When we talk about RGB to Grayscale we can convert in lot of ways like pixel by pixel, using Java API etc., Even in our below same codes we have tried with 2 ways like using Java Graphics class and next manually reading pixel by pixel and changing the RGB values. 
First lets see by using Graphics class 


import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ColorToGray {

 public static void main(String[] args) {
        
  try {
      File colorImage = new File("D://color.png");
      File grayImage = new File("D://gray.jpg");
      
   BufferedImage cImage = ImageIO.read(colorImage);
   
   BufferedImage image = new BufferedImage(cImage.getWidth(), cImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);  
   Graphics graphics = image.getGraphics();  
   graphics.drawImage(cImage, 0, 0, null);  
   graphics.dispose(); 
   
   ImageIO.write(image, "jpg", grayImage);   
   
        } catch (IOException e) {
   e.printStackTrace();
  } 
 }
}

OUTPUT:

          INPUT FILE                                                             OUTPUT FILE


Color ImageGrayscale Image


Next we will see about reading pixel by pixel and converting RGB to Grayscale which will be time consuming but where we can play around with the pixels value which we want. 


import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Grayscale {
   
    public static void main(String[] args11) throws IOException {
 
        File colorImage = new File("D://color.jpg");
        String grayImage = "D://gray.jpg";
        
        BufferedImage cImage = ImageIO.read(colorImage);
        BufferedImage gImage = new BufferedImage(cImage.getWidth(), cImage.getHeight(), cImage.getType());
        
        for(int i=0; i<cImage.getWidth(); i++) {
            
         for(int j=0; j<cImage.getHeight(); j++) {
 
                int alpha = new Color(cImage.getRGB(i, j)).getAlpha();
                int red = new Color(cImage.getRGB(i, j)).getRed();
                int green = new Color(cImage.getRGB(i, j)).getGreen();
                int blue = new Color(cImage.getRGB(i, j)).getBlue();
 
                
                int gray = (red + green + blue) / 3; 
                red = green = blue = gray;
                gray = (alpha << 24) + (red << 16) + (green << 8) + blue;
                
                gImage.setRGB(i,j,gray);
 
            }
        }
        
        ImageIO.write(gImage, "jpg", new File(grayImage));
    }
 }

OUTPUT:

          INPUT FILE                                                             OUTPUT FILE

Grayscale ImageColor Image