puzzler_03_solution - the correct answer Animals are equal:...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS1102S Java Puzzler: Animal Farm public class AnimalFarm { public static void main( String [ ] args ) { final String pig = ” length : 10” ; final String dog = ” length : ” + pig . length ( ) ; System . out . pr intln ( ”Animals are equal : + pig == dog ) ; } } What does this program print? Should be Animals are equal: true , right? Answer The actual print out is: false , not even Animals are equal: false !. Operator Precedences (again) The operator + has higher precedence than ==. Thus System . out . pr intln ( ”Animals are equal : + pig == dog ) ; means System . out . pr intln ( ( ”Animals are equal : ” + pig ) == dog ) ; Equality If we ±x the operator precedence problem using parentheses as in: System . out . pr intln ( ”Animals are equal : + ( pig == dog ) ) ; we would expect the print out to be: Animals are equal: true . To understand
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: the correct answer Animals are equal: false , we need to look at the operator == in more detail. For primitive data types, == implements literal equality. It tests whether the values are identical (to the bit). For object references (such as references to String objects), == checks whether the references refer to the same object. The two String references do not refer to the same object. They only contain the same characters. Thus the print out for the program public class AnimalFarm { public static void main( String [ ] args ) { 1 final String pig = ” length : 10” ; final String dog = ” length : ” + pig . length ( ) ; System . out . pr intln ( ”Animals are equal : ” + ( pig == dog ) ) ; } } will be Animals are equal: false . 2...
View Full Document

This note was uploaded on 06/09/2011 for the course CS 11025 taught by Professor Nil during the Spring '11 term at National University of Singapore.

Page1 / 2

puzzler_03_solution - the correct answer Animals are equal:...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online