In Java, class instance variables and static variables have default values: null for all object types, false for boolean primitive and 0 for numeric primitives. But local variables inside a method have no defaults.

Consider the following code snippet:
public static void main(String[] args){
java.util.Date d;
System.out.println(d);
}
It will fail to compile with this error:
variable d might not have been initialized
System.out.println(d);
1 error
However, the following will compile and run successfully:
public static void main(String[] args){
java.util.Date d;
}
Because the rule is that all local variables must be initialized before they are first read. So it's perfectly OK to first declare a local variable without initializing it, initialize it later, and then use it:
public static void main(String[] args){
java.util.Date d;
//do more work
d = new java.util.Date();
System.out.println(d);
}
It may be an old habit from languages like C, where you need to declare all local variables at the beginning of a code block. But in Java with this rule in place, it's best to defer declaring local variables till needed.

9

View comments

  1. well this rule is most frustrating when trying to close a resource in a finally block. if I instantiate the resource inside a try, but try to close it within the finally, I get this error. if I move the instantiation outside the try, I get another error stating that a it must be within a try.

    very frustrating.

    ReplyDelete
  2. Thanks for posting this! I searched on google and this page was the first result, very good to know!

    ReplyDelete
  3. If I am declaring PI, how about that,
    Do I have to specifically mention the value of PI(If so then wt the hell is this error) which I am getting for PI

    ReplyDelete
  4. Sometimes when you use for, while, etc. to initialize you need to use for example:
    variable1 = null;
    That message will dissapear.

    ReplyDelete
  5. Thanks! About 1 hour trying to find out... and in one minute you saved me.

    ReplyDelete
  6. Thank you, that was very helpful! :D

    ReplyDelete
  7. This is actually a huge feature of Java, and you should absolutely get out of the habit of typing "=0" or "=null" when declaring variables.

    This uses branch code checking to ensure that every possible path that could get to the use of a given variable has, at some point, initialized that variable.

    If you go around setting them to 0, you will eliminate this extremely useful warning. If you are getting the warning, look at it closely to figure out if you are missing something. Sometimes you still have to initialize it, but now I never do until I'm sure that's the best way to code it.

    ReplyDelete
  8. I wrote the following code to set a variable to an unused, random value:

    // Find an empty place in tmp
    boolean foundEmptyPlace = false;
    while (!foundEmptyPlace) {
    randomNumber = randomGenerator.nextInt(tmp.length);
    if (tmp[randomNumber] == null) {
    foundEmptyPlace = true;
    }
    }
    // do something with tmp[randomNumber]

    Here I get the "might not have been initialized" error, though reasonably it must have been initialized within the while loop. My solution was to initialize randomNumber (= 0) before the loop. But, as Bill points out, this seems to be an unpreferrable habit. Can I avoid the error in a more clean and correct way?

    ReplyDelete
Javadoc closing tags in IntelliJ
Diff tools: diff, vimdiff, opendiff & twdiff
java.util.Properties and character encoding
java.util.Properties and character encoding
java.util.Properties, trim, null, whitespace, and escaping
java.util.Properties, trim, null, whitespace, and escaping
NoSuchMethodError: javax.xml.parsers.DocumentBuilderFactory.newInstance
NoSuchMethodError: javax.xml.parsers.DocumentBuilderFactory.newInstance
java.io.IOException: No such file or directory and URI
java.io.IOException: No such file or directory and URI
Java Thread Pools and their Thread Dumps
Java Thread Pools and their Thread Dumps
Java Applicatioin Process Hangs on Windows and Cached Thread Pool
Java Applicatioin Process Hangs on Windows and Cached Thread Pool
How to Configure hprof in GlassFish 3.x
How to Configure hprof in GlassFish 3.x
My Intellij Notes
My Intellij Notes
How to Configure hprof in JBoss AS7
How to Configure hprof in JBoss AS7
How to Create Management and Application Users in JBoss AS7
How to Create Management and Application Users in JBoss AS7
How to Create Global Modules in JBoss AS7
How to Create Global Modules in JBoss AS7
GlassFish CLI and JBoss AS7 CLI Commands
GlassFish CLI and JBoss AS7 CLI Commands
How to Add System Properties to JBoss AS 7
How to Add System Properties to JBoss AS 7
JBoss AS7 Ant Tasks for Deploy and Undeploy
JBoss AS7 Ant Tasks for Deploy and Undeploy
How to Run JBoss Jandex
How to Run JBoss Jandex
My JBoss AS7 jboss-cli Notes
My JBoss AS7 jboss-cli Notes
GlassFish multimode Command for Batch Processing
GlassFish multimode Command for Batch Processing
How to Manage Type Visibility
How to Manage Type Visibility
GlassFish 3.1 to JBoss AS 7.1.1 EJB Invocation
Standalone Java Client for JBoss AS 7.1.1: Maven and JUnit Edition
Standalone Java Client for JBoss AS 7.1.1: Maven and JUnit Edition
Standalone Java Client for JBoss AS 7.1.1
Standalone Java Client for JBoss AS 7.1.1
Thoughts on ThreadLocal
Thoughts on ThreadLocal
Different Strategies for Acquiring Dependency inside a Method
Different Strategies for Acquiring Dependency inside a Method
2
How to Instantiate Annotation Type and Qualifier
ConcurrentHashMap Examples
ConcurrentHashMap Examples
How to Create POJO JavaBean Custom Resource in GlassFish
How to Create POJO JavaBean Custom Resource in GlassFish
How to Create Simple String and Primitive Resources in GlassFish
How to Create Simple String and Primitive Resources in GlassFish
Java Dynamic Proxy Example
Java Dynamic Proxy Example
1
My Unix Linux Notes
My Unix Linux Notes
Extend Thread vs implement Runnable
Extend Thread vs implement Runnable
1
My tcsh notes
My tcsh notes
Why use ThreadFactory
Why use ThreadFactory
Notes on Java Debugger (NetBeans)
Notes on Java Debugger (NetBeans)
Example of StackOverflowError
Example of StackOverflowError
Dependency Injection (DI) in Java EE
Dependency Injection (DI) in Java EE
JUnit Notes, Do's and Don'ts
JUnit Notes, Do's and Don'ts
Singleton, DCL, Holder Idiom, and When Singleton is not a Singleton
Singleton, DCL, Holder Idiom, and When Singleton is not a Singleton
2
Join threads with FutureTask and Callable
Join threads with FutureTask and Callable
2
When to join threads with CountDownLatch
When to join threads with CountDownLatch
My notes on java thread
My notes on java thread
Example of expensive computation
Example of expensive computation
My notes on serialization and de-serialization
My notes on serialization and de-serialization
Example of Java thread deadlock
Example of Java thread deadlock
1
Simple Example of JSF and EJB 3.1
Simple Example of JSF and EJB 3.1
Runnable, Callable, FutureTask, ExecutorService and thread pool
Runnable, Callable, FutureTask, ExecutorService and thread pool
1
Example of JPA and Hibernate with JBoss and MySql
Example of JPA and Hibernate with JBoss and MySql
2
How to programmatically copy jar files
How to programmatically copy jar files
2
Servlet init method vs PostConstruct method
Servlet init method vs PostConstruct method
Jetty to GlassFish Interoperability: Remote EJB Invocation
Jetty to GlassFish Interoperability: Remote EJB Invocation
Resin to GlassFish Interoperability: Remote EJB Invocation
Resin to GlassFish Interoperability: Remote EJB Invocation
1
Tomcat to GlassFish Interoperability: Remote EJB Invocation
Tomcat to GlassFish Interoperability: Remote EJB Invocation
1
javax.naming.Reference cannot be cast to in GlassFish
javax.naming.Reference cannot be cast to in GlassFish
VirtualBox shared folder for Ubuntu guest
VirtualBox shared folder for Ubuntu guest
My mvn notes
My mvn notes
My vim notes
My vim notes
GlassFish embedded, JPA, EJB, DataSource and glassfish-resources.xml
GlassFish embedded, JPA, EJB, DataSource and glassfish-resources.xml
3
How to create and look up thread pool resource in GlassFish
4
EJB lite, JPA, DataSource embedded in java application
EJB lite, JPA, DataSource embedded in java application
5
A sample glassfish-resources.xml
A sample glassfish-resources.xml
2
Simple webapp with FORM authentication and SSL
Simple webapp with FORM authentication and SSL
2
Simple webapp with BASIC authentication
Simple webapp with BASIC authentication
vnc notes on Linux
vnc notes on Linux
Programmatically bind global JNDI resources
Programmatically bind global JNDI resources
4
glassfish-application.xml and sun-application.xml examples
glassfish-application.xml and sun-application.xml examples
glassfish-application-client.xml and sun-application-client.xml examples
glassfish-application-client.xml and sun-application-client.xml examples
glassfish-web.xml and sun-web.xml examples
glassfish-web.xml and sun-web.xml examples
glassfish-ejb-jar.xml and sun-ejb-jar.xml examples
glassfish-ejb-jar.xml and sun-ejb-jar.xml examples
java -agentlib:jdwp for attaching debugger
java -agentlib:jdwp for attaching debugger
My subversion svn notes
My subversion svn notes
String.contains and String.indexOf
String.contains and String.indexOf
Java debug options in ant build.xml
Java debug options in ant build.xml
3
Some basic steps using Derby 10.5
Some basic steps using Derby 10.5
2
A sample web.xml (servlet 3.0) with ejb-ref and ejb-local-ref
A sample web.xml (servlet 3.0) with ejb-ref and ejb-local-ref
1
GlassFish rotate-log
GlassFish rotate-log
Double click in NetBeans 6.5 & 6.8 editor
Double click in NetBeans 6.5 & 6.8 editor
6
Example of EJB 3.1 Stateful Session Bean and Servlet
Example of EJB 3.1 Stateful Session Bean and Servlet
8
restart-domain in GlassFish
restart-domain in GlassFish
2
Example of EJB Interceptor class
Example of EJB Interceptor class
@Resource.lookup and classpath
@Resource.lookup and classpath
2
2 @ManagedBean in JavaEE 6
2 @ManagedBean in JavaEE 6
Env-entry enhancement in JavaEE 6
Env-entry enhancement in JavaEE 6
DataSourceDefinition Examples in JavaEE 6
DataSourceDefinition Examples in JavaEE 6
Message Driven Bean Example with Servlet Client
Message Driven Bean Example with Servlet Client
2
GlassFish set-web-env-entry
GlassFish set-web-env-entry
EJB 3.1 Timer Simple Example
EJB 3.1 Timer Simple Example
5
Simple Asynchronous methods in EJB 3.1
Simple Asynchronous methods in EJB 3.1
How to trim ant property string value
How to trim ant property string value
Portable JNDI names in EJB 3.1
Portable JNDI names in EJB 3.1
EJB Lite testing with JUnit and embeddable container
8
A sample EJB 3.1 Lite client
A sample EJB 3.1 Lite client
How to get module name and app name
How to get module name and app name
A sample application-client.xml (Java EE 5)
A sample application-client.xml (Java EE 5)
A sample application.xml (Java EE 5 and Java EE 6)
A sample application.xml (Java EE 5 and Java EE 6)
A sample ejb-jar.xml (EJB 3.0)
A sample ejb-jar.xml (EJB 3.0)
2
A minimal sample web.xml (servlet 2.5)
A minimal sample web.xml (servlet 2.5)
A sample web.xml (servlet 2.5)
A sample web.xml (servlet 2.5)
1
Servlet without web.xml
Servlet without web.xml
Print array content with Arrays.toString or Arrays.asList
Print array content with Arrays.toString or Arrays.asList
Labels
Archive
Popular Posts
Popular Posts
  • Two JVM options are often used to tune JVM heap size: -Xmx for maximum heap size, and -Xms for initial heap size. Here are some common mi...
  • Simple enum . The ; after the last element is optional, when this is the end of enum definition. public enum Color { WHITE, BLACK, RED, ...
  • How to set project classpath in Eclipse and NetBeans are similar: just right-click the project name, choose Properties to bring up the Prope...
  • Let's say I need to spawn multiple threads to do the work, and continue to the next step only after all of them complete. I will need t...
  • This is a sample web.xml based on Servlet 2.5 (part of Java EE 5) that declares common elements. All top-level elements are optional, and c...
  • The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toS...
  • Prior to JDK 6, we can check if a string is empty in 2 ways: if(s != null && s.length() == 0) if(("").equals(s)) Checking ...
  • When writing javadocs, IntelliJ automatically adds a closing tag for html elements. For instance, after typing <lt>, it automaticaly a...
  • StringBuilder was introduced in JDK 1.5. What's the difference between StringBuilder and StringBuffer? According to javadoc , StringBu...
  • With array, we can easily declare and initialize it at the same time: String[] favorites = new String[] {"EJB", "JPA", ...
Loading