Search This Blog

Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, December 28, 2012

Java Hashtable Example

import java.util.*;
public class MainClass {
  public static void main(String args[]) {
    Hashtable columnValues = new Hashtable();
    columnValues.put("Tokyo", "Japan");
    columnValues.put("Beijing", "China");
    columnValues.put("Bangkok", "Thailand");
    String city = "Beijing";
    String country = (String) columnValues.get(city);
    if (country != null)
      System.out.println(city + " is located in " + country);  //Beijing is located in China
    else
      System.out.println(city + " is not located in the hashtable");
  }
}

Tuesday, December 25, 2012

"this" keyword java examples - with and without "this"


Understanding the problem without "this" keyword

class Student{
    int id;
    String name;

    Student(int id, String name){
        id = id;
        name = name;
    }

    void display(){
        System.out.println(id+" "+name);
    }

    public static void main(String args[]){
        Student s1 = new Student(101, "Jahn");
        Student s2 = new Student(102, "Robin");
        s1.display(); //0 null
        s2.display(); //0 null
    }
}
Solution of the above problem using "this" keyword

class Student{
    int id;
    String name;

    Student(int id, String name){
        this.id = id;                    //try with "this" keyword
        this.name = name;                //try with "this" keyword
    }

    void display(){
        System.out.println(id+" "+name);
    }

    public static void main(String args[]){
        Student s1 = new Student(101, "Jahn");
        Student s2 = new Student(102, "Robin");
        s1.display();         s2.display();    }
}

Source: http://www.javatpoint.com/this-keyword
Check this link. It has all 6 types of examples using "this" keyword