The phrase "Hello World!" is a String literal (constant).
In your first program, you simply did:
System.out.println("Hello World!");
and did not directly use the String.
But like other variables, you could make the phrase a variable and use
it in outputing the message:
String greeting = "Hello World!";
System.out.println(greeting);
One useful feature for Strings is concatenation, combining two strings.
Here is another way to print out the message from above:
// One way
String greeting = "Hello ";
String name = "World";
String message = greeting + name;
System.out.println(message);
// Or simply
System.out.println(greeting + name);
One other advantage is concatenating using variables as well:
String name = "Christian";
int dollars = 1000;
System.out.println(name + " has " + dollars + " dollars in his pocket.");
System.out.println(name + " has $" + dollars + " in his pocket.");
// DANGER! DANGER! Be careful (the following do not behave the same way!)
System.out.println("Counting " + 1 + 2);
System.out.println(1 + 2 + " and counting ");
The "command" println(...) is a method associated with a class
called PrintWriter.
The class String also has methods associated with it.
The book goes over some of these in Section 2.2 (page 82), to be
helpful we shall cover some of these methods as well and show how to use
them.
| int length() | Returns the length of the string |
| boolean equals(String otherString) | Tests if two strings are equal |
| String toUpperCase() | Returns a new String with all characters in old string in upper case. |
| char charAt(int position) | Returns the character at the current position. Counting starts at 0! |
| String substring(int start) | Returns the subString starting at the given position start |
| String substring(int start, int end) | Returns the substring starting at start and ending just before end |
| int indexOf(char c) | Returns the index in the string of the first occurrence of the character c or -1 if the character does not exist. |
String message = "Fun with strings";
// positions 0123456789012345
int length = message.length(); // Returns 16
System.out.println(length); // Prints 16
String shout = message.toUpperCase();
System.out.println(shout); // "FUN WITH STRINGS"
System.out.println(message.substring(9)); // "strings"
System.out.println(message.substring(2,6)); // "n wi"
System.out.println(message.indexOf(' ')); // Prints 3
System.out.println(message.indexOf('z')); // Prints -1
As another example, let us see how to get the first word in a text.
What changes do you need to make to get the second word?
String text = "Hello there world";
int spaceAt = text.indexOf(' '); // spaceAt == 5
String firstWord = text.substring(0,spaceAt);
public class Retire {
public static void main(String[] args) {
System.out.println("How old are you?");
int age = SavitchIn.readLineInt();
if (age > 60)
System.out.println("Time to retire!");
else
System.out.println("Keep working");
System.out.println("Good bye!");
}
}
The format for the (if-else) is as follows:
if (boolean-expression) statement else statementNotice the above takes exactly one statement for the then and else portions. For multiple statements, we can simplify it to the following:
if (boolean-expression) {
multiple-statements
}
else {
multiple-statements
}
The else portion is also optional.
It can be removed completely.
Compound Statements:
The statements between an opening brace { and
a matching closing brace } form what is called a
compound statement.
This compound statement then is, in itself, a statement.
x == 3 // Tests if the variable x equals 3 x != 3 // Exact opposite x > 3, x >= 3, x < 3, x <= 3, (x+y) < (a+b), ...These expressions evaluate to either true or false depending on the condition. The expression (x==3) is true if x is equal to 3 and false otherwise. Sometimes we don't just have one "condition". For example, if I am older than 50 and rich, I'll retire early. There is one way to do this:
if (myAge > 50) {
if (myMoney >= 1000000) {
System.out.println("I'm retiring early!");
}
}
There is a better way:
if ((myAge > 50) && (myMoney >= 1000000)) {
System.out.println("I'm retiring early!");
}
The && is called a logical and operator.
The expression ((A)&&(B))
returns true only if both (A) AND (B) are true.
The three logical operators you should be concerned with now are:
int x = 2;
int y = 4;
if ((x < 3) && (y > 0)) {
System.out.println("Should be printed");
}
if ((x < 3) && (y > 4)) {
System.out.println("Should NOT be printed. Why?");
}
if ((x < 3) || (y > 4)) {
System.out.println("Shoud be printed. Why?");
}
if (!((x < 3) || (y > 4))) {
System.out.println("Shoud NOT be printed. Why?");
}
System.out.println("Who are you?");
String name = SavitchIn.readLine();
if (name.equals("Christian")) {
System.out.println("Great! I hoped it was you.");
}
System.out.println("What kind of computer should I get?");
if (myMoney >= 1000000) {
System.out.println("I am a millionaire. Let's buy a supercomputer!");
} else if (myMoney >= 100000) {
System.out.println("Well, I'll just buy a nice Dell system.");
} else if (myMoney >= 1000) {
System.out.println("Ok, maybe I'll just find a used Dell.");
} else {
System.out.println("Hmmm, where's that old Atari system of mine.");
}
In this case, the algorithm prints out one of several different values
depending on the value of the variable (myMoney).
Notice, that even if I have $1,000,000, the output does not produce multiple
lines of output.
However, if I remove the "else" words, it would. Why is this?
Imagine creating a menu driven program for example.
There are (at least) two ways to do this, the old fashioned way and the
switch way.
System.out.println("Please enter an option (1-3)");
int option = SavitchIn.readLineInt();
if (option == 1) {
System.out.println("You entered option 1");
System.out.println("I will restart your computer now");
}
if (option == 2) {
System.out.println("You entered option 2");
System.out.println("I will reformat your hard disk now");
}
if (option == 3) {
System.out.println("You entered option 3");
System.out.println("Your computer will self destruct... now");
}
else {
System.out.println("Hey, buddy, follow directions next time!");
}
// Or the following way...
switch (option) {
case 1:
System.out.println("You entered option 1");
System.out.println("I will restart your computer now");
break;
case 2:
System.out.println("You entered option 2");
System.out.println("I will reformat your hard disk now");
break;
case 3:
System.out.println("You entered option 3");
System.out.println("Your computer will now self destruct");
break;
default:
System.out.println("Hey, buddy! Follow directions next time");
}
The way it works should be straightforward (almost).
It takes the value of "option" and if it is a 0, it
performs the actions after the case 0.
If it is a 1, it performs the actions after the case 1, etc.
The one tricky part is that it starts executing commands
after the case and continues to the end of the switch or until
it encounters a break.
The book covers this topic fairly well so use it as a better reference.
The key pitfall to avoid here is forgetting
the break statement when needed.
For example, if the first break was commented out and the
user entered a 1, the system would print out the following (Why?):
You entered option 1
I will restart your computer now
You entered option 2
I will reformat your hard disk now
The second rule is that the values in the case statements must be
constants or literals.
Basically, think of it as numbers or letters.
The following are invalid examples:
// INVALID (can't use anything but primitives)
String name = SavitchIn.readLine();
switch (name) {
case "Alex":
case "Christian":
case "Duncan":
System.out.println("Yes?");
break;
default:
System.out.println("Who are you?");
}
// INVALID (can't use variables in the case statements)
char letter1 = 'Q';
char letter2 = 'W';
char opt = SavitchIn.readLineNonwhiteChar();
switch (opt) {
case letter1:
System.out.println("Q entered");
break;
case letter2:
System.out.println("W entered");
break;
}
if (a > b)
max = a;
else
max = b;
// Or
max = (a > b) ? a : b;
The format is:
(boolean-expression) ? expression :
expression
There are things to remember about this expression.
The value in the two expressions has to be of the same type.
In the following example, the first statement works and the second one
does not.
double grade;
char letter;
grade = SavitchIn.readLineDouble();
letter = (grade > 90) ? 'A' : 'B'; // WORKS
letter = (grade >= 60) ? "PASS" : 'F'; // WON'T COMPILE