1. Java is case sensitive.
2. The rules for class names in Java are quite generous. Names must begin with a letter, and after that, they can have any combination of letters and digits.
3. You need to make the file name for the source code the same as the name of the public class in that file, with the extension .java appended.
4. To run a compiled program, the Java virtual machine always starts execution with the code in the main method (exactly same as public static void main(String[] ) ) in the class you indicate. The Java launcher in Java SE 1.4 and beyond enforces that the main method is public.
5. If the main method exits normally, the Java program has the exit code 0, indicating successful completion. To terminate the program with a different exit code, use the System.exit method.
6. Java is a strongly typed language. Every variable must have a declared type. In Java, the sizes of all numeric types are platform-independent. Java does not have any unsigned types. (except char which is taken as a character type)
7. 0.125 = 2-3 can be written as 0x1.0p-3 . In hexadecimal notation, you use a p , not an e (An e is a hexadecimal digit.), to denote the exponent. Note that the mantissa is written in hexadecimal and the exponent in decimal. The base of the exponent is 2, not 10.
8. Starting with Java 7, you can write numbers in binary, with a prefix 0b. For example, 0b1001 is 9. Also starting with Java 7, you can add underscores to number literals, such as 1_000_000 (or 0b1111_0100_0010_0100_0000) to denote one million. The underscores are for human eyes only. The Java compiler simply removes them.
9. The constants Double.POSITIVE_INFINITY , Double.NEGATIVE_INFINITY , and Double.NaN (as well as corresponding Float constants) represent these special values, but they are rarely used in practice. x == Double.NaN is never true. All “ not a number ” values are considered distinct. However, you can use the Double.isNaN method: Double.isNaN(x) checks whether x is "not a number".
10. There is no precise binary representation of the fraction 1/10, just as there is no accurate representation of the fraction 1/3 in the decimal system. System.out.println(2.0 - 1.1) prints 0.8999999999999999, not 0.9. If you need precise numerical computations without roundoff errors, use the BigDecimal class.
11. Unicode code units can be expressed as hexadecimal values that run from \u0000 to \uFFFF . For example, \u2122 is the trademark symbol ( ™ ) and \u03C0 is the Greek letter pi ( p ).
12. You can use these escape sequences inside quoted character constants and strings, such as '\u2122' or "Hello\n" . The \u escape sequence (but none of the other escape sequences) can even be used outside quoted character constants and strings. For example, public static void main(String\u005B\u005D args) is perfectly legal. \u005B and \u005D are the encodings for [ and ] .
13. In Java, the char type describes a code unit in the UTF-16 encoding.
14. You cannot convert between integers and boolean values.
15. A variable name must begin with a letter and must be a sequence of letters or digits. Note that the terms “ letter ” and “ digit ” are much broader in Java than in most languages. A letter is defined as 'A' – 'Z', 'a' – 'z', '_', or any Unicode character that denotes a letter in a language. Similarly, digits are '0' – '9' and any Unicode characters that denote a digit in a language. If you are really curious as to what Unicode characters are “ letters ” as far as Java is concerned, you can use the isJavaIdentifierStart and isJavaIdentifierPart methods in the Character class to check.
16. After you declare a variable, you must explicitly initialize it by means of an assignment statement — you can never use the values of uninitialized variables.
17. const is a reserved Java keyword, but it is not currently used for anything. You must use final for a constant.
18. The / operator denotes integer division if both arguments are integers, and floating-point division otherwise. Integer division by 0 raises an exception, whereas floating-point division by 0 yields an Infinite or NaN result.
19. Some processors use 80-bit floating-point registers. These registers yield added precision in intermediate steps of a computation. By default, virtual machine designers are now permitted to use extended precision for intermediate computations. However, methods tagged with the strictfp keyword must use strict floating-point operations that yield reproducible results. For example, you can tag main as: public static strictfp void main(String[] args) , then all instructions inside the main method use strict floating-point computations. If you tag a class as strictfp , then all of its methods use strict floating-point computations.
20. When applied to boolean values, the & and | operators yield a boolean value. These operators are similar to the && and || operators, except that the & and | operators are not evaluated in “ short circuit ” fashion. That is, both arguments are first evaluated before the result is computed.
21. >>> operator fills the top bits with zero, whereas >> extends the sign bit into the top bits. There is no <<< operator. The right-hand side argument of the shift operators is reduced modulo 32 (unless the left-hand side is a long, in which case the right-hand side is reduced modulo 64). For example, the value of 1 << 35 is the same as 1 << 3 or 8.
22. The functions in the Math class use the routines in the computer ’ s floating-point unit for fastest performance. If completely predictable results are more important than fast performance, use the StrictMath class instead. It implements the algorithms from the “ Freely Distributable Math Library ” fdlibm, guaranteeing identical results on all platforms. See http://www.netlib.org/fdlibm/index.html for the source of these algorithms. (Whenever fdlibm provides more than one definition for a function, the StrictMath class follows the IEEE 754 version whose name starts with an “ e ” .)
23. The six solid arrows in the following figure denote conversions without information loss. The three dotted arrows denote conversions that may lose precision. Conversions in which loss of information is possible are done by means of casts. The syntax for casting is to give the target type in parentheses, followed by the variable name.
24. When two values with a binary operator (such as n + f where n is an integer and f is a floating-point value) are combined, both operands are converted to a common type before the operation is carried out:
• If either of the operands is of type double, the other one will be converted to a double.
• Otherwise, if either of the operands is of type float, the other one will be converted to a float.
• Otherwise, if either of the operands is of type long, the other one will be converted to a long.
• Otherwise, both operands will be converted to an int.
25. Java does not have a comma operator. However, you can use a comma-separated list of expressions in the first and third slot of a for statement.
26. Operators’ precedence table :
Operators |
Associativity |
[] . ()(method call) |
Left to right |
! ~ ++ -- +(unary) -(unary) ()(cast) new |
right to Left |
* / % |
Left to right |
+ - |
Left to right |
<< >> >>> |
Left to right |
< <= > >= instanceof |
Left to right |
== != |
Left to right |
& |
Left to right |
^ |
Left to right |
| |
Left to right |
&& |
Left to right |
|| |
Left to right |
?: |
right to Left |
= += -= *= /= %= &= \= ^= <<= >>= >>>= |
right to Left |
27. When you concatenate a string with a value that is not a string, the latter is converted to a string.
28. The String class gives no methods that let you change a character in an existing string. Because you cannot change the individual characters in a Java string, the documentation refers to the objects of the String class as being immutable. You cannot change the value of a string, but you can change the contents of the string variable and make it refer to a different string. It would seem simpler to change the code units than to build up a whole new string from scratch. However if various strings are sitting in a common pool and string variables point to locations in the pool, when you copy a string variable, both the original and the copy share the same characters. So overall, the designers of Java decided that the efficiency of sharing outweighs the inefficiency of string editing by extracting substrings and concatenating.
29. To test whether two strings are identical except for the upper/lowercase letter distinction, use the equalsIgnoreCase method.
30. If the virtual machine would always arrange for equal strings to be shared, then you could use the == operator for testing equality. But only string constants are shared, not strings that are the result of operations like + or substring . Therefore, never use == to compare strings lest you end up with a program with the worst kind of bug — an intermittent one that seems to occur randomly.
31. Java strings are implemented as sequences of char values. the char data type is a code unit for representing Unicode code points in the UTF-16 encoding. The length method yields the number of code units required for a given string in the UTF-16 encoding.
32. To get the true length, that is, the number of code points, call:
int cpCount = greeting.codePointCount(0, greeting.length());String.charAt(n) returns the code unit at position n. To get at the ith code point, use the statements:
int index = greeting.offsetByCodePoints(0, i); int cp = greeting.codePointAt(index);
33. If your code traverses a string, and you want to look at each code point in turn, use these statements:
int cp = sentence.codePointAt(i); if (Character.isSupplementaryCodePoint(cp)) i += 2; else i++;
the codePointAt method can tell whether a code unit is the first or second half of a supplementary character, and it returns the right result either way. You can move backwards with the following statements:
i--; int cp = sentence.codePointAt(i); if (Character.isSupplementaryCodePoint(cp)) i--;
34. Point your web browser to the docs/api/index.html subdirectory of your JDK installation, you will see the Java API documentation.
35. The StringBuilder class was introduced in JDK 5.0. Its predecessor, StringBuffer , is slightly less efficient, but it allows multiple threads to add or remove characters. If all string editing happens in a single thread (which is usually the case), you should use StringBuilder instead. The APIs of both classes are identical.
36. To read console input, you first construct a Scanner that is attached to System.in:
Scanner in = new Scanner(System.in) ;
The nextLine method reads a line of input. To read a single word (delimited by whitespace), call next method. To read an integer, use the nextInt method. Similarly, the nextDouble method reads the next floating-point number.
37.Whenever you use a class that is not defined in the basic java.lang package, you need to use an import directive.
38. The Scanner class is not suitable for reading a password from a console since the
input is plainly visible to anyone. Java SE 6 introduces a Console class specifically for this purpose. To read a password, use the following code:
Console cons = System.console(); String username = cons.readLine("User name: "); char[] passwd = cons.readPassword("Password: ");For security reasons, the password is returned in an array of characters rather than a string. After you are done processing the password, you should immediately overwrite the array elements with a filler value. Input processing with a Console object is not as convenient as with a Scanner . You can only read a line of input at a time. There are no methods for reading individual words or numbers.
39. Java SE 5.0 brought back the venerable printf method from the C library.
40. Each of the format specifiers that start with a % character is replaced with the corresponding argument. The conversion character that ends a format specifier indicates the type of the value to be formatted:
You can use the s conversion to format arbitrary objects. If an arbitrary object implements the Formattable interface, the object’s formatTo method is invoked. Otherwise, the toString method is invoked to turn the object into a string.
41. You can specify flags that control the appearance of the formatted output. For example, the comma flag adds group separators. That is, System.out.printf("%,.2f", 10000.0 / 3.0) prints 3,333.33.
You can use multiple flags, for example, "%,(.2f ", to use group separators and enclose negative numbers in parentheses. All flags are as below:
42. You can print the Date type by using a two-letter format, starting with t and ending in one of the letters in following table :
For example, System.out.printf("%tc", new Date()) prints the current date and time in the format: Mon Feb 09 18:05:19 PST 2004.