return : ? statement in Java [duplicate] - java

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Java: boolean in println (boolean ? "print true":"print false") [duplicate]
(11 answers)
Closed 8 years ago.
I was looking through the java source code, ArrayList.java->hugeCapacity, when I found something I'd never seen before:
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
I looked on this site before posting this question and found nothing helpful. I also looked at the docs for return(), but I had no success. Perhaps I'm looking for the wrong thing.
Anyways, what is that return statement doing?

It's not a special statement. It's ternary statement :
(condtion) ? value_if_true : value_if_flase;
You also can use it to put a value in a variable
string res = ( i < 3 ) ? "i < 3" : "i > 3";
it's a short way to write :
string res;
if(i<3)
res = "i < 3";
else
res = "i > 3";

return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
here return is having ternary operator passed to it. and it works similar to if-else
if(minCapacity > MAX_ARRAY_SIZE){
return Integer.MAX_VALUE;
}
else{
return MAX_ARRAY_SIZE;
}

The syntax
testStatement ? (return if true) : (return if false)
is a standard way of doing an if statement in one line. Basically you have a test (usually checking the value of a variable). If it tests true, the first statement after the test is executed. If it is false, the second statement (after the colon ':') is executed. It replaces the following:
if (statement) {
<return this value if true>;
} else {
<return this value if false>;
}

Related

what is the meaning and use of line... int ct = count.containsKey(ch) ? count.get(ch) : 0; in the code? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

question regarding recursive returns from java method [duplicate]

This question already has answers here:
Short form for Java if statement
(16 answers)
Closed 3 years ago.
Can anyone tell me what this statement means? getHead is the first integer in an integer list:
return (a.getHead() > m)? a.getHead():m;
Thank you
It's the same as the following:
if((a.getHead() > m))
return a.getHead();
else
return m;
This is the idea behind it:
if ' evaluate condition' ? 'what to do if condition is true' : 'what to do if condition is false'
... ? ... : ... is a ternary conditional.
The code you posted can be turned into
if (a.getHead() > m) {
return a.getHead();
} else {
return m;
}
That code will return the whichever is larger: the head of the list or m.

explanation of a for loop java code [duplicate]

This question already has answers here:
What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]
(7 answers)
Closed 8 years ago.
Could someone give me a detailed explanation of what's going on here; I'm getting confused by the ?:
for (int i = 0; i < datasize; i++) {
String data1value = data1.size() > i ? data1.get(i) : null;
String data2value = data2.size() > i ? data2.get(i) : null;
String data3value = data3.size() > i ? data3.get(i) : null;
The ternary operator is being used to prevent getting an IndexOutOfBoundsException here. If the size of the Collection is > than current index i, it assigns that value through get(i), otherwise it assigns null.
If you had assigned the values directly as
String data1value = data1.get(i);
your code could break if the loop runs for more than the number of items in the Collection.
The ? : operator in Java is an expression which returns one of two values.
In Java you might write
if (a > b) {
max = a;
}
else {
max = b;
}
Setting a single variable to one of two states based on a single condition is such a common use of if-else that a shortcut has been devised for it, the conditional operator, ?:. Using the conditional operator you can rewrite the above example in a single line like this:
max = (a > b) ? a : b;
They are used be the reason presented in the response from Ravi Thapliyal.

Could someone explain this bit of code to me (simple) [duplicate]

This question already has answers here:
What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]
(7 answers)
Closed 7 years ago.
I have these two methods. I understand the "getTotalSalary" one but don't really get the way in which "getAverageSalary" is written. I don't understand why the question mark and colon is used as well as the "(size() != 0)" and 0 at the end.
This is the coding:
public double getTotalSalary() {
double total = 0;
for (Employee e : empReg) {
total = total + e.getSalary();
}
return total;
}
public double getAverageSalary() {
return (size() != 0) ? this.getTotalSalary() / this.size() : 0;
}
empReg is the name of the ArrayList. Employee is a class which consists of "name" and "salary". getSalary is obviously a method returning the salary.
The question mark is called the ternary operator, and it is used to make a decision based on an evaluation. It is often used to replace if statements, since they do the same thing. For example, an if statement with that would be written:
if (size != 0)
return this.getTotalSalary() / this.size();
else
return 0;
In my experience, I only use it if I want to reduce the code size. However, it does make the code a bit more difficult to read.
You cannot divide by zero.
? and : is a ternary operator. It means that if the expression before ? is true, then this.getTotalSalary() / this.size()will be returned, otherwise return 0.
It's called ternary operator in java, here you have some examples: http://alvinalexander.com/java/edu/pj/pj010018
See this discussion: What is a Question Mark "?" and Colon ":" Operator Used for?
It explains
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;

What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 7 years ago.
Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.
int row = 10;
int column;
while (row >= 1)
{
column = 1;
while(column <= 10)
{
System.out.print(row % 2 == 1 ? "<" : "\r>");
++column;
}
--row;
System.out.println();
}
This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.
Here's a good example from Wikipedia demonstrating how it works:
A traditional if-else construct in C, Java and JavaScript is written:
if (a > b) {
result = x;
} else {
result = y;
}
This can be rewritten as the following statement:
result = a > b ? x : y;
Basically it takes the form:
boolean statement ? true result : false result;
So if the boolean statement is true, you get the first part, and if it's false you get the second one.
Try these if that still doesn't make sense:
System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");
Thats an if/else statement equilavent to
if(row % 2 == 1){
System.out.print("<");
}else{
System.out.print("\r>");
}
a=1;
b=2;
x=3;
y=4;
answer = a > b ? x : y;
answer=4 since the condition is false it takes y value.
A question mark (?)
. The value to use if the condition is true
A colon (:)
. The value to use if the condition is false
Also just though I'd post the answer to another related question I had,
a = x ? : y;
Is equivalent to:
a = x ? x : y;
If x is false or null then the value of y is taken.
Maybe It can be perfect example for Android,
For example:
void setWaitScreen(boolean set) {
findViewById(R.id.screen_main).setVisibility(
set ? View.GONE : View.VISIBLE);
findViewById(R.id.screen_wait).setVisibility(
set ? View.VISIBLE : View.GONE);
}
They are called the ternary operator since they are the only one in Java.
The difference to the if...else construct is, that they return something, and this something can be anything:
int k = a > b ? 7 : 8;
String s = (foobar.isEmpty ()) ? "empty" : foobar.toString ();
it is a ternary operator and in simple english it states "if row%2 is equal to 1 then return < else return /r"

Categories