Jumat, 30 Mei 2014

Why use @Override annotation in Java - Coding Best Practice




@Override annotation was added in JDK 1.5 and it is used to instruct
compiler that method annotated with @Override 
is an overridden
method from super class
or
interface.
Though it may look trivial
@Override is particularly useful while overriding methods which accept Object as parameter just like equals,
compareTo
or
compare() method of Comparator  interface. @Override is one of the three built in annotation provided by
Java 1.5, other two are
@SuppressWarnings and @Deprecated. Out of these three @Override is most used because of its
general nature, while
@SuppressWarnings is also used while using Generics, @Deprecated is
mostly for API and library. If you have read my article
common
errors while overriding equals method
than you have see that one of the
mistake Java programmer makes it,  write equals method with non object argument type as
shown in below example:






public class Person{

    private String
name;

 

    public boolean equals(Person
person){

        return
name.equals(person.name);

    }

}







@Override annotation in java best practice coding

here programmer is attempting to override equals() method,  but instead of overriding, its a overloaded
method
. This error silently escape from compiler and not even surface on
runtime by any Exception and it’s very hard to detect.
@Override
annotation in Java prevent this category of mistake. if you put @Override
annotation above equals method than compiler will verify  if this method actually overrides a super class or interface method or
not. if its not then it throw compilation error like "method does not
override or implement a method from a super type
. In short
@Override
annotation saves lot of debugging effort by avoiding this severe mistake
in Java. This single reason is enough to convince programmer to always use
@Override
annotation while implementing super type methods.






I will give you one more example, where @Override annotation  has saved me a lot of times. Sometime I make mistake like, overriding method without argument, which means, I intend to override a method, which takes an argument and ends up writing a new method with same name without argument. This become really nasty, especially if original method is not abstract, because then compiler will not show any warning or error. But if you are using @Override annotation, Compiler will alert you with error that it actually does not override super class method.





Apart from compile time checking of overriding, @Override
can also be used by IDE and static code analyzer to suggest a default
implementation or coding
best practices
.





@Override annotation
in Java 1.6



One of the major problem with @Override annotation
on JDK 1.5 was that it can only be used to in conjunction with super class
i.e. compiler throws error if you use
@Override annotation
with interface
method
. From Java 6 onwards you can use
@Override annotation
while implementing interface method as well. This provides robust compile time checking
of overriding. If you have been using Eclipse
IDE
than you must have faced issue along
@Override annotation
where compiler complains even if you override interface method and only fix was
either remove all
@Override annotation from interface method
or shift to Java source 1.6 from compiler settings.




You should always use @Override annotation whenever application, suggested by Google's Java best practice guide as well. @Override is legal in following cases :




  1. When a class method is overriding a super-class method.

  2. When a class method is implementing an interface method.

  3. When an interface method respecifying a super-interface method.




Only place, where you don't want to use @Override is when the parent method is @Deprecated.





That's all on @Override annotation in Java. It's one of
the best Java coding practice to use
@Override annotation
while overriding any method from super class or interface.





Other Java best practices tutorial from Javarevisited Blog






20
design pattern interview questions for Java developers























Source:http://javarevisited.blogspot.com/2012/11/why-use-override-annotation-in-java.html

What is static import in Java 5 with Example




Static import in Java allows to import static members of class and use
them, as they are declared in the same class. Static import is introduced in
Java 5 along with other features like Generics,
Enum,
Autoboxing
and Unboxing
and variable
argument methods
. Many programmer think that using static import can reduce
code size
and allow you to freely use static field of external class
without prefixing class name on that. For example without static import you will
access static constant
MAX_VALUE of Integer class as Integer.MAX_VALUE but by
using static import you can import
Integer.MAX_VALUE and refer
it as
MAX_VALUE. Similar to regular import
statements, static import also allows wildcard * to import all static
members
of a class. In next section we will see Java program to demonstrate
How to use static import statements to import static fields.






Static
import example in Java


What is static import in Java 5 with ExampleIn this static import example, we have imported constants Integer.MAX_VALUE and Integer.MIN_VALUE statically
and printing there value without prefixing class
name
on that.








package test;

import static
java.lang.Integer.MAX_VALUE;

import static
java.lang.Integer.MIN_VALUE;

/**

 *

 * Java program to demonstrate How to use static import in Java 5

 * By using static import you can use static field of external class

 * as they are declared in same class.

 *

 * @author Javin Paul

 */


public class
StaticImportExample {



    public static void
main(String args[]) {

     

       //without Static
import


        System.out.println("Maximum value of int variable in Java without "
+  


                            "static import
: "
 + Integer.MAX_VALUE);

        System.out.println("Minimum value of int variable in Java without "
+


                            static import :
"
+ Integer.MIN_VALUE);

     

        //after static
import in Java 5


        System.out.println("Maximum value of int variable using " +


                            static import :
"
+
MAX_VALUE);

        System.out.println("Minimum value of int variable using" +


                            static import : " + MIN_VALUE);

    }

}



Output:

Maximum value of int variable in Java
without static import : 2147483647

Minimum value of int variable in Java
without static import : -2147483648

Maximum value of int variable using static import
: 2147483647

Minimum value of int variable using static import
: -2147483648








If you look at import statements import static java.lang.Integer.MAX_VALUE, its
written as import static rather than static import, so just
beware of that. We are not using
* wildcard
here and importing only selected static member but you can also use
import
static java.lang.Integer.*
to import
all static
fields
in one go.





Advantages of Static Import in Java



Main advantage of using static
import
in Java is saving keystrokes. If you are frequently using
System.out.println() statements
and tried of typing it, you can static import
System.out or System.* and subsequently
you can type
out.println() in your code, Though I would
suggest to use this Eclipse
shortcut to generate System.out.println statement
which is much faster than
static import. This is the kind of usage I see one can benefit from static
import
, other than that static import is just extension of regular import
statement in Java. Similar to static field you can also import static
method
in your class, mostly in case of Utility classes.





Drawback
of Static Import in Java


Many Java programmer argue against static import with
reason that it reduces readability and goes against how static field
should be used i.e. prefixed with class name e.g.
Integer.MAX_VALUE. Static
import has another drawback in terms of conflicts, once you static
import
Integer.MAX_VALUE you can not use MAX_VALUE as
variable in your programmer, compiler will throw error. Similarly if you static
import both
Integer.MAX_VALUE and Long.MAX_VALUE and refer
them in code as
MAX_VALUE, you will get following compile
time
error :





java.lang.ExceptionInInitializerError


Caused by: java.lang.RuntimeException: Uncompilable source code -
MAX_VALUE is already defined in a static single-type import 


       
at test.StaticImportExample.(StaticImportExample.java:6)


       
Could not find the main class: test.StaticImportExample.  Program will exit.


       
Exception in thread "main" Java Re





Summary


Finally few points worth remembering about static import in Java :





1) Static import statements are written as "import
static"
in code and not "static import".





2) If you import two static fields with same name explicitly e.g. Integer.MAX_VALUE and Long.MAX_VALUE then Java
will throw compile time error. But if other static modifier is not imported
explicitly e.g. you have imported
java.lang.Long.*, MAX_VALUE will refer
to
Integer.MAX_VALUE.





3) Static import doesn't improve readability as expected, as many Java
programmer prefer
Integer.MAX_VALUE which is clear that which MAX_VALUE are you
referring.





4) You can apply static import statement not only
on static fields but also on static methods in Java.





That's all on What is static import in Java 5, What is advantages
and drawbacks of using static import in Java program and how to use static
import in Java. Honestly, its been almost a decade with Java 5 released but I
have rarely used
static import statements. May be in future I may
figure out a strong convincing reason to use static import





Other Java 5 tutorial from Javarevisited






























Source:http://javarevisited.blogspot.com/2012/10/what-is-static-import-in-java-5-example-tutorial.html

What is difference between java.sql.Time, java.sql.Timestamp and java.sql.Date - JDBC interview Question




Difference between java.sql.Time, java.sql.Timestamp and java.sql.Date  is most common JDBC question appearing on
many core Java interviews. As JDBC
provides three classes
java.sql.Date, java.sql.Time and java.sql.Timestamp to
represent date and time and you already have
java.util.Date which can
represent both date and time, this question poses lot of confusion among Java
programmer and that’s why this is one of those tricky
Java questions
which is tough to answer. It becomes really tough if
differences between them is not understood correctly. We have already seen some
frequently asked or common JDBC questions like why
JDBC has java.sql.Date despite java.util.Date
and Why
use PreparedStatement in Java
i
n our last tutorials and we will see
difference between java.sql.Date,
java.sql.Time and java.sql.Timestamp in this
article. By the way apart from these JDBC interview questions, if you are
looking to get most from JDBC you can also see 4
JDBC performance tips
and 10
JDBC best practices to follow
. Those article not only help you to
understand and use JDBC better but also help on interviews. Let’s come back to
difference sql time, timestamp and sql date.






Difference between java.sql.Time, java.sql.Timestamp
and java.sql.Date:



difference between java.sql.Date , java.sql.Time and java.sql.Timestamp in JDBCJDBC in Java has three date/time types corresponding to DATE, TIME and
TIMESTAMP type of ANSI SQL. These types are used to convert SQL types into Java
types.








1) First difference on java.sql.Time vs java.sql.Timestamp vs
java.sql.Date is about information they represent :


JDBC TIME or java.sql.Time represent only time information e.g.
hours, minutes and seconds without any date information.


JDBC DATE or java.sql.Date represent only date information
e.g.
year, month and day without any time information.


JDBC TIMESTAMP or java.sql.Timestamp  represent both date and
time information
including nanosecond details.





2) java.sql.Time and java.sql.Timestamp
extends java.util.Date
class but
java.sql.Date is independent.





3) Time information from java.sql.Date and Date
information from
java.sql.Time is normalized and may set to zero
in order to confirm ANSI SQL DATE and TIME types.





So difference between Time, Timestamp and Date of SQL package is clear in
terms of what they represent. On contrary
java.util.Date also
represent Date and time information but without nanosecond details and
that's why many people prefer to store date as long value (millisecond passed
from epoch January 1, 1970 00:00:00.000 GMT). If you compare to
java.sql.Timestamp with equals()
method
it will return
false as value of nanosecond is unknown.





That's all on difference between java.sql.Date, java.sql.Time and java.sql.Timestamp. All
differences lies on what exactly the represent. This kinds of questions are
worth looking before going to any JDBC interview as time and date are integral
part of any JDBC interview.





Other JDBC and SQL articles from Javarevisited Blog






























Source:http://javarevisited.blogspot.com/2012/10/difference-between-javasqltime-date-timestamp-jdbc-interview-question.html

JSTL foreach tag example in JSP - looping ArrayList




JSTL  foreach loop in
JSP




JSTL  foreach tag is pretty useful
while writing Java free JSP code.  JSTL
foreach tag allows you to iterate or loop
Array List
, HashSet
or any other collection without using Java code. After introduction of JSTL and
expression language(EL) it is possible to write dynamic JSP code without using
scriptlet which clutters jsp pages. JSTL
foreach tag
is a replacement of for loop and behaves similarly like foreach
loop of Java 5 but still has some elements and attribute which makes it hard
for first-timers to grasp it. JSTL foreach loop can iterate over arrays,
collections like List,
Set
and print values just like for loop. In this JSP tutorial we will see couple of
example of foreach loop which makes it easy for new guys to understand and use
foreach loop in JSP. By the way this is our second JSP tutorial on JSTL core
library, in last tutorial we have seen How
to use core tag in JSP page
.






How to
use forEach tag in JSP page


JSTL foreach tag example in JSPforEach tag is part of standard JSTL core package and written as <foreach> or <c:foreach> or <core:foreach> whatever
prefix you are using in taglib directive while importing JSTL core library. In
order to use foreach tag in JSP pages you need to import JSTL tag library in
jsp and also need to include
jstl.jar in your WEB-INF/lib
directory
or in Java
classpath
. if you are using Eclipse
or Netbeans
IDE than it will assist you on on code completion of foreach tag otherwise you
need to remember its basic syntax as shown below:





Syntax of foreach tag in JSTL





<c:forEach var="name of
scoped variable"


           items="Colleciton,List or Array"  varStatus="status">


where var and items are
manadatory and
varStatus, begin, end or step attributes
are optional. Here is an example of foreach tag:





<c:forEach var="window" items="${pageScope.windows}">

    
<c:out value="${window}"/> 


</c:forEach>





above JSTL  foreach tag is
equivalent to following foreach loop of Java 1.5





foreach(String
window: windows){

   System.out.println(window);

}





JSTL foreach tag examples



In this section of JSTL tutorial we will see some more examples of using foreach tag in JSP
page for looping purpose. Just try couple of example and you will get hold of
foreach it looks
more easy after trying few examples.





Iterating
over collections or List using JSTL forEach loop


In order to iterate over collections e.g. List
or Set
you need to create those collections and store that into any scope
mentioned above e.g.
pageScope and than access it using
expression language like
${pageScope.myList}. see the JSP page in last example
for complete code example of foreach tag.





Iterating
over array using JSTL  forEach loop


For iterating over an array e.g. String array or integer array in JSP
page,  
"items"
attribute must resolved to an array.
You can use expression language to get an Array stored in of scope available in
JSP e.g. page scope, request scope, session or application scope. These are
different than bean
scope in Spring MVC
and don’t confuse between Spring bean scope and JSP
variable scope if you are using Spring MVC in your Java web application. Rest
of foreach loop will be similar to foreach loop example of iterating over
Collections in Java.








JSTL  foreach example using varStatus variable


varStatus attribute declare name of
variable which holds current looping counter for
foreach tag. It
also expose several useful information which you can access using
varStatus e.g. what
is current row, whether you are in last row etc. Here is a code example of how
to use
varStatus in foreach JSTL tag on JSP:





<%-- JSTL foreach tag varStatus
example to show count in JSP  --%
>

<c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" >

    
<c:out value="count: ${loopCounter.count}"/>


 
 
<c:out value="${window}"/>

</c:forEach>



Output:

JSTL foreach tag example in JSP

count: 1 Windows XP

count: 2 Windows 7

count: 3 Windows 8

count: 4 Windows mobile








Some other handy properties are : first, last, step, begin,
end, current, index and count





Nested
foreach tag example in JSP JSTL


Another good thing of JSTL foreach tag is you can nest foreach
tag loop
inside another foreach tag which is quite powerful way of looping without using
scriptlets in JSP. Here is an example of nesting foreach tag in JSP JSTL tag
library:





<%-- JSTL foreach tag example to
loop an array in JSP and nesting of foreach loop --%
>

<c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" >

   
<c:out value="outer loop count: ${loopCounter.count}"/> 


   <c:forEach var="window" items="${pageScope.windows}" varStatus="loopCounter" > 

       
<c:out value="inner loop count: ${loopCounter.count}"/>

  
</c:forEach>

</c:forEach>



Output:

outer loop count: 1

inner loop count: 1

inner loop count: 2

outer loop count: 2

inner loop count: 1

inner loop count: 2





Complete
JSTL  foreach loop example in JSP


Here is complete JSP page which shows how
to use JSTL foreach tag for looping over String array
. Similarly you can
loop over any Collection
e.g. List or Set as well.





<%@page import="java.util.List"%>

<%@page import="java.util.Arrays"%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>

Transitional//EN"

 
 "http://www.w3.org/TR/html4/loose.dtd">


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>

   
<head>

      
<meta
http-equiv="Content-Type" content="text/html; charset=UTF-8">

      
<title>Welcome to JSTL foreach tag Example in
JSP
</title>

   
</head>



   
<body>

       
<h2>JSTL
foreach tag example in JSP
</h2>



        
<jsp:scriptlet>

            String[] windows = new
String[]{"Windows XP", "Windows 7", "Windows 8",
"Windows mobile"};

           
pageContext.setAttribute("windows", windows);

       
</jsp:scriptlet>



        
<%-- JSTL foreach
tag example to loop an array in jsp --%>


        
<c:forEach var="window" items="${pageScope.windows}"> 


            <c:out
value="${window}"/
> 


        </c:forEach>

   
</body>

</html>



Output:

JSTL foreach tag example in JSP

Windows XP

Windows 7

Windows 8

Windows mobile








That’s all on How to use JSTL forEach loop example in JSP page. We have
seen JSTL foreach tag example of
Iterating or looping over Array
, List, Collection and nesting of two
forEach loop which allows you to write powerful JSP pages without using any
Java code.





Other JSP tutorials from Javarevisited you may like






























Source:http://javarevisited.blogspot.com/2012/10/jstl-foreach-tag-example-in-jsp-looping.html