How to test if string is equal to "x" || "X"? - java

String c = JOptionPane.showInputDialog(null,"Pick a conversion to do:\nGrade");
if (c.equals("grade")||("Grade"))
I want it to start if the user enters grade or Grade not just grade, but when I use this I get a error. How would I fix that

The actual problem: You're using || improperly. It expects, on both sides, something of type boolean to be present.
From the JLS:
Each operand of the conditional-or operator must be of type boolean or Boolean, or a compile-time error occurs.
Since "Grade" isn't a boolean (but c.equals("grade") is), this becomes a compile-time error.
While you could fix it by correcting the boolean on the right hand side...
if(c.equals("grade") || c.equals("Grade"))
...why not do it in a more straightforward way?
if(c.equalsIgnoreCase("grade"))
This particular equals on String was likely engineered for this use case (or other use cases, as "GrAde" would fail your check too). It will perform a length check on your strings first, then a case insensitive comparison on each element.

You cannot put an || statement in the middle of a method call like that.
if (c.equals("grade")||c.equals("Grade")){
//do stuff
}
There are other ways to accomplish your task, IE using other methods, but your problem is coming form a misuse of the || operator.

You can try:
if (c.toLowerCase().equals("grade")) { }

Related

if conditionals : boolean expression variables placing order [duplicate]

This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 5 months ago.
When we're using an if-conditional, we specify the condition in a boolean expression such as following :
if(boolean expression).
If I have two variables in a boolean expression, such as (bagWeight > WEIGHT_LIMIT), does the order of the two variables in which they appear matter? In other words, can I swap those two variables' places such as following? (WEIGHT_LIMIT < bagWeight). Notice it would still be bag weight is less than weight limit, but I just switch the order of which one appears first in the boolean expression. AND Does it depend on which one becomes a subject, like one that gets focused on and evaluated? (In this case, we're trying to figure out if the bag weight is heavier than the limit or not. So the bag weight gets evaluated according to something.. I would call it a subject.)
Eclipse doesn't scream at me that it's wrong, and intuitively it makes sense, but somehow it just bothers me whether there's a more common programming practice or not. So my questions were, can I swap the two variables' places and would not matter? and does it depend on the context of which being a subject? and which is a more common programming practice?
You can freely change the order of the two variables as you prefer. Eclipse (or the compiler) doesn't care, it just evaluates the expression and returns a value, either true of false.
can I swap those two variables' places such as following? (WEIGHT_LIMIT < bagWeight)
Yes, it will still work exactly the same.
Order only comes in to play when using short circuit operates such as || or &&.
examples:
if (boolean1 || boolean2)
In this case, boolean1 will be evaluated first. If it evaluates to true, then boolean2 will not be evaluated, since the first one meets the criteria of the if statement.
if (boolean1 && boolean2)
In this case if boolean1 is evaluates to false, then boolean2 will never be evaluated because the fact that boolean1 is false means that even if boolean2 was true, the condition of the if statement would never be satisfied.
Hope that helps.
The order that Java evaluates && and || is not so important if everything is already evaluated into variables as in your example. If these where method calls instead then the second part of the "if" will not be called unless necessary. Examples of when the myMethod() would not be evaluated at all.
if (true || myMethod())
or
if (false && myMethod())
That's why you might see statements similar to this in actual code.
String myStr = null;
if (myStr != null && myStr.trim().size() > 0)
If Java were to evaluate the second part then you would get a NullPointerException when myStr is null. The fact that Java will bypass the second part keeps that from happening.
The order of the operands doesn't matter in your specific case. Since the if statement is comparing two values, the two values must be evaluated. However, there are some cases when order does matter:
|| and &&
|| and && are shorthand logic operators. The second operand of || will not be evaluated if the first is true. The second operand of && will not be evaluated if the first is false.
++ and --
These can yield different results:
if (i++ > i)
if (i < i++)
In the first line, i is evaluated after the increment is done, so the first operand is 1 less than the second.
In the second line, i is evaluated first, which evaluates to i, then i++, which evaluates to i as well.

if switch not working

I am trying to make a control that will block the user from entering a term year for their home loan that is over 30.
HomeLoan hLoan=new HomeLoan(name, custID, loanID);
System.out.println("You selected Home Loan");
System.out.println("Enter term: ");
term=input.nextInt();
boolean l=false;
boolean s = hLoan.termCorrect(term);
System.out.println(s);
if (s=true){
System.out.println("Error: Maximum of 30 years");}
else {l=false;}
It calls a method that termCorrect() that determines if the term is over 30, and returns true or false. When I run it, the value of s is correct for the input that I use, but it always run the error message for some reason, regardless of s.
Any help would be greatly appreciated.
You are using the assignment operator =:
if (s=true){
Use the comparison operator == instead:
if (s == true) {
or, because it's already a boolean, use s itself:
if (s)
The last form is preferable. It's concise, and there's no chance to an operator confused with =.
Assignment operator in if statement is invalid. Change from
if (s=true){// this invalid
To
if (s){
= is assignment. == is equality comparison.
Your if statement is incorrect. By using s=true you are setting s to true inside the if. The equality operator in Java is ==. Therefore, you could do this:
if(s==true)
Or, since s==true is logically equivalent to s (think about it), you can do this:
if(s)

Does Java evaluate remaining conditions after boolean result is known?

That is, if I have a statement that evaluates multiple conditions, in say a 'or' statement like so..
if(isVeryLikely() || isSomewhatLikely() || isHardlyLikely())
{
...
}
In the case that isVeryLikely() returns true at runtime, will isSomewhatLikely() and isHardlyLikely() execute? How about if instead of methods they were static booleans?
The || and && operators are short-circuiting.
true || willNeverExecute();
false && willNeverExecute();
The first thing that you need to note is that Java conditional statements can only take boolean, unlike other languages like C/C++ where any non-zero value will evaluate to true.
That being said, there are 2 types of operators, the first is known as the shor-circuit types:
&& and ||
while the other are the NON-short-circuit types:
& and |
For the Short-Circuit types, once a logical output can be found as an answer to the expression, the rest of the statement will be dumped. For the NON-Short-Circuit types, they will continue to evaluate all conditions.
With this in mind, what you have:
if(isVeryLikely() || isSomewhatLikely() || isHardlyLikely())
{
...
}
Java will:
First check if isVeryLikely()
returns true. If true, then it will
not continue further.
If isVeryLikely() returns false,
then invoke isSomewhatLikely() to
see if it returns true. If true,
nothing else if evaluated. If false,
goto 3.
isHardlyLikely() is invoked. If
true, entire expression is true,
otherwise false, entire
expression is false.
The entire concept you're asking about is "How does Java evaluate Logical Expressions." Good question :)
Hope it helps! Cheers!
No, java uses short-circuit evaluation on expressions using || and &&. See here for more info.
Because the || is short circuiting, the statement will be evaluated to true as soon as it hits the first true condition, regardless of whether or not the operands are static.
In short, no the two other functions will not be evaluated if the first returns true.
The short answer is, it will evaluate until has enough to conclude whether it is T/F.
There is something called boolean short-circuiting. Essentially it will try and evaluate only what it needs to (if you use the && or || operators) and the leave. You can take advantage of this in a few ways:
(a() || b())
If b() would throw an exception, if a() is true, then it would not even try and check the b(). A type of chain-checking mechanism.
If the latter evaluations are resource consuming, you can move them to the end of the evaluation (eg. b() takes 10 times longer)
If the most likely path can be determined by a certain clause, put them first. This would also speed up execution.
As an update for Kotlin users, you can use 'or' operator in Kotlin std library in order to check all the expressions in the if statement and not performing a short-circuit.
In the expression presented in the initial question the code in Kotlin should be:
if(isVeryLikely() or isSomewhatLikely() or isHardlyLikely()) {
...
}
Whether for boolean expression specified in the questions are static booleans, or they are methods returning a boolean value, in both the cases - expression evaluation will start from the left and conditions will be evaluated one-by-one. The first condition which gives a value true will short-circuit the evaluation. It will directly give the result as true with the remaining conditions not being evaluated. This is how ||(OR) works in Java using the concept of short-circuit evaluation.
If you want to understand more about short-circuits in general you can refer an article I have written on my blog - http://www.javabrahman.com/programming-principles/short-circuiting-or-short-circuits-in-boolean-evaluations-in-programming-and-java/

Strings don't seem to be equal in Java on Android, even though they print the same

I've got a problem that I'm rather confused about. I have the following lines of code in my android application:
System.out.println(CurrentNode.getNodeName().toString());
if (CurrentNode.getNodeName().toString() == "start") {
System.out.println("Yes it does!");
} else {
System.out.println("No it doesnt");
}
When I look at the output of the first println statement it shows up in LogCat as "start" (without the quotes obviously). But then when the if statement executes it goes to the else statement and prints "No it doesn't".
I wondered if the name of the node might have some kind of non-printing character in it, so I've checked the length of the string coming from getNodeName() and it is 5 characters long, as you would expect.
Has anyone got any idea what's going on here?
Use String's equals method to compare Strings. The == operator will just compare object references.
if ( CurrentNode.getNodeName().toString().equals("start") ) {
...
Use CurrentNode.getNodeName().toString().equals("start").
In Java, one of the most common mistakes newcomers meet is using == to compare Strings. You have to remember, == compares the object identity (Think memory addresses), not the content.
You need to use .equals
if ("start".equals(CurrentNode.getNodeName().toString()) { ... }

What is the Java ?: operator called and what does it do?

I have been working with Java a couple of years, but up until recently I haven't run across this construct:
int count = isHere ? getHereCount(index) : getAwayCount(index);
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
if isHere is true, getHereCount() is called,
if isHere is false getAwayCount() is called.
Correct? What is this construct called?
Yes, it is a shorthand form of
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
It's called the conditional operator. Many people (erroneously) call it the ternary operator, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there could be another ternary operator, whereas there can only be one conditional operator.
The official name is given in the Java Language Specification:
§15.25 Conditional Operator ? :
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.
In fact, by the grammar of expression statements (§14.8), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.
So, if doSomething() and doSomethingElse() are void methods, you cannot compress this:
if (someBool)
doSomething();
else
doSomethingElse();
into this:
someBool ? doSomething() : doSomethingElse();
Simple words:
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's a ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the spec is pretty clear that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has.
According to the Sun Java Specification, it's called the Conditional Operator. See section 15.25. You're right as to what it does.
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
The conditional operator is syntactically right-associative (it groups right-to-left), so that a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).
ConditionalExpression:
ConditionalOrExpression
ConditionalOrExpression ? Expression : ConditionalExpression
The conditional operator has three operand expressions; ? appears between the first and second expressions, and : appears between the second and third expressions.
The first expression must be of type boolean or Boolean, or a compile-time error occurs.
condition ? truth : false;
If the condition is true then evaluate the first expression. If the condition is false, evaluate the second expression.
It is called the Conditional Operator and it is a type of Ternary Operation.
int count = isHere ? getHereCount(index) : getAwayCount(index);
means :
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
Not exactly correct, to be precise:
if isHere is true, the result of getHereCount() is returned
otheriwse the result of getAwayCount() is returned
That "returned" is very important. It means the methods must return a value and that value must be assigned somewhere.
Also, it's not exactly syntactically equivalent to the if-else version. For example:
String str1,str2,str3,str4;
boolean check;
//...
return str1 + (check ? str2 : str3) + str4;
If coded with if-else will always result in more bytecode.
Ternary, conditional; tomato, tomatoh. What it's really valuable for is variable initialization. If (like me) you're fond of initializing variables where they are defined, the conditional ternary operator (for it is both) permits you to do that in cases where there is conditionality about its value. Particularly notable in final fields, but useful elsewhere, too.
e.g.:
public class Foo {
final double value;
public Foo(boolean positive, double value) {
this.value = positive ? value : -value;
}
}
Without that operator - by whatever name - you would have to make the field non-final or write a function simply to initialize it. Actually, that's not right - it can still be initialized using if/else, at least in Java. But I find this cleaner.
You might be interested in a proposal for some new operators that are similar to the conditional operator. The null-safe operators will enable code like this:
String s = mayBeNull?.toString() ?: "null";
It would be especially convenient where auto-unboxing takes place.
Integer ival = ...; // may be null
int i = ival ?: -1; // no NPE from unboxing
It has been selected for further consideration under JDK 7's "Project Coin."
This construct is called Ternary Operator in Computer Science and Programing techniques. And Wikipedia suggest the following explanation:
In computer science, a ternary operator (sometimes incorrectly called a tertiary operator) is an operator that takes three arguments. The arguments and result can be of different types. Many programming languages that use C-like syntax feature a ternary operator, ?: , which defines a conditional expression.
Not only in Java, this syntax is available within PHP, Objective-C too.
In the following link it gives the following explanation, which is quiet good to understand it:
A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.
In Perl/PHP it works as: boolean_condition ? true_value : false_value
In C/C++ it works as: logical expression ? action for true : action for false
This might be readable for some logical conditions which are not too complex otherwise it is better to use If-Else block with intended combination of conditional logic.
We can simplify the If-Else blocks with this Ternary operator for one code statement line.For Example:
if ( car.isStarted() ) {
car.goForward();
} else {
car.startTheEngine();
}
Might be equal to the following:
( car.isStarted() ) ? car.goForward() : car.startTheEngine();
So if we refer to your statement:
int count = isHere ? getHereCount(index) : getAwayCount(index);
It is actually the 100% equivalent of the following If-Else block:
int count;
if (isHere) {
count = getHereCount(index);
} else {
count = getAwayCount(index);
}
That's it!
Hope this was helpful to somebody!
Cheers!
Correct. It's called the ternary operator. Some also call it the conditional operator.
Its Ternary Operator(?:)
The ternary operator is an operator that takes three arguments. The first
argument is a comparison argument, the second is the result upon a true
comparison, and the third is the result upon a false comparison.
Actually it can take more than 3 arguments. For instance if we want to check wether a number is positive, negative or zero we can do this:
String m= num > 0 ? "is a POSITIVE NUMBER.": num < 0 ?"is a NEGATIVE NUMBER." :"IT's ZERO.";
which is better than using if, else if, else.
?: is a Ternary Java Operator.
Its syntax is:
condition ? expression1 : expression2;
Here, the condition is evaluated and
condition returns true, the expression1 will execute.
condition returns false, the expression2 will execute.
public class Sonycode {
public static void main(String[] args) {
double marks = 90;
String result = (marks > 40) ? "passed in exam" : "failed in exam";
System.out.println("Your result is : " + result);
}
}
Output :-
Your result is : passed in exam
It's the conditional operator, and it's more than just a concise way of writing if statements.
Since it is an expression that returns a value it can be used as part of other expressions.
Yes, you are correct. ?: is typically called the "ternary conditional operator", often referred to as simply "ternary operator". It is a shorthand version of the standard if/else conditional.
Ternary Conditional Operator
I happen to really like this operator, but the reader should be taken into consideration.
You always have to balance code compactness with the time spent reading it, and in that it has some pretty severe flaws.
First of all, there is the Original Asker's case. He just spent an hour posting about it and reading the responses. How longer would it have taken the author to write every ?: as an if/then throughout the course of his entire life. Not an hour to be sure.
Secondly, in C-like languages, you get in the habit of simply knowing that conditionals are the first thing in the line. I noticed this when I was using Ruby and came across lines like:
callMethodWhatever(Long + Expression + with + syntax) if conditional
If I was a long time Ruby user I probably wouldn't have had a problem with this line, but coming from C, when you see "callMethodWhatever" as the first thing in the line, you expect it to be executed. The ?: is less cryptic, but still unusual enough as to throw a reader off.
The advantage, however, is a really cool feeling in your tummy when you can write a 3-line if statement in the space of 1 of the lines. Can't deny that :) But honestly, not necessarily more readable by 90% of the people out there simply because of its' rarity.
When it is truly an assignment based on a Boolean and values I don't have a problem with it, but it can easily be abused.
Conditional expressions are in a completely different style, with no explicit if in the statement.
The syntax is:
boolean-expression ? expression1 : expression2;
The result of this conditional expression is
expression1 if boolean-expression is true;
otherwise the result is expression2.
Suppose you want to assign the larger number of variable num1 and num2 to max. You can simply write a statement using the conditional expression:
max = (num1 > num2) ? num1 : num2;
Note: The symbols ? and : appear together in a conditional expression. They form a conditional operator and also called a ternary operator because it uses three operands. It is the only ternary operator in Java.
cited from: Intro to Java Programming 10th edition by Y. Daniel Liang page 126 - 127

Categories

Resources