0

I have this java code:

String e;
if(true){
e = "ee";    
}
if(e == "ee"){
 System.out.println(e);
}

How I can "use" the variable e out the first if statement? I add some stupid conditions (if(true).. etc.) just for try.

I'm SOrry for my bad english :v

Frank
  • 125
  • 1
  • 2
  • 8
  • Comparing strings using the `==` operator doesn't do what you think it does. Use `"ee".equals(e)` instead. – JonK Mar 29 '16 at 10:40
  • 2
    Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – JonK Mar 29 '16 at 10:42
  • Can you clarify what your problem is and whether you are getting an error and what is it? – Peter Lawrey Mar 29 '16 at 10:53

4 Answers4

1

You have saved it, you're just comparing it wrong. Use the equals method to compare values. The == operator compares referential equality.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
1

To compare the variable with another string use equals and not ==. See How do I compare strings in Java?

String e;

if(true){
  e = "ee";    
}

if(e.equals("ee")){
  System.out.println(e);
}
Community
  • 1
  • 1
  • This will do the same thing in this case. – Peter Lawrey Mar 29 '16 at 10:47
  • 1
    "ee".equals(e) (as JonK suggested in the comments) is safer. As soon as the condition is no longer if ( true), or as soon as mutation testing will be done on this code, it will throw one NullPointerException after the other. – Stultuske Mar 29 '16 at 10:49
  • @Stultuske it is safer, but is it an answer to the problem or more of a comment? – Peter Lawrey Mar 29 '16 at 10:50
  • 1
    @PeterLawrey when putting code in answers, isn't it best to make the snippets as good as possible? Anyway, I didn't downvote and only posted it as a comment, since I agree the vital information is in there, doesn't mean the remark can't help. – Stultuske Mar 29 '16 at 10:52
0

The problem is likely to be that the compiler doesn't know your variable must be set. There is a number of way to solve this.

Give it a default.

String e = null;

or make it clear that the alternative branch is impossible

if (condition) {
   e = "ee";    
} else {
   throw new AssertionError();
}

or give it an alternative value.

if (condition) {
   e = "ee";    
} else {
   e = "that was unexpected";
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You can use:

String e;

if(true){
  e = "ee";    
}

if("ee".equals(e)){
  System.out.println(e);
}

Because If e will be null then you will not get nullPointerException, If you will use like above

if("ee".equals(e)){ //Some operation }