CoreJava - Chapter 3: Fundamental Programming Structures in Java

3.1 A Simple Java Program

public class FirstSample
{
    public static void main(String[] args)
    {
        System.out.println("We will not use 'Hello, World!'");
    }
}
  • The keyword public is called an access modifier; these modifiers control the level of access other parts of a program have to this code
  • The keyword class reminds you that everthing in a Java program lives inside a class
  • The standard naming convention is that class names are nouns that start with an uppercase letter
  • You need make the file name for the source code the same as the name of the public class, with the extension .java appended
  • If You have named the file correctly and not made any typos in the source code, then when you compile this source code, you end up with a file containing the bytecodes for this class. The Java compiler automatically names the bytecode file FirstSample.class and stores it in the same directory as the source file
  • When you use java Classname to run a compiled program, the Java virtual machine always starts execution with the code in the main method in the class you indicate. Thus, you must have a main method in the source of your class for your code to execute

3.2 Comments

  • Ways to make comments
    • //
    • /* */
    • /** */: this is used to generate documentation automatically

3.3 Data Types

  • Java is a stronly typed language, which means that every variable must have a declared type
  • primitive data types
    • int        4 bytes 
    • short.   2 bytes
    • long     8 bytes
    • byte     1 byte
    • (Under Java, the range of integer types do not depend on the machine on which you will be running the Java code)
    • Longer integer numbers have a suffix L or l (e.g., 4000L). Hexdecimal numbers have a prefix 0x or 0X. Octal numbers have a prefix. Starting with Java 7, you can write numbers in binary with prefix 0b or 0B
    • float     4 bytes
    • double 8 bytes
      • there are three special floating-point values to denote overflow and errors
        • Positive infinity
        • Negative infinity
        • NaN (not a number)
    • char
      • Unicode encoding scheme: to unify different encodings
      • In Java, the char type describes a code unit in the UTF-16 encoding
    • boolean

3.4 Variables and Constants 

  • Declare a variable
  • Initialize a variable
  • Constants
    • In Java, you use the keyword final to denote a constant
      • class constants:
        • the variable would be availabe to multiple methods inside a single class
        • can be set up with the keyword static final
  • Enumerated Types
    • For the situation when a varaible should only hold a restricted set of values

3.5 Operators 

  • Arithmetic Operators
    • strictfp: must use strict floating point operations that yield reproducible results
  • Mathematical Functions and Constants
  • Conversion between numeric types
    • When two values are combined with a binary operator, both operands are converted to a common type before the operation is carried out
      • If either of the operands is of type double, the ohter one will be converted to a double
      • Otherwise, if either of hte operands is of type float, the other one will be converted to float
      • Otherwise, if either of hte operands is of type long, the other one will be converted to a long
      • Otherwise, both operands will be converted to an int
    • In the above picture, the solid line indicates lossless conversion, whereas the dashed line indicates lossy conversion
    • Casts
  • double x = 997;
    int nx = (int) x; // the loss of information is possible

     

  • Combining Assignment with Operators
  • Increment and Decrement Operators
  • Relational and boolean Operators
    • ==, !=
    • <, >, <=, >=
    • &&, ||
    • ternary ?: (e.g., condition ? expression1 : expression2)
  • Bitwise Operator
    • &, |, ^, ~,
    • >>, <<
  • Parentheses and Operator Hierarchy

3.6 Strings 

  • Conceptually, Java strings are squences of Unicode characters

  • Substrings

String greeting = "Hello Java";
String sub = greeting.substring(0, 3);
  • Concatenation

    • When you concatenate a string with a value that is not a string, the latter is converted to a string

  • Strings are immuatble

    • The String class gives no methods that let you change a character in an existing string

    • The compiler can arrange that strings are shared

      • To understand how this works, think of the various strings as sitting in a common pool. String variables then point ot locations in the pool. If you copy a string variable, both the origina and the copy share the same characters

      • The efficiency of sharing outweigh the inefficiency of string editing by extracting substrings and concatenating

  • Testing strings for equality

    • To test whether two strings are euqal, use the equals method: s.equals(t)

    • To test whether tow strins are indentical except for the upper/lower letter distinction, use the equalsIgnoreCase method

    • Do not use the == operator to test whether tow strings are equal. It only determines whehter or not the strings are stored in the same location

      • If the virtual machine always arranges for equal strings to be shared, then you could use the == operator for testing equality. But only string lieterals are shared

  • Empty and Null Strings

    • A string variable can hold a sepcial value, called null, that indicates that no object is curretnly associated with the variabl

      • if (str == null)

         

    • Code Points and Code Units

      • Java strings are squences of char values. The char data type is a code unit for represetning Unicode code points in teh UTF-16 encoding

      • The call s.charAt(n) reutrns the code unit at position n, hwere n is between 0 and s.length() - 1

      • Q: What is the relationship between Code Units and Code Points?

  • The String API 

  • Building Strings

    • StringBuilder

3.7 Input and Output

  • Reading Input
    • Scanner in = new Scanner(System.in);
      
      String name = in.nextLine(); // read the next line
      
      String firstName = in.next(); // read a single word
      
      int age = in.nextInt(); // read an integer

       

      • The Scanner class is not suitable for reading a password from console since the input is plainly visible to anyone. Java 6 introduces a Console class specifically for this purpose

      • Console cons = System.console();
        String username = cons.readLine("User name: ");
        char[] passwd = cons.readPassword("Password: ");

         

  • Formatting Output
    • System.out.printf("%8.2f", x);
      System.out.printf("Hello, %s. Next year, you will be %d", name, age);

       

    • Flags for printf

    • Java date conversion

      • System.out.printf("%tc", new Date())

         

    • Format specifier syntax
      • Q: What does flag do in this case?

  • File Input and Output

    • Scanner in = new Scanner(Path.of("myfile.txt"), StandardCharsets.UTF_8); //read a file
      
      PrintWriter out = new PrintWriter("myfile.txt", StandardCharsets.UTF_8); //write to a file
      
      /* Caution: you can construct a Scanner with a string parameter, but he scanner inteprets the string as data, not a file name */
      
      Scanner in = new Scanner("myfile.txt");
      
      /* When you specify a relatvie file name, such as "myfile.txt", the file is located relative to the directory in which the Java virtual machine was started */
      
      String dir = System.getProperty("user.dir"); // use this to obtain the current user directory

       

    • Q: how to determine the directory in which the Java virtual machine started?

3.8 Control Flow

  • Block scope
    • Block defines the scope of your variable
    • A block can be nested inside another block
    • You cannot declare identically named variables in two nested blocks
      • public static void main(String args[]) {
            int n;
            {
                int k;
                int n; // Error
            }
        }

         

  • Conditional Statements
    • 1. if (condition) statement1 else statement2
      
      2. if (condition) {
          statement1
      } else {
          statement2
      }
      
      3. if (x <= 0) if (x == 0) sign = 0; else sign = -1;
      
      4. if (condition1) {
      } else if (condition2) {
      } else if (condition3) {
      } else {
      ...
      }

       

  • Loops

    • while

    • do statement while  (condition) 

      • this loop executes the statement and only then tests the condition

    • for

    • switch
      • Scanner in = new Scanner(System.in);
        System.out.print("Select an option (1, 2, 3, 4) ");
        int choice = in.nextInt();
        switch (choice)
        {
            case 1:
                . . .
                break;
            case 2:
                . . .
                break;
            case 3:
                . . .
                break;
            case 4:
                . . .
                break;
            default:
                // bad input
                . . .
                break;
        }

         

      • Caution: it is possible for multiple alternatives to be triggered. If you forget to add a break at the end of an alternative, execution falls through to the next alternative, which is plainly dangerous and a common cause for errors

        • if you like the switch statement, consider compiling your code with the -Xlint:fallthrough option, e.g.,

          • javac -Xlint:fallthrough Test.java

             The compiler will issue a warning whenever an alternative does not end with a break statement. If you actually want to use the fallghrough behavior, tag the surrounding method with the annotation @SupressWarnings("fallthrough"). Then not warnings will be generated for that method

      • Case label

        • A constant expression of type char, byte, short, or int

        • An enumerated constant

        • Starting with Java 7, a string literal 

  • Statemetns That Break Control Flow

    • Although the designers of Java kept goto as a reserved word, they decided not to include it in the language

    • break

    • labelled break

      • Scanner in = new Scanner(System.in);
        int n;
        read_data:
        while (. . .) // this loop statement is tagged with the label
        {
            . . .
            for (. . .) // this inner loop is not labeled
            {
                System.out.print("Enter a number >= 0: ");
                n = in.nextInt();
                if (n < 0) // should never happen—can't go on
                break read_data;
                // break out of read_data loop
                . . .
            }
        }// this statement is executed immediately after the labeled break
        if (n < 0) // check for bad situation
        {
            // deal with bad situation
        }else
        {
        // carry out normal processing
        }

        (Notice the label above the while loop: "read_data:")

      • You can apply a label to any statement, even an if statement or a block statement

        • label:
          {
              ...
              if (condition) break label; // exit block
              ...
          }

           

    • continue

      • The continue statement transfers control to the header of the innermost enclosing loop

 

3.9 Big Numbers 

  • If the precision of the basic integer and floating-point types is not sufficent, you can turn to a couple of handy classes in the java.math package: BigInteger and BigDecimal
  • The BigInteger class implements arbitrary-precision integer arithmetic, and BigDecimal does the same for floating-point numbers
  • Contructions & manipulation of BigInteger
    • BigInteger a = BigInteger.valueOf(100);
      
      BigInteger reallyBig
      = new BigInteger("222232244629420445529739893461909967206666939096499764990979600"); // using string argument
      
      BigInteger c = a.add(b); // c = a + b
      BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); //

       

3.10 Arrays

  • Declaring Arrays
    • An array is a data structure taht stores a collection of values of the same type
    • int a[]; // only declares an array variable
      
      int[] a; // this way also works
      
      int a[] = new int[100]; // this statement declares and initializes an array of 100 integers
      
      int [] smallPrimes = {2, 3, 5, 7, 11, 13}; // Notice that you do not use new with this syntax, and you don't specify the length
      
      new int[]{17, 19, 23} //anonymous array
      
      

       

  • 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 spcial value null, which indicates that they do not (yet) hold any objects

  • The "for each" Loop

    • for (variable : collection) statement

      The collection expression must be an array of  an object of a class that implements the Iterable interface

  • Array Copying

    • You can copy one array variable into another, but then both variables refer to the same array

    • Deep copy

      • int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);
        
        luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length); //the additional elements are filled with the default values

         

  • Compared to C++ array

    • A java array is quite different from a C++ array on the satck. It is, however, essentially the same as a pointer to an array allocated on the heap

      • int[] a = new int[100]; // Java
        
        int a[100]; // not the same as C++
        
        int* a = new int[100]; // but rather this one
        

        In Java, the [] operator is predefined to perfrom bounds checking. Furthermore, there is no pointer arithmetic -- you can't increment a to point to the next element in the array 

  • Command-Line Parameters

    • Every Java program has a main method wit ha String[] args parameter. This parameter indicates that the main method receives an array of strings -- namely, the arguments specified on the command line

      • public class Message {
            public static void main(String[] args) 
            { 
                if (args.length == 0 || args[0].equals("-h"))
                    System.out.print("Hello,");
                else if (args[0].equals("-g"))
                    System.out.print("Goodbye,");
                //print the other command-line arguments
                for (int i = 1; i < args.length; i++)
                    System.out.print(" " + args[i]);
                System.out.println("!");
            }
        }
        
        // if the program is called as "java Message -g cruel world"
        // the output would be "Goodbye, cruel world!"

        In the main method of a Java program, the name of the program is not stored in the args array

  • Array sorting

    • Arrays.sort method

      • This method uses a tuned version of the QuickSort algorithm 

  • 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}
      };

       

  • Ragged Arrays

    • Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays are faked as "arrays of arrays"

    • In the previous example, the expression magicSquare[i] refers to the ith subarray

    • Since rows of arrays are individually acessible, you can actually swap them

      • double[] temp = balances[i];
        balances[i] = balances[i + 1];
        balances[i + 1] = temp;

         

    • It is also easy to make "ragged" arrays -- arrays in which different rows have different lengths

      • int[][] odds = new int[NMAX + 1][];
        
        for (int n = 0; n <= NMAX; n++)
            odds[n] = new int[n + 1];

         

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值