Monday, 29 September 2014

Serialization

Serialization
Def : Serialization in java is a mechanism of writing the state of an object into a byte stream.
Used In  : It is mainly used in Hibernate, RMI, JPA, EJB, JMS technologies.

 DeSerialization
Def  : The reverse operation of serialization is called deserialization.

The String class and all the wrapper classes implements java.io.Serializable interface by default.

Advantage of Java Serialization

It is mainly used to travel object's state on the network (known as marshaling).
Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability.

ObjectOutputStream class 

An ObjectOutputStream is used to write primitive data types and Java objects to an OutputStream.Only objects that support the java.io.Serializable interface can be written to streams. 

Constructor

1) public ObjectOutputStream(OutputStream out) throws IOException {}:-creates an ObjectOutputStream that writes to the specified OutputStream.

Important Methods

1) public final void writeObject(Object obj) throws IOException {} :-writes the specified object to the ObjectOutputStream.
2) public void flush() throws IOException {}:-flushes the current output stream.
3) public void close() throws IOException {} :-closes the current output stream.

ObjectInputStream class

An ObjectInputStream deserializes objects and primitive data written using an ObjectOutputStream.

Constructor

1) public ObjectInputStream(InputStream in) throws IOException {} :-creates an ObjectInputStream that reads from the specified InputStream.

Important Methods

1) public final Object readObject() throws IOException, ClassNotFoundException{} :-reads an object from the input stream.
2) public void close() throws IOException {}:-closes ObjectInputStream.

 Example of Java Serialization
import java.io.Serializable;
public class Employee implements Serializable {
  public String name;

  public void mailCheck() {
    System.out.println("Mailing a check to " + name + " " + name);
  }
}


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeDemo {
  public static void main(String[] args) {
    Employee e = new Employee();
    e.name = "Reyan Ali";
    try {
      FileOutputStream fileOut = new FileOutputStream("employee.txt");
      ObjectOutputStream out = new ObjectOutputStream(fileOut);
      out.writeObject(e);
      out.close();
      fileOut.close();
      System.out.printf("Serialized data is saved in employee.txt");
    }
    catch (IOException i) {
      i.printStackTrace();
    }
  }
}
 O/P : Serialized data is saved in employee.txt

Example of Java Deserialization

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeDemo {
  public static void main(String[] args) {
    Employee e = null;
    try {
      FileInputStream fileIn = new FileInputStream("employee.txt");
      ObjectInputStream in = new ObjectInputStream(fileIn);
      e = (Employee) in.readObject();
      in.close();
      fileIn.close();
    }
    catch (IOException i) {
      i.printStackTrace();
      return;
    }
    catch (ClassNotFoundException c) {
      System.out.println("Employee class not found");
      c.printStackTrace();
      return;
    }
    System.out.println("Name: " + e.name);
  }
}

 O/P : Name: Reyan Ali is printed in console


 

Print Friendly and PDF
Print Friendly Version of this pagePrint Get a PDF version of this webpagePDF

Java Swings


Java Swing tutorial is a part of Java Foundation Classes (JFC) that is used to create window-based applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight components.
The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu etc.
Difference between AWT and Swing 
There are many differences between java awt and swing that are given below.
No.Java AWTJava Swing
1)AWT components are platform-dependent.Java swing components are platform-independent.
2)AWT components are heavyweight.Swing components are lightweight.
3)AWT doesn't support pluggable look and feel.Swing supports pluggable look and feel.
4)AWT provides less components than Swing.Swing provides more powerful components such as tables, lists, scrollpanes, colorchooser, tabbedpane etc.
5)AWT doesn't follows MVC(Model View Controller) where model represents data, view represents presentation and controller acts as an interface between model and view.Swing follows MVC.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop applications.

Hierarchy of javax.swing
The hierarchy of java swing API is given below.

http://www.javatpoint.com/images/swinghierarchy.jpg

Commonly used Methods of Component class

The methods of Component class are widely used in java swing that are given below.
MethodDescription
public void add(Component c)add a component on another component.
public void setSize(int width,int height)sets size of the component.
public void setLayout(LayoutManager m)sets the layout manager for the component.
public void setVisible(boolean b)sets the visibility of the component. It is by default false.

Java Swing Examples

There are two ways to create a frame:
  • By creating the object of Frame class (association)
  • By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Example of Swing by Association inside constructor

import javax.swing.*;
public class Sample{
    JFrame frame;
    Simple(){
    frame = new JFrame ();//creating new instance of JFrame
    JButton button = new JButton("Click");
    button.setBounds(130,100,100,40);//setBounds(int xaxis, int yaxis, int width, int height)
     frame.add(button); //adding button to JFrame
     frame.setSize(400,500);//setSize(int width,intheight)
     f.setLayout(null);//using no Layout mangers
     f.setVisible(true);
    }
   public static void main(String[] args){
          new Sample();
   }
}

Simple example of Swing by inheritance

import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
    JFrame frame;
    Simple2(){
    JButton button = new JButton("click");//create button
    button.setBounds(130,100,100, 40);
    add(button);//adding button on frame
    setSize(400,500);
    setLayout(null);
    setVisible(true);
    }
public static void main(String[] args) { 
    new Simple2();
    }
}

 

Wednesday, 21 May 2014

Maths(Formulas)

Time And Distance (Related Formulas)

1. Speed = Distance ,
Time = Distance , Distance = (Speed x Time).

2. km/hr to m/sec conversion: 
x km/hr = x x 5 m/sec.
3.m/sec to km/hr conversion:
     x m/sec = x x 18 km/hr.
4.If the ratio of the speeds of A and B is a : b, then the ratio of the times taken by then to cover the same distance is
                            1 : 1 or b : a.
                            a b




5.Suppose a man covers a certain distance at x km/hr and an equal distance at y km/hr. Then,the average speed during the whole journey is
                      
                                 2xy km/hr.
x + y



Selling And Cost Price (Related Formulas)

Cost Price:
The price, at which an article is purchased, is called its cost price, abbreviated as C.P.
Selling Price:
The price, at which an article is sold, is called its selling prices, abbreviated as S.P.
Profit or Gain:
If S.P. is greater than C.P., the seller is said to have a profit or gain.
Loss:
If S.P. is less than C.P., the seller is said to have incurred a loss.

      IMPORTANT FORMULAE
  1. Gain = (S.P.) - (C.P.)
  2. Loss = (C.P.) - (S.P.)
  3. Loss or gain is always reckoned on C.P.
  4. Gain Percentage: (Gain %)
    Gain % = Gain x 100
C.P.






  • Loss Percentage: (Loss %)
        Loss % = Loss x 100
    C.P.

  • Selling Price: (S.P.)
        SP = (100 + Gain %) x C.P
    100

  • Selling Price: (S.P.)
        SP = (100 - Loss %) x C.P.
    100

  • Cost Price: (C.P.)
        C.P. = 100 x S.P.
    (100 + Gain %)

  • Cost Price: (C.P.)
        C.P. = 100 x S.P.
    (100 - Loss %)

  • If an article is sold at a gain of say 35%, then S.P. = 135% of C.P.
  • If an article is sold at a loss of say, 35% then S.P. = 65% of C.P.
  • When a person sells two similar items, one at a gain of say x%, and the other at a loss of x%, then the seller always incurs a loss given by:
        Loss % = Common Loss and Gain % 2 = x 2 .
    10 10

  • If a trader professes to sell his goods at cost price, but uses false weights, then
        Gain % = Error x 100 %.
    (True Value) - (Error)



  •   Time And Work(Related Formulas)

    1. Work from Days:
      If A can do a piece of work in n days, then A's 1 day's work = 1 .
      n
    2. Days from Work:
      If A's 1 day's work = 1 , then A can finish the work in n days.
      n
    3. Ratio:
      If A is thrice as good a workman as B, then:
      Ratio of work done by A and B = 3 : 1.
      Ratio of times taken by A and B to finish a work = 1 : 3.

    Thursday, 20 March 2014

    Difference Between String , StringBuilder and StringBuffer Classes

    String

    String is immutable  ( once created can not be changed )object  . The object created as a String is stored in the  Constant String Pool  .
    Every immutable object in Java is thread safe ,that implies String is also thread safe . String can not be used by two threads simultaneously.
    String  once assigned can not be changed .

    String  demo = " hello " ;
    // The above object is stored in constant string pool and its value can not be modified.


    demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable           
     // "hello" string still exists in string constant pool and its value is not overrided but we lost reference to the  "hello"string 

    StringBuffer

    StringBuffer is mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap .  StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

    Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

    But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

    StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
    String Buffer can be converted to the string by using
    toString() method.

    StringBuffer demo1 = new StringBuffer("Hello") ;
    // The above object stored in heap and its value can be changed .

    demo1=new StringBuffer("Bye");
    // Above statement is right as it modifies the value which is allowed in the StringBuffer

    StringBuilder

    StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
    StringBuilder is fast as it is not thread safe . 


    StringBuilder demo2= new StringBuilder("Hello");
    // The above object too is stored in the heap and its value can be modified
    demo2=new StringBuilder("Bye");
    // Above statement is right as it modifies the value which is allowed in the StringBuilder


    ----------------------------------------------------------------------------------
                                        String                    StringBuffer         StringBuilder
    ----------------------------------------------------------------------------------                
    Storage Area | Constant String Pool           Heap                       Heap
    Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
    Thread Safe   |           Yes                                  Yes                              No
     Performance |         Fast                                Very slow                    Fast
    -----------------------------------------------------------------------------------


    For Example
    String s = "Let’s test";
    s.concat("if the String object is IMMUTABLE");
    System.out.println(s);

    O/P:
    Let's test.

    IF u rewrite the program as below
    String s = "Let’s test";
    s = s.concat("if the String object is IMMUTABLE");
    System.out.println(s);
       
    O/P:
    Let’s testif the String object is IMMUTABLE

    By above example we can say that String is immuatble. It will create new objects every time when ever we assign the values. It will not refer to the old object.


    To Overcome this we have StringBuilder  and StringBuffer

        StringBuilder s1 = new StringBuilder("Hello");
        s1.append("Hai");
        System.out.println("StringBuilder : "+s1);
        
        StringBuffer s2 = new StringBuffer("testing");
        s2.append("Hai");
        System.out.println("StringBuffer : "+s2);

    O/P:
    StringBuilder : HelloHai

    StringBuffer : testingHai


    Print Friendly and PDF

    Wednesday, 19 March 2014

    Difference between Hashtable and Collections.synchronizedMap(HashMap)

    DifferenceS :

    1.The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits 
        nulls. (HashMap allows null values as key and value whereas Hashtable doesn't allow nulls).

    2.One of the major differences between HashMap and Hashtable is that HashMap is non 
       synchronized whereas Hashtable is synchronized.
       Which means Hashtable is thread-safe and can be shared between multiple threads but HashMap can not
       be shared between multiple threads without proper synchronization. Java 5 introduces 
       ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in 
       Java.

    3.HashTable is legacy class promoted into collection framework. It got its own extra features like enumerators.


    NOTE:
    HashMap can be synchronized by

    Map m = Collections.synchronizeMap(hashMap);

    Tuesday, 18 March 2014

    How To make an class as an Immutable

    Before converting the java class as Immuatable .
    I will explain what is Mutable and Immutable

    Mutable object - an object that is liable to change.
    Immutable object - an object that is unchanging over time or unable to be changed.

    For Ex:
    IMMUTABLE :
    String imm = "abc";
    imm = "abc"+"d";

    Here we are not adding the value to exist object ("abc"),  
    1)"d" will add to "abc",
    2) will create new object "abcd" 
    3) the reference of "abc" will map to "abcd";

    MUTABLE:
    StringBuffer mut = new StringBuffer("abc");
    mut.append("d");

    Here the value of "mut" changing directly.

    Guidelines to make a class immutable

    1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
    2) Make all fields final and private
    3) Don’t allow subclasses to override methods
    4) Special attention when having mutable instance variables



    Print Friendly and PDF

    Monday, 17 March 2014

    How to remove null in the List (JAVA)

    Just add as below
    listnameObject.removeAll(Collections.singleton(null));

    For Ex:
    public class MapTest {
      public static void main(String[] args) {
        List<String> scores = new ArrayList<String>();
        scores.add("100");
        scores.add("90");
        scores.add("80");
        scores.add("97");
        scores.add(null);
        scores.removeAll(Collections.singleton(null));
       
        for(String a : scores){
          System.out.println(a.toString());
        }
      }
    }

    O/P:
    100
    90
    80
    97

    Simplest way to display Server Time in JSP using js

    THE BELOW CODE WORKS ONLY IN JSP : <html> <body > <table width="95%" border="1" cellpadding="1...