Program prog53 below checks whether string my_name is more than 6 characters long. If so, it then looks to see if the seventh character is an X. The two conditional statements are joined by && so the second test is only carried out if the first is true:
andrew@UBUNTU:~/Java$ cat prog53.java
public class prog53
{
public static void main (String args[])
{
String my_name = "Andrew";
if ((my_name.length() > 6)
&& (my_name.charAt(6) == 'X'))
System.out.println ("7th character = X");
else
System.out.println ("7th character not = X");
}
}
andrew@UBUNTU:~/Java$ javac prog53.java
andrew@UBUNTU:~/Java$ java prog53
7th character not = X
andrew@UBUNTU:~/Java$
Program prog54 does the tests in the wrong order and produces a run-time error:
andrew@UBUNTU:~/Java$ cat prog54.java
public class prog54
{
public static void main (String args[])
{
String my_name = "Andrew";
if ((my_name.charAt(6) == 'X')
&& (my_name.length() > 6))
System.out.println ("7th character = X");
else
System.out.println ("7th character not = X");
}
}
andrew@UBUNTU:~/Java$ javac prog54.java
andrew@UBUNTU:~/Java$ java prog54
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:694)
at prog54.main(prog54.java:6)
andrew@UBUNTU:~/Java$
Program prog55 is similar to prog53 but joins the two conditional statements with & (a single ampersand). This evaluates the 2nd conditional statement even if the first is false so it also produces a run-time error:
andrew@UBUNTU:~/Java$ cat prog55.java
public class prog55
{
public static void main (String args[])
{
String my_name = "Andrew";
if ((my_name.length() > 6)
& (my_name.charAt(6) == 'X'))
System.out.println ("7th character = X");
else
System.out.println ("7th character not = X");
}
}
andrew@UBUNTU:~/Java$ javac prog55.java
andrew@UBUNTU:~/Java$ java prog55
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 6
at java.lang.String.charAt(String.java:694)
at prog55.main(prog55.java:6)
andrew@UBUNTU:~/Java$