Try to predict the output of following code:
The output is
This unpredictable output is due the fact that the compiler evaluates the given expression from left to right given that the operators have same precedence. Once it encounters the String, it considers the rest of the expression as of a String (again based on the precedence order of the expression).
- System.out.println(2 + 0 + 1 + 6 + “GeeksforGeeks”); // It prints the addition of 2,0,1 and 6 which is equal to 9
- System.out.println(“GeeksforGeeks” + 2 + 0 + 1 + 6); //It prints the concatenation of 2,0,1 and 6 which is 2016 since it encounters the string initially. Basically, Strings take precedence because they have a higher casting priority than integers do.
- System.out.println(2 + 0 + 1 + 5 + “GeeksforGeeks” + 2 + 0 + 1 + 6); //It prints the addition of 2,0,1 and 5 while the concatenation of 2,0,1 and 6 based on the above given examples.
- System.out.println(2 + 0 + 1 + 5 + “GeeksforGeeks” + (2 + 0 + 1 + 6)); //It prints the addition of both 2,0,1 and 5 and 2,0,1 and 6 based due the precedence of ( ) over +. Hence expression in ( ) is calculated first and then the further evaluation takes place.
This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java lang.Long.byteValue() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java.util.function.LongPredicate interface in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java lang.Long.highestOneBit() method in Java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.util.function.DoublePredicate interface in Java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java.util.function.IntPredicate interface in Java with Examples
- Java.util.function.BiPredicate interface in Java with Examples
- Java Deprecated API Scanner tool (jdepscan) in Java 9 with Examples
- Java.util.LinkedList.peek() , peekfirst(), peeklast() in Java
- Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java
- Java.util.concurrent.RecursiveAction class in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java.util.concurrent.Phaser class in Java with Examples
- Java.util.concurrent.RecursiveTask class in Java with Examples