import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Equals { // where is the constructor? // what does that mean? public void testEqualsEquals (String a, String b) { System.out.println("Testing '" +a + "' == '" + b + "' is " + (a == b)); } public void testDotEquals (String a, String b) { System.out.println("Testing '" +a + "' .equals() '" + b + "' is " + (a.equals(b))); } public void testTwo(String msg, String a, String b) { System.out.println("Testing: " + msg); testEqualsEquals(a, b); testDotEquals(a, b); System.out.println(); } public void testEquals(){ int Five1 = 5; int Five2 = 4+1; double doubleFive = 5.0; // primitives // no surprise: if (Five1==Five2) System.out.println("primitive comparison: " + Five1 + "==" + Five2 +"\n"); else System.out.println("primitive comparison: " + Five1 + "!=" + Five2 +"\n"); // surprised? if (Five1==doubleFive) System.out.println("primitive comparison: " + Five1 + "==" + doubleFive +"\n"); else System.out.println("primitive comparison: " + Five1 + "!=" + doubleFive +"\n"); String h = "hello "; String w = "world"; String hw1 = "hello world"; String hw2 = h+w; testTwo("String literal concatenation", hw1, hw2); // Look at different result here, java has only one copy of literals String s3 = "string"; String s4 = "string"; testTwo("two identical String literals\nJava keeps only one copy of identical Strings", s3, s4); System.out.println("LESSON:\n\"==\" for Strings is non intuitive\n" + "Better use \".equals\" !!"); } /** * @param args: two Strings * @throws FileNotFoundException */ public static void main(String[] args) throws FileNotFoundException { // goal of this code: == vs .equals new Equals().testEquals(); } }