Friday, September 21, 2012

Java Comparable vs Comparator interface



Let us see the basic interfaces and its methods:

public interface java.lang.Comparable{
    public abstract int compareTo(java.lang.Object);
}


public interface java.util.Comparator{
    public abstract int compare(java.lang.Object, java.lang.Object);
    public abstract boolean equals(java.lang.Object);
}


Let us observe the following code :

            Here i am trying to sort some group of stirng objects using Arrays.sort() method and collections.sort() method respectively it sorted and gave me the proper output ....but when i tried to sort group of employee objects i got the exception as :Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;


public class Test {

            public static void main(String[] args) {
                       
                        String names []={"Apple","Avacado","Apricot","Grapes","Gooseberries"};
                       
                        Arrays.sort(names);
                        System.out.println("Using Arrays.sort()");
                        for (String lString : names) {
                                    System.out.println("Fruit :"+lString);
                        }
                       
                        List fruits = new ArrayList();
                        for (String lString : names) {
                                    fruits.add(lString);
                        }
                       
                        Collections.sort(fruits);
                        System.out.println("Using Collections.sort()");
                        for (String lString : fruits) {
                                    System.out.println("Fruit :"+lString);
                        }
                       
                       
                        Employee emp[] = new Employee[5];
                       
                        emp[0] = new Employee("R001", "Robin", 45000);
                        emp[1] = new Employee("R012", "Antony", 55000);
                        emp[2] = new Employee("R011", "Williams", 75000);
                        emp[3] = new Employee("R121", "John", 65000);
                        emp[4] = new Employee("R061", "James", 35000);

                       
                        Arrays.sort(emp);
                       
                        for(Employee e:emp){
                                  
                                    System.out.println("Employee :id :"+e.getEmpId()+" \t Name :"+e.getEmpName()+"\t sal :"+e.getEmpSal());
                                   
                        }
            }
}


Output:

Using Arrays.sort()
Fruit :Apple
Fruit :Apricot
Fruit :Avacado
Fruit :Gooseberries
Fruit :Grapes

Using Collections.sort()
Fruit :Apple
Fruit :Apricot
Fruit :Avacado
Fruit :Gooseberries
Fruit :Grapes

Exception in thread "main" java.lang.ClassCastException: Employee cannot be cast to java.lang.Comparable
            at java.util.Arrays.mergeSort(Unknown Source)
            at java.util.Arrays.sort(Unknown Source)
            at Test.main(Test.java:40)


When trying to sort Employee objects the error because Arrays.sort()

See the method :

 public static void sort(java.lang.Object[]);

     All elements in the array must implement the Comparable interface.Then only it can do natural ordering of elements.
So i changed my Employee class as below :

import java.util.Comparator;

public class Employee implements Comparable {

      private String mEmpId;
      private String mEmpName;
      private double mEmpSal;

      public Employee(String pEmpId, String pEmpName, double pEmpSal) {
            super();
            mEmpId = pEmpId;
            mEmpName = pEmpName;
            mEmpSal = pEmpSal;
      }

      public String getEmpId() {
            return mEmpId;
      }

      public void setEmpId(String pEmpId) {
            mEmpId = pEmpId;
      }

      public String getEmpName() {
            return mEmpName;
      }

      public void setEmpName(String pEmpName) {
            mEmpName = pEmpName;
      }

      public double getEmpSal() {
            return mEmpSal;
      }

      public void setEmpSal(double pEmpSal) {
            mEmpSal = pEmpSal;
      }

      @Override
      public int compareTo(Employee empObj) {
            double empSal = empObj.getEmpSal();
            return empSal > mEmpSal ? 0 : 1;
      }
      /*
       * This is to compare based on empName
       */
      public static Comparator EmployeeNameComparator = new Comparator() {

            @Override
            public int compare(Employee e1, Employee e2) {
                return e1.getEmpName().compareTo(e2.getEmpName());
            }

      };
      /*
       * This is to compare based on employee id
       */
      public static Comparator EmployeeIdComparator = new Comparator() {

            @Override
            public int compare(Employee e1, Employee e2) {

                  return e1.getEmpId().compareTo(e2.getEmpId());
            }

      };
}



Here with this class you can observe i have implemented method
             public abstract int compareTo(java.lang.Object);

            This method will automatically have current object and then gets the next object to compare.
This method i have overriden to sort employee based on their salary.


Now coming to Comparator interface you can observe
             public abstract int compare(java.lang.Object, java.lang.Object);

            It takes two arguments obj1,obj2.

When ever you want to add any other sorting techniques for your custom objects you can use this.

Here in my class i have created two anonymous classes to sort employee objects based on their name and employeeId.

           

import java.util.Arrays;


public class EmpMain {
     
            public static void main(String[] args) {
            Employee emp[] = new Employee[5];
                 
            emp[0] = new Employee("R001", "Robin", 45000);
            emp[1] = new Employee("R012", "Antony", 55000);
            emp[2] = new Employee("R011", "Williams", 75000);
            emp[3] = new Employee("R121", "John", 65000);
            emp[4] = new Employee("R061", "James", 35000);

           Arrays.sort(emp);
           System.out.println("Without any comparator : ");
           for(Employee e:emp){
                    
             System.out.println("Employee :id :"+e.getEmpId()+" \t Name :"+e.getEmpName()+"\t sal :"+e.getEmpSal());
                       
                  }
                 
            Arrays.sort(emp,Employee.EmployeeIdComparator);
                 
            System.out.println("With empId comparator : ");
            for(Employee e:emp){
            System.out.println("Employee :id :"+e.getEmpId()+" \t Name :"+e.getEmpName()+"\t sal :"+e.getEmpSal());
                       
                  }
                 
            }
}

Without any comparator :
Employee :id :R061       Name :James      sal :35000.0
Employee :id :R001       Name :Robin      sal :45000.0
Employee :id :R012       Name :Antony     sal :55000.0
Employee :id :R121       Name :John sal :65000.0
Employee :id :R011       Name :Williams   sal :75000.0
With empId comparator :
Employee :id :R001       Name :Robin      sal :45000.0
Employee :id :R011       Name :Williams   sal :75000.0
Employee :id :R012       Name :Antony     sal :55000.0
Employee :id :R061       Name :James      sal :35000.0
Employee :id :R121       Name :John sal :65000.0

This also u can use :


List empList = new ArrayList();
                  empList.add(emp[0]);
                  empList.add(emp[1]);
                  empList.add(emp[2]);
                  empList.add(emp[3]);
                  empList.add(emp[4]);
                 
                 
                  Collections.sort(empList);
                 
                  for (Employee lEmployee : empList) {
                        System.out.println("Employee :id                              :"+lEmployee.getEmpId()+" \t Name :"+lEmployee.getEmpName()+"\t sal :"+lEmployee.getEmpSal());
                  }
           

Collections.sort(empList,Employee.EmployeeNameComparator);
                 
                  for (Employee lEmployee : empList) {
                        System.out.println("Employee :id :"+lEmployee.getEmpId()+" \t Name :"+lEmployee.getEmpName()+"\t sal :"+lEmployee.getEmpSal());
                  }
                       
Conclusion :

Use Comparable for natural sort ordering and use Comparator for any custom sorting .....


Always Arrays.sort() and Collections.sort() can sort only objects of type comparable.

Tuesday, June 22, 2010

Eclipse key board shortcuts -Techies

Eclipse key board shortcuts :


Ctrl+space. Autocomplete.
This will recommend a list of classes they will fit what you have typed so far. If there is only one match, it will just print it out for you. After it does print it out for you, it will include the import for you. If something is ever missing the import at the top, I will just go to the Class declaration and just hit Ctrl+space.

Ctrl+Shift+O : Import packages:
This is very much required when we have to import packages for classes. (Organizing)

Ctrl+Shift+R. Open resource.
I cannot live without this shortcut. It is such a time saver. Whenever you are trying to find a specific class, just start typing it and it will populate which classes match that criteria. Once you found it, select it and there you go! It also works great if you are new to a framework and need to find certain classes or if you partly recall the class name but not 100% sure.

Ctrl+O. Show inherited members.
This is another one that works great when you are working with classes with a massive lump of methods attached to it. You COULD do this within the Package Explorer, but no one likes touching that mouse! You can even type to filter down your methods. If you have methods with the same name and just different parameters, this also works great. Just type in part of the method name and get a few overview and access to each of the methods.

Ctrl+H. Loads search box.
I cant tell you how often this saves me. This isnt just a ‘find’ box, this does a ‘find in files’ within the File Search tab. Within here, you can specify what you are looking for in the files, what you file types you want to search in, etc. There are other types of search you can use, but I have not run into a case where I need them. Have you?

Ctrl+Shift+C. Comments a block of code.
This is perfect for debugging. It is strange because really when you think about it, you are only talking about having something put a /* at the begging of what you selected and a */ at the end of what you selected. However, I use this a lot more often than you would expect.

Ctrl+D. Delete a line.
Self explanatory. Extremely useful. If I didn’t have that, I’d have to waste time with Shift+End, Delete!.

Ctrl+E. Menu for opened files.
This will bring up a list of opened files that you have. Not only that, it will also allow you to type in your class names to narrow down your choices.

Ctrl+Shift+E : Window for Opened files:
This key is used to view all the files opened in the editor , where it will be easy to identify & open the files .

Ctrl+1:
Is used for renaming variables at a time through out the file. Will be useful when we want to rename the variable name where the variable being used at many places.

F4. Shows class hierarchy.
This is extremely useful when you are new to a with a massive framework and you really want to get a sense of how things are all connect, who extends what, etc.

F3 and Ctrl+Left Mouse Click. Shows declaration.
I enjoy using this when I am working with larger files or anything with long methods (which always irks me). It can get extremely annoying to see where some variables are declared. All you have to do is high light the variable then hit F3. Sometimes I will hold control and hover over variable names if I am having a problem.

F5, F6, F7, F8. In debug mode.
There three shortcuts are probably used more than anything. I wanted to group them all into one section.

F5 – Step Into. When you are debugging an application and you come across a function call, F5 will step into that function and proceed from there.

F6 – Step. This allow you to debug line by line. However, this will not step into any functions.

F7 – Step out. If you are debugging in a function and you want to step out of it to where the function was called, this is what is used.

F8 – Skip to next breakpoint. If there arent any other break points to high, you will be just running the application until your application hits another breakpoint, taking you back into debug mode.

Alt+leftarrow or Alt+rightarrow. Jump back to a line, Jump forward to a line.
According to eclipse, this is “Next word, Previous word’. I am not sure what that means. All I know if I am stepping into functions, debugging through multiple files and breakpoints, this is a life saver. It allows me to retrace my steps, step by step. If I go back with Alt+leftarrow, I can go right back to where I was with Alt+rightarray.

Ctrl+Shift+L. Displays all shortcuts.
Self explanitory. Dig in and find your favorite!This last one is not about using a shortcut. It is about what you have to do to turn it of.

Ctrl+W or Ctrl+F4: close the single file.
This is used to close the current file that is opened in the editor.

Ctrl+Shift+W or Ctrl+Shift+F4 : Close all the files:
When many files we have opened this is very much useful to close all the files opened in the editor in a single shot.

Alt + left key : Navigation
This is used to navigate from one page to another page in the left direction .

Alt+right key : the same as above for right navigation.

Ctrl+Shift+/ : comment
This is used to add the block level comment in a page.

Ctrl+Shift+\ : remove comment

Ctrl+Shift+F : Formatting contents

Save your time using keyboard.......
 
Rocking,
Shyamala

Saturday, June 19, 2010

ECLIPSE DEBUGGING TUTORIAL

Debugging Using eclipse :

Let us consider one simple Java project :

Where i have created in the following manner.












Presently it is in java perspective.......

we can change the perspective into debugging by clicking WINDOW-->Open perspective ---> and go

to other and select “Debug”.

Then :











We can add the break point lines by double clicking on the line in source code...

  • You can observe clearly there are areas EXECUTION STACK,WATCH VARIABLES AND EXPRESSION AREA,SOURCE CODE Area,and as well CONSOLE SCREEN.

Observe the following screen shot to add watch expression as well as execution environment













  •   By using F11 key we can start debugging any Java application.
               Here in this case i have added two watch expression one is “i” value and another is “str1” value.

  •   By using F6 key we can do step by step execution of a program.

  • By using F8 key we can skip the current break point it will be jumping into the next break point start.

 Observe the next screen shot which shows the values of “i” & str1













Thats it ..............

This is simple debugging of Java application.

JUST SCROLL DOWN........













This is how it will be after termination of Program...which stops with THREAD....

Very much required as a developer to know how to use Eclipse debugging ......as in the real world applications development no body will prefer using System.out.println();......


So be the best by learning & practicing this .....

Keep Rocking
Shyamala

Tuesday, April 13, 2010

Displaying IP Address of the system using Runtime

Runtime is a class which is specifically made for the purpose to run any kind of process using "exec" method

import java.io.*;
class DisplayIP{
public static void main(String args[]){

Runtime runtime = Runtime.getRuntime();
try{
Process process = runtime.exec("cmd.exe /c ipconfig");
InputStream in = process.getInputStream();
int ch = in.read();
while(ch!=-1){
System.out.print((char)ch);
ch=in.read();
}
in.close();
}
catch(IOException e){
System.out.println(e);
}
}
}

Still any doubt !!! check out by clicking the link
http://www.java-tips.org/java-se-tips/java.util/from-runtime.exec-to-processbuilder.html
Cheers
Shyamala

Deep Copy vs Shallow Copy in C++

Usually in c++ we will be more confused about these constructors about deep copying & shallow copying.....

Here is a simple example where there is a class called String where we have to strings which is used to store firstname ,lastname and the age of the person.

Where in case of this I am creating the Object of String with the name s1 which after reading the details I am assigning it to one more Object s2.



#include<iostream.h>
#include<string.h>
#include<conio.h>

class String
{
char *firstname; // declaring pointer to store string
char *lastname;
int age;

public:
String()
{
firstname = new char[30];
lastname = new char[30];
age=0;
}
void read()
{
cout<<"\n Enter name:";
cin>>firstname>>lastname;
cout<<"\n age :";
cin>>age;
}
void print()
{
cout<<"\n name is "<<firstname<<" "<<lastname;
cout<<"\n Age :"<<age;
}
~String()
{
delete[]firstname;
delete[]lastname;
}
};

void main()
{
clrscr();

String s1;
s1.read();
s1.print();

String s2=s1; //assigning the object s1 to s2
s2.print();

s1.read();

s1.print();
s2.print();

getch();
}

U can observe after u make any changes to the s1 object with the Strings that is firstname,lastname it will be reflected in s2 object also.

So by default there is one copy constructor given for you in your c++ classes which will be of this prototype which just assigns the values using "=" operator.

Prototype of Copy constructor:
ClassName(ClassName &Object){
}
This is "SHALLOW COPYING"
For the above class :
String(String &s){
firstname=s.firstname;
lastname=s.lastname;
age = s.age;
}

To over come this problem where it should be allocated with the own memory allocations just keep this below code and observe which is called "DEEP COPYING"

String(String &s)
{
cout<<"\n copying......";
int l1= strlen(s.firstname)+1;
int l2= strlen(s.lastname)+1;
firstname = new char[l1];
lastname = new char[l2];
strcpy(firstname,s.firstname);
strcpy(lastname,s.lastname);
age=s.age;
}


SHALLOW COPYING IS DEFAULT DONE .......WHICH OVERLOADS "=" operators.

DEEP COPYING YOU SHOULD WRITE ON YOUR OWN!!

Cheers
Shyamala

Saturday, April 10, 2010

SCJP Questions

Question 1 :
class Demo{
public static void main(String args){
System.out.println("welcome to java");
}
}

What will be the output of the program:
a) Error at compile time b) Error at Runtime
c) prints welcome to java d) No Error and no output

===============================================================
Question 2:
Which of the following are legal statements in Java?
a) float f=1/3; b) float f=1.01;
c) int i=1/3; d) double d=999d;

===============================================================
Question 3:
What will happen when you compile and run the following code?
public class MyClass{
static int i;
public static void main(String argv[]){
System.out.println(i);
}
}
a) Error Variable i may not have been initialized c) 1
b) null d) 0

===============================================================
Question 4:
class Demo{
static void print(){
System.out.println("Hello");
}
public static void main(String args){
Demo d =null;
d.print();
}
}

a) Error at compile time b) Error at Runtime
c) prints Hello d) No Error and no output

===============================================================Question 5:
Which of the following statements are true?
a) A byte can represent between -128 to 127
b) A byte can represent between -256 to 256
c) A byte can represent between -127 to 128
d) A char can represent between -2x2 pow 16 2 x2 pow 16 - 1

===============================================================Question 6:
Which of the following statements are true?
a) Constructors cannot have a visibility modifier
b) Constructors can only have a primitive return type
c) Constructors can be marked public and protected, but not private
d) Constructors are not inherited

===============================================================Question 7:
What will happen when you attempt to compile and run the following class?
class Base{
Base(int i){
System.out.println("Base");
}
}
class Severn extends Base{
public static void main(String argv[]){
Severn s = new Severn();
}
void Severn(){
System.out.println("Severn");
}
}
a) Compilation and output of the string "Severn" at runtime
b) Compilation and no output at runtime
c) Compile time error
d) Compilation and output of the string "Base"

===============================================================Question 8:
Given the following code
class Base {}

class Agg extends Base{
public String getFields(){
String name = "Agg";
return name;
}
}
public class Avf{
public static void main(String argv[]){
Base a = new Agg();
//Here
}
}
What code placed after the comment //Here will result in calling the getFields method resulting in the output of the string "Agg"?
a) System.out.println(a.getFields());
b) System.out.println((Base) a.getFields());
c) System.out.println(a.name);
d) System.out.println( ((Agg) a).getFields());

===============================================================Question 9:
What will happen when you attempt to compile and run the following code?
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}
a) Compile time error b) Output of 1
c) Output of 2 d) Output of 0

===============================================================Question 10:
Given the following class
public class Ombersley{
public static void main(String argv[]){
boolean b1 = true;
if((b1 ==true) || place(true)){
System.out.println("Hello Crowle");
}
}

public static boolean place(boolean location){
if(location==true){
System.out.println("Borcetshire");
}
System.out.println("Powick");
return true;
}
}
What will happen when you attempt to compile and run it?
a) Compile time error
b) Output of Borcetshire and Powick followed by "Hello Crowle"
c) Output of "Hello Crowle"
d) No output
===============================================================Question 11:
What will happen when you attempt to compile and run the following code?
public class Sandys{
private int court;
public static void main(String argv[]){
Sandys s = new Sandys(99);
System.out.println(s.court);
}
Sandys(int ballcount){
court=ballcount;
}
}
a) Compile time error, the variable court is defined as private
b) Compile time error, s is not initialized when the System.out method is called
c) Compilation and execution with no output
d) Compilation and run with an output of 99
===============================================================
Question 12:
Given the following code
class Base{
static int oak=99;
}
public class Doverdale extends Base{
public static void main(String argv[]){
Doverdale d = new Doverdale();
d.amethod();
}
public void amethod(){
//Here
}
}
Which of the following if placed after the comment //Here, will compile and modify the value of the variable oak?
a) super.oak=1; b) Base.oak=22;
c) oak=33; d) oak=50.1;
===============================================================Question 13:
Which of the following statements are true?
a) A method cannot be overloaded to be less public in a child class
b) To be overridden a method only needs the same name and parameter types
c) To be overridden a method must have the same name, parameter and return types
d) An overridden method must have the same name, parameter names and parameter types
===============================================================Question 14:
You want to loop through an array and stop when you come to the last element. Being a good java programmer and forgetting everything you ever knew about C/C++ you know that arrays contain information about their size. Which of the following can you use?

a)myarray.length();
b)myarray.length;
c)myarray.size
d)myarray.size();
===============================================================Question 15:
What will happen when you attempt to compile and run this program
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main
private class Inner{
String name =new String("Inner");
void showName(){
System.out.println(name);
}
}//End of Inner class
}
a) Compile and run with output of "Outer"
b) Compile and run with output of "Inner"
c) Compile time error because Inner is declared as private
d) Compile time error because of the line creating the instance of Inner
===============================================================Question 16:
Given the following class definition, which of the following methods could be legally placed after the comment //Here

public class Rid{
public void amethod(int i, String s){}
//Here
}
a)public void amethod(String s, int i){}
b)public int amethod(int i, String s){}
c)public void amethod(int i, String mystring){}
d) public void Amethod(int i, String s) {}
===============================================================Question 17:
public class Test7{
public Test7(){}
public Test7(Test7 ref){
this (ref,"Hai");
}
public Test7(Test7 ref,String str){
ref.Test7(str);
System.out.println("Hi");
}
public void Test7(String str){
System.out.println(str);
}
public static void main(String[] args){
Test7 t = new Test7();
Test7 t7 = new Test7(t);
}
}
a) HI b) hai
c) Hai Hi d) Hi Hai
===============================================================Question 18:
What will be the output of the following program?

class Sup1{
public Sup1(){
System.out.println("Hai");
}
private Sup1(String str){
System.out.println(str);
}
}

public class Test5 extends Sup1{
private Test5(String str){
System.out.println(str);
super();
}
public static void main(String[] args) {
Test5 t5 = new Test5("HI");
}
}

a) Hai,Hi,Hi b) Hai,Hi
c) Hi,Hi d) Compiler Error
===============================================================Question 19:
class VarArgOne {
public static void printArgs(String s, int ... i, String s) { //line1
for(int j : i) { //line 2
System.out.print(j + " " + s); //line 3
}
}
public static void main(String ... args) { //line 4
printArgs("exam", 12, 34, "scjp"); //line 5
}
}
a) Compilation fails due to error at line 1.
b) Compilation fails due to error at line 2.
c) Compilation fails due to error at line 4.
d) Compilation fails due to error at both line 1 and line 4.
e) Compiles fine and Prints output "12 scjp 34 scjp".
===============================================================Question 20:
class A{
private void print(){
System.out.println("===print in A===");
}
}
class B extends A{
void print(){
System.out.println("===print in B===");
}
}
class M{
public static void main(String args[]){
A ref = new B();
ref.print();
}
}
What happens when we try to compile the above program:
a)Error at compile time b)Error at run time
c)prints print in A d) prints print in B
===============================================================Question 21 :
interface I{
void print();
}
class A{
static void print(){
System.out.println("===print in A===");
}
}
class B extends A implements I{
public void print(){
System.out.println("===print in A===");
}
}
class M{
public static void main(String args[]){
A ref = new B();
ref.print();
}
}
What will be the output & Write explanation?
===============================================================Question 22:
What all gets printed when the following code is compiled and run? Select the three correct answers.
public class xyz {
public static void main(String args[]) {
for(int i = 0; i < 2; i++) {
for(int j = 2; j>= 0; j--) {
if(i == j) break;
System.out.println("i=" + i + " j="+j);
}
}
}
}
===============================================================Question 23:
What is the result of compiling and running the following program. Select the one correct answer.
class test {
public static void main(String args[]) {
int[] arr = {1,2,3,4};
call_array(arr[0], arr);
System.out.println(arr[0] + "," + arr[1]);
}
static void call_array(int i, int arr[]) {
arr[i] = 6;
i = 5;
}
}
a. 1,2 b. 5,2
c. 1,6 d. 5,6
===============================================================Question 24:
Assume that class A extends class B, which extends class C. Also all the three classes implement the method test(). How can a method in a class A invoke the test() method defined in class C (without creating a new instance of class C). Select the one correct answer.
a. test();
b. super.test();
c. super.super.test();
d. ::test();
e. C.test();
f. It is not possible to invoke test() method defined in C from a method in A.
===============================================================Question 25:
Which of the following are legal array declarations. Select the three correct answers.
a. int i[5][]; b. int i[][];
c. int []i[]; d. int i[5][5];
e. int[][] a;
===============================================================
ALL THE BEST