Computer Applications
Determine the output of the following program.
public class PredictOutput1
{
public static void main(String args[])
{
int a = 4, b = 2, c = 3;
System.out.println("Output 1: " + (a = b * c));
System.out.println("Output 2: " + (a = (b * c)));
}
}
Answer
Output
Output 1: 6
Output 2: 6
Explanation
In the first println statement, the expression is (a = b * c)
. * has higher precedence than = so first b and c are multiplied and after that the result is assigned to a. Assignment operator returns the value of the assignment so the result of this (a = b * c)
entire expression is 6.
In the second println statement, the expression is (a = (b * c))
. Putting b * c in brackets causes b * c to be evaluated first but the result is same as the first println statement as * has higher precedence than =
Related Questions
Determine the output of the following program.
public class PredictOutput3 { public static void main(String args[]) { int a = 2, b = 2, c = 2; System.out.println("Output 1: " + (a + 2 < b * c)); System.out.println("Output 2: " + (a + 2 < (b * c))); } }
Determine the output of the following program.
public class PredictOutput2 { public static void main(String args[]) { int a = 6, b = 2, c = 3; System.out.println("Output 1: " + (a == b * c)); System.out.println("Output 2: " + (a == (b * c))); } }
What is the difference between the following two statements in terms of execution? Explain the results.
x -= 5;
x =- 5;What is concatenation? On which data type is concatenation performed?