Java if statment ending with a semi-colim [duplicate] - java

This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 3 years ago.
I have encountered the following strange behavior in Java using jdk 13.0:
String foo = "Something";
String bar = "Other";
if (foo.equals(bar));
{
System.out.println("Face palm");
}
Sadly, the above comparison succeeds and the "Face palm" is printed out.
What causes this behavior is the existence of the semi-colon in the end of the if statement.
The correct way of doing this is:
String foo = "Something";
String bar = "Other";
if (foo.equals(bar))
{
System.out.println("Face palm");
}
Could anyone explain why Java behaves like this ?
Could that be just an uncaught syntax error by the compiler ?

It does not mean that comparison succeeds - basically you just created if statement with empty body and then opened the local anonymous code block (starting from {)
The Face palm value in this case will be printed out always - no matter what the condition result will be
Read more here:
Semicolon at end of 'if' statement
Anonymous code blocks in Java

Related

Android: java.lang.IllegalArgumentException: Unknown color error [duplicate]

This question already has answers here:
CardView setCardBackgroundColor won't work
(4 answers)
Closed 2 years ago.
When I try building a project, an error appears, indicated in the name of the topic. directs here:
if (arrList[position].color != null){
holder.itemView.cardView.setCardBackgroundColor(Color.parseColor(arrList[position].color))
}else{
holder.itemView.cardView.setCardBackgroundColor(Color.parseColor(R.color.ColorLightBlack.toString()))
}
if I remove the condition that is written in "else", the project starts without errors. Tried changing the color, nothing changed!
From this post we can see that you should write
holder.itemView.cardView
.setCardBackgroundColor(ContextCompat.getColor(getActivity(), R.color.ColorLightBlack))
You are trying to use parseColor, which takes a hexadecimal string as an argument. But calling toString() probably isn't making the conversion to hexadecimal.
R.color.ColorLightBlack is an integer value assigned by the Android System. You are trying to pass this value to parseColor method which required String. Even if you use toString on R.color.ColorLightBlack, the value still remains Integer, hence you are getting the error.
You can update the code like this:
if (arrList[position].color != null){
holder.itemView.cardView.setCardBackgroundColor(Color.parseColor(arrList[position].color)) }
else {
holder.itemView.cardView.setCardBackgroundColor(R.color.ColorLightBlack))
}

Ternary operator gives "Not a statement" error [duplicate]

This question already has answers here:
ternary operator not working
(3 answers)
Closed 4 years ago.
Hi below statement throws error . It says "Not a statement"
map.containsKey(1)? someObject.setFlag(true) : map.put(1,"hello");
Is it needed to store the returned value in some variable on the left hand side of the statement?
You are using the Ternary operator as a statement, not an assignment. In your case, you should use if else
if(map.containsKey(1)) {
someObject.setFlag(true)
}else{
map.put(1,"hello");
}
Here is the java docs of Ternary operator.
The ternary operator is an expression, not a statement. It is commonly used to set the value of a variable depending on some condition. In this case, you need to assign the result to a variable in order to make it into a statement:
String result = map.containsKey(1) ? someObject.setFlag(true) : map.put(1,"hello");
(Note: You should choose a better variable name.)
I think you will still have problems here because setFlag() probably doesn't return a String. Also, since you are creating side effects, you should replace this with an if statement.

Integer.toString() add "\u0000" characters, and if statement fails... [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
OK, my first question in stackOverflow.
This is something that I left me completely baffled.
Java (I use android Studio), I write the following code:
Integer aNumber = 200;
String aNumberInString;
aNumberInString = Integer.toString(aNumber);
Boolean result;
if(aNumberInString == "200"){
result = true;
} else {
result = false;
}
Log.i("result:",result+"");
OK, logic and what I expect is that the condition is true... But NO! it fails.
I was really shocked by this behavior, then investigate a little more, and run the code in debug mode step by step.
when I get to the condition, I inspect the value of "aNumberInString" and to my surprise, this is what I find:
OK, so the first thing I think is: "Integer.toString ()" are doing something wrong.
Let's try another way: "String.valueOf ()"
Run in debug mode, and:
THE SAME! and fails, of course.
Obviously fails because it compares different characters, and in Internet I found a way to fix it,
string.replace ("\\ u0000", "");
but my question is not how to fix it, is:
Why is this happening?
Is there a correct way to prevent this from happening?
From already thank you very much to all,
Regards, Nicolas
You are doing a reference comparison. For comparing Strings, you need to call equals. By doing == with an Object, you are asking Java to make sure they are the same object, not if they have the same value.
Change:
if(aNumberInString == "200"){
To this:
if(aNumberInString.equals("200") {
Or better yet, to reduce the chance of a NullPointerExcpetion:
if("200".equals(aNumberInString))

Why does Java have an empty statement? [duplicate]

This question already has answers here:
Semicolon at end of 'if' statement
(18 answers)
Closed 7 years ago.
Just a general Java question. Why does the null variable exist? I'm working with some introduction to CS students and one of the most common mistakes is semi-colons where they are not supposed to be. For example
if(isTired());{
sleep(10);
}
The misplaced semi-colon before the open parenthesis keeps the if statement from working correctly, and I was wondering why the null line did in a Java program. In this example null seems to be a detriment and was wondering when someone would use it when coding.
The null statement is useful because there are some places in Java where you want to do nothing. They are not frequent, but they exist. Often they are the 'compulsory' statements that you have to put in as part of a construct. For example, if you want to write a for loop that only terminates on a 'break', then you want there to be nothing in the 'conditional' part of the for:
for (int i=0;;i++) {
int j = complexCalculation(i);
if (j<0 && complexCondition(j)) {
break;
}
}
If the null statement wasn't allowed, that wouldn't compile. If it was allowed there, but not in other places, that would be inconsistent (and make life more difficult for compiler writers).
The reality is that, once you get to be fairly proficient with the language, errors caused by accidentally adding null statements are rare.

The ? boolean zen operator [duplicate]

This question already has answers here:
Short IF - ELSE statement
(6 answers)
Closed 9 years ago.
Ive never used the ? operator before and i'm trying to figure out how it works.
I have been reading countless pages and decided to try for my self.
i have the following statement:
getSelection().equalsIgnoreCase("Måned") ? calendarView.currentlyViewing.set(Calendar.Year) : showPopup();
So as far as i cant understand if the left hand side (boolean) is true it will set my calendarView.to year and if not (getSelection is not equal to måned) it will call the method showPopup();
but when i type this into eclipse i get a syntax error.
can someone explain what i am doing wrong?
You're trying to use the conditional ? : operator to decide which statement to execute. That's not its intention. The conditional operator can't be used as a statement - it's only to choose which expression to use as the overall result.
So this is fine:
foo(condition ? nonVoidMethod1() : nonVoidMethod2());
but this isn't:
condition ? voidMethod1() : voidMethod2();
You should just use an if statement here:
if (getSelection().equalsIgnoreCase("Måned")) {
calendarView.currentlyViewing.set(Calendar.Year);
} else {
showPopup();
}

Categories