In java, if a variable should hold a value from predefined set of constants , we can use enum for define those constants set.We must always use enums when a variable can only take one out of a small set of possible values. Enum was introduced by Java version five. Let's say we want to define a variable as month. We know that there are only twelve constant values which month variable can have. So, we can define an enum for this situation as shown in the below code segment.
This is the output of above programme :
Previous month was FEBRUARY
This month is MARCH
Next month is APRIL
JANUARY
FEBRUARY
MARCH
APRIL
MAY
JUNE
JULY
AUGUST
SEPTEMBER
OCTOMBER
NOVEMBER
DECEMBER
Enum class provide a static method as values() which returns all the emum values into an array and we can iterate through that array by using for each loop.
Further we can define enums with parameter values. To crate a this type of enum, we have to create an enum class as shown in below code segment.
This is the output of above programme :
COLOMBO university is situated in colombo with 8 faculties
RUHUNA university is situated in matara with 5 faculties
JAFFNA university is situated in jaffna with 9 faculties
UWA university is situated in badhulla with 5 faculties
Advantages Of Using Enums :
1.Enum is type-safe so we can't assign anything else other than predefined Enum constants to an Enum variable.
2.Enum can be used as an argument on switch statment like int,char or string.
Saturday, March 28, 2015
Wednesday, March 25, 2015
LinkedHashMap Vs TreeMap
Through this blog post I am going to discuss about the LinkedHashMap and TreeMap.
First consider about the LinkedHashMap. It extends the HashMap. This is the Hash table and linked list implementation of the Map interface. One difference between HashTable and LinkedHashMap is this stores data using doubly linked lists.LinkedHashMap stores data as key and value pairs.And another important thing about LinkedHashMap is it maintains the insertion order.Further it cannot have duplicate keys.But it can have any number of duplicate values.If we insert duplicate keys into a LinkedHashMap it will overwrite previous value with the same key. By referring below code segment we can get an idea about how LInkedHashMap works.
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapEx {
public static void main(String[] args) {
LinkedHashMap myMap= new LinkedHashMap();
myMap.put(1,"hasitha");
myMap.put(2, "kasun");
myMap.put(3, "amal");
myMap.put(4, "hasitha");
myMap.put(5, "sumudu");
for (Map.Entry entry : myMap.entrySet()) {
System.out.println(entry.getValue());
}
}
}
Now consider about the TreeMap. This is another one implementation of Map interface. One of the most important point about TreeMap is, it maintains the natural order of keys.Further even though HashMap and LinkedHashMap can contains null keys , TreeMap cannot contain null keys.Anyhow TreeMap can contains duplicate values as HashMap and LinkedHash map. Now the tome to move for a coding example and see how TreeMap works.
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
TreeMap treeMap= new TreeMap();
treeMap.put("name", "hasitha");
treeMap.put("village", "matara");
treeMap.put("school;", "mcc");
treeMap.put("university", "ucsc");
treeMap.put("job","ASE" );
treeMap.put("sex", "male");
for(Map.Entry entry : treeMap.entrySet()) {
System.out.println(entry.getValue());
}
}
Output of above code as below.
ASE
hasitha
mcc
male
ucsc
matara
So we can see that values have been sorted according to the ascending order of the keys.
Tuesday, March 24, 2015
LinkedList VS ArrayList VS LInkedHashSet
Through this post I am going to discuss about the differences among LinkedList , ArrayList and LinkedHashSet and there behaviors.
LinkedList class extends from AbstractSequentialList class and implements the List interface and Deque interface. When talk about storing the data, LinkedList uses doubly linked lists to store data. As well as it maintains the insertion order. Further LinkedLists can hold duplicate elements. Below code segment illustrates the behavior of LinkedList class.
Now move to discuss about LinkedHashSet. As its name says this is a one of the set implementation. It extends HashSet class. This uses List elements for storing data.Another main important point about linkedhashset is it doesn't hold duplicate values since this is a set implementation.And also this maintains the insertion order. Now consider about a coding example of LinkedHashSet.
LinkedList class extends from AbstractSequentialList class and implements the List interface and Deque interface. When talk about storing the data, LinkedList uses doubly linked lists to store data. As well as it maintains the insertion order. Further LinkedLists can hold duplicate elements. Below code segment illustrates the behavior of LinkedList class.
public class LinkedListEx {
public static void main(String[] args) {
LinkedList<String> list= new LinkedList<String>();
list.add("hasitha");
list.add("kamal");
list.add("saman");
list.add("amala");
list.add("hasitha");
for (String string : list) {
System.out.println(string);
}
}
}
Now consider about ArrayList. It extends the AbstractList class and implements the List Interface. ArrayList has a initial size and after it exceeds the initial size, arraylist can dynamically increases its size.One main difference between arraylist and linkedlist is while arraylist uses arrays to store the data linkedlist uses nodes to store data.Most of the other behaviors are same in arraylists and linkedlist. Below code segment illustrates how arraylist works.
public class ArrayListEx {
public static void main(String[] args) {
ArrayList<String> cities= new ArrayList<String>();
cities.add("matara");
cities.add("colombo");
cities.add("galle");
cities.add("tangalle");
cities.add("anuradhapura");
for (String string : cities) {
System.out.println(string);
}
}
}
Now move to discuss about LinkedHashSet. As its name says this is a one of the set implementation. It extends HashSet class. This uses List elements for storing data.Another main important point about linkedhashset is it doesn't hold duplicate values since this is a set implementation.And also this maintains the insertion order. Now consider about a coding example of LinkedHashSet.
public class LinkedHashSetEx {
public static void main(String[] args) {
LinkedHashSet<String> countries= new LinkedHashSet<String>();
countries.add("Sri lanka");
countries.add("India");
countries.add("Korea");
countries.add("Canada");
countries.add("maldives");
for (String string : countries) {
System.out.println(string);
}
}
}
Sunday, March 22, 2015
How to handle Exceptions when doing method overriding
There are several possible scenarios when talk about this topic. Let's look at them one by one
1 . When the super class method does not declare exceptions.
Three possible scenarios comes under this.
(i) . Child class overriding method may not declare any exception.
(ii). Child class overriding method should not declare any checked exception.Below example illustrates this situation.
Here I get a compile time error since I have declared a checked exception.
(iii).Child class overriding method can declare any unchecked exception.Below example illustrates this situation.
1 . When the super class method does not declare exceptions.
Three possible scenarios comes under this.
(i) . Child class overriding method may not declare any exception.
(ii). Child class overriding method should not declare any checked exception.Below example illustrates this situation.
public class SuperClass1 {
public void printName(){
System.out.println("..");
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ChildClass1 extends SuperClass1 {
@Override
public void printName() throws FileNotFoundException {
File f= new File("C:\\Users\\Hasitha\\Desktop\\syn");
}
}
Here I get a compile time error since I have declared a checked exception.
(iii).Child class overriding method can declare any unchecked exception.Below example illustrates this situation.
public class SuperClass2 {
public int devision(){
int num=10;
int ans = 0;
for (int i = 5; i >=1 ; i--) {
ans=num/i;
}
return ans;
}
}
public class ChildClass2 extends SuperClass2 {
@Override
public int devision() throws ArithmeticException {
int num=10;
int ans = 0;
for (int i = 5; i >=0 ; i--) {
ans=num/i;
}
return ans;
}
public static void main(String[] args) {
ChildClass2 c= new ChildClass2();
c.devision();
}
}
Here I have declared an unchecked exception with child class overriding method.
2.When super class method declare exceptions.(Checked or Unchecked Exceptions)
There are three possible scenarios comes under here also.
(i). Sub class overriding method may not declare any exception.
Below example illustrates this situation.
public class SuperClass3 {
public void testArray() throws ArrayIndexOutOfBoundsException{
int num[]={1,2,3,4,5};
for (int i=0;i<8;i++) {
System.out.println(num[i]);
}
}
}
public class ChildClass3 extends SuperClass3 {
@Override
public void testArray() {
int num[]={1,2,3,4,5};
for (int i=0;i<8;i++) {
System.out.println(num[i]);
}
}
}
Here I have declared a checked exception in the super class . But when overriding the super class method I have not declare that exception.
(ii). Sub class overriding method may declare the same exception.
Below example illustrates this situation.
public class SuperClass3 {
public void testArray() throws ArrayIndexOutOfBoundsException{
int num[]={1,2,3,4,5};
for (int i=0;i<8;i++) {
System.out.println(num[i]);
}
}
}
public class ChildClass3 extends SuperClass3 {
@Override
public void testArray() throws ArrayIndexOutOfBoundsException {
int num[]={1,2,3,4,5};
for (int i=0;i<8;i++) {
System.out.println(num[i]);
}
}
}
(iii).Sub class overriding method may declare a more specific exception when compared with the super class exception. As an example if super class have declared an IOException child class can declare a FileNotFoundException instead of IOException. But keep in mind that child class overriding method cannot declare more general exception when compare with the super class method.
Below Example illustrates how child class overriding method can declare a more specific exception.
import java.io.File;
import java.io.IOException;
public class SuperClass4 {
public void handleMyFile() throws IOException{
File f= new File("C:\\Users\\Hasitha\\Desktop\\syn");
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ChildClass4 extends SuperClass4 {
public void handleMyFile() throws FileNotFoundException{
File f= new File("C:\\Users\\Hasitha\\Desktop\\syn");
}
}
Saturday, March 21, 2015
How to change the return type when doing method overriding
From the version of Java 5 , we can change the return type of a method when overriding that method.
This concept is called as covariant return type in java. With this concept we can not change the primitive return types. We can only change the object return types.
This is how covariant return type works. If we override a super class method and if it returns an object , then we can change the return type of that method to, one of its sub classes return type.
Let's look for an example.
public class Super {
//This method returns an object of class Super;
Super get(){
return this;
}
}
In the above code segment I have created a class called super.It has a method called get which returns an object of type Super.
public class Child extends Super {
@Override
Child2 get() {
return new Child2();
}
}
In the above code segment ,I have overridden the get() method of Super class. When overridden I have changed the return type of this method to Child2 . Since Child2 is a sub class of Super class I can do so. Further If I want I can change the return type of this method as "Child" since it is also a sub class of Super.
public class Child2 extends Super {
@Override
Child2 get() {
return this;
}
}
Finally I have created another sub class from super class and overriden the get method as return an object from that class itself.
Tuesday, March 17, 2015
HOw To Use Variable Arguments In JAVA
In this post I am going to talk about varags in JAVA. Varargs is the short term for variable argument. Vararg allows a method to have zero or multiple number of parameters.Sometimes when we create methods we have no idea how many parameters should have to that method. As an example we want to create a method which calculate the total of few numbers , and the number of parameters to this method is differed from time to time. To solve this problem java gives us a concept called varargs.
Syntax for write a vararg is as this.
return_type method_name(data_type...variableName){}
Below code segment describes how can we use varargs.
Output of the above program is given below.
total =0
total =15
total =30
total =50
When using varargs we have to follow several rules.
1. There can only be one varargs in a method.
2. If there are few arguments in the method vararg should come as the final argument of that method.
Syntax for write a vararg is as this.
return_type method_name(data_type...variableName){}
Below code segment describes how can we use varargs.
public class Test {
//Here method parameter is a vararg.
public static int total(int...num) {
int sum=0;
for(int a:num){
sum=sum+a;
}
return sum;
}
public static void main(String[] args) {
System.out.println("total ="+total());
System.out.println("total ="+total(5,10));
System.out.println("total ="+total(5,10,15));
System.out.println("total ="+total(5,10,15, 20));
}
}
Output of the above program is given below.
total =0
total =15
total =30
total =50
When using varargs we have to follow several rules.
1. There can only be one varargs in a method.
2. If there are few arguments in the method vararg should come as the final argument of that method.
Monday, March 16, 2015
Why String Is Immutable
From this blog post I am going to talk about why String is immutable. Simply immutable means we cannot change the value of an object after it is created.
Before talk about immutable, first look at what happen in the computer memory when we create a string variable.
Here reference variable called "a" is created inside the stack memory and object with the value of "matara" is created inside heap memory of the computer. Actually this object is created inside the memory area called String pool.
Now let's say I will create another String named "b" with the same value as above
Here what happen is reference variable called "b" is created inside the stack memory and this reference variable will also point to the same object which String "a" is pointing to.The most important point here is no other object is created inside the String pool with the value of "matara".The reason for not to creating another object is , each time when creating a new String literal , JVM checks whether that String value is already in the String pool.If so, without creating new String object , pointing to the same String object.
Now move to the our topic.
Here both "a" and "b" reference variables are pointing to same object. Suppose I change the value of the String "a" as "colombo".
If String was mutable now what happen is "matara" will be changed as "colombo" . Then value of the String "b" also become to "colombo" since both "a" and "b" were pointing to the same object. But actually what should happen is value of the variable "b" should still be as "matara" since we didn't change its value. To achieve this purpose String objects are created as immutable.
Now, sometimes you may have a confusion, can't we change the value of the variable "a" .Actually we can . You no need to bother about anything. Java will internally solve this problem . Actually what happen when you change the value of the variable "a" as "colombo" is, separate object with the value of "colombo" is created inside the heap memory and variable "a" will be pointed to that object from that onwards . And still reference variable "a" is pointing to the object of the value with "matara".
By referring the below code segment you will be able to get more clear idea what I have discussed so far.
Before talk about immutable, first look at what happen in the computer memory when we create a string variable.
String a="matara";
Here reference variable called "a" is created inside the stack memory and object with the value of "matara" is created inside heap memory of the computer. Actually this object is created inside the memory area called String pool.
Now let's say I will create another String named "b" with the same value as above
String b = "matara";
Here what happen is reference variable called "b" is created inside the stack memory and this reference variable will also point to the same object which String "a" is pointing to.The most important point here is no other object is created inside the String pool with the value of "matara".The reason for not to creating another object is , each time when creating a new String literal , JVM checks whether that String value is already in the String pool.If so, without creating new String object , pointing to the same String object.
Now move to the our topic.
Here both "a" and "b" reference variables are pointing to same object. Suppose I change the value of the String "a" as "colombo".
a="colombo";
If String was mutable now what happen is "matara" will be changed as "colombo" . Then value of the String "b" also become to "colombo" since both "a" and "b" were pointing to the same object. But actually what should happen is value of the variable "b" should still be as "matara" since we didn't change its value. To achieve this purpose String objects are created as immutable.
Now, sometimes you may have a confusion, can't we change the value of the variable "a" .Actually we can . You no need to bother about anything. Java will internally solve this problem . Actually what happen when you change the value of the variable "a" as "colombo" is, separate object with the value of "colombo" is created inside the heap memory and variable "a" will be pointed to that object from that onwards . And still reference variable "a" is pointing to the object of the value with "matara".
By referring the below code segment you will be able to get more clear idea what I have discussed so far.
public class ImmutableTest {
public static void main(String[] args) {
String a= "matara";
String b= "matara";
System.out.println("Before changing the value....");
System.out.println("value of a = "+a);
System.out.println("value of b = "+b);
System.out.println();
a="colombo";
System.out.println("After changing the value....");
System.out.println("value of a = "+a);
System.out.println("value of b = "+b);
}
}
Introduction
This is my personal blog about java and related technologies. Specially from this blog site,I am not going to teach Java from very beginning. Instead of , I hope to discuss about important topics which are related to java technology. Hang on with me.
Subscribe to:
Comments (Atom)