Why is the output 25?
// CODE 1
public class YourClassNameHere {
public static void main(String[] args) {
int x = 8;
System.out.print(x + x++ + x);
}
}
Hi!
I am aware that the above code will print 25. However, I would like to clarify on how x++ will make the statement be 8 + 9 + 8 = 25.
If we were to print x++ only as such, 8 will be printed while x will be 9 in-memory due to post incrementation.
// CODE 2
public class YourClassNameHere {
public static void main(String[] args) {
int x = 8;
System.out.print(x++);
}
}
But why is it that in code 1 it becomes 9 ultimately?
I thank you in advance for your time and explanation!
Here is a good way to test the reason that equals to 25 is because the third x is equal to 9.
public class Main {
public static void main(String[] args) {
int x = 8;
System.out.println(printPassThrough(x, "first") + printPassThrough(x++, "second") + printPassThrough(x, "third"));
}
private static int printPassThrough(int x, String name) {
System.out.println(x + " => " + name);
return x;
}
}
Result
8 => first
8 => second
9 => third
25
I think it's worth of clarify:
x++ -> operate x , and then increment x (meaning x=x+1)
++x -> increment x (meaning x=x+1) , and then operate x
x-- -> operate x , and then decrement x (meaning x=x-1)
--x -> decrement x (meaning x=x-1) , and then operate x
Related
This question already has an answer here:
Why in one case multiplying big numbers gives a wrong result?
(1 answer)
Closed 2 years ago.
I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
Output: 2043765249
But normally answer is: 13561255518721
If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE which is 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
You may use a bigger type like double or BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
You're using an int for the answer, you're getting a numeric overflow.
Use double or long or BigInteger for y and you'll get the right answer.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919*1919*1919*1919);
}
}
Outputs the same value.
Use long instead of int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
Read about variables in Java.
I am having trouble grasping four different return statement problems in java which deal with integers. They usually go by the names of "mystery" and "enigma". I have tried solving them numerous times, and the web and my text book do not contain any similar examples for me to work with. My gut feeling is I am missing something with the logic. If someone can maybe just explain on of the problems (preferably the hardest one), I am sure I will understand it. I apoligise in advance if the format is not on par with this site's requirements, since it is my first time posting.
1 public class Program 1{
2
3 public static int y = 2;
4
5 public static int mystery(int x, int y) {
6 y = y + x;
7 return x + y;
8 }
9
10 public static void main(String[] args) {
11 int x = 1;
12 x = mystery(x, y);
13 y = mystery(y, x);
14 System.out.println(x + " " + y);
15 }
16}
17 // Answer : 4 8
I get x to be 4, but I struggle to get y to be 8.
1 public class Program 2{
2
3 public static int y = 2;
4
5 public static int mystery(int a, int b) {
6 y = b + a;
7 return a + b;
8 }
9
10 public static void main(String[] args) {
11 int x = 1;
12 x = mystery(x, y);
13 y = mystery(y, x);
14 System.out.println(x + " " + y);
15 }
16}
17 // Answer : 3 6
I get x to be 3, but I struggle to get y to be 6.
1 public class Program 3{
2
3 public static int x = 1;
4 public static int y = 2;
5
6 public static int mystery1(int a, int b) {
7 x = a + b;
8 return b + a;
9 }
10
11 public static int mystery2(int a, int b) {
12 y = b + a;
13 x = mystery1(a, b);
14 return a + b;
15 }
16
17 public static void main(String[] args) {
18 x = mystery2(x, y);
19 System.out.println(x + " " + y);
20 }
21
22}
23 // Answer : 3 3
I get x to be 3, but I struggle to get y to be 3.
public class Enigma {
public static int x = 1;
public static int y = 2;
public static int n = 0;
public static int aaa(int a, int b) {
n++;
return a + b;
}
public static int bbb(int a, int b) {
n++; x = aaa(x, a); y = aaa(y, b);
return x + y;
}
public static void ccc(int x, int q) {
n++; x = bbb(1, x); y = bbb(2, q);
}
public static void main(String[] args) {
int x = aaa(3, y);
y = bbb(x, y); ccc(x, 1);
System.out.println(x + " " + y + " " + n);
// Answer : 5 25 11
I get x to be 5, but I struggle to get y = 25 and n = 11, although incrementing n at each method is probably the reason why.
Try to make things less confusing by not keep using the same variables. For example, in main program, create new variables (lets say a and b) and instead write "int a=mystery(x,y);" and "int b=mystery(y,x);" for program 1.
1) Lets first solve the problem you have in Program 1. First the program runs code line 12, which is x=mystery(x,y), and x is 1, y=2.
2) So x=mystery(1,2). When you run that, you assign y=y+x, y is still 2, and x is still 1, 2+1=3, therefore now y is 3 and x is still 1.
3) Then you tell the program to return y+x, or 3+1, and you assign it to x. Now x=4 and y is 3.
4)Your program runs line 13, with y=3 and x=4, therefore y=(3,4). So y=y+x is y=3+4, or 7.
5) THIS IS WHEN YOU MESSED UP! you expected x to still be 1, but it isn't anymore, it is 4, and therefore you get 11.
Please leave a comment if you don't understand. If possible, please tell me where you get stuck by using the numbering I provided :) Good luck
Program1:
x = mystery(x, y) -> returning 4 , so x=4, your class y stays 2(if you want to access class y, use 'this' keyword.
y = mystery(y, x) -> mystery(2,4) returning 2+6=8
Program2:
x = mystery(x, y) -> class y is now 3, returning 3, x=3
y = mystery(y, x) -> mystery(3,3) returning 6
Program3:
x = mystery2(x, y) -> class y is now 3, mystery1(1, 2) -> returning 3, so class x=3
Enigma:
int x = aaa(3, y) -> returning 5, n=1
y = bbb(x, y) -> n=4, x=6, y=4, returns 10. So class y=10
In method ccc, n becomes 11 (1+3+3).
Note that in method ccc you're shadowing the class member x. instead it is the local one from the parameter.
If I only put y>x; y--; in the inner loop it prints 5432 but when I put y>=x; y--; in the inner loop it prints 54321. What happened there?
What does y>=x; y--; mean? It means y is greater than or equal to x right? But why did it print 54321?
public class TestClass {
public static void main (String[] args) {
int x;
int y;
for(x=1; x<=5; x++){
for(y=5; y>=x; y--){
System.out.print(y);
}
System.out.println();
}
}
}
if y > x and x is 1 then 1 will not be included in you printed list as y will never be less then x which is 1. When you made it = x then you allowed 1 to be allowed by y
Here is my Java code:
public class Prog1 {
public static void main(String[] args) {
int x = 5;
while (x > 1) {
x = x + 1;
if (x < 3)
System.out.println("small x");
}
}
}
And this is the output:
small x
I was expecting an infinite loop... Any idea why it is behaving this way?
There is an infinite loop. Just in some time, x get so bit that it overflows the limit of a signed int, and it goes negative.
public class Prog1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) {
x = x + 1;
System.out.println(x);
if(x < 3)
System.out.println("small x");
}
}
}
x starts out 5. Then as you loop through it goes to 6, 7, 8, etc. Eventually it hits the largest possible int. The next x=x+1 sets it to the most negative int, negative 2 billion-whatever. This is less than 3 so the message is output. Then you execute the while condition again which now fails, exiting the loop.
So while it appears to be an infinite loop, it isn't really.
Is this a homework problem? Why would you have written such odd code?
Java integers are signed, and they overflow (as in C and many other languages).
Try this to check this behaviour:
public class TestInt {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
System.out.println(x);
x++;
System.out.println(x);
}
}
X is overflowing the limits of an int. Check the value by adding a println statement for x
public static void main(String[] args) {
// TODO Auto-generated method stub
int x = 5;
while (x > 1) {
x = x + 1;
if(x < 3){
System.out.println(x);
System.out.println("small x");
}
}
My jvm showed x as -2147483648
Is there a difference between ++x and x++ in java?
++x is called preincrement while x++ is called postincrement.
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
yes
++x increments the value of x and then returns x
x++ returns the value of x and then increments
example:
x=0;
a=++x;
b=x++;
after the code is run both a and b will be 1 but x will be 2.
These are known as postfix and prefix operators. Both will add 1 to the variable but there is a difference in the result of the statement.
int x = 0;
int y = 0;
y = ++x; // result: x=1, y=1
int x = 0;
int y = 0;
y = x++; // result: x=1, y=0
Yes,
int x=5;
System.out.println(++x);
will print 6 and
int x=5;
System.out.println(x++);
will print 5.
In Java there is a difference between x++ and ++x
++x is a prefix form:
It increments the variables expression then uses the new value in the expression.
For example if used in code:
int x = 3;
int y = ++x;
//Using ++x in the above is a two step operation.
//The first operation is to increment x, so x = 1 + 3 = 4
//The second operation is y = x so y = 4
System.out.println(y); //It will print out '4'
System.out.println(x); //It will print out '4'
x++ is a postfix form:
The variables value is first used in the expression and then it is incremented after the operation.
For example if used in code:
int x = 3;
int y = x++;
//Using x++ in the above is a two step operation.
//The first operation is y = x so y = 3
//The second operation is to increment x, so x = 1 + 3 = 4
System.out.println(y); //It will print out '3'
System.out.println(x); //It will print out '4'
Hope this is clear. Running and playing with the above code should help your understanding.
I landed here from one of its recent dup's, and though this question is more than answered, I couldn't help decompiling the code and adding "yet another answer" :-)
To be accurate (and probably, a bit pedantic),
int y = 2;
y = y++;
is compiled into:
int y = 2;
int tmp = y;
y = y+1;
y = tmp;
If you javac this Y.java class:
public class Y {
public static void main(String []args) {
int y = 2;
y = y++;
}
}
and javap -c Y, you get the following jvm code (I have allowed me to comment the main method with the help of the Java Virtual Machine Specification):
public class Y extends java.lang.Object{
public Y();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_2 // Push int constant `2` onto the operand stack.
1: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
2: iload_1 // Push the value (`2`) of the local variable at index `1` (`y`)
// onto the operand stack
3: iinc 1, 1 // Sign-extend the constant value `1` to an int, and increment
// by this amount the local variable at index `1` (`y`)
6: istore_1 // Pop the value on top of the operand stack (`2`) and set the
// value of the local variable at index `1` (`y`) to this value.
7: return
}
Thus, we finally have:
0,1: y=2
2: tmp=y
3: y=y+1
6: y=tmp
When considering what the computer actually does...
++x: load x from memory, increment, use, store back to memory.
x++: load x from memory, use, increment, store back to memory.
Consider:
a = 0
x = f(a++)
y = f(++a)
where function f(p) returns p + 1
x will be 1 (or 2)
y will be 2 (or 1)
And therein lies the problem. Did the author of the compiler pass the parameter after retrieval, after use, or after storage.
Generally, just use x = x + 1. It's way simpler.
Yes.
public class IncrementTest extends TestCase {
public void testPreIncrement() throws Exception {
int i = 0;
int j = i++;
assertEquals(0, j);
assertEquals(1, i);
}
public void testPostIncrement() throws Exception {
int i = 0;
int j = ++i;
assertEquals(1, j);
assertEquals(1, i);
}
}
Yes, using ++X, X+1 will be used in the expression. Using X++, X will be used in the expression and X will only be increased after the expression has been evaluated.
So if X = 9, using ++X, the value 10 will be used, else, the value 9.
If it's like many other languages you may want to have a simple try:
i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check
If the above doesn't happen like that, they may be equivalent
Yes, the value returned is the value after and before the incrementation, respectively.
class Foo {
public static void main(String args[]) {
int x = 1;
int a = x++;
System.out.println("a is now " + a);
x = 1;
a = ++x;
System.out.println("a is now " + a);
}
}
$ java Foo
a is now 1
a is now 2
OK, I landed here because I recently came across the same issue when checking the classic stack implementation. Just a reminder that this is used in the array based implementation of Stack, which is a bit faster than the linked-list one.
Code below, check the push and pop func.
public class FixedCapacityStackOfStrings
{
private String[] s;
private int N=0;
public FixedCapacityStackOfStrings(int capacity)
{ s = new String[capacity];}
public boolean isEmpty()
{ return N == 0;}
public void push(String item)
{ s[N++] = item; }
public String pop()
{
String item = s[--N];
s[N] = null;
return item;
}
}
Yes, there is a difference, incase of x++(postincrement), value of x will be used in the expression and x will be incremented by 1 after the expression has been evaluated, on the other hand ++x(preincrement), x+1 will be used in the expression.
Take an example:
public static void main(String args[])
{
int i , j , k = 0;
j = k++; // Value of j is 0
i = ++j; // Value of i becomes 1
k = i++; // Value of k is 1
System.out.println(k);
}
The Question is already answered, but allow me to add from my side too.
First of all ++ means increment by one and -- means decrement by one.
Now x++ means Increment x after this line and ++x means Increment x before this line.
Check this Example
class Example {
public static void main (String args[]) {
int x=17,a,b;
a=x++;
b=++x;
System.out.println(“x=” + x +“a=” +a);
System.out.println(“x=” + x + “b=” +b);
a = x--;
b = --x;
System.out.println(“x=” + x + “a=” +a);
System.out.println(“x=” + x + “b=” +b);
}
}
It will give the following output:
x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17
public static void main(String[] args) {
int a = 1;
int b = a++; // this means b = whatever value a has but, I want to
increment a by 1
System.out.println("a is --> " + a); //2
System.out.println("b is --> " + b); //1
a = 1;
b = ++a; // this means b = a+1
System.out.println("now a is still --> " + a); //2
System.out.println("but b is --> " + b); //2
}
With i++, it's called postincrement, and the value is used in whatever context then incremented; ++i is preincrement increments the value first and then uses it in context.
If you're not using it in any context, it doesn't matter what you use, but postincrement is used by convention.
There is a huge difference.
As most of the answers have already pointed out the theory, I would like to point out an easy example:
int x = 1;
//would print 1 as first statement will x = x and then x will increase
int x = x++;
System.out.println(x);
Now let's see ++x:
int x = 1;
//would print 2 as first statement will increment x and then x will be stored
int x = ++x;
System.out.println(x);
Try to look at it this way:
from left to right do what you encounter first. If you see the x first, then that value is going to be used in evaluating the currently processing expression, if you see the increment (++) first, then add one to the current value of the variable and continue with the evaluation of the expression. Simple