Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Monday, August 19, 2013

Behavior of Object reference when assigned to null and ""

Difference between assigning String reference to null or empty quotes

Instance variables are initialized to a default value each time a new instance is created
But String and other Object references are assigned to null by default.Its always a good practice to assign a value explicitly to variables which increases code readability.

Lets see what happens when we invoke String related methods when String reference is assigned to null or "".

Program 1 :-

public class StringReference {

/**
* @param args
*/
String str1;

public String getStr1() {
return str1;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
StringReference sr = new StringReference();
String strl = sr.getStr1();
System.out.println(strl.length());
}

}
Run the above program it throws nullpointer exception because str1 is a reference and is not pointed to any object. So invoking a reference which doesnt point to an Object will throw null pointer exception.
Output :-
Exception in thread "main" java.lang.NullPointerException
at StringReference.main(StringReference.java:16)

Now lets see assigning String variable to ""

public class StringReference {

/**
* @param args
*/
String str1="";

public String getStr1() {
return str1;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
StringReference sr = new StringReference();
String strl = sr.getStr1();
System.out.println(strl.length());
}

}


Output :- 0

Here Str1="" creates an empty String object

Now Str1 is referring to an object so invoking String related methods liketoUpperCase(),length() etc. will not throw null pointer exception.

Happy Learning

Please provide your valuable comments on this article and share it across your network.



Tuesday, August 6, 2013

Converters In Java Server Faces--How to convert form data into respective data types?

Converters in JSF :-


In a web application the data entered in a form is always of String data type.
Consider a web page form having first name,last name and Age.Here names are of String type and Age is Number data type. But when the data is sent from form to server every filed is String type.

How to convert Age field data to integer type before assigning it to managed bean/backing bean? We can explicitly convert it by using Integer.parseInt() etc.Doing this way is tedious and not reusable.

Does JSF provide any mechanism to handle this?
Yes JSF provides a mechanism to convert these String types into respective data type.

  • For implicit data types JSF provides implicit conversion
  • For non primitive types we need to convert explicitly by using Standard Converters( for converting String to Date etc.)or by creating custom converters

First we will see different standard converters.


    SNO
    NAME
    MAIL
    1
    ByteConverter
    Converts input String value to java.lang.Byte
    2
    BooleanConverter
    Converts input String value to java.lang.Boolean
    3
    BigDecimalConverter
    Converts input String value Java.lang.BigDecimal
    4
    BigIntegerConveter
    Converts input String value to java.lang.BigInteger
    5
    CharacterConverter
    Converts input String value to java.lang.Character
    6
    DateTimeConverter
    Converts input String value to java.util.Date
    7
    NumberConverter
    Converts input String value to java.lang.Number
    8
    IntegerConverter
    Converts input String value to java.lang.Integer
    9
    FloatConverter
    Converts input String value to java.lang.Float

Similarly we have EnumConverter,ShortConverter etc.

There are three different ways to use this Standard converters.
  1. Using Converter attribute in input tags
  2. Using nested sub-tag <f:converter>
  3. Using standard converters like <f:convertDateTime>,<f:convertNumber> etc.
Lets see each of the above with examples.

1.Using Converter attribute in input tags :-
  • inputText,inputSecret,inputHidden,outputText are supported tags
  • Lets takes an example of entering date and using converter attribute
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Date</title>
</head>
<body>
<f:view>
<h:form>
Date <h:inputText id="myDate" value="#{loginBean.date}"
converter="javax.faces.DateTime">
</h:inputText>
<h:commandButton value="submit" ></h:commandButton>
<h:message for="myDate"></h:message>
</h:form>
</f:view>
</body>
</html>
  • Here we have used DateTime converter attribute in input text,the value entered should be like Aug 5, 2013--> mmm d, yyyy. If we enter a value with different value it will throw error it is displayed by using <h:message> tag



2.Using nested sub-tag <f:converter> :-

<h:inputText id="myDate" value="#{loginBean.date}">
<f:converter converterId="javax.faces.DateTime" />
</h:inputText>

Here we have used converter tag inside inputText tag

3.Using standard converters :-

we will use <f:convertdateTime> tag
<h:inputText id="myDate" value="#{loginBean.date}">
<f:convertDateTime type="date" dateStyle="short" />
</h:inputText>

There are different types of dateStyles like short,full etc.
Short type will expect date as mm/dd/yyyy or mm/dd/yy .
Long type will expect date as August 5, 2013 etc, this is generally used for outputText tag.

We can change/add the behavior of this converters by developing custom converters.
This will be discussed in my next post.



Happy Learning

Please provide your valuable comments on this article and share it across your network.



Sunday, August 4, 2013

Passing values to methods in Java-Primitives and Objects

In this post we will discuss about how method calling ,value passing happens in Java.

1.Passing Object reference variables to a method :-
  • when we pass an object to a method we are not actually passing object itself, we are passing object reference
  • Reference variable holds the address location of object and a way to load into memory
  • We are not passing actual reference variable,but a copy of reference variable-which holds the copy of bits present in actual value

Lets see below code snippent

Employee emp1=new Employee();
method1(emp1);
void method1(Employee emp)
{
}
Here both emp1 and emp point to same Employee Object in heap.

Example1 :-

public class ObjectReference {
private int var1;
private int var2;

public ObjectReference(int x, int y) {
var1 = x;
var2 = y;
}

public static void main(String[] args) {
ObjectReference op = new ObjectReference(5, 10);
System.out.println("before modify " + op.var1 + "&&" + op.var2);
op.modify(op);
System.out.println("after modify " + op.var1 + "&&" + op.var2);
}

void modify(ObjectReference pop) {
pop.var1 = pop.var1 + 10;
pop.var2 = pop.var2 + 10;
System.out.println("in modify " + pop.var1 + "&&" + pop.var2);
}
}



Output :-
before modify 5&&10
in modify 15&&20
after modify 15&&20

Here both op and pop reference variables are referring to same ObjectReference object .If one reference variable tries to change the value autotically it gets reflected to another varaible.

In the above example in change method we changed the value of var1 and var2 and when we print the value in main method it got reflected.
Now lets see what happens in case of primitive data types.

2.Passing primitive variables to a method :-
When we are passing primitive values to a method we are actually passing copy of bits that represent a value.Suppose we have int a=5,when we pass a to a method we are actually passing copy of bits of value 5. For this we use a terminology passbyvalue rather its passbycopyofvalue .

Example :-
public class PrimitivePass {
int a = 10;

public static void main(String[] args) {
PrimitivePass pp = new PrimitivePass();
System.out.println("Before change" + pp.a);
pp.change(pp.a);
System.out.println("After change" + pp.a);
}

void change(int pNum) {
pNum = pNum + 10;
System.out.println("in change" + pNum);
}
}

output :-
Before change10
in change20
After change10

From the output we can observe that value of a is not changed ,but in previous case we observed for object references the value has changed.

Note :-
  • While passing an Object we actually pass copy of the object reference
  • While passing a primitive type we pass the bits value stored in that variable
  • In both the cases we send copy of bits,in primitives actual value is stored but in case of Object reference it stores the address of the object

Happy Learning

Please provide your valuable comments on this article and share it across your network.



Like and Share