aspose file tools*
The moose likes Beginning Java and the fly likes Variable initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable initialization" Watch "Variable initialization" New topic
Author

Variable initialization

Gregory Thomas
Greenhorn

Joined: Jun 01, 2004
Posts: 11
I am confused about when to initialize a variable and when not to. For example, in my code snippet

This example the String variable ex needs to be initialize:

why?

Thanks in advance

Gregory

[ edited to preserve formatting using the [code] and [/code] UBB tags -ds ]
[ September 17, 2004: Message edited by: Dirk Schreckmann ]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
When posting code, please be sure to surround the code with the [code] and [/code] UBB Tags. This will help to preserve the formatting of the code, thus making it easier to read and understand.


[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Dirk Schreckmann
Sheriff

Joined: Dec 10, 2001
Posts: 7023
Gregory, in your first example, did you mean for the comment to read, "This example String variable ex does need to be initialize?" Notice that your comment says the variable does not need to be initialized, which is incorrect.

In general, a variable must always be initialized before you use it for something other than assigning a value to.

In your first example, the variable is not initialized, and then you tried to use it to do something in the if-statement. Do you understand how that's a problem?

On the issue of when to initialize a variable, I'd recommend not declaring a variable until you're ready to initialize and use it. So, initialize variables when they're declared.
Gregory Thomas
Greenhorn

Joined: Jun 01, 2004
Posts: 11
oh boy... I was so confused that I did not read my comment thoroughly. Yes you are right.

Thank you for replying to me. Why do you "recommend not declaring a variable until you're ready to initialize and use it"? I had the same thought but my manager was questioning why I did that in a loop. For example:



Is it because I am creating several string instances?

Thanks again.
Gregory
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variable initialization
 
Similar Threads
Serialization
Serialization
Better handling of the ubiquitous NullPointerException?
exceptions in try and catch statements
wizlab mock question