What is meant by Serialization? , Why we need Serialization ? , How to do serialization ? These are the questions come to our mind when we talk about serialization. From this post I am going to answer for above questions one by one.
Serialization is the process of converting an object to a byte stream. Deserialization is the process of reconstructing an object that has been serialized before.
Let's look at why we need to do serialization. Java objects are created on the memory area called a Heap.This is a temporary memory location. Which means when we terminate our application heap memory is cleaned. So all the objects which were on the heap memory are lost. So, if we need to save those objects for future use Serialization is the way to go. And also when we want to transfer objects through a network we can use serialization.
Below code segment demonstrate how to do serialization in java. Here I have created two java classes .First one is Participant class. It is the one I am going to serialize. My second class is called TestSerialization . In that class I have serialized an Arraylist of Participant objects into a file.
Now let's look at how to do deserialization. For testing deserialization I am going to create a new class called TestDeserialization. Here what I am going to do is deserialize participant objects in the "participantlist.ser" file.
Above class will print below result in the console as the output.
[firstName = hasitha lastName = thamaranga Age = 25, firstName = sansala lastName = dilshan Age = 22, firstName = kasun lastName = amarasena Age = 26, firstName = akila lastName = sathsara Age = 28, firstName = gayan lastName = kumara Age = 30]
IMPORTANT JAVA STUFFS
Saturday, November 28, 2015
Saturday, March 28, 2015
Enum IN JAVA
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.
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.
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.
Subscribe to:
Comments (Atom)