/*
Comparisons.java
*/
public class Comparisons
{
public static void main(String[] args)
{
double num1 = 10, num2 = 20, num3 = 10;
// For primitive data types, == and != work as
expected
if (num1 == num2)
System.out.println("Same
numbers");
if (num1 != num2)
System.out.println("Different
numbers");
// Java includes same logical and relational
operators as C++
if (num1 < num2 && num2 > num3)
System.out.println("Num2 is
largest");
System.out.println("Max num: " + ((num1 > num2) ?
num1 : num2));
double tolerance = num3 - num1;
if (tolerance < .0000001)
System.out.println("num1 equals
num3");
// Strings in Java are objects
// str1 and str2 will point to the same memory
location
String str1 = "This is a string";
String str2 = "This is a string";
String str3 = "This is also a string";
String str;
// This will be a new location, with the same
contents as str1 and str2
str = new String("This is a string");
// This will succeed, since same memory
if (str1 == str2)
System.out.println("str1 and str2
are the same string");
// Not same memory location
if (str == str1)
System.out.println("str and str1
are the same string");
// use equals to check the contents
if (str1.equals(str2))
System.out.println("str1 and str2
say the same thing");
if (str.equals(str1))
System.out.println("str and str1
say the same thing");
if (str1.equalsIgnoreCase(str2))
System.out.println("str1 and str2
say essentially the same thing");
// compareTo returns an integer result, similar to
strcmp in C++
System.out.println("Comparison of str1 and str2 = " +
str1.compareTo(str2));
System.out.println("Comparison of str1 and str3 = " +
str1.compareTo(str3));
System.out.println("Comparison of str3 and str1 = " +
str3.compareTo(str1));
}
}