【学习笔记】Core Java - Chapter 3

154 阅读3分钟
  1. Java is case sentitive.
  2. Everything in a Java program lives inside a class.
  3. Java is a strongly typed language.
  4. There are eight primitive types in Java.

Java - Primitive Data Types.png 5. Under Java, the ranges of the integer types do not depend on the machine on which you will be running the Java code. 6. The boolean type has two values, false and true. It is used for evaluating logical conditions. You cannot convert between integers and boolean values.

3.4.3 Constants

  1. In Java, you use the keyword final to denote a constant.
  2. It is customary to name constants in all uppercase.
public class Constants
{
    public static void main(String[] args) 
    {
        final double CM_PER_INCH = 2.54; 
        double paperWidth = 8.5; 
        double paperHeight = 11; 
        System.out.println("Paper size in centimeters: " 
            + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); 
    }
}
  1. class constants

Set up a class constant with the keywords static final.

public class Constants2
{
    public static final double CM_PER_INCH = 2.54; 
    public static void main(String[] args) 
    {
        double paperWidth = 8.5; 
        double paperHeight = 11; 
        System.out.println("Paper size in centimeters: " 
            + paperWidth * CM_PER_INCH + " by " + paperHeight * CM_PER_INCH); 
    }
}

3.5.2 Mathematical Functions and Constants

  1. Math.pow()
double y = Math.pow(x, a); 

y = x^a. The pow method's parameters are both of type double, and it returns a double as well.

  1. Math.PI & Math.E

3.5.6 Increment and Decrement Operators

int m = 7; 
int n = 7; 
int a = 2 * ++m;    // a = 16, m = 8
int b = 2 * n++;    // a = 14, n = 8

The prefix form does the addition first; the postfix form evaluates to the old value of the variable.

3.5.7 Relational and boolean Operators

expression1 && expression2
If the truth value of the first expression has been determined to be false, then it is impossible for the result to be true. Thus, the value for the second expression is not calculated.
expression1 || expression2
Similarly, the value of expression1 || expression2 is automatically true if the first expression is true, without evaluating the second expression.

3.6 Strings

3.6.1 Substrings

String greeting = "hello"; 
String s = greeting.substring(0, 3);   // output: hel

3.6.2 Concatenation

If you need to put multiple strings together, separated by a delimiter, use the static join method:

String all = String.join(" / ", "S", "M", "L", "XL"); 
// all is the string "S / M / L / XL"

3.6.3 Strings Are Immutable

3.6.4 Testing Strings for Equality

  1. To test whether two strings are equal, use the equals method. The expression s.equals(t) returns true if the strings s and t are equal, false otherwise.
String greeting = "hello"; 
"Hello".equals(greeting);   // false 
"Hello".equalsIgnoreCase("hello");   // true 
  1. Do not use the == operator to test whether two strings are equal!

3.6.5 Empty and Null Strings

  1. The empty string "" is a string of length 0.
if (str.length() == 0) 
if (str.equals(""))
  1. To test whether a string is null, use if (str == null)
  2. Sometimes you need to test whether a string is neither null nor empty. Then use: if (str != null && str.length() != 0)
    You need to test that str is not null first. It is an error to invoke a method on a null value.

3.6.9 Building Strings

StringBuilder builder = new StringBuilder(); 
builder.append(ch);  // append a single character
builder.append(str); // append a string 
String completedString = builder.toString(); 

string-api.png

3.7.3 File Input and Output

To read from a file, construct a Scanner object like this:
Scanner in = new Scanner(Path.of("myfile.txt"), StandardCharsets.UTF_8);
If the file name contains backslashes, remember to escape each of them with an additional backslash: "C:\\mydirectory\\myfile.txt".

3.10 Arrays

Useful reference: introcs.cs.princeton.edu/java/14arra…

3.10.1 Declaring Arrays

int[] a;
int[] a = new int[100];
Once you create an array, you cannot change its length. It is legal to have arrays of length 0. Note that an array of length 0 is not the same as null.

3.10.2 Accessing Array Elements

When you create an array of numbers, all elements are initialized with zero.
Arrays of boolean are initialized with false.
Arrays of objects are initialized with the speciall value null. For example,
String[] names = new String[10];
creates an array of ten strings, all of which are null.
To find the number of elements of an array, use array.length.

3.10.4 Array Copying

If you actually want to copy all values of one array into a new array, use the copyOf method in the Arrays class: int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);
A common use of this method is to increase the size of an array:
luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);
The additional elements are filled with 0 if the array contains numbers, false if the array contains boolean values. Conversely, if the length is less than the length of the original array, only the initial values are copied.

3.10.6 Array Sorting

int[] a = new int[10000]; 
...
Arrays.sort(a); 

3.10.7 Multidimensional Arrays

double[][] balances; 
balances = new double[NYEARS][NRATES]; 
int[][] magicSquare = 
{
    {16, 3, 2, 13}, 
    {5, 10, 11, 8}, 
    {9, 6, 7, 12}, 
    {4, 15, 14, 1}
}; 

3.10.8 Ragged Arrays

Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays are faked as “arrays of arrays.”
There is no requirement that all rows in a two-dimensional array have the same length - an array with rows of nonuniform length is known as a ragged array. The possibility of ragged arrays creates the need for more care in crafting array-processing code. For example, this code prints the contents of a ragged array:

for (int i = 0; i < a.length; i++) { 
    for (int j = 0; j < a[i].length; j++) {
        System.out.print(a[i][j] + " ");
    }
    System.out.println();
}