1

Can I do something like this?

if(variable = class.GetVariable() != null){
    variable.doSomething()
}

As I said in the comments I'm doing this with a HttpSession, so my goal is to check if there is a parameter in the session with a specific name and if it is do something.

Nuno Mendes
  • 113
  • 1
  • 11
  • Do you only need to check if the variable is null? – Hasitha Jayawardana Sep 09 '19 at 10:53
  • 1
    `if((variable = class.GetVariable()) != null){`. Parentheses help. – Federico klez Culloca Sep 09 '19 at 10:55
  • @HasithaMJayawardana In truth I want to check if the session contains a parameter and if it does I do some code. I just don't want to call the session.getParameter twice because I feel that's a massive waste of resources. – Nuno Mendes Sep 09 '19 at 10:58
  • 1
    I think it's duplicate https://stackoverflow.com/questions/16148580/assign-variable-value-inside-if-statement[enter link description here](https://stackoverflow.com/questions/16148580/assign-variable-value-inside-if-statement) – dawis11 Sep 09 '19 at 11:00
  • 1
    @dawis11 Yes, it seems to be a duplicate of that question, unfortunately I couldn't find it before. – Nuno Mendes Sep 09 '19 at 11:01

3 Answers3

2

You can, so long as variable has already been defined and you add additional brackets:

Foo variable;
if ((variable = GetVariable()) != null) {
    variable.doSomething();
}

You tend not to see this pattern often as it's not the most readable, but it is often seen when reading from a BufferedReader line by line (as it provides a convenient, quick way to read lines until there aren't any):

String line;
while((line=reader.readLine())!=null) {
    //Process each line
}
Michael Berry
  • 70,193
  • 21
  • 157
  • 216
1

!= has precedence over =, so here the code means assigning the boolean value resulting from class.GetVariable() != null to the variable variable :

if(variable = class.GetVariable() != null){
...
}

That is not what you want.
So enclose the assignment between () to set explicitly the precedence :

String variable = null; 
if( (variable = class.GetVariable()) != null){
    variable.doSomething()
}
davidxxx
  • 125,838
  • 23
  • 214
  • 215
1

As long as you define the variable first, yes but you must put them in parenties:

MyObject variable;
if( ( variable = class.GetVariable()) != null){
    variable.doSomething();
}
Grim
  • 1,938
  • 10
  • 56
  • 123