How to use the variable defined in the 'if' expression?

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

    callAMethod(greeting);
}

When I define a String inside an if statement, I get a "cannot find character" error. How can I get around this and still be able to create a string depending on the above condition?

+3
source share
4 answers

What about

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

 callAMethod(greeting);
}
+4
source

Declare it out of scope -

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

callAMethod(greeting);
+2
source

if.

if String greeting = "";

, if else, greeting = "hello"; ..

, .

+1

:

String greeting;

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

System.out.println(greeting);
+1

All Articles