Review Question 5 If two Strings contain the same text, then we would expect them to be equal in some sense. For example, consider this section of Java: String string1 = "hello"; String string2 = "hello"; String string3 = "there"; if (string1 == string2) System.out.println("strings 1 and 2 are equal"); if (string1 == string3) System.out.println("strings 1 and 3 are equal"); We might expect this section of program to print: Strings 1 and 2 are equal Because both contain the word "hello". In fact, neither line is printed; Java does not think the "hello" is equal to "hello"! This may seem rather odd at first. If x and y were integers, and both had the value 2 , thJava would think x and y were equal. So why does Java treat Strings and integers differently in this respect? (Hint: what is different in the way these data types are implemented). There is a short answer to this question, and a longer one which takes into account the philosophy behind the answer (i.e. why Java works this way). If we can't use == to test whether two strings have the same text, how can we do it? Discussion of Review Question 5 Back to top 
RITSEC - Global Campus Copyright ?1999 RITSEC- Middlesex University. All rights reserved. webmaster@globalcampus.com.eg |