String
Never use the == operator to compare strings. The comparison
location == "World" // Don’t do that!
returns true only if location and "World" are the same object in memory.
When comparing a string against a literal string,it is a good idea to put the literal
string first:
This test works correctly even when location is null.
Input and Output
To read a password,you do not want to use the Scanner class since the input is
visible in the terminal. Instead,use the Console class:
Console terminal = System.console();
String username = terminal.readLine(“User name: “);
char[] passwd = terminal.readPassword(“Password: “);
The password is returned in an array of characters. This is marginally more secure
than storing the password in a String because you can overwrite the array when
you are done.
Loop
Label
you want to jump to the end of another enclosing statement,use a labeled break statement. Label the statement that should be exited,and provide the label with the break like this:
outer:
while (…) {
…
while (…) {
…
if (…) break outer;
…
}
…
}
// Labeled break jumps here
A regular break can only be used to exit a loop or switch,but a labeled break can
transfer control to the end of any statement,even a block statement:
exit: {
…
if (…) break exit;
…
}
// Labeled break jumps here
The Enhanced for Loop
You can use the enhanced for loop with array and array lists.
ArrayList
When that array becomes too small or is insufficiently utilized,another
internal array is automatically created,and the elements are moved into it.
Wrapper Classes for Primitive Types
Just like with strings,you need to remember to call the equals method with
wrapper objects.
Command-Line Arguments
If the program is called as
java Greeting -g cruel world
then args[0] is "-g",args[1] is "cruel",and args[2] is "world".
Note that neither "java" nor "Greeting" are passed to the main method.