Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables not initalizing" Watch "Variables not initalizing" New topic

Variables not initalizing

John Walker

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");
if (number == 2)
card = ("2");
if (number == 3)
card = ("3");
if (number == 4)
card = ("4");

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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.
I agree. Here's the link:
subject: Variables not initalizing
It's not a secret anymore!