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] );
  }
 }
}

Java - HashMap example and iterating through HashMap

Here is example of HashMap.

Now we will put some objects to the HashMap.
First we will create new Car class.
After that you can see how to add some object to these collection in line #39.
In line #46 we are checking if there is key "two" in our HashMap.
In line #49 we are checking if there is value "four" in HashMap.
In line #52 we are checking how much keys there is in our HashMap.
In line #54 you can see how get Object from HashMap by key.
In line #59 we are removing Object by key.

In lines #62 and #68 there is iterating through HashMap by key and
in line #74 there is iterating by value.

package p_2013_04_03;

import java.util.HashMap;
import java.util.Map;

class Car
{
 private String brand;
 private int year;
 
 public Car( String aBrand, int aYear )
 {
  this.brand = aBrand;
  this.year = aYear;
 }
 
 public void showBrand()
 {
  System.out.println( this.brand );
 }
 
 public void showYear()
 {
  System.out.println( this.year );
 }
}

public class MyHashMap 
{
 public static void main(String[] args) 
 {
  HashMap hm = new HashMap();
  
  Car opel = new Car("Opel", 2009);
  Car ford = new Car("Ford", 2007);
  Car bmw = new Car("BMW", 2011);
  Car mercedes = new Car("Mercedes", 2011);
  
  // put new value to the Map
  hm.put("one", opel);
  hm.put("two", ford);
  hm.put("three", bmw);
  hm.put("four", mercedes);
  
  // check if Map contains key: true or false
  System.out.println( hm.containsKey("two") );
  
  // check if Map contains value: true or false
  System.out.println( hm.containsKey("four") );
  
  // return the number of keys
  System.out.println( hm.size() );  
  
  // get object from the Map by key 
  Car carFromThree = hm.get("three");
  carFromThree.showBrand();
  
  // remove object from Map
  hm.remove("three");  
  
  // Iterate through Map - by key
  for(Map.Entry entry : hm.entrySet())
  {
   System.out.println( "Key: " + entry.getKey() + " | Value : " + entry.getValue() );
  }
  
  // Iterate through Map - by key
  for(String key : hm.keySet())
  {
   System.out.println( "Key: " + key );
  }
  
  // Iterate through Map - by value
  for(Car car : hm.values())
  {
   System.out.print( "Value: " );
   car.showBrand();
  }
 }
}

Java final field, method and class.

Here is some short example of:
- final field
- final method
- final class


package p_2013_04_03;

public class MyFinalExamples 
{
 // final field is defined and cannot be reassign 
 private final String myFinalString = "I am final string";
 
 // Final field cannot be assigned and if you inherit class you can't override final method 
 public final void setMyFinalString( String aFinalString )
 {
  this.myFinalString = aFinalString;
 }  
}

final class MyFinalExamples02 extends MyFinalExamples
{
 // Final methods can not be overridden 
 public void setUserName( String aUserName )
 {
  this.userName = aUserName;  
 }
}

// Misconception - can't subclass the final subclasses 
class MyFinalExamples03 extends MyFinalExamples02
{
 
}



Example of final field:
In line #9 we are trying to redefine the final field - but you can't do that.

Example of final method:
In line #9 there is final method that can't be overridden when that class will be inherited. So we are trying to override that method in line #18 in inherited class - that is not possible.

Example of final class:
In line #15 we have got final class which is inherited by class in line #25. It can't be done because final class cannot be inherited.

Sunday, March 31, 2013

jQuery / $.post - How to send data with jQuery to other file

How to send data to other file with jQuery post() method?

Sometimes we want to send data without refreshing page.
Solution is simple. Using jQuery post() method we can send different types of  data (variables, arrays, forms, serialized data, etc.) and after that we can for example write these data to the database.

index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery post method</title>

<script type="text/javascript">
$(document).ready(function()
{
    $('#J_action_sendPersonSalary').click( function()
 {
  var personId = 34;
  var personSalary = 2000;
  
  $.post( "person.php", {personId: personId, personSalary: personSalary} ); 
 });
});
</script>
 
</head>
<body>

 <a id="J_action_sendPersonSalary" href="javascript:void(0)">Send data with salary</a>
    
</body>
</html>

person.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<?php

 $personId = $_POST['personId'];
 $personSalary = $_POST['personSalary'];
 
 // Here we can do something with our data. For example send it to the database.
 $query = 'INSERT INTO ....';

?>

</body>
</html>