Jayden
Jayden

Reputation: 71

How do I use a variable defined in an 'if' statement?

public class Help
{
    public static void main (String[] args)
    {
        if (index = 1)
        {
            String greeting = "hello";
        }
        else
        {
            String greeting = "goodbye";
        }
    }

    callAMethod(greeting);
}

When I define the String within the if statement I get a 'cannot find symbol' error. How can I get around this and still be able to create a string depending upon an above condition?

Upvotes: 3

Views: 2015

Answers (4)

hithwen
hithwen

Reputation: 2203

How about

public static void main (String[] args){
    String greeting;
    if( index == 1){
       greeting = "hello";
    }else{
       greeting = "goodbye";
    }
 }

 callAMethod(greeting);
}

Upvotes: 4

user83643
user83643

Reputation: 2971

You can define the greeting variable before the statement:

String greeting;

if (index == 1) {
   greeting = "hello";
} else {
   greeting = "bye";
}

System.out.println(greeting);

Upvotes: 1

Wolfwyrd
Wolfwyrd

Reputation: 15916

Declare it outside the scope -

String greeting = "goodbye";
if( index == 1)
{
    greeting = "hello";
}

callAMethod(greeting);

Upvotes: 2

DOK
DOK

Reputation: 32851

Declare the variable outside of the if block.

Right before the if statement, you can say String greeting = "";

Then, inside the if and else blocks, you say greeting = "hello"; and so on.

So you have separated declaring the variable from assigning the value to it.

Upvotes: 1

Related Questions