Java 10

Java 10

Java

1.1 Java

1.2 Java

Java

//

www.oracle.com/technetwork

//11

horstmannn.com/corejava/ja

1.2.1

1.2.2

1.2.3

  • Java TCP/IP

  • JavaApp URL

1.2.4

Java

1.2.5

1.2.6

Java

1.2.7

Java

1.2.8

Java Java

1.2.9

1.2.10

Java JavaSE8

1.2.11

Java Java

1.3 Java applet Internet

applet

1.4 Java

1.5 Java

  1. Java HTML

Java HTML

  1. XML Java

XML XML

  1. Java

  2. Java

Java

  1. Java

  1. Java

Java

  1. Java

C++

  1. Java

  2. Java

  3. JavaScript Java

  4. Java Internet

Android

Java

2.1 Java

2.1.1 JDK

  • JDK

docs.oracle.com/javase/8/do

  • Java
JDK Java App
JRE Java App
Server JRE JRE Server Java App
SE Server Java
EE Server Java
ME Java
Java FX Java11 SE
OpenJDKSE
Java2 J2 98~06 Java
SDK 98~06 JDK
Update u Oracle Java8 bug
NetBeansOracle
  • JRE

2.1.2 JDK

  • Path

docs.oracle.com/javase/8/do

2.1.3

  • lib/src.zip

openjdk.java.net

  • API

www.oracle.com/java/techno

2.2

  • javac.exe Java java.exe javac
  • Pay attention to the following points:
    1. The input source program is case sensitive.
    2. The file name is required to run javac.exe. To run java.exe, you only need to specify the class name, without the extension.
    3. If javac reports an error stating that the file cannot be found, use the dir command to check whether the file exists in the directory, and do not use the graphical interface.

2.3 Use Integrated Development Environment

  • IDEA official website usage guide

www.jetbrains.com/help/idea/d...

2.4 Run graphical applications

2.5 Build and run the applet

The third chapter Java's basic programming structure

3.1 A simple Java application

public class FirstSample { public static void main ( String [] args ) { System.out.println( "We will not use'Hello,World!'" ); } } Copy code

Java is case sensitive. The keyword public in the source code is called access modifier (access modifier), these modifiers are used to control the access level of other parts of the program to this code. The keyword class indicates that all the content in the program is contained in the class, and the program logic defines the behavior of the application.

Classes are the building blocks for building all Java applications, and all content in a Java application must be placed in the class.

Java class name definition rules are very loose. It must start with a letter and can be followed by any combination of letters and numbers. There is no limit to the length. Java reserved words cannot be used (see the appendix for the list of reserved words).

Standard naming convention: The class name is a noun beginning with a capital letter. If the name consists of multiple singles, the first letter of each word must be capitalized (camel nomenclature).

The file name of the source code must be the same as the name of the public class, and use

.java
As the extension.

Run javac to compile and generate a file containing the bytecode of this class, and change the extension to

.class
, And stored in the source files (Source files) directory.

When running java to execute a compiled program, the virtual machine always starts execution from main() in the specified class, main() is also called main method and main function. Therefore, a main() must be included in the source code. main() must be declared as public.

Used in source code

{}
The enclosed part is called a code block.

{ System.out.println( "We will not use'Hello,World!'" ); } Copy code

A pair of curly braces indicate the beginning and end of the method body. Every statement must use

;
the end. Here the object of System.out is used to call its println method.
.
Used to call objects.

The example calls println() and passes one of its string parameters. println() displays the parameters passed to it on the console, and then terminates the output line. Therefore, each call to println() will display the output on a new line.

Java adoption

""
Define the string. Java methods can have no parameters, or one or more. Use empty parentheses even if there are no parameters
()
.
System.out.println();
The statement will print a blank line.

3.2 Notes

  • Java

  • Java 3

    1. //
      //
    2. /* */
      /*
      */
    3. /** */
      /**
      */

3.3

Java Java 8 primitive type 4 2 1 1 boolean

3.3.1

  • Java
min max
int4 -21474836482147483647
short2 -3276832767
long8 -92233720368547758089223372036854775807
byte1 -128127
  • long L l

  • 0X 0x 0 8

  • Java7 0b 0B javac

  • Java unsigned int long short byte

3.3.2

float4 3.40282347E+38F 6~7
double8 1.79769313486231570E+308 15

double float float

  • float F f double

    • 0.125= 0x1.0p-3

      0.125 0.001

      0b1.0*2^-3

      0 0

      p 0x 0x1.0p-3

      16 10 p e e 2 10

      4

    1. NaN
    • Double.POSITIVE_INFINITY Double.NEGATIVE_INFINITY Double.NaN

      Double.isNaN() if(Double.isNaN(x))

BigDecimal

3.3.3 char

  • char Unicode char char

    '

    /** 'A' 65 "A" A */
  • char/u0000~\uFFFF

  • /u

Unicode
\b \u0008
\t \u0009
\n \u000a
\r \u000d
" \u0022
' \u0027
\ \u005c

Unicode

1."\u0022+\u0022" "+"

2.

///u000a is a newline
/u000a

3.

//look inside c:\users
/u 4 16

3.3.4 Unicode char

  • code point Unicode 17 code plane basic multilingual plane 16
  • char UTF-16 code unit char UTF-16

3.3.5 boolean

boolean false true boolean

3.4

  • Java type

  • Java Java

  • 'A'-'Z' 'a'-'z' '_' '$' Unicode

    /** //' ' */

    '0'-'9' Unicode

    • Character isJavaIdentifierStart() isJavaIdentifierPart() Unicode Java

      '$' Java

3.4.1

Java

/** int x = 12; //x 12 x */

3.4.2

  • Java final final

    /** final int X = 12; */
  • Java

    static final
    main()

public class Constants{ public static final double ACONSTANT = 10; public static void main(String[] args){ System.out.println(ACONSTANT); } }

public

3.5

  • Java + - *//%

  • 0 0 NaN

    • strictfp

      strictfp main() strictfp

      /** public static strictfp void main(String[] args) */

      Intel

3.5.1

  • Math
  1. sqrt()a

    /** double y = Math.sqrt(4); System.out.println(y); */
    • println() System.out sqrt()
  2. Java Math.pow()

    /** double y = Math.pow(x,a); //y x a xa pow() double double */
  3. floorMod(x,y)

Math.sin()

Math.cos()

Math.tan()

Math.atan()

Math.atan2()

  1. Exponential function and its inverse function:

Math.exp()

Math.log()

Math.log10()

  1. Java provides two approximate values for representing the constants of and e: (1) Math.PI (2) Math.E
    • By statically importing the Math class at the top of the source file, there is no need to prefix the method name and constant name with "Math"

      /** import static java.lang.Math.*; */ Copy code
    • In order to achieve the fastest performance in the Math class, all methods use routines in the computer's floating-point unit. If you want completely predictable results instead of the fastest running speed, you can use the StrictMath class.

      About the algorithm used by StrictMath: www.netlib.org/fdlibm

3.5.2 Conversion between numeric types

The 6 solid arrows indicate conversions without loss of information. 3.dashed arrows indicate conversions that may have a loss of precision.

  • When performing binary operations on floating-point numbers and integers. To convert the two operands to the same type and then calculate.
    1. If one operand is double, the other operand will be converted to double.
    2. If one operand is float, the other operand will be converted to float.
    3. If one operand is int, the other operand will be converted to int.
    4. Otherwise, both operands are converted to int.

3.5.3 Forced type conversion

  • The grammatical format of cast is to indicate the target type of conversion in parentheses, followed by the variable to be converted.

    /** double x = 1.233; int y = (int)x; //Truncate the decimal part to force the floating-point value to an integer. */ Copy code
  • Math.round() can perform rounding operations.

    /** double x = 9.997; int y = (int)Math.round(x); //round() returns a long, and you also need to force an int conversion. */ Copy code

3.5.4 Combining assignments and operators

  • You can use binary operators in assignments.

    /** x %= 4; equivalent to x = x% 4; */ Copy code
    • int x = 3;

      x += 3.5;

      The type of the value obtained is different from the type of the left operand and will be coerced. Equivalent to x = (int)(x + 3.5);

3.5.5 Increment and decrement operators

  • Postfix form of increment and decrement operators:

n++;
Add 1 to the current value of n.

n--;
Decrease the current value of n by 1.

  • Prefix form of increment and decrement operators:

++n;
Add 1 to the current value of n.

--n;
Decrease the current value of n by 1.

  • The prefix form first adds 1 and then the variable is manipulated; the suffix form manipulates the variable first, then adds one

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

3.5.6 Relations and boolean operators

  • Determine the relationship between two values and generate a boolean value:

equal

==
,not equal
!=
, Less than
<
,more than the
>
, Less than or equal to
<=
,greater or equal to
>=

/** 3==7 is false 3!=7 is true */ Copy code
  • Determine the value of the two expressions and generate a boolean value:

Logical AND operator:

&&
, Logical OR operator:
||

&&
with
||
According to the "short-circuit method" evaluation, if the boolean value of the first relational expression can be determined, the second expression is not calculated and the boolean value of the first expression is generated.

/** expression1&&expression2 */ Copy code
  • Logical NOT operator:
    !
  • Ternary operator:
    ?:

If the condition is true, the value of the first expression is calculated, otherwise the second expression is calculated.

/** condition?expression1:expression2 */ Copy code

3.5.7 Bitwise operators

  • Processing integer type binary numbers, directly operating on the individual binary bits that make up the integer type value. apart from
    ~
    It is a unary operator, and the others are all binary operators.
  1. &
    (And): The corresponding digits of two numbers are identical and true

    /** 0b1100&&0b1000 //Result: 0b1000 */ Copy code
  2. |
    (Or): Two numbers correspond to the same false or false

    /** 0b1100||0b1000 //Result: 0b1100 */ Copy code
    • &
      ,
      |
      When applied with a relational operator, a boolean value will also be obtained, but the expressions on both sides of the operator require a value to generate the boolean result of the entire expression.
  3. ^
    (Xor): Same false but different true

    /** 0b1100||0b1000 //Result: 0b0100 */ Copy code
  4. ~
    (Not): Inverted by bit

    /** ~0b1100 //Result: 0b0011 */ Copy code
  5. Shift left

    <<
    : Shift all binary digits to the left, discard the overflow bit, and add 0 to the empty bit.

  6. Shift right

    >>
    : Shift all binary digits to the right, discard the overflow bit, and make up the sign bit of the original number with a vacant bit.

  7. Unsigned right shift

    >>>
    : Shift all binary bits to the right, discard the overflow bits, and fill in the empty bits with 0.

    /** 0b1100>>1 //Result: 0b1110 */ Copy code

The right operand of the shift operator must perform the operation modulo 32 (unless the left operand is of type long, in which case the right operand must be modulo 64).

3.5.8 Parentheses and operator levels

Without using (), see the operator precedence table:

OperatorAssociativity
.
From left to right
!
~
++
-
+
(Unary operation)
-
(Unary operation)
()
(Forced type conversion)
new
From right to left
*
/
%
From left to right
+
-
From left to right
<<
>>
>>>
From left to right
<
<=
>
>=
instanceof
From left to right
==
!=
From left to right
&
From left to right
^
From left to right
|
From left to right
&&
From left to right
||
From left to right
?:
From right to left
=
+=
-=
*=
/=
%=
&=
|=
^=
<<=
>>=
>>>=
From right to left

3.5.9 Enumerated Type

When the value of the variable is only in a limited set, you can customize the enumeration type. Enumeration types include a limited number of named values.

/** E.g: { enum Size {SMALL,MEDIUM,LARGE,EXTRA_LARGE}; Size s = Size.SMALL; } */ Copy code

Enumeration type variables can store a special value null, which means that the current variable does not have any value set.

3.6 String

A Java string is a sequence of Unicode characters. Java does not have a string type, but provides a predefined class called String in the standard Java class library, each with

"
"
The enclosed string is an instance of the String class.

/** String e = "Hello"; */ Copy code

3.6.1 Substring

String substring()

/** String e = "Hello"; String e1 = e.substring(0,3); //Hel */

3.6.2

  • Java

    +

    /** String e = "Hello"; String s = "!"; String x = e + s; */
  • Java

    /** String e = "page"; int s = "47"; String x = e + s; //x page47 */
  • join()

    /** String all = String.join("\","p","i","g"); //all p\i\g */

3.6.3

  • String substring() Java String

    /** String e = "Hello"; String s = e.substring(0,3) + "p!"; //s Help! */
  • Java

3.6.4

  • equals() boolean

    /** s.equals(t) */
  • equalsIgnoreCase()

    /** s.equalsIgnoreCase(t) */
  • ==
    ==
    ==
    +
    substring()

3.6.5 null

  • 0 length()

    /** int x = s.length(); */

    Java 0

  • String null

    null

    ==

    /** if(s != null && s.length() != 0) */

3.6.6

  • length()

    /** String greeting = "Hello"; int n = greeting.length(); //n 5 */
  • codePointCount()

    /** String greeting = "Hello"; int cpCount = greeting.codePointCount(0,greeting.length()); */
  • charAt(n) n

    /** String greeting = "Hello"; char first = greeting.charAt(0); //first H char last = greeting.charAt(4); //last o */
  • i

    /** String greeting = "Hello"; int index = greeting.offsetByCodePoints(0,i); */
    • Java 0
  • , codePoint() int int

    /** int[] codePoints = str.codePoints().toArray(); */

    /** String str = new String(codePoints,0,codePoints.length()); */

3.6.7 StringAPI

API java.lang String CharSequence

  • API java.lang.String
char charAt(int index)
int codePointAt(int index)
int offsetByCodePoints(int startIndex,int cpCount) startIndex cpCount
int compareTo(String other) other other 0
IntStream codePoints()
new String(int[] codePoints,int offset,int count) offset count
boolean equals(Object other) other true
boolean equalsIgnoreCase(String other) other true
boolean startsWith(String prefix) prefix true
boolean endsWith(String suffix) suffix true
int indexOf(String str) str 0 str -1
int indexOf(String str,int fromIndex) str fromIndex str -1
int indexOf(int cp) cp 0 cp -1
int indexOf(int cp,int fromIndex) cp fromIndex cp -1
int lastIndexOf(String str) str
int lastIndexOf(String str,int fromIndex) str fromIndex
int lastIndexOf(int cp) cp
int lastIndexOf(int cp,int fromIndex) cp fromIndex
int length()
int codePointCount(int startIndex,int endIndex) startIndex endIndex
String replace(CharSequence oldString,CharSequence newString) newString oldString String StringBuilder CharSequence
String substring(int beginIndex) beginIndex
String substring(int beginIndex,int endIndex) beginIndex endIndex
String toLowerCase()
String toUpperCase()
String trim()
String join(CharSequence delimiter,CharSequence... elements)

3.6.8 API

API

3.6.9

  • StringBuilder String

    /** //, StringBuilder String builder = new StringBuilder(); //append() builder.append(char); builder.append(String); //toString() builder String String completedString = builder.toString(); */
    • JDK5.0 StringBuilder StringBuffer StringBuilder API
    • StringBuilder
StringBuilder()
int length()
StringBuilder append(String str) this
StringBuilder append(char c) this
StringBuilder appendCodePoint(int cp) this
void setCharAt(int i,char c) i c
StringBuilder insert(int offset,String str) offset this
StringBuilder insert(int offset,char c) offset this
StringBuilder delete(int startIndex,int endIndex) startIndex endIndex this
String toString()

3.7

3.7.1

  • System.out.println

  • Scanner System.in

    /** Scanner in = new Scanner(System.in); */

    nextLine()

    /** Scanner in = new Scanner(System.in); String name = in.nextLine(); */

    next()

    /** Scanner in = new Scanner(System.in); String firstame = in.next(); */

    nextInt()

    /** Scanner in = new Scanner(System.in); int age = in.nextInt(); */

    nextDouble() Scanner java.util java.lang

    /** import java.util.*; *
    • Scanner Console

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

      Console Scanner

  • API java.util.Scanner

Scanner(InputStream in) Scanner
String nextLine()
String next()
int nextInt()
Double nextDouble()
boolean hasNext()
boolean hasNextInt()
boolean hasNextDouble()
  • API java.lang.System
static Console console() console null console
  • API java.io.Console
static char[] reaPassword(String prompt,Object...args) prompt args
static String readLine(String prompt,Object...args) prompt args

3.7.2

  • System.out.print(x)
    x 0 x

    /** double x = 10000.0/3.0; System.out.print(x); //3333.3333333333335 */
  • JavaSE8 C printf()

    /** System.out.printf("%8.2f",x); //8 x 3333.33 */

    printf()

    /** System.out.print("Hello,%s.Next year,you'll be %d",name,age); */

    %

  • printf

d
x
o
f
e
g
a
s
c
bboolean
h
%%
n
/** //42628b2 */

s Formattable formatTo() toString()

  • .

    /** //`"%,(.2f"` */
+ -3333.33
| 3333.33|
0 0003333.33
- |3333.33 |
( (3333.33)
, 3,333.33
# f 3333.
# x o 0x 00xcafe
$ 159 9f %1$d,%1$x
< 159 9f %d%<x
  • String.format()

    /** String message = String.format("Hello,%s.Next year,you'll be %d",name,age); */

1

3.7.3

  • File Scanner

    /** Scanner in = new Scanner(Paths.get(myfile.txt"),"UTF-8"); //`\` `\` `\` //UTF-8 */
  • PrintWriter

    /** PrintWriter out = new PrintWriter("myfile.txt","UTF-8"); // */
  • Java

    java XXX
    IDE IDE System.getProperty()

    /** String dir = System.getProperty("user.dir"); */
  • Scanner PrintWriter IOexception javac 0 javac main() throw

    /** public static void main(String[] args) throws IOException{ Scanner in = new Scanner(Path.get("myfile.txt"),"UTF-8"); ... } */
    • shell System.in System.out

      /** java MyProg<myfile.txt>output.txt */
  • API java.util.Scanner

Scanner(File f) Scanner
Scanner(String data) Scanner
  • java.io.PrintWriter
PrintWriter(String fileName) PrintWriter
  • java.nio.file.Paths
static Path get(String pathname) Path

3.8

Java

3.8.1

block

{}
Java

/** public static void main(String[] args){ int n; ... { int k; ... } } */

3.8.2

  • if(condition)statement

  • if(condition)statement else statement2

    else else if

3.8.3

  • true while false

    while(condition) statement

  • do/while

    do statement while(condition)

3.8.4

  • for

    /** for(int i = 1; i <= 10; i++) System.out.print(i); //1~10 */

    for

  • Java for for for

/** for(double x = 0; x != 10; x +=0.1;) //0.1 x 9.999 999 999 999 98 10.099 999 999 999 98 */

3.8.5 switch

  • switch switch condition case statement
    break;
    switch default default
switch(condition){ case 1: statement1; ... break; case 2: statement1; ... break; case ... default: statement; ... break; }

case case

break;
case case
break;

-Xlint:fallthrough
javac break

/**

javac -Xlint:fallthrough Test.java

*/

break

@SuppressWarnings("fallthrough")

javac Java

  • case
    1. char byte short int
    2. JavaSE7
    switch case

3.8.6

  • break;
    Java break break break break

    /** ... label: while(...){ ... break label; } //label break */
  • continue;
    for for

    continue

3.9

  • java.math BigInteger BigDecimal

    valueOf()

    /** BigInteger a = BigInteger.valueOf(100); */

    add() multiply()

    /** BigInteger c = a.add(b); BigInteger d = c.multiply(b.add(BigInteger.valueOf(2))); */
  • API java.math.BigInteger

BigInteger add(BigInteger other) other
BigInteger substract(BigInteger other) other
BigInteger multiply(BigInteger other) other
BigInteger divide(BigInteger other) other
BigInteger mod(BigInteger other) other
int compareTo(BigInteger other) other 0 other
static BigInteger valueOf(long x) x
  • API java.math.BigDecimal
BigDecimal add(BigDecimal other) other
BigDecimal substract(BigDecimal other) other
BigDecimal multiply(BigDecimal other) other
BigDecimal divide(BigDecimal other) other ,
RoundingMode.HALF_UP
int compareTo(BigDecimal other) other 0 other
static Bigcemal valueOf(long x) x
static Bigcemal valueOf(long x,int scale) x/10^scale

3.10

  • n

    /** int[] a = new int[100]; //100 int */

    0 0 boolean false null

  • array.length

    /** int x = a.length; */

    -- array list

3.10.1 for each

  • foreach

    for(variable : collection) statement

    variable collection statement collection Iterable

    • array.toString()

      /** System.out.println(Arrays.toString(a)); */

3.10.2

  • new

    /** int[] a = {2,3,4,6}; */
  • /** new int[] = {2,3,4,6}; */

    • Java 0 0 null

3.10.3

  • Java Arrays copyOf()

    /** int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers,luckyNumbers.length); */

    0 false

    • Java
      []
      a+1

3.10.4

  • Java String arg[] main() main

    /** 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,"); for(int i = 1,i < args.length;i++) // System.out.print(" " + args[i]); System.out.println("!"); } } //java Messa -g cruel world args[] = {"-g","cruel","world"} //Goodbye, cruel world! */
    • Java args

3.10.5

  • Arrays sort()

    /** int[] a = new int[10000]; ... Arrays.sort(a); */
  • API java.util.Arrays

static String toString(type[] a) a
,
a char byte boolean
static type copyOf(type[] a,int length) length a
,
a char byte boolean
static type copyOfRange(type[] a,int start,int end) end-start a
,
a char byte boolean start
static void sort(type[] a) a char byte boolean
static int binarySearch(type[] a,type v) a v r -r-1 a v a char byte boolean v a
static int binarySearch(type[] a,int start,int end,type v) a b v r -r-1 a v a char byte boolean v a
static void fill(type[] a,type v) v a char byte boolean v a
static booleav equals(type[] a,type[] b) true false a char byte boolean b a
### 3.10.6
  • /** double[][] = balances; */

    [][]

    /** balances[i][j] //balances i j */
    • foreach

    • deepToString()

      /** System.out.println(Arrays.deepToString(a)); // //[[1,2,3][4,5,6][7,8,9]] */

3.10.7

  • Java

    /** double[] temp = balances[i]; balances[i] = balances[i+1]; balances[i+1] = balances[temp]; */

4

4.1 OOP

4.1.1

  • class construct instance

  • encapsulation instance field method state

  • inheritance Java Object

4.1.2

  1. behavior --

  2. state --

  3. identity --

4.1.3

OOP

4.1.4

  1. use-a

dependence

  1. has-a

aggregation A B

  1. is-a

inheritance

4.2

OOP Math

4.2.1

  • constructor

    new

    /** new Date() */

    /** System.out.pringln(new Date()); // String s = new Date().toString(); // Date birthday = new Date(); */
  • /** Date deadline; //deadline Date //deadline */
  • Java new

    /** Date deadline = new Date(); //New Date() Date //deadline */

    null null new null

    • Java heap

4.2.2 Java LocalDate

  • Data LocalDate

  • LocalDate factory method

    /** LocalDate.now() // LocalDate.of(1999,12,31) // */
  • getYear() getMonthValue() getDayOfMonth()

    /** LocalDate newYearsEve = LocalDate.of(1999,12,31) int year = newYearsEve.getYear(); int month = newYearsEve.getMonthValue(); int day = newYearsEve.getDayOfMonth(); */

4.2.3

  • mutator method accessor method

    /** LocalDate.getYear() */
  • API java.time.LocalDate

static LocalTime now()
static LocalTime of(int year,int month.int day)
int getYear()
int getMonthValue()
int getDayOfMonth()
DayOfWeek getDayOfWeek()
DayOfWeek getValue() 1~7
LocalDate plusDays(int n) n
LocalDate minusDays(int n) n

4.3

  • workhorse class main() main()

    • 4-3 EmployeeTest.java/Employee.java
import java.time.*; /** * This program tests the Employee class. * @version 1.12 2015-05-08 * @author Cay Horstmann */ public class EmployeeTest { public static void main(String[] args){ //fill the staff array with three Employee objects Employee[] staff = new Employee[3]; staff[0] = new Employee("Carl Cracker", 75000, 1987, 12, 15); staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tony Tester", 40000, 1990, 3, 15); //raise everyone's salary by 5% for (Employee e : staff) e.raiseSalary(5); //print out information about all Employee objects for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary() + ",hireDay=" + e.getHireDay()); } } class Employee{ private String name; private double salary; private LocalDate hireDay; public Employee(String n, double s, int year, int month, int day){ name = n; salary = s; hireDay = LocalDate.of(year, month, day); } public String getName(){ return name; } public double getSalary(){ return salary; } public LocalDate getHireDay(){ return hireDay; } public void raiseSalary(double byPercent){ double raise = salary * byPercent/100; salary += raise; } }

4.3.1 Employee

  • Java
class ClassName{ field1 field2 ... constructor1 constructor2 ... method1 method2 ... }

public

4.3.2

  1. /** javac Employee*.java // */
  2. javac main()

    /** javac EmployeeTest.java //javac .class //.java //.java .class */

4.3.3 Employee

  • public

    private

  • /** private String name; private LocalDate hireday; private double salary; */

4.3.4

  • /** public Employee(String n, double s, int year, int month, int day){ name = n; salary = s; hireDay = LocalDate.of(year, month, day); } */

    new

    • Java

4.3.5

  • /** public void raiseSalary(double byPercent){ double raise = salary * byPercent/100; salary += raise; } */
  • implicit explicit

    ()

    this

    /** public void raiseSalary(double byPercent){ double raise = this.salary * byPercent/100; this.salary += raise; } */
    • Java Java

4.3.6

/**

//4-3

//Employee getHierDay() Date

class Employee{ private Date hireDay; ... public Date getHireDay(){ return hireDay; } ... }

//LocalDate Date getTime() Date

Employee harry = ...; Date d = harry.getHireDay(); double tenYearsInMilliSeconds = 10*365.25*24*60*60*1000; d.setTime(d.getTime()-(long)tenYearsInMilliSeconds);

//d harry d //clone //clone

class Employee{ ... public Date getHireDay(){ return (Date)hireDay.clone(); } ... }

*/

4.3.7

4.3.8

public public private

4.3.9 final

final final primitive immutable

/** //String */

4.4

4.4.1

static

4.4.2

  • out System
    • System setOut() out setOut() Java Java

4.4.3

4.4.4

/** //NumberFormat NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(); MunberFormat percentFormatter = NumberFormat.getPercentInstance(); double x = 0.1; System.out.println(currencyFormatter.format(x)); System.out.println(percentFormatter.format(x)); // //1. //2. Factory DecimalFormat NumberFormat */

4.4.5 main()

  • main() main()
    • main() main()
      java Classname
      java Application
      , main()

4.5

  • call by value call by reference

    call by//// Java

    /** // public static void tripleValue(double x){ x = 3 * x; } double percent = 10; tripleValue(percent); //1.x percent //2.x 3 30 percent //3. x // public static void tripleSalary(Employee x){ x.raiseSalary(200); } harry = new Employee(...); tripleSalary(harry); //1.x harry //2.raiseSalary() x harry //3. x harry */
  • Java

    /** // */

4.6

Java

4.6.1

  • overloading

    javac

    javac overloading resolution

    • Java signature

      /** //String 4 indexOf() //indexOf(int) //indexOf(int,int) //indexOf(String) //indexOf(String,int) */

4.6.2

4.6.3

4.6.4

4.6.5

/** public Employee(String name,double salary){ this.name = name; this.salary = salary; } */

4.6.6

this

/** public Employee(double s){ //Employee(String,double) this("Employee #" + nextId,s); nextId++; } */

4.6.7

Random()
int nextInt(int n) 0~n-1
### 4.6.8 finalize()
  • finalize() finalize() finalize()
    • System.runFinalizersOnExit(true) finalize() Java

      Runtime.addShutdownHook shutdown hook API

    close()

4.7

  • Java package
  • Java java.lang java.util java.net Java Java java javax

4.7.1

  • public class

    1. import
  • import import import package

    /** //java.util import java.util.*; */

    *
    java

  • compiler

4.7.2

import

/** //import System import static java.lang.System.*; // */

4.7.3

  • /** package com.horstmann.corejava; public class Employee{ ... } */

    package default package

  • javac

    /** com.horetmann.corejava Windows com/horstmann/corejava */
  • javac

javac

4.7.4

  • public private

    private

  • JDK1.2

    java.
    java

    package sealing JAR

4.8

  • JAR java JAR third-party JAR

    • JAR ZIP ZIP
    1. JAR

    2. class path Windows

      ;

      /** c:\classdir;.;c:\archives\archive.jar */
    1. JAR

    JAR

    /** c:\classdir;.;c:\archives\* */

    rt.jar jre/lib jre/lib/ext JAR

javac

.
.
.

  • javac javac import javac import java.lang import

    javac

4.8.1

  • -classpath
    -cp
    , shell

    /** java -cp c:\classdir;.;c:\archives\* MyProg */
  • CLASSPATH shell

    /** //Windows shell set CLASSPATH=c:\classdir;.;c:\archives\* */

  1. CLASSPATH
  2. jre/lib/ext

4.9

JDK javadoc HTML API Java javadoc

4.9.1

  • javadoc utility

    /**
    */

  • free-form text

    @

    javadoc

    HTML

    • doc-files doc-files javadoc

4.9.2

import

4.9.3

  1. @param

param HTML

@param

  1. @return

return HTML

  1. @throws

/** /** Raise the salary of an employee. @param byPercent the percentage by which to raise the salary(e.g. 10 mean 10%) @return the amount of the raise */ public double raiseSalary(double byPercent){ double raise = salary * byPercent/100; salary += raise; return raise; } */

4.9.4

4.9.5

    1. @author

    author

    @author
    @author

    1. @version

    version

    1. @since

    since

    1. @deprecated

  • javadoc

    1. @see

    see also

    @see

    1

    package.class#feature label

    label link anchor javadoc label URL

    #

    /** @see com.horstmann.corejava.Employee#raiseSalary(double) */

    2

    <a href="...">label</a>

    URL label link anchor label URL

    /** @see <a href="www.horstmann.com/corejava.html">The Core Java home page</a> */

    3

    "text"

    " "
    see also

    /** @see "Core Java 2 volume 2" */
    1. @link

    {@link package.class#feature label}
    label link anchor javadoc label URL
    #

    /** {@link com.horstmann.corejava.Employee#raiseSalary(double)} */

4.9.6

  • Java 2
    1. package.html
      <body>...</body>
    2. package-info.java
      /**
      */
      javadoc
  • overview.html overview.html
    <body>...</body>
    Overview

4.9.7

  • HTML docDirectory

    1. javadoc -d docDirectory nameOfPackage

      javadoc -d docDirectory nameOfPackage1,nameOfPackage2...

      javadoc -d docDirectory *.java

      -d docDirectory HTML

  • javadoc

    -author -version @author @version

    -link

    /** javadoc -link http://docs.orcle.com/javase/8/docs/api *.java //Oracle */

    -linksource HTML

    javadoc

    docs.oracle.com/javase/8/do

4.10

  1. bug

  2. Java

  3. get set

  4. LocalDate java.time plusDays()

5

  • Java

    • 5-1 inheritance/Empolyee.java
package inheritance; import java.time.*; public class Employee{ private String name; private double salary; private LocalDate hireDay; public Employee(String name, double salary, int year, int month, int day){ this.name = name; this.salary = salary; hireDay = LocalDate.of(year, month, day); } public String getName(){ return name; } public double getSalary(){ return salary; } public LocalDate getHireDay(){ return hireDay; } public void raiseSalary(double byPercent){ double raise = salary * byPercent/100; salary += raise; } }

5.1

5.1.1

  • extends superclass base class parent class subclass derived class child class
  • OOP

5.1.2

  • override

    /** // //Employee Manager */
    • 5-2 inheritance/Manager.java
package inheritance; public class Manager extends Employee{ private double bonus; /** * @param name the employee's name * @param salary the salary * @param year the hire year * @param month the hire month * @param day the hire day */ public Manager(String name, double salary, int year, int month, int day){ super(name, salary, year, month, day); bonus = 0; } public double getSalary(){ double baseSalary = super.getSalary(); return baseSalary + bonus; } public void setBonus(double b){ bonus = b; } }
  • super

    /** //5-2 public class Manager extends Employee{ private double bonus; ... public void setBonus(double bonus){ this.bonus = bonus; } public double getSalary(){ double baseSalary = super.getSalary(); return baseSalary + bonus; } ... } */
    • super this super super javac

5.1.3

  • super super

  • javac

    • this super this super
  • polymorphism dynamic binding

    /** //5-3 for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()); //e Employee e Employee Manager */
    • 5-3 inheritance/ManagerTest.java
package inheritance; /** * This program demonstrates inheritance. * @version 1.21 2004-02-21 * @author Cay Horstmann */ public class ManagerTest{ public static void main(String[] args){ //construct a Manager object Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15); boss.setBonus(5000); Employee[] staff = new Employee[3]; //fill the staff array with Manager and Employee objects staff[0] = boss; staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1); staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15); //print out information about all Employee objects for (Employee e : staff) System.out.println("name=" + e.getName() + ",salary=" + e.getSalary()); } }

5.1.4

inheritance hierarchy inheritance chain

/** //Manager Executive */

5.1.5

Java

Java ArrayStoreException

5.1.6

  • x C x.f(param)

    1. javac javac C f() public f()
    2. javac 1 overloading javac
    1. private static javac static binding

      /** //x.f("Hello") javac f(String) */
    2. x

      /** //x.f("Hello") C f(String) C f(String) */

      method table

public public javac

5.1.7 final

  • final

    /** public final class Executive extends Manager{ ... } */
  • final final final

    • final final final
  • final

  • inlining

5.1.8