Quick java IF question

Soldato
Joined
11 Dec 2004
Posts
3,871
Hi all,

Just wanted to ask a quick question, I have googled and checked the sun jaca forums but cant really find the answer.

I want to have two conditions that must be met before the if statement is carried out

where as this is what it would like with just one...

if (variable_one.compareTo("*") == 0)
{
do this
}

I want to do it with two conditions like this, but I dont know how to write it...

if (variable_one.compareTo("*") == 0) AND (variable_two.compareTo("*") == 0)
{
do this
}

Sorry for the noob question :o

Thanks
 
... and if you want to compare if something == x OR something == y then it's '||'

E.g.

Code:
if ( variable1 || variable2 ) {

  do this

}
 
This is another basic concept but it's useful to know. When using AND (&&), the order of the opperands can be important.

Code:
String str = null;
if (str != null && str.length > 0){
// If 'str' is not null then the length will be checked
}

This would cause problems:

Code:
String str = null;
if (str.length > 0 && str != null)
// NullPointerException as the variable 'str' is null and wasn't checked first;

It's also useful to note that with the AND(&&) operator, if the first opperand is false then the remaining expression is not checked as the first opperand being false is enough to make the whole expression false.

Likewise with OR (||), it it an inclusive or operation meaning that if the first opperand is true then other remaining opperands are not checked, even if they are true.
 
Code:
String str = null;
if (str.length > 0 && str != null)
// NullPointerException as the variable 'str' is null and wasn't checked first;

Oh how I am doing this for sheer badness, BUT it is length is a method of String class and you can't access it by just reffering to it.

Code:
String str = null;
if (str.length() > 0 && str != null)
// NullPointerException as the variable 'str' is null and wasn't checked first;

;) I know you think I am an ******* now, and you are right :( Can you tell I am bored?
 
Back
Top Bottom