This question already has answers here:
Strange Null pointer exception case: ternary conditional operator not working with string concatenation
(6 answers)
Closed 6 years ago.
how can i get null pointer exception from this line of code?
String a = "localUri: "+ mCurrentImageUri == null? "none" : mCurrentImageUri.toString();
mCurrentImageUri == null, but I have thought it won't evaluate mCurrentImageUri.toString() if so
half-related:
how to write similar to this c# syntax?
string a = myVar?? "none"
You need parentheses:
"localUri: " + (mCurrentImageUri == null ? "none" : mCurrentImageUri.toString())
Without parentheses, it's parsed as (("localUri: "+ mCurrentImageUri) == null) ? ..., which is always false.
As to the Java code, as others pointed out,
what you have written in Java is equivalent to:
String a = ("localUri: " + mCurrentImageUri == null ) ? "none" : mCurrentImageUri.toString();
and that's why you get the NullPointerException (NPE).
In C# you can just do:
myVar == null ? "none" : myVar.ToString()
The syntax is quite similar to Java
( in Java you have toString(), in C# you have ToString() )
In C#, as you suggested, you can also use the
left coalesce operator. For more details, check here:
http://msdn.microsoft.com/en-us/library/ms173224.aspx
how can i get null pointer exception from this line of code?
If you look the table operators precedence + has a higher precedence than the ternary operator, so you concatenate your string first then it's not null so you go in the second condition.
Related
This question already has answers here:
Java ternary (immediate if) evaluation
(3 answers)
Closed 7 years ago.
I recently got help writing a statement checking if input text was blank or only whitespace. I got it working but do not really understand the code since its too advanced refactoring for me. Could someone please translate this to more basic code?
name = name == null ? "" : name.trim();
Your code is similar to:
String name = //your input
if(name==null) {//if name si null
name = "";//assign empty string
} else {
name = name.trim(); //remove leading and trailing whitespace
}
The if else is replace with "? :" operator
The thing you are seeing is a "ternary operator". It follows this syntax:
boolean ? ifTrue : ifFalse
Ternary operators do not work quite like if/else statements: They provide you with a value (like 3 + 4).
So in this example, you set name to the result of the following ternary expression:
is name null? -+- true --> ""
|
+- false -> name.trim() (this function removes whitespace at
the beginning and at the end of the string)
You could also write:
public static String parseName(String name)
{
if (name == null)
return "";
//else (else not neccesary here)
return name.trim();
}
// in some block...
name = parseName(name);
if name is equal to null it will be equal to "";
else it will be equal to name.trim()
name = name == null ? "" : name.trim();
that means
String name;
//You performed some processing here, your logic.
if(name==null){
name="";
}
else{
name=name.trim();
}
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
So i was just wondering if there was actually a name for this if-statement:
public void checkEvenNumber(number) {
return ((number % 2 == 0) ? true : false)
}
Or if it is just called an if-statement.
Yes. That's an example of a ternary operator.
JLS-15.25 Conditional Operator ? : describes it as,
The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.
It is called a terniary operator. However in this case, terniary operator isn't needed as the function it can be simplified to look like this:
public boolean isEvenNumber(int number) {
return number % 2 == 0;
}
Please note that I changed the name of the function to match what it actually does.
The ternary operator, so-called as it has 3 components:
The condition
The expression returned if it's true
The expression returned if it's false
that's a function (as i recognize it), you pass parameter(s) to it and it is passes it/them down to the function (where you do your stuff) and it returns only 1 variable.
You may also refer it as inline if statement
Here's a link for your reading up: http://en.wikipedia.org/wiki/%3F:
If you are familiar with how if-statements work in MS Excel, it shouldn't be too hard to understand.
By the way, your code should change to:
public void checkOddNumber(number) {
return ((number % 2 != 0) ? true: false)
}
This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 8 years ago.
I've been trying to Google it, but googling the key "?" doesn't really work out that good.
I really want to know what it does and when to use it.
Thanks!
I've seen it a couple times, but here is an example of one I just saw
String name = perms.calculateRank().getColor() + player.getName();
//This is a custom ranking system ^
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
player.setDisplayName(name + ChatColor.RESET);
Chat.sendMessage(player, "Tab Name Set");
This is a ternary operator. In Java specifically, it is called the Conditional Operator. It is a way of writing short-hand simple if..else statements. For example:
if (a == b) {
c = 123;
} else {
c = 456;
}
is the same as:
c = a == b ? 123 : 456;
It is also used for a wildcard generic.
public List<?> getBizarreList();
The ternary operator someBoolean ? x : y evaluates to x if someBoolean is true, and y otherwise.
It is called ternary operator and it is only operator that takes 3 operands. In better sense, it is conditional operator that represent shorter format
General Syntax :
boolean expression ? value1 : value2
your example:
player.setPlayerListName(name.length() > 15 ? name.substring(0, 16) : name);
as same as
if( name.length() > 15)
player.setPlayerListName(name.substring(0, 16));
else
player.setPlayerListName(name);
This question already has answers here:
Java logical operator short-circuiting
(10 answers)
Closed 8 years ago.
I am not convinced why below statement is valid and does not throw exception.
ArrayList <String> some_list = null;
if (some_list != null && some_list.size() > 0) {
// do something...not important if I get here or not.
}
some_list is null, and first check in if() is valid, but what about getting size on a null reference?
isn't this illegal ?
or does it work this way:
if (codition1 && condition2) {
}
only if condition1 is true check condition2 ?
since I am not convinced , although I confirmed by writing test code. I always do like below:
if (some_list != null) {
if (some_list.size() > 0) {
}
}
Please help me understand the logical && and null point checking in if statement.
Thank you.
&& is "short circuiting". The expression on the right is never executed if the expression on the left evaluates to false.
The same is true for ||, which never executes the expression on the right if the expression on the left is true.
& and | are normally used for bit operations on integers, but can also be used on booleans. These are not short-circuiting. If you had done
if ((some_list != null) & (some_list.size() > 0)) {
then it would have failed in exactly the way you're asking about.
I know you can have
String answer = (5 == 5) ? "yes" : "no";
Is it somehow possible to have only:
String answer = (5 == 5) ? "yes";
It gives a compile error when I try.
NOTE: (5==5) is just an example. In its place will be statement which could be either true or false.
if one line is important
String answer = (5 == 5) ? "yes": null;
Since a String's default value is null.
You're looking for an if statement:
if (5 == 5)
answer = "yes";
Your idea is impossible because an expression (such as the conditional value) must always have a value.
In your code, if 5 != 5, the expression would have no value, which wouldn't make any sense.
No. you can't have it. You need to specify both the ? and :.
Use a straight if.