Wednesday, July 2, 2014

Integer Literal - Octals

What is the Output of the below Program:
//OcatalSample.java
public class OcatalSample{
    public static void main(String []args){
      int i = 012;
      int j = 034;
      int k = 056;
      int m = 08; 
      System.out.println("i=" +i + ", j="+j+ ", k="+k+ ", m="+m);
    }
}
public class ReverseNumber {
   public static void main(String[] args) {
      int number = 987;
      System.out.println("Reverse of given number is: "+
               getReverseNumber(number));   
   }

   private static int getReverseNumber(int number) {
      int reverseNumber = 0;
      while (number > 0) {
          int reminder = number % 10;
          reverseNumber = reverseNumber * 10 + reminder;
          number = number / 10;
      }
      return reverseNumber;
   }
}

//Output:
//Reverse of given number is: 789

 Output: It won’t compile. It gives below compilation error
             Exception in thread "main" java.lang.Error: Unresolved compilation problem:
                       The literal 08 of type int is out of range
            at OcatalSample.main(OcatalSample.java:7)

Why??
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
Octal representation in java(base 8) :
An integer literal prefixed with 0 is treated as octal. It means when an integer literal starts with 0 in Java, it's assumed to be in octal notation. The digits 8 and 9 are illegal in octal—the digits can range only between 0 and 7.

In the above example #line7 gives an error, because as per above line range of octal is 0 to 7 only.

Note: Generally in octal representation, 7 + 1 is 10.



Wednesday, June 18, 2014

String comparison tip

In Java if you actually want to test whether two strings have the same value you should use .equals(). It checks value equality. I think most of the people knew it. 

Today I want to add a very valuable tip:
If you have strings or constants to compare, always put them first in the equals clause. 
//StringComparisonTip.java
public class StringComparisonTip {
   public static void main(String[] args) {
     // Recommended String comparison
     if("Venkatesh".equals(getMyName())){  
        System.out.println("We are equal");
     }
     // It is Correct but it may be throws NPE at runtime
     if(getMyName().equals("Venkatesh")){  
        System.out.println("We are equal");
     }
   }
   public static String getMyName(){
     return null;
   }
}
In the above code line #5 (if("Venkatesh".equals(getMyName()))) is much better than the line #9 (if(getMyName().equals("Venkatesh"))) because in the second case getMyName() may be null and throws an java.lang.NullPointerException while in the first case it doesn't matter if getMyName() is null. 

Note: I am not saying second one is wrong but I am saying it is not recommended by Java Guru's(Who has great knowledge in Java). Both are syntactically correct and you never get compilation error.

Tuesday, June 10, 2014

Count occurrence of an element

Write a program to count the total number of duplicated entries in a List.

For Example :
Input List of countries : japan,usa,uae,japan,uae,usa,australia
Expected output:
japan:2
usa:2
uae:2
australia:1

Solutions:

Solution 1:
1) Java API provides a class called Collections. This class contains static utility methods for manipulating collections. It provides a static method for counting the number of elements in specified collection, as you can see below for more information. 

static intfrequency(Collection<?> c, Object o)
 Returns the number of elements in the specified collection equal to the specified object.
     c - the collection in which to determine the frequency of o
     o - the object whose frequency is to be determined

// CountDuplicates.java
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

public class CountDuplicates {
   public static void main(String[] args) {
      String[] listOfArray = 
      { "japan", "usa", "uae", "japan", "uae", "usa", "australia" };
      List list = Arrays.asList(listOfArray);
      System.out.println("Frequency of each country ");
      Set uniqueSet = new LinkedHashSet(list);
      for (String countryName : uniqueSet) {
      System.out.println(countryName + ": " 
      + Collections.frequency(list, countryName));
      }
   }
}
//Output::
//Frequency of each country 
//japan: 2
//usa: 2
//uae: 2
//australia: 1

Solution 2:
// CountDuplicates1.java
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Map;

public class CountDuplicates1 {
   public static void main(String[] args) {
      String[] listOfArray = 
      { "japan", "usa", "uae", "japan", "uae", "usa", "australia" };
      Map<String, Integer> map = new LinkedHashMap<String,Integer>();
      for( String countryName : listOfArray){
          int count = 0;
          if(map.get(countryName) != null){
               count = map.get(countryName);
          }
          map.put(countryName, count+1);
      } 
      for (Entry countryEntry : map.entrySet()) {
          System.out.println(countryEntry.getKey()+ ": " 
         + countryEntry.getValue() );
      }
   }
}
//Output::
//Frequency of each country 
//japan: 2
//usa: 2
//uae: 2
//australia: 1

Monday, June 9, 2014

Swap two numbers

Solutions:
1) Using temporary variable / Using extra space
2) Without using temporary variable / Without using extra space
     a) Using arithmetic operators
     b) Using bitwise operator

Solution 1: Using temporary variable
//SwapUsingExtraVariable.java
public class SwapUsingExtraVariable {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;
        System.out.println("Values before swapping");
        System.out.println("a= " +a + " b= "+b);
        int temp = a;
        a = b;
        b = temp;
        System.out.println("Values after swapping");
        System.out.println("a= " +a + " b= "+b);
    }
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
Solution 2 a: Using arithmetic operators
//SwapUsingArthematic.java
public class SwapUsingArthematic {
	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		
		System.out.println("Values before swapping");
		System.out.println("a= " +a + " b= "+b);
		
		a = a + b;
		b = a - b;
		a = a - b;
                
                // a = a * b;
                // b = a / b;
                // a = a / b;

		System.out.println("Values after swapping");
		System.out.println("a= " +a + " b= "+b);
	}
}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10
   
We can use "*" & "/" operators also instead of "+" & "-". Check the above program lines 14, 15 and 16 for the reference. But problem with "/" operator is it gives java.lang.ArithmeticException: / by zero Exception for "b" value is zero.

Solution 2 b: Using bitwise operator
//SwapUsingBitWiseOperator.java
public class SwapUsingBitWiseOperator {

	public static void main(String[] args) {
		int a = 10;
		int b = 20;
		
		System.out.println("Values before swapping");
		System.out.println("a= " +a + " b= "+b);
		
		a = a ^ b;
		b = a ^ b;
		a = a ^ b;

		System.out.println("Values after swapping");
		System.out.println("a= " +a + " b= "+b);
	}

}
// Output:
//Values before swapping
//a= 10 b= 20
//Values after swapping
//a= 20 b= 10

Sunday, June 8, 2014

Technical Interview Question 1

You have an array of numbers from 0 to N-1, one of the numbers is removed, and replaced with a number already in the array which makes a duplicate of that number. How can we detect this duplicate in time O(N).
For example an array of 6 integers - 0,1,2,3,4,5. one of the number i.e "3" removed and replaced with "2". now array would become 0,1,2,2,4,5
Solution :

// InterviewQuestion1.java
public class InterviewQuestion1 {
   public static void main(String[] args) {
      int[] testArray = { 0, 1, 2, 2, 4, 5 };
      boolean[] testBool = new boolean[testArray.length];
      for (int i = 0; i < testArray.length; i++) {
         testBool[testArray[i]] = true;
      }
      System.out.print("Duplicate Number is : ");
      for (int i = 0; i < testArray.length; i++) {
        if (!testBool[i]) {
         System.out.print(testArray[i]);
         break;
        }
      }
   }
}

// Output: Duplicate Number is : 2

Sample Code

    // Hello World.java
    public class HelloWorld{
      public static void main(String[] args){
        System.out.print("Hi");      
      }      
    }