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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables not initalizing" Watch "Variables not initalizing" New topic
Author

Variables not initalizing

John Walker
Greenhorn

Joined: Oct 28, 2003
Posts: 9
Hello everyone, I'm trying to make a little program that will output a random card from a deck. I just started but I'm getting the error that the card variable might not be initalized. What am I doing wrong?
public class Cards {

public static void main (String[]args) {
int number;
String card;
number = (int)(Math.random()*4+1);

if (number == 1)
card = ("Ace");
else
if (number == 2)
card = ("2");
else
if (number == 3)
card = ("3");
else
if (number == 4)
card = ("4");
else
System.out.println(card);

}
}
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

What gets assigned to "card" if "number" is not 1, 2, 3, or 4? Nothing, right. But you're printing the value in that case. Java won't let you read from a variable that's never been assigned to.
There are several ways to deal with this. One would be to initialize "card" when you declare it:

Another would be to add a bare "else" case to the end of your chain of if-else's to assign a value if one hasn't been assigned so far, or throw an exception.
Another would be to change the if-elses to a switch statement, and include a default case that assigns some value or throws an exception.


[Jess in Action][AskingGoodQuestions]
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
For what it's worth, Java guarantees that all instance variables (static or otherwise) will be initialized. All objects become "null", booleans are "false" and all other primitives will be zero (0, 0L, 0.0, as appropriate). I think it's a good idea to explicitly initialize them, but the JVM will take care of it.
However local variables, such as "number" and "card" in your class, must be explicitly initialized as Ernest pointed out.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Variables not initalizing