Tuesday, May 13, 2014

ASCII - Char conversion in Java

This is the ASCII to Char mapping table :



We can convert a char to its ASCII equivalent and ASCII back to a char in java.

  char a= 'a';   
  System.out.println((int) a);   

prints 97 in the console.


ASCII to char:
 int dotAscii = 46;   
 System.out.println((char) dotAscii);   

prints '.' in the console.


Now we know that char can be converted to ASCII and vice versa.

1) Convert a string to ASCII.

 public static void convertStringTosASCII(String input) {  
  char[] inputArray = input.toCharArray(); // Convert string to char array.  
  StringBuilder sb = new StringBuilder();  
  for (int i = 0; i < inputArray.length; i++) {  
      sb.append((int) inputArray[i]); //Append the ascii code of the character array to the string builder  
  }  
  System.out.println(sb.toString());  
  }  

we give "Test String" as the input the output will be "841011151163283116114105110103"

2) Convert ASCII to String

 public static void convertASCIIToString(String input) {  
  StringBuilder sb = new StringBuilder();  
  for (int i = 0; i < input.length(); i += 2) {  
   String temp = input.substring(i, i + 2);  
   int string_ascii = Integer.parseInt(temp);  
   if (string_ascii < 32) {            // ASCII code for characters ranges from 32-127. It                                           can be either 2-digit or 3-digit.  
   temp = input.substring(i, i + 3);  
   string_ascii = Integer.parseInt(temp);  
   i = i + 1;  
   }  
   sb.append((char) string_ascii); //append the char to the string builder  
  }  
  System.out.println(sb.toString());  
  }  

if we give "841011151163283116114105110103" as input then we get "Test String" as the output.



Thursday, May 8, 2014

All about Java Constructors

1) Constructors can have only public,private,protected and default access modifiers. final,abstract,static keywords are not allowed.

                                        public  abstract Constructor() {

                                         }


2)Constructors do no have a return type.If it has a return type then it becomes a method, showing a warning that "The method has the constructor name".

                                        public void  Constructor() {

                                         }

3)Constructors can have any number of parameters  and can be of any type. But only final modifier is allowed for the parameters.

public Constructor(int a,String b,boolean c,final String d,int e,transient String f) {
System.out.println("Invoking constructor");
}

Here, transient keyword is not allowed. Only final modifier is allowed.

4)You can call one constructor from the other using 'this'

                                  public Constructor(int a) {
                                   this();
                                   System.out.println("Parameterized constructor");
                             }
this() will call the default constructor.
                                 public Constructor() {
                                System.out.println("Default constructor");
                             }

5) If you are calling this() then the default constructor should be implemented. Else it will give "default constructor undefined".

6)Now what happens if we do like this :

                                  public Constructor(int a) {
                                      this();
                                     System.out.println("Parameterized constructor");
                             }
this() will call the default constructor.

                                 public Constructor() {
                                          this(2);
                                        System.out.println("Default constructor");
                             }
this(2) will call the parameterized constructor.

It is not allowed as it will result in loop. It is a compile time error "Recursive Constructor Invocation".

7) When there are two classes say, A and B where B extends A then we should follow the below rules
      1. If a subclass B wants to invoke super class A default constructor then "super()"  method should be used. No need to define the default constructor in super class.
      2. Even if we do not mention super() in any of the constructors, the default constructor of the super class is called by default. This does not apply for the parameterized constructor.
      3. If a subclass B wants to invoke super class A parameterized constructor then super(parameters) should be used. The super class default and parameterized constructors should be defined. Else it will show compile time error.



















Wednesday, May 7, 2014

Given a string, compute recursively a new string where identical chars that are adjacent in the original string are separated from each other by a "*".


pairStar("hello") → "hel*lo"
pairStar("xxyy") → "x*xy*y"
pairStar("aaaa") → "a*a*a*a"


public static String pairStar(String str) {
String result = "";
if (str == null) {
return result;
}
result = str.substring(0, 1);

if (str.trim().length() == 1)
return result;

if (result.equals(str.substring(1, 2))) {
result += "*";
}

str = str.substring(1);
return result + pairStar(str);

}


ex : hello

 - checks whether  "h".equals("e")
 - if No
        - "h" will be added to the result
        - pairStar() is invoked again with the string "ello".

   [In program, it can be mapped like return "h"+pairStar("ello");]

  - checks whether  "e".equals("l")
  - if No
        - "e" will be added to the result
        - pairStar() is invoked again with the string "llo".
 - checks whether  "l".equals("l")
  - if Yes
        - "l" will be added to the result with a "*" after it.
        - pairStar() is invoked again with the string "lo".
  - checks whether  "l".equals("o")
  - if No
        - "l" will be added to the result.
        - pairStar() is invoked again with the string "o".
  - checks whether  string "o" has one character
  - if Yes
        - return o;
        - result will now have hel*l with the o appended at the last

So the output will be "hel*lo";


Given a string, compute recursively a new string where all the 'x' chars have been removed. noX("xaxb") → "ab" noX("abc") → "abc" noX("xx") → ""

public static String noX(String str) {
String result = "";
if (str == null || str.trim().length() == 0)
return result;
String c = str.substring(0, 1);
str = str.substring(1);
if (!(c.equals("x"))) {
result = c;
}
return result + noX(str);

}

Given a non-negative int n, return the count of the occurrences of 7 as a digit, so for example 717 yields 2. (no loops).

public int count7(int n) {
int count=0;
if(n==0){
   return 0;
}
int num = n % 10;
if(num ==7 ){
    count++;
}
n=n/10;
return count+count7(n);

}

What is the contract between hashCode() and equals() method?

Lets take an example of Book.

class Book{
String name ;
int bookid;
public Book(String name,int bookid) {
this.name=name;
this.bookid=bookid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBookid() {
return bookid;
}
public void setBookid(int bookid) {
this.bookid = bookid;
}
}


Now lets create books (Book objects) and store it in hashtable.

                Book book1 = new Book("Java", 123);
Book book2 = new Book("C++", 456);
                Book book3 = new Book("Java", 123);

Hashtable<Book, String> ht = new Hashtable<Book, String>();
ht.put(book1, book1.getName());
ht.put(book2, book2.getName());

From the above code we can see that a Java book and C++ book is added to the hashtable. Lets check the equality of the two objects.

               System.out.println("Book1 equals Book2 :" + book1.equals(book2));  =  false

System.out.println("Book1 equals Book3 :" + book1.equals(book3)); = false



So though book1 and book3 are same equals() method returns false. So we should override the equals of method in the Book class.

@Override
public boolean equals(Object o) {
Book book = (Book)o;
return (this.bookid == book.bookid && this.name.equals(book.name));
}

Now we are checking whether book ids and the names match in the overridded equals() method.

So book1 and book3 will be equal now as both have name 'Java' and id '123'

               System.out.println("Book1 equals Book3 :" + book1.equals(book3)); = true

Now we know that book1 and book3 are same. So lets try to get the book1 from the hashtable.


                System.out.println(ht.get(book3)); = null
     
                System.out.println("Book 1 hashcode :" + book1.hashCode());  = 1021653256

System.out.println("Book 2 hashcode :" + book2.hashCode());  = 1794515827

System.out.println("Book 3 hashcode :" + book3.hashCode());   = 1167165921
 
ht.get(book3) method will return null. If you think if book1 and book3 are same then ht.get(book3) should have returned 'Java', then you are missing something. hashCode() method comes into picture now.

In my previous post i have explained what is the use of hashCode(). So now hashCode(book3) will be calculated which is 1167165921  and it will check whether there is a any entry for the key equals(1167165921)?. So it will return false.

book1 and book3's hashCode should match in order to retrive book1 by giving book3 as the key.

As we have not overridden the hashCode() method in the Book class it will never find a matching value.

@Override
public int hashCode() {
return this.bookid;
}

Lets try again to check whether book object is there?

      
System.out.println("Book1 equals Book3 :" + book1.equals(book3)); = true

System.out.println("Book 1 hashcode :" + book1.hashCode()); = 123

System.out.println("Book 3 hashcode :" + book3.hashCode()); = 123

System.out.println(ht.get(book3)); = Java.

so to summarize,
1) When two objects are equal, their hashcode should be equal and not vice versa.
2 ) When you override equals() you should override hashCode() method also.

Lets discuss Point 1:

When hashCode() of two objects are equal it is not necessary that they should be equal.

Let us create two book objects:
               Book book1 = new Book("Java", 123);

Book book2 = new Book("JSON", 456)

Now override hashCode() method in Book.

@Override
public int hashCode() {
return this.name.length();
}

The hashcode of book1 and book2 are same, but they are not equal.

   System.out.println("Book1 equals Book2 :" + book1.equals(book2)); = false
System.out.println("Book 1 hashcode :" + book1.hashCode()); = 4

System.out.println("Book 2 hashcode :" + book2.hashCode()); = 4
  

             

Tuesday, May 6, 2014

Print the count of the longest sequence in an array.

Question :  Write a program to print the count of the longest sequence in the input array

Lets take an example of

input: 1,2,14,3,4,5,10,7,8,9,10,11,12,13,14,15
output: 9

Here we have sequence 1,2              count=2
                                     3,4,5           count=3
                                     7,8,..15       count=9

So the output should be 9.

public class LongSequence {

public static int printCounter(int[] arg) {

int counter = 1;
int resultCounter = 0;
for (int i = 0; i < arg.length - 1; i++) {
if (arg[i] + 1 == arg[i + 1]) {
++counter;
} else {
if (counter >= resultCounter) {
      resultCounter = counter;
}
counter=0;
}
}
System.out.println(resultCounter);
                return resultCounter;
}

}