View RSS Feed

My Java Tips

  1. Avoiding null pointer exception

    by , 11-01-2011 at 06:26 PM (My Java Tips)
    One should try avoiding null pointer exception. In case of coding an application that needs high degree of reliability, don't take risks. I will present an example.

    Check the following piece of code.

    Java Code:
    private boolean isNullString(String string) {
    return (string.equals(""));
    It seems a normal piece of code. But still there's a hidden trap here. What is the string which is passed is null? So try to rephrase ...
    Java SE , Performance
  2. HashMap - useful methods

    by , 11-01-2011 at 06:24 PM (My Java Tips)
    I will present few important methods of HashMap class in this post.

    The most useful methods are: get and put.

    get(Object key) returns the value associated with specified key. It returns null if there is no value for this key.
    put(K key, V value) associates the specified value with the specified key.

    Other useful methods are:

    containsKey(Object key) - (boolean) returns true if this map contains a value for the specified key
    Java SE
  3. xsl output tag

    by , 11-01-2011 at 06:21 PM (My Java Tips)
    As you know, you may apply XSLT transformers and filters on XML documents in Java. To do so, you should know some basic XSLT tags. I will present xsl:output tag in this post.

    It is a top-level element, and must appear as a child node of or . The element defines the format of the output document.

    Example follows:

    omit-xml-declaration="yes|no" ...
  4. XML Prolog

    by , 11-01-2011 at 06:15 PM (My Java Tips)
    Developer who are working with XML, should know about XML prolog. This post will brief you about the said topic.

    Its an optional component of the XML document. If you wish to include it, then it must appear before the root element. A prolog consists of two parts:

    Part 1 comprises of XML declaration
    Part 2 comprises of Document Type Declaration (DTD)

    You can include both depending on your needs.


    <!--?xml ...
  5. Defining own annotation type

    by , 10-31-2011 at 06:49 PM (My Java Tips)
    The Java language supports defining new annotation types. An annotation type looks similar to an ordinary class, but it has some unique properties. One can use it with the at sign in the classes to annotate your other Java code.

    Its right to say that defining a new annotation type is similar to creating an interface. We have to precede the interface keyword with the @ sign.

    The following example shows the simplest possible annotation type:

    Java Code:
    package com.domain.tiger.a;
  6. Custom annotations - Adding a member

    by , 10-31-2011 at 06:45 PM (My Java Tips)
    Annotation types can have member variables. You will understand its importance when you use annotations for metadata, not just raw documentation. These member variables provides very useful information to code-analysis tools.

    Data members in annotation types are set up to work using limited information. The way to add member is to define a single method that should be named after the member which you want to allow for. The data type should be the return value of the ...
  7. Custom annotations - default values

    by , 10-31-2011 at 06:40 PM (My Java Tips)
    I'll focus on setting some default values for the annotation.

    Yes, you want the users to specify values for the annotations but only if their values differ some default values. Default values should be provided to make things easier.

    The following example shows how one can associate default values with custom annotations.

    Java Code:
    package com.domain.tiger.a;
    // Annotation type with default values
    public @interface GroupTODO {
  8. Annotating an annotation

    by , 10-31-2011 at 06:32 PM (My Java Tips)
    I will briefly write about annotating annotations. You should have good idea about the set of predefined annotation types we have seen in the last few posts.

    When you start writing your own annotation types, the main purpose of your annotation types is to provide basic documentation. Also you write annotation types that are specific to a certain member type,
    or perhaps a certain set of member types. This requires you to supply some sort of metadata on your annotation type, ...
  9. Adding public documentation

    by , 10-31-2011 at 06:24 PM (My Java Tips)
    Documented is a meta-annotation and its a marker annotation. A marker annotations have no member variables.

    Documented annotation is used to indicate that an annotation should appear in the Javadoc for a class. Remember that the default behavior is that annotations are not included in Javadocs. The presented example shows what the Documented meta-annotation looks like in use:

    Java Code:
    package com.domain.tiger.a;
    import java.lang.annotation.Documented;
  10. Setting up inheritance

    by , 10-31-2011 at 06:19 PM (My Java Tips)
    Inherited is a meta-annotation that is complicated as compared to other annotations. It is least-often used.

    Let me present a scenarios for better understanding: Suppose that you use your custom annotation called InProgress to mark a class as being in progress.
    If the Documented meta-annotation is applied correctly, then this will show up in the Javadoc. All is well till here.

    Suppose you write a new class and extend the in-progress class. Now remember one this: ...
  11. Java Persistence API - annotations

    by , 10-31-2011 at 06:15 PM (My Java Tips)
    The Java Persistence API heavily depends on the metadata annotations. The API consists of:

    Java Persistence API
    The Java Persistence query language
    Metadata annotations

    An entity is a persistence object. It is coded as a POJO, and marked as an entity with the @Entity (javax.persistence.Entity) annotation. By default, all properties/fields are persisted into the datastore, except those marked with the @Transient annotation. Following example shows few annotations ...
  12. SAX is underneath most XML processing

    by , 10-31-2011 at 06:08 PM (My Java Tips)
    SAX is a simple API for XML and is largely used because it is very popular because almost all XML processing involves SAX at some level.

    SAX is blazing fast and has been around for a while. XML is fairly easy to work with, but it's not an intuitive language in lots of ways. Most of the XML parsers these days use SAX since it already works pretty well.
    SAX is great at parsing XML. And if you know how to handle errors in SAX, then you know how to handle errors in almost any XML ...
  13. JAXP exposes SAX

    by , 10-31-2011 at 06:04 PM (My Java Tips)
    Many of you must be using JAXP API, the Java API for XML Processing for XML processing.

    The code below shows a fragment that uses JAXP for some SAX parsing.

    Java Code:
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    parser.parse(new File(args[0]), new MyHandler());
    This surely looks similar ...
  14. Categories of annotations

    by , 10-31-2011 at 05:57 PM (My Java Tips)
    There are three categories of annotations namely Marker, Single-Value and Full annotation.

    Let me present these one by one:

    Marker annotations

    There annotations have no variables. These are identified by name, with no additional data supplied. For example:


    Single-value annotations

    These are similar to markers, but also provide a single piece of data. You can only ...
  15. Broken Pipe - Transaction

    by , 10-31-2011 at 05:51 PM (My Java Tips)
    I assume that you are having a J2EE environment with connection pool and you are using hibernate.

    When you use transactions, you have to explicitly commit or rollback every time. Some programmers believe that queries do not have to be committed. This is not right in my opinion. If you do not commit, the connection is left assigned. Which means we have dangling connections that later will be killed by the database server like: MySQL. Connection pool would later attempt to reattach ...
  16. Hibernate Session

    by , 10-31-2011 at 05:44 PM (My Java Tips)
    Declaring your hibernate session as static is not a good idea because a session/connection does not have an endless lifetime.

    If you have static hibernate session, change it to dynamic. Everytime you want to run one or more transactions at once, obtain a new session object from sessionfactory. The given code shows
    static hibernate session. A new session will be created when getSession() is called for the first time. In the later calls, the same session will be returned. ...
  17. Using pagging techniques

    by , 10-30-2011 at 06:59 PM (My Java Tips)
    When displaying long lists on the web, we use paging techniques. In this post, I will show how to do that.

    Normally we display 10 or 15 results at a time and the user can scroll through the list. If list is a long one, then it does not make an sense to loat it completely. Loading the complete list in session and then loop through the results is not a nice approach. An approach can be to use pagination tags which means fetching and displaying the results one page at a time. Pagination ...
    Java EE , JSF , JSP
  18. Setting up hibernate.cfg.xml

    by , 10-30-2011 at 06:50 PM (My Java Tips)
    Hibernate.cfg.xml is a configuration file that is put in the project's root directory and it has to be put into class path as well.

    A sample cfg file for MySQL is given below. Do change the database URL, database name, username and password.

    <!--?xml version='1.0' encoding='UTF-8'?-->
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    ""&gt; ...
  19. Hibernate - Mapping files

    by , 10-30-2011 at 06:45 PM (My Java Tips)
    Mapping files are there to map entities with the database tables. In this post, I will present 2 sample mapping files.

    Mapping file for MySql is given below:
    <pre lang="java">
    <!--?xml version="1.0" encoding="UTF-8"?-->

    <class name="com.domain.example.Student" table="student">
    <id name="id" column="id" type="java.lang.Integer"> ...
  20. Java to JSON

    by , 10-30-2011 at 06:43 PM (My Java Tips)
    Creating JSON or XML from Java is simple. I'll show some short code sample.

    Java Code:
    Person p = new Person();
    JSONSerializer serializer = new JSONSerializer();
    String json = serializer.serialize( p );
    Created JSON String:

    Java Code:
       "class": "Person",
       "name": "William Shakespeare",
       "birthday": -12802392000000,
       "nickname": "Bill"
  21. HiveMind

    by , 10-30-2011 at 06:41 PM (My Java Tips)
    HiveMind is a services and configuration microkernel. I will elaborate this point in this post.

    HiveMind allows services which are actually POJOs (Plain Old Java Objects) to be easily accessed and combined. You should use interfaces to work with HiveMind because each service defines a Java interface it implements. Instantiating and configuring of each service just as necessary is handled by HiveMind. It allows these services to collaborate with each other via dependency injection. ...
    HiveMind , Software
  22. Log method entry and exit

    by , 10-30-2011 at 06:39 PM (My Java Tips)
    The typical approach we use in Java is given below:

    Java Code:
    public String myMethod(String param)
      if (LOG.isDebugEnabled())
        LOG.debug("myMethod(" + param + ")");
    String result = // . . .
    if (LOG.isDebugEnabled())
      LOG.debug("myMethod() returns " + result);
    return result;

    This will work ...
    HiveMind , XML
  23. StringBuilder

    by , 10-30-2011 at 06:32 PM (My Java Tips)
    Java 5 introduces StringBuilder which implements Serializable and CharSequence interfaces. It represents a mutable sequence of characters.

    StringBuilder is an API compatible with StringBuffer, but with no guarantee of synchronization. Following are the available constructors:

    Java Code:
    StringBuilder(CharSequence seq)
    StringBuilder(int capacity)
    StringBuilder(String str)
    This can be used in place of StringBuffer ...
    Java SE
  24. java.util.Locale

    by , 10-30-2011 at 06:27 PM (My Java Tips)
    Locale object deals with the geographical details. Different parts of the world have different languages, currencies and time zones. There are some operations that are different for different geographical areas. These are referred as locale-sensitive operations. These operations uses Locale to tailor the information according to the needs.

    Representing numbers is a locale-sensitive operation as formatting of number is different in different parts of the world. The example below prints ...
    Java SE
  25. Using prepaid statements

    by , 10-30-2011 at 06:22 PM (My Java Tips)
    SQL statements are executed on a database tables using Statement object. If the sql statement takes parameter, then it is a wise decision to use PreparedStatement as they are more flexible and makes coding easier.

    Creating SQL statements that take parameters provides flexible statements to work with. We can use the same statement and supply it with different values each time we execute it.
    We use place holders (question marks) in the query, which are supplied values to make ...
  26. Using Batches in JDBC

    by , 10-30-2011 at 06:18 PM (My Java Tips)
    Updating a record from Java using executeUpdate() method of Statement object is used commonly by JDBC programmers. Thing to note is that this is a costly activity in terms of time, as a database trip is made. As a programmer/developer, our aim should be to write efficient Java code. In this post, I will write about how you can efficiently make several updates.

    Batch update allows us to execute several update statements in a batch. It means only one database trip will be make, thus ...
  27. Logical Operators

    by , 10-30-2011 at 06:08 PM (My Java Tips)
    Following are logical operators that one can use in Java programming.

    ! Is not…
    ^ Exclusive Or…
    | Or… (bitwise)
    & And… (bitwise)
    || Or… (short cut, see &&)
    && And

    In this Java programming tutorial, I will code And, Or and Not operators as they are commonly used.

    Java Code:
    int a= 15;
    int b = 25;
    if(a<10 || b>10)
    System.out.println("Entered: Java
    Java SE
  28. Content Assist

    by , 10-30-2011 at 06:05 PM (My Java Tips)
    Eclipse provides content assist that really can save lot of development time. For instance putting try catch blocks where needed, for loop to iterate over an array/list etc.

    Key stokes required: Ctrl-Space

    Here is a list of useful things that can be done using content assistant:

    - Code completion, name completion, etc.
    - Does lots of useful completions in different contexts. Try it!
    - When the cursor is among the methods of a class declaration, ...
  29. Repositories

    by , 10-30-2011 at 05:48 PM (My Java Tips)
    In Maven, projects can share dependencies which means that different project can use common jar files.

    These jar files will be updated over time and Maven keeps each project current with the latest jar file. These jar files will be placed in a repository on a remote server and are accessed by the projects. These files will be mirrored in a local repository under the Maven installation. The remote repository location is given in the file which is located in your Maven ...
    XML , Maven
  30. Hibernate - SessionFactory

    by , 10-29-2011 at 07:44 PM (My Java Tips)
    We are writing an application that will use Hibernate to manage our application persistence object. We will need a SessionFactory which creates or open a session to talk to a database.

    Creating SessionFactory is easy. We can define the configuration in, hibernate.cfg.xml or create it programatically. I will present an example that will use the hibernate.cfg.xml configuration file, which is mostly use when creating Hibernate application.

    Below is ...

    Updated 10-29-2011 at 07:47 PM by Java Tip

Page 12 of 15 FirstFirst ... 21011121314 ... LastLast