Wednesday, March 5, 2014

Java EE / Deployment descriptor (web.xml)

Java: Deployment Decriptor: web.xml

Deployment descriptor describes the classes, resources and configuration of the application
and how the web server uses them to serve web requests.
When the web server receives a request for the application,
it uses the deployment descriptor to map the URL of the request to the code that ought to handle the request.

The deployment descriptor is a file named web.xml.
It resides in the app's WAR under the WEB-INF/ directory.
The file is an XML file whose root element is <web-app>.

Simple example of decriptor:

    
        spring
        org.springframework.web.servlet.DispatcherServlet
    
    
        spring
        *.html
    


Descriptor defines mappings between URL paths and the servlets that handle requests with those paths.
The web server uses this configuration to identify the servlet to handle a given request
and call the class method that corresponds to the request method.

The <servlet-mapping> element specifies a URL pattern and the name of a declared servlet to use for requests whose URL matches the pattern.
The URL pattern can use an asterisk (*) at the beginning or end of the pattern to indicate zero or more of any character.
The pattern matches the full path of the URL, starting with and including the forward slash (/) following the domain name.

More details for example here.

Tuesday, March 4, 2014

Java keywords - words, that cannot be used in Java as identifiers

There are some words in java which cannot be used as identifiers.

Java keywords:
abstract, continue, for, new, switch, assert, default, goto, package, synchronized, boolean, do, if, private, this, break, double, implements, protected, throw, byte, else, import, public, throws, case, enum, instanceof, return, transient, catch, extends, int, short, try, char, final, interface, static, void, class, finally, long, strictfp, volatile, const, float, native, super, while

Friday, February 28, 2014

jQuery / Hide and show element using toggle() method

How to hide some element on page using jQuery?
We can use jQuery toggle() method.
It will add css style: "display:block" or "display:none"


jQuery
 

 

 

 
 
     
    Hide / Show
 
    
Some div content

jQuery / Hide or show elements on page

How to hide and show some element on page using jQuery?
We can do that using jQuery method: hide() or show().
It will add css style - "display: none;" or "display: block;"


jQuery
 

 

 

 
 
     
    Hide element 
Show element
Some div content

There is also other way to hide and show elements on www page.
You can use jQuery method: toggle(). See HERE

Wednesday, February 26, 2014

jQuery / get or set - text input value

How to check value of text input?
var myInputValue = $('#myInput').val();



jQuery
 

 

 

 
 
     
    Get input value
 
    


How to set input text value?
$('#myInput').val('My new value');



jQuery
 

 

 

 
 
     
    Set msg to second input

    Type here new msg
    

Wednesday, February 12, 2014

jQuery / Check if checkbox is checked

How to check if input checkbox is checked?

$('#inputId').is('checked');
return true || false



jQuery
 

 

 

 

 
 
     
    Check checkbox
 
    

Java / Exception

There are three exceptions components:
- try
- catch
- finally

First example demonstrate what will happen when we don't use exception handling.

public class Main 
{
 public static void main(String[] args)
 { 
  int a = 10;
  int b = 0;
  float result;
  result = a / b;    
  
  System.out.println("Program end");
 }    
}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at test.Main.main(Main.java:45)

Program fails.

Second example demonstrate program with exception handling.
public class Main 
{
 public static void main(String[] args)
 { 
  int a = 10;
  int b = 0;
  float result;
  
  try 
  {
   result = a / b;   
   System.out.println(result);
  }
  catch (ArithmeticException e) 
  {
   System.out.println("Exception catched:");   
      e.printStackTrace();
  }
  finally
  {
   System.out.println("Block finally");
  }
  
  System.out.println("Program end");
 }    
}

Output:

Exception catched:
java.lang.ArithmeticException: / by zero
 at test.Main.main(Main.java:48)
Block finally
Program end

Exception catched.
Program didn't fails and run to the end.


TIP: Sequence of block is important!
// That code will couse error - code will not compile
try {

} 
catch (Exception e) {
    
} 
catch (ArithmeticException e) {
    
}

Output:

Unresolved compilation problems: 
Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception


TIP: Block finally is optional. Never mind whether Exception will occur (will be catched) or not. Block finally will execute everytime.

Tuesday, February 11, 2014

Hibernate - Entity

@Entity annotation - declares class as entity
Class User has to have setters and getters.
We defined table name by @Table(name="user") annotation. If these annotation will be omitted the name of table will be generated using class name.

@Entity
@Table(name="user")
public class User 
{
 @Id
 @GeneratedValue
 @Column(name="id", unique=true, nullable=false)
 private int id;
 
 @Column(name="login")
 private String login;
 
 @Column(name="password")
 private String password;
 
 @Column(name="name")
 private String name;
 
 @Column(name="surname")
 private String surname;

 
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getLogin() {
  return login;
 }

 public void setLogin(String login) {
  this.login = login;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSurname() {
  return surname;
 }

 public void setSurname(String surname) {
  this.surname = surname;
 }
}

Java / Polymorphism

Polymorphism

To demonstrate how polymorphism works we need base class named Person.
class Person 
{
 public void showDescription()
 {
  System.out.println("I am Person");
 }
}

// Class Boy extends class Person and override "showDescription()" method.

class Boy extends Person
{
 public void showDescription()
 {
  System.out.println("I am Boy");
 }
}

// Class Girl extends class Person and override "showDescription()" method.

class Girl extends Person
{
 public void showDescription()
 {
  System.out.println("I am Girl");
 }
}

// Class PersonService is used to do some action.
// We print only kind of person.

class PersonService
{
 // Method agrument: object person
 public void showPersonDecription(Person person)
 {
  person.showDescription();
 }
}

// Start program

public class Main 
{
 
 public static void main(String[] args)
 { 
  // Create three kinds of persons
  // Each object (p01, p02, p03) is assigned to class "Person".
  Person p01 = new Person();
  Person p02 = new Boy();
  Person p03 = new Girl();
  
  /* print persons description */
  new PersonService().showPersonDecription(p01);
  new PersonService().showPersonDecription(p02);
  new PersonService().showPersonDecription(p03);
 }    
}


Explanation:

There are two classes which extends basic class Person.
Then method showDescription() is overridden.

Class PersonService
Here is the key: Class PersonService has got one method which prints decription of given object of class Person (object of class Person, not class Boy or class Girl).

Class Main
Create three objects of class Person and pass it to the method of class PersonService.

TIP: Do you know that object is passed by reference? :)

Result of the program is:
I am Person
I am Boy
I am Girl

Polymorphism allows to work on the higher level of abstraction.
Now you can add new functionality to class Person and use it in every class which extends class Person.
You can simply add new class which extends class Person (for example class Baby) and don't have to change any functionality of class PersonService!

Reference:
Java official tutorial

Java / String equals() vs "=="

Comparing Strings in Java.

public class Main 
{
 
 public static void main(String[] args)
 { 
  String a = new String("abcd");
  String b = new String("abcd");
    
  if(a == b)
   System.out.println("true");
  else
   System.out.println("false");
  
  if(a.equals(b))
   System.out.println("true");
  else
   System.out.println("false");
 }  
}

The output will be:
false
true

Explanation:
The operator "==" check if String "a" and String "b" refers to the same object - to the same place in the memory.
Method equals() compare the content of Strings (content of two objects).

Take a look at second example;

public class Main 
{
 
 public static void main(String[] args)
 { 
  String a = new String("abcd"); 
  String b = a;
    
  if(a == b)
   System.out.println("true");
  else
   System.out.println("false");   
 }  
}

Now the result is:
true
true

Explanation:
The operator "==" check if String "a" and String "b" refers to the same object. Yes, it refers to the same object (String b = a;).

Remember:
The operator "==" check if objects refers to the same memory location.
Method equals() check the value of the object.

Monday, February 10, 2014

Java / field, method: modifiers

Access to members of class.
Modifiers of field, method:

public
- is visible everywhere

private
- is visible only in owner class

protected
- is visible in owner class and subclass but only in the same package (and sub-package)

no-modifier (also known as package-private)
- is visible in owner class and subclass in the same package (not in sub-package)


EXAMPLES:

Modifier: public

package test;
class Car
{
 public String brand; // visible everywhere

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Possible use:

package test;
import test.Car;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // OK
  // OR
  tc.setBrand("Opel") // OK
 }  
}

Modifier: private

package test;
class Car
{
 private String brand; // visible only in own class

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Possible use:

package test;
import test.Car;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // field is not visible (Exception in thread "main" java.lang.Error: Unresolved compilation problems: )
  // But you can do that way
  tc.setBrand("Opel") // OK
 }  
}

Modifier: protected

package test;
class Car
{
 protected String brand; // visible only in package "test" and also in each sub-package of "test"

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Second class in sub-package

package test.subtest;
class SportCar extends Car
{
  
}

Possible use:

package test;
import test.Car;
import test.SportCar;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // OK    
    
  SportCar sportCar = new SportCar();
  sportCar.brand = "Ferrari";  // OK  
 }  
}

Modifier: no-modifier (package-private)

package test;
class Car
{
 String brand; // visible only in package "test" (not in sub-package of "test")

 public String getBrand() {
  return brand;
 }
 public void setBrand(String brand) {
  this.brand = brand;
 } 
}

Second class in sub-package

package test.subtest;
class SportCar extends Car
{
  
}

Possible use:

package test;
import test.Car;
import test.subtest.SportCar;
public class Main 
{
 public static void main(String[] args)
 {
  Car car = new Car();
  tc.brand = "Opel";  // OK    
    
  SportCar sportCar = new SportCar();
  sportCar.brand = "Ferrari";  // field is not visible 
 }  
}


Reference:
Java official tutorial

Monday, February 3, 2014

Hibernate / Adding new User to DB

Hibernate - Add new user to database.

Needded classes:
- HibernateUtil_c_users_DB .class
- hibernate-c_users.cfg.xml
- User.class
- UserDAO.class


HibernateUtil_c_users_DB.class

package util;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


public class HibernateUtil_c_users_DB 
{
 private static SessionFactory sessionFactory;
 private static ServiceRegistry serviceRegistry;
 
 static
 {
  try 
  {
   Configuration configuration =  new Configuration().configure("hibernate-c_users.cfg.xml");
   serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
   sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  }
  catch (HibernateException he)
        {
            System.err.println("Error creating Session: " + he);
            throw new ExceptionInInitializerError(he);
        }
 } 

 public static SessionFactory getSessionFactory() 
 {
  return sessionFactory;
 }

 public static void saveEntity(Object entity) 
 {
  Session session = HibernateUtil_c_users_DB.getSessionFactory().getCurrentSession();
  Transaction transaction = session.beginTransaction();
  session.save(entity);
  transaction.commit();
 }
 
 public static List getEntities(Class criteria) 
 {
  Session session = HibernateUtil_c_users_DB.getSessionFactory().getCurrentSession();
  Transaction transaction = session.beginTransaction();
  List result = session.createCriteria(criteria).list();
  transaction.commit();
  return result;
 }
}



hibernate-c_users.cfg.xml





 
  org.hibernate.dialect.MySQLDialect
  com.mysql.jdbc.Driver    
  jdbc:mysql://192.168.0.105:3306/c_users 
  root 
  
  thread
        false
        true
        validate
        org.hibernate.cache.internal.NoCacheProvider
        
        
        0
  3
  1
  50
  3000
                
        
     

 




User.class

@Entity
@Table(name="user")
public class User 
{
 @Id
 @GeneratedValue
 @Column(name="id", unique=true, nullable=false)
 private int id;
 
 @Column(name="login")
 private String login;
 
 @Column(name="password")
 private String password;
 
 @Column(name="name")
 private String name;
 
 @Column(name="surname")
 private String surname;

 
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getLogin() {
  return login;
 }

 public void setLogin(String login) {
  this.login = login;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSurname() {
  return surname;
 }

 public void setSurname(String surname) {
  this.surname = surname;
 }
}



UserDAO.class

public void addNewUser()
 {
  User user = new User();
  
  user.setLogin("jbond");
  user.setPassword("!James12345");
  user.setName("James");
  user.setSurname("Bond");  
  
  Session session = HibernateUtil_c_users_DB.getSessionFactory().openSession();        
  session.beginTransaction();
                 
  session.save(user);     
        
        session.getTransaction().commit();                       
        session.close();
 }

Hibernate / Get user data from DB

Get user data from DB using Hibernate Criteria.

Needded classes:
- HibernateUtil_c_users_DB .class
- hibernate-c_users.cfg.xml
- User.class
- UserDAO.class


HibernateUtil_c_users_DB.class

package util;

import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;


public class HibernateUtil_c_users_DB 
{
 private static SessionFactory sessionFactory;
 private static ServiceRegistry serviceRegistry;
 
 static
 {
  try 
  {
   Configuration configuration =  new Configuration().configure("hibernate-c_users.cfg.xml");
   serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
   sessionFactory = configuration.buildSessionFactory(serviceRegistry);
  }
  catch (HibernateException he)
        {
            System.err.println("Error creating Session: " + he);
            throw new ExceptionInInitializerError(he);
        }
 } 

 public static SessionFactory getSessionFactory() 
 {
  return sessionFactory;
 }

 public static void saveEntity(Object entity) 
 {
  Session session = HibernateUtil_c_users_DB.getSessionFactory().getCurrentSession();
  Transaction transaction = session.beginTransaction();
  session.save(entity);
  transaction.commit();
 }
 
 public static List getEntities(Class criteria) 
 {
  Session session = HibernateUtil_c_users_DB.getSessionFactory().getCurrentSession();
  Transaction transaction = session.beginTransaction();
  List result = session.createCriteria(criteria).list();
  transaction.commit();
  return result;
 }
}



hibernate-c_users.cfg.xml





 
  org.hibernate.dialect.MySQLDialect
  com.mysql.jdbc.Driver    
  jdbc:mysql://192.168.0.105:3306/c_users 
  root 
  
  thread
        false
        true
        validate
        org.hibernate.cache.internal.NoCacheProvider
        
        
        0
  3
  1
  50
  3000
                
        
     

 




User.class

@Entity
@Table(name="user")
public class User 
{
 @Id
 @GeneratedValue
 @Column(name="id", unique=true, nullable=false)
 private int id;
 
 @Column(name="login")
 private String login;
 
 @Column(name="password")
 private String password;
 
 @Column(name="name")
 private String name;
 
 @Column(name="surname")
 private String surname;

 
 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getLogin() {
  return login;
 }

 public void setLogin(String login) {
  this.login = login;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getSurname() {
  return surname;
 }

 public void setSurname(String surname) {
  this.surname = surname;
 }
}



UserDAO.class

public class UserDAO 
{  
 public User getUserData(String login, String password)
 {
  User user = new User();  
  Session session = HibernateUtil_c_users_DB.getSessionFactory().openSession();
        
  session.beginTransaction();
                 
  Criteria criteria = session.createCriteria(User.class);
  criteria.add(Restrictions.eq("login", login));
  criteria.add(Restrictions.eq("password", password));
  
  user = (User) criteria.list().get(0);   
        
        session.getTransaction().commit();                       
        session.close();
  
  return user;
 }
}

Thursday, May 2, 2013

Java / Inner classes


Inner classes.
There are two types of inner classes:
- static (static nested classes)
- non-static (inner classes)

Non-static nested classes have access to other members of the enclosing class,
even if they are declared private.
Static nested classes don't have access to other members of the enclosing class.

There are few reasons for using nested classes.
- logical grouping classes used in one place
- increasing encapsulation
- more readable and maintainable code

public class MyNested 
{
 private int x = 10;
 private int y = 15;
 
 public void showAddition()
 {
  Operation o = new Operation();  
  System.out.println( o.add() );
 }
 
 class Operation
 {
  private int add()
  {
   System.out.println( "Adding" );
   return x+y;
  }
 }
 
 // ! 
 // Static nested classes don't have access to members of enclosing classes 
 static class StaticOperation
 {
  private int add()
  {
   return x+y;
  }
 }
 
 public static void main(String[] args) 
 {
  MyNested n = new MyNested();
  n.showAddition();
  
  // To instantiate an inner class, you must first instantiate the outer class. 
  // Then, create the inner object within the outer object 
  MyNested.Operation op = n.new Operation();
  op.add();

 }
}

Java / Initialization of variables


How can we initialize fields?
There are few ways to do it.

1. Initialization in its declaration - but sometimes we need some logic to do that.
2. Initialization in static block
3. Initialization in block
4. Initialization in constructor
5. Initialization by method


public class MyInitialization 
{
 static int a, b;
 int x, y;
 String name;
 String address;
 
 
 // 1. initialization in its declaration 
 int age = 30;
 
 // 2. initialization in static block 
 static
 {
  a = 7;
  b = 9;  
 }
 
 // 3. initialization in block 
 {
  x = 21;
  y = 23;  
 }
 
 // 4. initialization in constructor 
 MyInitialization()
 {
  this.name = "John";
 }
 
 // 5. initialization by method 
 public void setAddress(String aAddress)
 {
  this.address = aAddress;
 }
 
 public void setX(int aX)
 {
  this.x = aX;
 }

 public static void main(String[] args) 
 {  
  MyInitialization mt = new MyInitialization();
  
  System.out.println( mt.age );  // 1
  
  System.out.println( MyInitialization.a ); // 2
  System.out.println( MyInitialization.b ); // 2
  
  System.out.println( mt.x ); // 3
  System.out.println( mt.y ); // 3
  
  System.out.println( mt.name ); // 4
    
  mt.setAddress("London"); // 5
  System.out.println( mt.address );
 }
}

Java / Enum type


Enum type is a data type that enables for a variable to be a set of predefined constants.
The variable must be equal to one of the values that have been predefined for it.
Because they are constants, the names of an enum type's fields are in uppercase letters.
enum WeekDays 
{
 MONDAY, THUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class MyEnum
{
 WeekDays weekDays;
 
 public MyEnum(WeekDays aWeekDays) 
 {
  this.weekDays = aWeekDays;
 }
 
 public void showCommentForEachDay()
 {
  if( weekDays.equals(WeekDays.SATURDAY) || weekDays.equals(WeekDays.SUNDAY) )
   System.out.println("I like weekends");
  else
   System.out.println("Waiting for weekend... it's " + this.weekDays);
 }
 
 public static void main(String[] args)
 {
  MyEnum me = new MyEnum(WeekDays.SATURDAY);
  me.showCommentForEachDay(); /* out: I like weekends */
 }
}

Sunday, April 28, 2013

Java / break and continue statements


Difference between break and continue statement.
- break - loop is terminated
- continue - stops the normal flow of loop and returns to the loop without executing statement after the continue statement.


public class MyBreak 
{
 public static void main(String[] args) 
 {
  for(int i=0; i<30; i++)
  {
   System.out.print(i);
   
   if(i == 10)
   {
    System.out.println(" \nBreaking the loop when i == 10 ");
    break;    
   }
   System.out.println(" NEXT...");
  }
  System.out.println("End of first loop\n");
  
  for(int i=0; i<30; i++)
  {
   System.out.print(i);
   
   if(i == 10)
   {
    System.out.println(" \nContinue statement when i == 10");
    continue;    
   }
   System.out.println(" and still iterating...");
  }
 }
}


As you can see break statement terminated loop when i == 10.
Continue statement only terminated flow when i == 10 and returned to the iteration.

Wednesday, April 3, 2013

Java - references and passing object to the method


In below example you can see how object is passed to the method.

Objects in Java are passed by reference (or value of the reference). Objects are stored on the heap.

Primitive types in Java are passed by value and they are stored on the stack.

package p_2013_04_03;

class Dog
{
 public String name;
 
 public Dog( String aName )
 {
  this.name = aName;
 }
 
 public void getName()
 {
  System.out.println(this.name);
 }
 
 public void setName( String aName )
 {
  this.name = aName;
 }
}

public class Reference 
{ 
 
 public static void main(String[] args) 
 {
  Dog myDog = new Dog("Raff");
  myDog.getName();
  
  Reference ref = new Reference();
  ref.foo(myDog); // changing name for "Rex" in foo method 
  
  // "myDog" have got new name = "Rex". NOT "Max"
  myDog.getName();
 }
 
 // object is passed by reference (value of reference is passed to function)
 public void foo( Dog aSomeDog )
 {
  // reference to "myDog"
  aSomeDog.getName();
  aSomeDog.setName("Rex");
  
  // assigning new reference to object "aSomeDog" (NOT "myDog"!!!)
  aSomeDog = new Dog("Max");
  aSomeDog.getName();
 }
}

As you can see reference to "myDog" named Raff was passed to the foo method.
Now we have got two references to the "myDog" object.
Then we changed named from Raff to Rex.

After that we have assign new object to the given reference and we have changed name to Max - but name of "myDog" wasn't changed because that reference doesn't point longer at the "myDog" object.

Java / serialize and deserialize object

Serialization is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer, or transmitted across a network connection link) and "resurrected" later in the same or another computer environment. From Wikipedia


In our example we have got class Person which is implementing Serializable interface. It is needed for serialization our Person class.

In line #42 we are starting serialization and writing serialized data to the file.

In line #64 we are starting reading data from file and then data is deserialized.

It is very simple.

package p_2013_04_03;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


class Person implements java.io.Serializable
{
 private static final long serialVersionUID = 1L;
 
 private String name;
 private int age;
 
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}


public class MySerialization 
{

 public static void main(String[] args) 
 {
  Person john = new Person();
  john.setName("John");
  john.setAge(30);       
  
  // serialize and write serialized data to the file
  FileOutputStream fos = null;
  ObjectOutputStream oos = null;
     
  try 
  {
   fos = new FileOutputStream("person.txt");
   oos = new ObjectOutputStream(fos);
   
   oos.writeObject(john);
   fos.close();
   oos.close();
  } 
  catch (FileNotFoundException e) 
  {  
   e.printStackTrace();
  } 
  catch (IOException e) 
  { 
   e.printStackTrace();
  }
  
  // Read serialized data from the file and deserialize 
  FileInputStream fis = null;
  ObjectInputStream ois = null;
  Person desPersonJohn = new Person();   
  
  try 
  {
   fis = new FileInputStream("person.txt");
   ois = new ObjectInputStream(fis);
      
   desPersonJohn = (Person)ois.readObject();
  } 
  catch (FileNotFoundException e) 
  {  
   e.printStackTrace();
  } 
  catch (IOException e) 
  {  
   e.printStackTrace();
  } 
  catch (ClassNotFoundException e) 
  {  
   e.printStackTrace();
  }
  
  System.out.println(desPersonJohn.getName() + " " + desPersonJohn.getAge());  
 }
}

Java - for and for each loop

Below you can see example of looping over an array.
First loop is done using "for each" statement.
Second loop is done using "for" statement.
package p_2013_04_03;

public class MyLoop 
{
 //Examples of iterating through an arrays
 public static void main(String[] args) 
 {  
  int[] myTable = {1,2,4,7,44,56,44};  
 
  // for each loop in java 
  for( int x : myTable )
  {
   System.out.println( x );
  }
  
  // Another way of iterating through an array 
  for(int i=0; i < myTable.length; i++)
  {
   System.out.println( myTable[i] );
  }
 }
}