Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like to understand how can the int x be incremented inside an if (Boolean expression) for every loop iteration
How is that possible?? How does it work?
public class MethodsTest {
public static void main(String[] args) {
int x= 0;
for (int z = 0; z < 5; z++)
{
if(x++ > 2){
}
System.out.println(x);
}
}
}
the output will be
1
2
3
4
5
x++ is a compound assignment operator, which is equivalent to x = x + 1, with the side effect taking place after the evaluation. Therefore, the if statement is equivalent to a pair of statements like this:
if(x > 2) {
x = x + 1;
// At this point, the side effect has taken place, so x is greater than it was before the "if"
...
} else {
// The side effect takes place regardless of the condition, hence the "else"
x = x + 1;
}
Note that this code is forced to repeat the x = x + 1 part. Using ++ lets you avoid this repetition.
There is a pre-increment counterpart of x++ - namely, ++x. In this form the assignment takes place before the expression is evaluated, so the condition becomes
if ((x = x + 1) > 2) {
// Note that the condition above uses an assignment. An assignment is also an expression, with the result equal to
// the value assigned to the variable. Like all expressions, it can participate in a condition.
}
To break your notion that the condition of an if can't "do things", imagine that you have a function that returns a boolean, like:
boolean areThereCookies(int numCookies)
{
return numCookies > 0;
}
then you could use it in your if statement:
if (areThereCookies(cookies))
{
eatCookies(cookies);
}
However the method areThereCookies(int) that we are calling to evaluate the if condition could be making anything in the world. It could change variable values, read input, write output, steal cookies...
So the language is perfectly capable of "doing things" in the if evaluation. The other answers explain what your code was specifically doing.
Cheers.
You are allowed to have expressions inside a if statement as long as the expression resolves to a boolean. For example,
int i = 0
if (i = i + 1)
is not a valid expression inside an if statement because the expressions resolves to 1, which is an integer.
However,
int i = 0
if (2 == i = 2)
is a valid expression because 2 is first assigned to the variable i and then is compared to 2, and thus the expression resolves to “true”.
In your example if statement, you have a post-incremented variable x that is compared against 2 with the greater than operator, resulting in a boolean value, and thus it is a valid expression. Hotlinks has described what a post-incremented variable is in the comments.
Related
I was going through some exercises but I am confused in this one:
public static int f (int x, int y) {
int b=y--;
while (b>0) {
if (x%2!=0) {
--x;
y=y-2;
}
else {
x=x/2;
b=b-x-1;
}
}
return x+y;
}
What is the purpose of b=y--?
So, for example, x=5 and y=5
when we first go inside of while loop (while (b>0)) will b = 4 or 5? When I am running the code in my computer b is 5. And the return is 3. It is really unclear to me. Sorry if I am unclear in my question.
int b=y--; first assignes b=y and then decrements y (y--).
Also take a look at the prefix/postfix unary increment operator.
This example (taken from the linked page) demonstrates it:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
// prints 4
System.out.println(i);
++i;
// prints 5
System.out.println(i);
// prints 6
System.out.println(++i);
// prints 6
System.out.println(i++);
// prints 7
System.out.println(i);
}
}
The difference between a post-increment/decrement and a pre-increment/decrement is in the evaluation of the expression.
The pre-increment and pre-decrement operators increment (or decrement) their operand by 1, and the value of the expression is the resulting incremented (or decremented) value. In contrast, the post-increment and post-decrement operators increase (or decrease) the value of their operand by 1, but the value of the expression is the operand's original value prior to the increment (or decrement) operation.
In other words:
int a = 5;
int b;
b = --a; // the value of the expression --a is a-1. b is now 4, as is a.
b = a--; // the value of the expression a-- is a. b is still 4, but a is 3.
Remember that a program must evaluate expressions to do everything. Everything is an expression, even just a casual mention of a variable. All of the following are expressions:
a
a-1
--a && ++a
System.out.println(a)
Of course, in the evaluation of expressions, operator precedence dictates the value of an expression just as the PEMDAS you learned in grade school. Some operators, such as increment/decrement, have side effects, which is of course great fun, and one of the reasons why functional programming was created.
I believe b would equal 5 entering the loop because
b=y--;
When the "--" is behind the variable it decrements it after the action.
It's poor coding, as it can confuse new programmers.
The function, assuming it is passing by value, like in the example above (as opposed to passing by reference) takes a copy of y, decrements it, and assigns it to b. It does not alter the argument passed to the function when it was called.
Post increment
x++;
x += 1;
Post decrement
x--;
x -=1;
Pre increment : ++x;
Pre decrement : --x;
According to the Head First Java:
Difference between x++ and ++x :
int x = 0; int z = ++x;
Produces: x is 1, x is 1
in x = 0; int z = x++;
Produces: x is 1, z is 0
I was asked a question what the difference is between having counter += 5 and counter + 5 in the java programming language. I said they essentially do the same thing but I did not know how to explain why. I felt one was considered a shorthand representation of the same problem but now thinking about it more, I feel I am not correct. Can anyone give me a simple explanation the difference between them?
counter += 5 modifies counter. counter += 5 can be used as a statement (e.g. line of code) on its own, because it does something (increments counter by 5).
counter + 5 does not modify anything. counter + 5 can only be used as an expression within a statement, because it doesn't do anything on its own.
Here is some code that demonstrates the difference:
int counter = 1;
System.out.println(counter + 5); // 6
System.out.println(counter); // 1
// counter + 5; // not a valid statement
counter += 5; // counter is now 6
System.out.println(counter); // 6
System.out.println(counter += 5); // 11
System.out.println(counter); // 11
counter += 5 is assigning the value of whatever counter was plus 5 to the counter variable while counter+5 is return the result of 5 plus counter but the counter variable stays the same.
+= operator
For example you have a a variable counter that equals 3. When you do counter += 5, you are actually assigning a new value to the variable counter. so if counter was 5 and you do counter+=3, counter will now equal 8.
+ operator without the equal
In this case if your counter equals 3. when you do counter+3 it will return 8 for that instance but your counter will still be 3.
Code to demonstrate the differences:
int counter = 3;
counter += 5;
int y = 0;
/*this will return 8, since the result of 5 and counter was newly assigned to
counter*/
System.out.println(counter);
//resetting counter value.
counter =3;
y = counter+5;
//here counter still remains at 3, because there wasn't anything assigned to it
System.out.println(counter);
//will return 8, because you assigned the result of counter and 5 to y.
System.out.println(y);
Only the JLS holds the true answer!
(Assuming count is a numeric type. If it's a String, for example, then everything everyone told you above is wrong at the time I wrote this.)
+= operator
JLS 15.26.2 Compound Assignment Operators:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
following,
[...] the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator.
[...] the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (§5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.
(emphasis mine). In the above above notation, E1 and E2 will perform the operation indicated by += (meaning E1 + E2). The result is stored in E1.
+ operator
JLS 15.18.2. Additive Operators (+ and -) for Numeric Types:
The binary + operator performs addition when applied to two operands of numeric type, producing the sum of the operands.
Note that there is no assignment here.
counter += 5 is the one that is shorthand, but it's shorthand for counter = counter + 5. counter + 5 is just an expression, what you get is a value that is 5 greater than the value of counter, but this value is just left behind and nothing is done with it. In order for something else to happen, an additional operator needs to be present, such as the =, or assignment operator. This operator takes an expression on the right hand side and an identifier on the left, evaluating the expression and assigning the result to the identifier. Without assignment, values don't change, and even when you use methods that seem to change values without assignment (String.append() for example) there is an assignment hidden in the code of the function. As an added fact, counter += 5 can be reduced (if you really want to call it reducing it) to counter++ used 5 times.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
This is classical, but writing to Google did not give me hits.
My code:
Integer i = ..; // Sth is put from database.
if (i != 1) {
// do sth
} else {
// do not.
}
Case:
I know that this comparison is not correct java and I should compare:
if (i.intValue != 1) {}
or
if(!i.equals(1)) {}
but my code had the first one and I seem to get the true from somewhere, where the Integer is not 1 and when it is 1 there comes false.
Question:
What is happening there around?
but my code had the first one and I seem to get the true from somewhere, where the Integer is not 1 and when it is 1 there comes false.
If I understand your issue correctly, the following might explain the behavior:
Integer i = 1;
Integer j = new Integer(1);
Integer k = Integer.valueOf(1);
System.out.println(i == j); // false
System.out.println(i == k); // true
In other words, you can get both true or false when comparing with 1 depending on how the Integer was constructed. Integer.valueOf will reuse objects while new Integer will not.
If you indeed did the comparison with an integer literal (or with an int) then any Integer should be automatically unboxed by the compiler, and you should never get any surprises.
The compiler changes :
if (i != 1)
to
if(i.intValue()!=1)
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
See this link
if (i != 1) , if (i.intValue != 1) and if(!i.equals(1)) are all equal and will return the same value. The compiler will automatically unbox i, turning it into a primitive int.
This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
public class main {
public static void main(String[] args) {
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
System.out.printf("%d %d\n",x,y);
}
//Output : 56,93
#include<stdio.h>
void main()
{
int x=20,y=35;
x = y++ + x++;
y = ++y + ++x;
printf("%d %d ",x,y);
}
//Output : 57 94
According to Operator Precedence Rules whatever output I got through Java code is right but when executing the same in 'C' code it incremented the output values by 1. I am using ubuntu 12.04 64-bit Operating System.
It's not the same thing because Java and C are different languages.
The behaviour of post increment in Java is defined as performing the increment after the expression has been evaluated.
The behaviour in C is undefined but often follows the order of precedence.
Note: order of evaluation and precedence are different things and this is more obvious for post increment/decrement and short cut boolean operations.
e.g.
Sting s = null;
if (s == null || !(s.length() > 0))
In this case ! has the highest precedence, but in reality will never be evaluated because the lower precedence || prevents it.
Precedence only determines where the implied brackets are, but only suggest how the expression might be evaluated.
I'm doing some small program for a beginners programming course and in my program I have 2 variables which hold numbers. Anyway I need to find out which number is bigger and print the appropriate message according to it, for example I have:
int x = 5;
int y = 10;
I need to print:
"it is true that y is bigger than x";
Now the thing is that I know I can use a simple if statement but I'm not allowed to use it, now it makes me wonder, is it even possible? If so, how can I do that? How can I check which number is bigger WITHOUT doing something like:
if (x > y)
answer = true;
...
Thanks in advance.
Well you can do:
boolean answer = x > y;
The expression x > y is just an expression of type boolean. While boolean expressions are often used for conditions in if statements, loops etc, they don't have to be - simple assignment works fine too.
It sounds like you want the reverse though:
boolean answer = y > x;
Then you can use the value of answer to build the string to display...
Use the ternary operator:
System.out.println(x > y ? "It is true that x is greater than y" : "");
ternary operator "?:"
String output = (x > y)? "x is greater than y":"y is greater than x";
The ternary conditional operator that others mentioned will work. Assuming you are looking for creative ways to do this rather than practical ones, here's another method:
int x = 5;
int y = 10;
while(y > x){
System.out.println("It is true that y is bigger than x.");
return;
}
System.out.println("It is false that y is bigger than x.");
The while is just acting as a fancy if, because the return means the otherwise infinite loop will only execute at most once.
Here's another example that instead relies upon short-circuit boolean evaluation:
public static void main(String...args){
int x = 5;
int y = 10;
boolean answer = (y > x);
boolean testTrue = answer && printTrue();
boolean testFalse = testTrue || printFalse();
}
private static boolean printFalse() {
System.out.println("It is false that y is bigger than x.");
return true;
}
private static boolean printTrue() {
System.out.println("It is true that y is bigger than x.");
return true;
}
Of course you shouldn't do this in real production code, but it can be fun to think of unorthodox ways to code something and it can be helpful for exploring the language.
Your question is tagged as Java but you do not specify Java in your question. In Java there are multiple ways to get the same result that involve testing the boolean expression x > y somehow, such as the ternary operator. I would consider these equivalent to an explicit if statement.
Other possibilities:
Compute the square root of x - y. This will raise an exception if y is bigger. Catch the exception in the caller and report that y is the larger quantity. If there is no exception, report that x is the larger.
In LISP, Ruby or another language that supports the symbol type, form a list ((symbol x, x), (symbol y, y)) and sort the list. Then report the second symbol as the variable with the larger value.
If using assembly, BASIC, PL/1, etc. you can use an arithmetic expression to choose the target of a GOTO statement. Depending on whether x or y is larger, execution will resume at a different part of the code. Or use the list-sorting trick in the previous bullet to select the GOTO label.
In general, the expression ((x - y) / abs(x - y) + 1) / 2 will produce 1 if x is larger and 0 if y is larger. This result could be used to choose data, a function, etc. out of a list of two alternatives, producing conditional behavior without an if statement.
You could use recursion (but I would not recommend it)
public int compare ( int a , int b )
{
switch ( a )
{
case Integer.MIN_VALUE :
switch ( b )
{
case Integer.MIN_VALUE :
return 0 ;
default :
return -1 ;
}
default :
switch ( b )
{
case INteger.Min_VALUE :
return 1 ;
default :
return compare ( a-1 , b-1 ) ;
}
}
}
(a+b)/2 + Abs(a-b)/2 is the bigger number.
I know in some languages you can use short-circuit evaluation to construct the answer.
The expression (A && B) always evaluates to B if A is true. If A is false then B is never evaluated.
Similarly (A || B) evaluates to B if A is false. If A is true B is never evaluated.
Though I'm not 100% sure of Java, the expression you want is:
String output = ((x > y) && "it is true that X is greater than Y")
|| (((x < y) && "it is true that X is less than Y")
|| "it is true that X is equal to Y");