0% found this document useful (0 votes)
6 views212 pages

Learn Java Programming Basics

The document is a comprehensive guide to learning Java, covering topics such as installation, basic concepts, operators, statements, object-oriented programming, multithreading, exceptions, and file I/O. It includes practical examples and detailed explanations to cultivate programming interest and understanding. The book aims to simplify complex concepts and provide a fun programming experience.

Uploaded by

juanpi.dangelo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views212 pages

Learn Java Programming Basics

The document is a comprehensive guide to learning Java, covering topics such as installation, basic concepts, operators, statements, object-oriented programming, multithreading, exceptions, and file I/O. It includes practical examples and detailed explanations to cultivate programming interest and understanding. The book aims to simplify complex concepts and provide a fun programming experience.

Uploaded by

juanpi.dangelo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Easy Learning Java

YANG HU

The complexity of life, because they do not understand to


simplify the complex, to simplify the complexity, simple
is the beginning of wisdom.
From the essence of practice, to briefly explain the
concept, and vividly cultivate programming interest, this
book deeply analyzes Java object-oriented programming,
combined with the use of scene interpretation in practice,
to experience the fun of programming.
[Link]
Copyright © 2019 Yang Hu
All rights reserved.
ISBN: 9781091940338

CONTENTS
1. Java JDK installation
2. Eclipse installation
3. Basic concepts of Java
3.1 HelloWorld detailed explanation
3.2 Identifier
3.3 Variable
3.4 Basic data types
3.5 Constant
3.6 Data type conversion
4. Java Operators
4.1 Arithmetic operator
4.2 Assignment operator
4.3 Relational operator
4.4 Logical Operators
4.5 Trinocular Operator
5. Java Statement
5.1 If statements
5.2 Switch statement
5.3 While loop statement
5.4 Do while loop
5.5 For loop statement
6. Java array
6.1 One-dimensional array
6.2 One-dimensional array append element
6.3 One-dimensional array remove elements
6.4 Bubble sorting algorithm
6.5 Two-dimensional array
6.6 Examples: Minesweeper
7. Java Object-Oriented
7.1 Encapsulation
7.2 Methods Encapsulation
7.3 Construction method
7.4 Method overload
7.5 Passed by reference
7.6 Static keyword
7.7 Code block
7.8 Inheritance
7.9 Method override
7.10 abstract class
7.11 instanceof
7.12 interface
7.13 final
7.14 enum
7.15 Polymorphism
7.16 Polymorphic Example
7.17 Internal class
7.18 Static internal class
7.19 Basic data wrap class
7.20 Anonymous inner class
7.21 package
8. Multithreading
8.1 Thread
8.2 Runnable
9. Exception
9.1 Runtime exception
9.2 Compile-time exception
9.3 finally
10. String
10.1 String assignment and comparison
10.2 Byte and string conversion
10.3 String judgment operation
10.4 String replacement
10.5 String search and cut
10.6 String split
10.7 StringBuffer and StringBuilder
11. Common class library
11.1 Arrays
11.2 Calandar
11.3 Date
11.4 Math
11.5 Comparable
11.6 Comparator
11.7 Random
11.8 Timer TimerTask
12. Collection data structure
12.1 List and ArrayList
12.2 LinkedList
12.3 Iterator
12.4 Vector
12.5 Collections
12.6 Set HashSet TreeSet
12.7 Map HashMap Hashtable
12.8 Map user login example
12.9 Stack
12.10 Generic
12.11 Generic Housing rental example
12.12 Generic about school examples
13. File IO
13.1 File
13.2 File and Folder
13.3 FileInputStream reads a file
13.4 FileOutputStream writes to file
13.5 FileWriter writes characters
13.6 FileReader reads files as characters
13.7 InputStreamReader byte to character stream
13.8 File copy
14. Java network programming
14.1 TCP protocol
14.2 UDP protocol

Java JDK installation


1. Download the JDK ( Java development kit )

[Link]

There are 3 JDK versions. We use [Link] as an example.

[Link]

[Link]

[Link]

2. Install the JDK development kit

Unzip [Link]

Click [Link] all to the next step to complete the


installation.
Installation path: C:\Program Files (x86)\Java\jdk1.6.0_45
Configuring environment variables in window 7:

Right click -> My Computer -> Properties

Click Advanced System Settings


Click Advanced -> Environment Variables
Click the New button to create 3 environment variables.
JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_24

CLASSPATH=%JAVA_HOME%\lib\[Link];%JAVA_HOME%\lib\[Link];.

PATH=%JAVA_HOME%\bin
Click OK to exit.

Then open the Command Window and test if the installation is successful.

Click the Start menu -> Search box -> Enter cmd
Input java -version The installation is successful. bellow picture:
Eclipse installation
1. Download the Eclipse development tools

[Link]

[Link]

2. Install eclipse development tools

Unzip [Link] to D:\eclipse

Click D:\eclipse\[Link] to run


Create a new Java project
Click Eclipse -> File -> New -> Project

Select Java Project -> next


Enter the Project name helloworld -> Finish
Right click on the src of the hellowolrd project -> New -> Class
Enter the program Class name HelloWorld -> Finish
src -> HelloWorld class code:
In the HelloWorld code editing window
Right click -> Run As -> Java Application
HelloWorld
output in Console Panel
running successfully
HelloWorld Detailed Explanation
/**
1. // : double slashes represent comments
2. public : is the keyword of java
3. class : each java file must contain a class
4. HelloWord : is called the class name
5. static : the main method must be written to the static java virtual
machine to find
6. void : no return value
7. main : is called the main method, is the entry of the java program.
8. String : is a series of combinations of numeric characters enclosed in
double quotes
9. String[] : string array
10. args : is called the parameter of the main method

Coding Standards:
1. Class name The first word is capitalized. If there are multiple words, the
first letter of each word is capitalized.
2. java is a case-sensitive language
3. When writing a class body {} parentheses must appear in pairs
4. When writing the method body {} brackets should appear in pairs
5. The method is written in the class body. Leave a tab space in front of each
method.
6. Each execution statement leaves a tab space before the method,
each statement is written with a semicolon; it indicates the end of the
statement execution.
*/

public class HelloWorld {


public static void main(String[] args) {
// Print out the Hello Word message to the console and then change the
line
[Link]("Hello Word");
// Print input information to the console, but do not wrap
[Link]("Good beginning \t");
[Link]("is the half of the success");
}
}

Output Result:

Hello Word
Good beginning is the half of the success
Identifier
/**
The naming rules for identifiers:
1. It consists of letters, numbers, descending lines _ and dollar signs $
2. Can't start with a number
3. Case sensitive
4. Cannot be a reserved keyword for java
*/
public class TestIdentifier{
public static void main(String[] args){
// can not start with a number
//int 1number=1;

// identifier is case sensitive


int var1=2;
int VAR1=3;
[Link](var1);
[Link](VAR1);
//Cannot be a reserved keyword for java
//int class=4;

int salary=20000;
//Two strings are concatenated with a plus sign +
[Link]("Your salary is:"+salary);
}
}

Output Result:

2
3
Your salary is:20000
Variable
/**
1. Variable naming does not allow repetition
2. The naming rules for variables: consisting of characters, underscores, $,
numbers,
and the beginning of the first letter must be a character, the descending line
or $, can not be a number
*/
public class TestVariable {
public static void main(String[] args) {
// Variable definition: a memory area allocated by the system to store data
//String: character enclosed in double quotes " ".
//cup: variable name.
// =: the "mineral water" data is stored in the memory area
named cup.
String cup = "mineral water";

// Print the data of the variable name cup memory area to the console
[Link](cup);

// Modify the value of the variable


cup = "cola";
[Link](cup);

// Empty the variable, empty the cup's memory data


cup = "";
[Link](cup);

// Assign a value to the null to delete the variable


//cup variable will automatically reclaim allocated memory space
cup = null;
[Link](cup);

//variable name cannot be defined repeatedly.


//String cup="ice black tea";
//[Link](cup);
// Variable naming rules: consists of characters, underscores, $, numbers,
//and the beginning of the first letter must be a character, the down line or
$
//can not be a number
//String 1var="a";
//[Link](1var);
String $var = "b";
[Link]($var);
String _var = "_var";
[Link](_var);

}
}

Output Result:

mineral water
cola

null
b
_var
Basic Data Types
/**
Java has 8 basic data types.
1. Integer (byte, short, int, long)
2. Floating point (float, double)
3. Character type (char)
4. Boolean (boolean)
*/
public class BaseDataType {
public static void main(String[] args){
// integer byte, short, int , long
byte a1=1; //byte occupies 1 byte = 8 bits -2^7~2^7-1(-128~127)
short a2=10; //short 2 bytes=16 bits -2^15~2^15-1
int a3=100; //int 4 bytes = 32 bits -2^31~2^31-1
long a4=1000; //long occupies 8 bytes = 64 bits -2^63~2^63-1
[Link](a1);
[Link](a2);
[Link](a3);
[Link](a4);
//1. If the integer assignment is out of the storage range, compile the error,
lose the precision.

//float type , double


double b1=10.1; //double occupies 8 bytes = 64 bits
float b2=12.2f; //float occupies 4 bytes = 32 bits
float b3=(float)13.3;
[Link](b1);
[Link](b2);
[Link](b3);
//1. Floating-point data defaults to double type. If you want to assign a
value to float, you must cast it.
//There are two ways to force type conversion for floating point numbers.
One is: Add f directly to the back. One is: add (float) in front.

//char is a single character enclosed in single quotes


char c1='a'; // char takes 2 bytes = 16 bits
char c2='1';
[Link](c1);
[Link](c2);

//boolean
boolean d1=true; // boolean occupies 1 byte = 8 bits
boolean d2=false;
[Link](d1);
[Link](d2);
//1. The boolean type of true cannot be equal to 1, and false is not equal to
0. This is different from the c language.
}
}

/**
Review summary:
1. Basic data type variables: 8 basic data types (byte, short, int, long, float,
double, boolean, char)
2. String is not a basic data type. It is a reference data type.
*/

Output Result:

1
10
100
1000
10.1
12.2
13.3
a
1
True
false
Constant
/**
The constants in java:
1. Integer constant
2. Floating point constants
3. Character constants
4. Boolean constants
5. String constants
*/
public class FinalVariable {
public static void main(String[] args) {
// Constant definition: variables that can not be changed
//1. Integer constant
final int UP = 0;
final int DOWN = 1;
final int LEFT = 2;
final int RIGHT = 3;
[Link](UP);
[Link](DOWN);
[Link](LEFT);
[Link](RIGHT);
//1. The definition of a constant is generally capitalized.

//2. Floating point constant


final float PI = 3.14f;
[Link](PI);
//3. Boolean constant
final boolean RUN = true;
[Link](RUN);

//4. Character constants


final char A = 'A';
[Link](A);
[Link]('\r');
[Link]('\'');
[Link]('\"');
[Link]('\\');

//5. String constants


final String CONST = "love for forever";
[Link](CONST);
}
}
/**
Summary:
1. The naming rules for constants are the same as variables
2. Constants are generally uppercase
3. Add a final keyword before the constant
4. Constants cannot change values
*/

Output Result:

0
1
2
3
3.14
true
A

'
"
\
love for forever
Data Type Conversion
/**
Data type conversion :
1. Integer type conversion
2. Floating point type conversion
3. Boolean type conversion
4. Character type conversion
*/
public class TypeConvert {
public static void main(String[] args) {
byte varByte = 1;
int varInt = 2;
// Small integer type converted to a large integer type, direct conversion
varInt = varByte;
[Link](varInt);

byte varBtye2 = 1;
int varInt2 = 2;
int varInt3 = 128;
// Large integer types are converted to small integer types, which require a
cast,
// and may lose precision. The high bits will be cut.
varBtye2 = (byte) varInt2;
varBtye2 = (byte) varInt3;
[Link](varBtye2);

byte c1 = 1;
float c2 = 10.3f;
//Integer to floating point type, direct conversion
c2 = c1;
[Link](c2);

byte d1 = 1;
float d2 = 10.3f;
float d3 = 128.2f;
//Floating point type rounding directly removes the fractional part,
requires cast, and may lose precision
d1 = (byte) d2;
d1 = (byte) d3;
[Link](d1);

// Boolean can’t be converted to other types, other types can’ be converted


to Boolean
boolean e1 = true;
//e1=(boolean)1;

char f1 = 'a';
int f2 = 1;
char f3 = 'b';
int f4 = 'b' + 1;
char f5 = 'b' + 1;
//Integer can be converted to a character type, which requires a cast,
//and an integer can be converted to a character. The conversion rule by
ACSII.
f1 = (char) f2;
f2 = f3;
[Link](f1);
[Link](f2);
[Link](f4);
[Link](f5);

//string connection + conversion


String str = "Perseverance in the ordinary";
String str2 = str + 1;
String str3 = str + 2.5;
String str4 = str + true;
String str5 = str + 'F';
// String is added to other basic types Other types are automatically
converted to string connections
[Link](str2);
[Link](str3);
[Link](str4);
[Link](str5);
}
}
/**
Summary:
1. Type conversion small value to large value conversion
byte<short<int<float<long<double
*/

Output Result:

1
-128
1.0
-128
98
99
c
Perseverance in the ordinary1
Perseverance in the ordinary2.5
Perseverance in the ordinarytrue
Perseverance in the ordinaryF

Arithmetic operator
/**
Arithmetic operation:
add +, minus -, multiply *, divisible /, take modulo %, decrement ---,
increase ++
*/
public class ArithmeticOperator {
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 3;
int d = 4;
[Link](a + b);
[Link](a - b);
[Link](a * b);
[Link](b / a);
[Link](a / b);
// modulo is the remaining number after the division
[Link](c % b);
[Link](d % b);
[Link](4 % -3);
[Link](-4 % -3);
[Link](-4 % 3);
[Link](d++);
[Link](++d);
[Link](d--);
[Link](--d);
}
}
/**
Summary:
1. The decimal part is automatically cut off when divisible
2. When the modulo is taken, the positive and negative result values ​depend
on the numerator symbol.
3. ++ after the variable is output first then plus 1,
if ++ is placed in front of the variable, then add + first then output.
4. -- after the variable, it is output first and then decremented by 1.
If it is placed in front of the variable, it is first reduced by 1 and then
output.
*/

Output Result:

3
-1
2
2
0
1
0
1
-1
-1
4
6
6
4
Assignment operator
public class AssignmentOperator {
public static void main(String[] args) {
int var = 10;
var = var + 1;
var++;
var += 1;
var /= 2;
var %= 2;
var *= 2;
[Link](var);

short s = 10;
s = (short) (s + 5);
s += 5;
[Link](s);
}
}

Output Result:

0
20
Relational operator
/**
Relational operator There are only two results: true , false
Includes:
Greater than >, greater than or equal to >=
Less than <, less than or equal to <=
Equal to ==, not equal to !=
*/
public class RelationalOperator {

public static void main(String[] args) {


[Link](100 > 200);
[Link](100 >= 100);
[Link](100 < 200);
[Link](100 <= 200);
[Link](100 == 100);
[Link](100 != 200);
[Link](100 == 100.0);
[Link]('A' == 65);

//true cannot be equal to 1 and false cannot be equal to 0;


//[Link](true==1);
}
}

Output Result:

false
true
true
true
true
true
true
true
Logical Operators
/**
include:
and &&, or ||, not !
1. && returns true if both sides of the operation are true, otherwise false
2. || The result is false when both sides of the operation are false, otherwise
true;
3. ! the operation returns true, the result is false, otherwise it is true
*/
public class LogicalOperator {
public static void main(String[] args) {
[Link](true && false);
[Link](false && true);
[Link](false && false);
[Link](true && true);

[Link]("---------------");

[Link](true || false);
[Link](false || true);
[Link](true || true);
[Link](false || false);

[Link]("---------------");

[Link](!true);
[Link](!false);

[Link]("----------------");

boolean b = true;
[Link](b);
[Link](1 > 2 && (b = 3 > 4));
[Link](b);
[Link](2 > 1 && (b = 3 > 4));
[Link](b);
//Short circuit characteristics of &&: Because the program is executed
from top to bottom, from left to right, when the left side is judged to be false
//The result of && is already destined to be false, so the subsequent
judgment computer will not be executed.

[Link]("--------------");

boolean b1 = true;
[Link](b1);
[Link](2 > 1 || 3 > 4);
[Link](2 > 1 || (b1 = 3 > 4));
[Link](b1);
[Link](1 > 2 || (b1 = 3 > 4));
[Link](b1);
//Short circuit characteristics of ||: Because the program is executed from
left to right, when the left side is judged to be true,
//the return result is already destined to be true, so the subsequent
judgment computer does not execute.
}
}

Output Result:

false
false
false
true
---------------
true
true
true
false
---------------
false
true
----------------
true
false
true
false
false
--------------
true
true
true
true
false
false

Trinocular Operator
public class TrinocularOperator {
public static void main(String[] args) {
int score = 90;
String result = score >= 60 ? "Pass" : "Fail";
[Link](result);
}
}

Output Result:

Pass
If Conditional statements
/**
Conditional statement
include:
1. if(expression){statement}
2. if (expression) { statement } else { statement }
3. if (expression) {statement } else if { statement }

Topic:
tax amount = (basic salary -3500) * tax rate
level:
500 -- 2000 $ : 10% tax rate
2000--5000 $: tax rate 15%
5000-- 20000 $: tax rate 20%
More than 20000 : tax rate 30%
*/
public class IfStatement {

public static void main(String[] args) {

int salary = 23500;// basic salary


int extra = salary - 3500;// Excessive tax is required
double tax = 0; //tax amount
if (extra >= 500 && extra < 2000) {
tax = extra * 0.1;
} else if (extra >= 2000 && extra < 5000) {
tax = extra * 0.15;
} else if (extra >= 5000 && extra < 20000) {
tax = extra * 0.2;
} else {
tax = extra * 0.3;
}
[Link]("tax amount=" + tax);
}
}
Output Result:

tax amount=6000.0
Switch statement

/**
Keyboard input a number 0, 1 , 2, 3
0 : Output The airplane moves up
1 : Output The airplane moves down
2 : Output The airplane moves to the left
3: Output The airplane moves to the right
Otherwise the output does not move
*/
import [Link];

public class SwitchStatement {

public static void main(String[] args) {


Scanner in = new Scanner([Link]);
[Link]("Keyboard enters a number 0: up, 1: down, 2: left, 3:
right");
int num = [Link]();

//switch statement
switch (num) {
case 0:
[Link]("Airplane moves up");
break; // terminate the code to continue execution
case 1:
[Link]("Airplane moves down");
break;
case 2:
[Link]("Airplane moves to the left");
break;
case 3:
[Link]("Airplane moves to the right");
break;
default:
[Link]("Airplane does not move");
}
}
}
/**
Summary:
1. default: is the default execution when there is no matching condition
2. break: the switch is terminated. If there is no break statement, the
program will continue to execute.
3. The switch (expression) expression can only be a byte, short, int, char
type constant
String jdk1.6 version is not working, but after jdk1.7 version String can be
used in switch
*/

Output Result:

Keyboard enters a number 0: up, 1: down, 2: left, 3: right


2
Airplane moves to the left
While loop statement
/**
While(expression){
statement;
}
continues execution if the expression is true, otherwise exits the loop

Topic :
In 2006, 80,000 students were trained, an annual increase of 25%.
According to this growth rate, how many years the total number of students
will reach 200,000 ?
2006 year : sum=8(1+0.25)^0
2007 year : sum=8+8*0.25=8(1+0.25)^1;
2008 year : sum=8(1+0.25) + 8(1+0.25)*0.25=8(1+0.25)
(1+0.25)=8(1+0.25)^2
n year : sum=8(1+0.25)^n
*/
public class WhileStatement {
public static void main(String[] args) {
int sum = 8;
int n = 0; //The total number will reach 200,000
while (sum < 20) //condition is true to execute, otherwise the loop is
terminated
{
sum = (int) (sum * (1 + 0.25));
n++;
}
[Link]("After " + n + " years the total of students will reach
200,000");
}
}

Output Result:

After 5 years the total of students will reach 200,000


Do while loop

/**
do{
statements;
}while (expression):
until the while expression evaluates to false exit loop
*/
import [Link];

public class DoWhileStatement {

public static void main(String[] args) {


/*
Cut fruit game:
keyboard input 1: watermelon, 2: banana, 3: peach, -1: thunder
Enter the number to print the corresponding fruit, if enter -1 to
terminate the game
*/
[Link]("Keyboard Input 1: Watermelon, 2: Banana, 3: Peach,
-1: Thunder");
Scanner in = new Scanner([Link]);
int num = 0; //defined a variable
do {
num = [Link]();//The life cycle of the variable
if (num == 1) {
[Link]("You cut the watermelon");
} else if (num == 2) {
[Link]("You cut the banana");
} else if (num == 3) {
[Link]("You cut the peach");
} else if (num == -1) {
[Link]("You cut the thunder game termination");
}
} while (num != -1); //If you enter -1 to terminate the game
}
}

Output Result:

Keyboard Input 1: Watermelon, 2: Banana, 3: Peach, -1: Thunder


2
You cut the banana
1
You cut the watermelon
3
You cut the peach
-1
You cut the thunder game termination

Do while loop 2
/**
Enter the student's name continuously, enter "q" to exit the system
*/
import [Link];

public class DoWhileStatement2 {


public static void main(String[] args) {
Scanner in = new Scanner([Link]);
[Link]("Please enter the student name until enter q to quit the
system");
String name = "";
do {
name = [Link]();
} while (![Link]("q"));
[Link]("Exit System");
}
}

Output Result:

Please enter the student name until enter q to quit the system
grace
q
Exit System

For loop statement


/**
For loop Definition:
for (initialization variable; judgment condition; update loop variable){
statement;
}

Implementation process:
1. Initialization variable
2. Execute the judgment condition. If true continues to execute,
after the execution, update the loop variable and then judge the condition.
Exit the loop until the condition is false
*/
public class ForStatement {
public static void main(String[] args) {
// Print out 0-9
/*
Implementation process:
1. Initialize i=0;
2. Execute i<10 if true, execute [Link](i);
After the execution, i++ and then i<10 judge this cycle until i>=10 exits
the loop.
*/
for (int i = 0; i < 10; i++) {
[Link](i + " , ");
}
}
}

Output Result:

0,1,2,3,4,5,6,7,8,9,
For loop statement 2

public class ForStatement2 {


public static void main(String[] args) {
/*
In the bubble ball game,
the game starts with 64 balls, requiring 8 balls per line. *
Representative ball
Print (1 -- 64)
*/
for (int i = 1; i <= 64; i++) {
[Link]("* ");
if (i % 8 == 0) // 8%8==0, 16%8==0, 24%8==0, 32%8==0, 48%8==0,
64%8= =0
{
[Link]("");//wrap one line
}
}
}
}

Output Result:

********
********
********
********
********
********
********
********

One-dimensional array

public class OneArray {


public static void main(String[] args) {
// One-dimensional array definition and initialization
// Statically define a one-dimensional array
int[] scores = { 90, 70, 50, 80, 60, 85 };
// Dynamically define a one-dimensional array
int[] arr = new int[6];
arr[0] = 90;
arr[1] = 70;
arr[2] = 50;
arr[3] = 80;
arr[4] = 60;
arr[5] = 85;

//print out the score of the array scores


for (int i = 0; i < [Link]; i++) {
[Link](scores[i] + ",");
}

[Link]("\n-------------------------------");

//print out the arr of the array scores


for (int i = 0; i < [Link]; i++) {
[Link](arr[i] + ",");
}
}
}

Output Result:

90,70,50,80,60,85,
-------------------------------
90,70,50,80,60,85,

One-dimensional array append element


Add a student's grade to the end of the one-dimensional array scores.

/**
Step:
1. First create a temporary array larger than the original scores array length
tempArray
2. Copy each value of the scores array to tempArray
3. Then assign a score of 75 to the new last index position of tempArray
4. Finally assign the tempArray address pointer reference to the scores;
*/
public class ArrayAppend {
public static void main(String[] args) {
int[] scores = { 90, 70, 50, 80, 60, 85 };

int[] tempArray = new int[[Link] + 1];


for (int i = 0; i < [Link]; i++) {
tempArray[i] = scores[i];
}
tempArray[[Link]] = 75;
scores = tempArray;

//Print outs scores


for (int i = 0; i < [Link]; i++) {
[Link](scores[i] + ",");
}

}
}

Output Result:

90,70,50,80,60,85,75,

One-dimensional array remove elements


Deleting the value of the index position of the scores array

/**
Title:
Deleting the value of the index position of the scores array
Step:
1. Create a temporary array tempArray that is temporarily smaller than
scores by 1.
2. Copy the data in front of index to the front of tempArray
3. Copy the array after index to the end of tempArray
4. Assign the tempArray address pointer reference to the scores
5. Printout scores
*/
import [Link];

public class ArrayDelete {


public static void main(String[] args) {
int[] scores = { 90, 70, 50, 80, 60, 85 };
[Link]("Please enter the index to be deleted:");
Scanner in = new Scanner([Link]);
int index = [Link]();

//1. Create a temporary array tempArray that is temporarily smaller than


scores by 1.
int[] tempArray = new int[[Link] - 1];
for (int i = 0; i < [Link]; i++) {
if (i < index) //2. Copy the data in front of index to the front of
tempArray
tempArray[i] = scores[i];
if (i > index) //3. Copy the array after index to the end of tempArray
tempArray[i - 1] = scores[i];
}

//4. Assign the tempArray address pointer reference to the scores


scores = tempArray;
for (int i = 0; i < [Link]; i++) {
[Link](scores[i] + ",");
}

}
}

Output Result:

Please enter the index to be deleted:


2
90,70,80,60,85,
One-dimensional array search element

/**
Title:
Finding the value of the given value from the scores
Step:
1. Traverse the value in the array scores,
if there is a value equal to the given value, print out the current index
Otherwise print -1 not found
*/
import [Link];
public class ArraySearch {
public static void main(String[] args) {
int[] scores = { 90, 70, 50, 80, 60, 85 };
[Link]("Please enter the value you want to find value:");
Scanner in = new Scanner([Link]);
int value = [Link]();
/*
Traverse the value in the array scores,
if there is a value equal to the given value, print out the current index
Other print-1 not found
*/
boolean isSearch = false;
for (int i = 0; i < [Link]; i++) {
if (scores[i] == value) {
isSearch = true;
[Link]("Found value: " + value + " the index is: " + i);
break;
}
}
if (!isSearch) {
[Link]("The value was not found in the array scores: " +
value);
}
}
}

Output Result:

Please enter the value you want to find value:


70
Found value: 70 the index in the array scores is: 1

Bubble sorting algorithm


First time sort:
1. Start from the first element.
2. If the previous data is larger than the latter data then two swap positions
until the end of the loop, then the largest data will be placed in the last position
of the array.
/**
Bubble sorting algorithm:
sort the output of the results arrays from small to large
Step:
First sort
1. Start from the first element.
2. If the previous data is larger than the latter data then two swap positions
until the end of the loop, then the largest data will be placed in the last position
of the array.
3. By analogy, the unsorted n-i elements will be similar to the 1,2 process
again,
so that after the end of the loop n times, the elements are sorted from
small to large.
*/

public class BubbleSort {


public static void sort(int[] arrays) {
// The first loop n-1 times
for (int i = 0; i < [Link] - 1; i++) {
// The second loop the number of elements to be compared each time n-
1
for (int j = 0; j < [Link] - i - 1; j++) {
if (arrays[j] > arrays[j + 1]) {
int flag = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = flag;
}
}
}
}

public static void main(String[] args) {


int[] scores = { 90, 70, 50, 80, 60, 85 };

sort(scores);

// Output sorted scores


for (int i = 0; i < [Link]; i++) {
[Link](scores[i] + ",");
}

}
}

Output Result:

50,60,70,80,85,90,
Two-dimensional array

public class BinaryArray {


public static void main(String[] args) {
// Two-dimensional array definition and initialization
int[][] arrs ={
{ 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 }
};

// i: row index, j: column index


for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < arrs[i].length; j++) {
[Link](arrs[i][j]);
}

[Link]("");
}

//Enhanced for loop is a new feature that is only available after jdk 5.0
String[] names ={ "Joseph", "James", "Grace" };
for (String name : names) {
[Link](name + ",");
}
// Define a two-dimensional table structure of the course
String[][] courses ={
{ "C001", "English" },
{ "C002", "Mathematics" },
{ "C003", "Java Programming" }
};

[Link]("\n---------------------");

//output
for (String[] rows : courses) {
for (String col : rows) {
[Link](col + ",");
}
[Link]("");
}
}
}

Output Result:

10 20 30
40 50 60
70 80 90
David,James,Grace,
---------------------
C001,English,
C002,Mathematics,
C003,Java Programming,
Examples: Minesweeper

/**
Mine-sweeping game:
1: no thunder 2: there are thunder
keyboard input row number and column number, to determine whether it
has swept to thunder.
*/
import [Link];

public class BinaryArrayMine {

public static void main(String[] args) {


int[][] thundes = {
{ 1, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 1, 2, 1, 1 },
{ 1, 1, 1, 1 }
};
Scanner in = new Scanner([Link]);
[Link]("Please enter the line number:");
int row = [Link]();
[Link]("Please enter the column number:");
int col = [Link]();
int value = thundes[row][col];//values ​obtained from the array
// Determine whether it has swept the thunder
for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < thundes[i].length; j++) {
// If value exists in the array and equal to 2
if (value == thundes[i][j] && value == 2) {
[Link](" 雷 ");
} else {
[Link]("* ");
}
}
[Link]("");
}
}
}

Output Result:

Please enter the line number:


2
Please enter the column number:
1
****
****
*雷 **
****
Encapsulation

/**
Steps:
1. If you want to access the Person class, you must first instantiate a Person
object.
2. Then through the object reference name to access the attributes and
methods
For example, the object reference p: [Link], [Link], [Link]()
*/

public class TestEncapsulation {


public static void main(String[] args) {
//Object instantiation: p is a reference name to the object generated by
new Person() in the heap
Person p = new Person();
// Use the p access attributes and methods
[Link] = "Joseph";
[Link] = 22;
[Link]();

Person p2 = new Person();


[Link] = "David";
[Link] = 23;
[Link]();

//Assign p2 to p, this time p points to the object of p2


p = p2;
[Link]();

/*
If you declare an empty Person object without instantiation, this time
accessing attributes and methods
The compile time can pass, but the NullPointerException will be reported
at runtime.

Person p3=null;
[Link]="Renia";
[Link]=24;
[Link]();
*/
}
}

/**
1. Define a Person class The class consists of attributes and methods
2. There are two attributes in the Person class: name, age
*/
class Person {
String name;
int age;

public void say(){


[Link]("My name is: "+name+", this year: "+age+" years
old");
}
}

Output Result:

My name is: Joseph, this year: 22 years old


My name is: David, this year: 23 years old
My name is: David, this year: 23 years old
Methods Encapsulation

package [Link];

/**
The encapsulation attribute:
privatize the attributes of the class and then provide a public method to
access it.
*/

public class TestEncapsulationMethod {


public static void main(String[] args) {
/*
1. The reference object cannot access the private attribute of the class
2. If you want to access private attribute, you should provide a public
method.
*/
Person p = new Person();
[Link]("Joseph");
[Link](22);
[Link]();
[Link](p);
[Link]([Link]() + " " + [Link]());
}
}

class Person {
//private attribute
private String name;
private int age;

// Define a public method to set private attribute


public void setName(String name) {
//this: represents a reference to the current object
[Link](this);
[Link] = name;
}

// Define a public method to get private attribute


public String getName() {
return [Link];
}

public void setAge(int age) {


[Link] = age;
}

public int getAge() {


return [Link];
}

public void say() {


[Link]("My name is: " + name + ", this year " + age + " years
old");
}
}
/**
Review summary
1. The variables defined in the class are called member variables.
2. The variables defined in the method are called local variables and can
only be accessed in the defined methods.
When a local variable and a member variable have the same name, the
local variable back covers the member variable.
To distinguish member variables, you must add this in front of member
variables.
*/
Output Result:

[Link]@1d5550d
My name is: Joseph, this year 22 years old
[Link]@1d5550d
Joseph 22
Construction method

package com.test1;

/**
What is the constructor:
The method name is the same as the class name, no return value, even no
void
*/

public class TestConstructor {


public static void main(String[] args) {
Person p = new Person();

// Instantiate Person with a constructor with parameters


Person p2 = new Person("Joseph", 22);
[Link]();

//Anonymous object
new Person("David", 23).say();
}
}

class Person {
private String name;
private int age;

// Define the parameter without constructor


public Person() {
[Link]("Person is instantiated");
}

// Define the constructor with parameters


public Person(String name, int age) {
[Link] = name;
[Link] = age;
}

public void say() {


[Link]("My name is :" + name + ", this year: " + age + " years
old");
}

}
/**
The characteristics of the constructor:
1. When the instantiated object is a constructor, it is called automatically.
2. When there is no constructor with no parameters defined in the class,
the java virtual machine automatically creates a constructor to instantiate it.
3. When the constructor with parameters, the virtual machine does not
automatically generate a constructor with no arguments. It must be manually
added.

Overloading constructor:
In the same class, the method name is the same, the number or type of
parameters is different
*/

Output Result:

My name is: Joseph, this year 22 years old


My name is: David, this year 23 years old
Method overload

package com.test2;

public class TestOverLoad {


public static void main(String[] args) {
Caculator c = new Caculator();
int result = [Link](10, 20);
[Link](result);

// Call the overload method with different parameter types


double result2 = [Link](30.5, 40.2);
[Link](result2);

}
}

/**
Method overload:
In the same class, there is a method name with the same name, different
parameter numbers or parameter types.

Method overloading feature:


When calling method, it will automatically call the corresponding overload
method.
*/
class Caculator {

// Enter the two numbers to add, return the sum


public double add(double a, double b) {
return a + b;
}
public int add(int a, int b) {
return a + b;
}

Output Result:
30
70.7

Passed by reference

package com.test3;

/**
reference delivery:
1. Method parameter reference passing
2. Passing a reference between an object and an object
3. this pointer object reference pass
*/
public class TestRefenrence {
public static void main(String[] args) {

Utils utils = new Utils();

// Define a counter variable


int count = 1;
[Link](count);
[Link](count);
[Link](count); // the value not changed

// Define a counter class variable


Count value = new Count();
[Link](1);
[Link]([Link]());
[Link](value);
[Link]([Link]()); // the value changed

}
}

class Utils {
public void increment(int count) {
count++;
}

public void increment(Count count) {


[Link]([Link]() + 1);
}
}

class Count {
private int value;

public int getValue() {


return [Link];
}

public void setValue(int value) {


[Link] = value;
}
}

Output Result:

1
1
1
2
Static keyword

package com.test4;

public class TestStatic {


public static void main(String[] args) {
//Static variables can be accessed directly through the class name
[Link]++;
[Link]("users count: " + [Link]);
}
}

class User {
public static int count;

public User(){

}
}
/**
the difference between normal variables and static variables:
1. A normal variable is a dynamically assigned value at runtime.
The static variable is assigned to the initial value at compile time.
2. Normal variables must be accessed through instance object references
Static variables can be accessed directly through the class name
*/

Output Result:

users count: 1
Code block
public class CodeBlock {
//Construct code block
public CodeBlock() {
[Link]("Construct code block Initialization");
}

//Static code block


static {
[Link]("Static code block Initialization");
}

public static void main(String[] args) {


new CodeBlock();
}
}
/**
Static code blocks are run during program compilation, so static code blocks
are called before the constructor code blocks
*/

Output Result:

Static code block Initialization


Construct code block Initialization
Inheritance

package com.test5;

/**
Title:
Students inherit the Person
Step:
[Link]: Student, Person
2. Relationship: Student extends Person
3. Attributes: Person characteristics (name , age )
4. Methods: People's actions (say)
*/

public class TestInheritence {


public static void main(String[] args) {

Student s = new Student();


[Link] = "Sumi";
[Link] = 22;

// Use the constructor with parameters to instantiate the subclass Student


Student s2 = new Student("Isacc", 23);
[Link]();
}
}

class Person {
protected String name;
protected int age;

public Person() {
[Link]("parent class Person instantiation");
}

public Person(String name, int age) {


[Link]("the parent class of Person instantiated ");
}

public void say() {


[Link]("Person can speaking");
}
}

/**
Person is called parent class or super class
Student is called a subclass of Person
*/
class Student extends Person {
public Student() {
super();
[Link]("Subclass Student Instantiation");
}

public Student(String name, int age) {


super(name, age);
[Link]("Subclass Student " + name + " instantiated");
}
}
/**
Summary:
1. The subclass cannot access the private attribute of the parent class
2. The subclass can access the protected, public attribute of the parent
class.
3. When instantiating a subclass with a constructor with no arguments,
first call the constructor of the parent class with no arguments.
After instantiating the parent class and then instantiating the child class.
4. When instantiating a subclass with a constructor with parameters, it
also defaults to calling the constructor of the parent class without parameters.
After that, call the constructor of the subclass with parameters.
5. If you want the constructor of the parent class with parameters to be
called, you must use the super called the parent constructor.
*/

Output Result:

parent class Person instantiation


Subclass Student Instantiation
the parent class of Person instantiated
Subclass Student Isacc instantiated
Person can speaking

Method Override
package com.test6;
/**
override:
the subclass overwrites the method of the parent class, the instance of the
subclass
will call the method of subclass replication, and will not call the method
of the parent class.
*/
public class TestOverride {
public static void main(String[] args) {

ChineseStudent s = new ChineseStudent();


[Link]();

AmericaStudent as = new AmericaStudent();


[Link]();
}
}

class Person {
public void say() {
[Link]("Person speaking");
}
}

class ChineseStudent extends Person {


public void say() {
[Link]("Speak Chinese");
}
}

class AmericaStudent extends Person {


public void say() {
[Link]("Speak English");
}
}

Output Result:

Speak Chinese
Speak English

abstract class
package com.test7;

/**
Title:
Dad told me to buy a pound of fruit
Step:
1. Abstract class: Father, Son
2. Relationship: Son inherits Dad
3. Method: Buy (buy) is the father called his son to buy fruit, means father
not buy
*/
public class TestAbstract {
public static void main(String[] args) {

Son s = new Son("Luke");

[Link]("Fruit");

[Link]("Dad, Dad, I bought a pound: " + [Link]());


}
}

abstract class Father {


protected String fruit;
public String getFruit() {
return [Link];
}

//Declare that you want to buy fruit


public abstract void buy(String fruit);

class Son extends Father {


private String name;

public Son(String name) {


super();
[Link] = name;
}

//The son fulfills the requirement of his father to buy fruit


public void buy(String fruit) {
[Link] = fruit;
}

public String getName() {


return [Link];
}
}
/**
Summary:
1. The abstract method can't have a method body implementation, only the
method declaration
2. When there is an abstract method declared in class, the class must be
appended with the abstract indicates that the class is an abstract class
3. If a subclass inherits an abstract class, the subclass must implement all
the abstract methods of the parent class.
4. Abstract methods can also declare implementation methods.
5. Abstract classes cannot be instantiated directly, they must be
instantiated by subclasses
*/
Output Result:

Dad, Dad, I bought a pound: Fruit


instanceof

package com.test8;

/**
Title:
Exporting People's Classification Information for Oracle Conference
Step:
1. Abstract class: Person {Programmer, Manager}
*/
public class TestInstanceof {
public static void main(String[] args) {
//The conference can have a capacity of 1,000 people.
Person[] persons = new Person[1000];

//Start registration
persons[0] = new Programer("Joseph");
persons[1] = new Programer("james");

persons[2] = new Manager("Page");


persons[3] = new Manager("Joe");
//Pint out
for (int i = 0; i < [Link]; i++) {
if (persons[i] != null) {
if (persons[i] instanceof Programer) {
[Link](persons[i].getName() + " belong to the
programmer");
}
if (persons[i] instanceof Manager) {
[Link](persons[i].getName() + " belong to the
manager");
}
}
}

}
}

abstract class Person {


protected String name;

public Person(String name) {


[Link] = name;
}

public String getName() {


return [Link];
}
}

class Programer extends Person {


public Programer(String name) {
super(name);
}
}

class Manager extends Person {


public Manager(String name) {
super(name);
}
}

Output Result:

Joseph belong to the programmer


james belong to the programmer
Page belong to the manager
Joe belong to the manager
interface

package com.test9;
/**
interface: Interface is a convention
Title:
Chairman says to Establish a Harmonious Society, Prime Minister says to
Serve the People
Step:
1. interface: Chairman, Governor
*/
public class TestInterface
{
public static void main(String[] args)
{
[Link]([Link]);

[Link]("Start conferences...");
Governer g1=new Governer("Governer");
[Link]("Education");
[Link]("Charitable");

}
}
interface ChairMan
{
String name="ChairMan";

public void buildHarmonyCommunity(String method);


}

interface PrimeMinister
{
String name="PrimeMinister";

public void serviceForPeople(String method);


}

class Governer implements ChairMan,PrimeMinister


{
private String name;

public Governer(String name)


{
[Link]=name;
}

public void buildHarmonyCommunity(String method)


{
[Link](name+" build harmony community by "+method);
}

public void serviceForPeople(String method)


{
[Link](name+" service for people by "+method);
}

public String getName()


{
return [Link];
}
}
/**
Summary:
1. Declare an interface by interface keyword
2. The implementation of the defined method is not allowed in the interface.
3. The declaration of the method in the interface can omit the keyword
abstract , the abstract method in the abstract class can not be omitted
4. The methods in the interface are all public by default.
5. The attributes in the interface are static constants. The static final keyword
can be omitted.
does not allow private, protected keyword modifiers.
6. The implementation class must implement all the declaration methods in
the interface, just like the abstract class.
7. Can not instantiate an interface, must have its implementation class
indirectly instantiated, just like the abstract class
8. If you want to implement multiple interfaces, separate them by ,
9. Interfaces can inherit multiple interfaces, abstract classes do not .
*/

Output Result:

ChairMan
Start conferences...
Governer build harmony community by Education
Governer service for people by Charitable

final keyword
package com.test10;

/**
final keyword:
1. The variable of the final keyword modification is a constant. It cannot be
modified.
2. Final keyword modification method, subclass can not be rewritten
3. The final keyword modified class cannot be inherited
*/
public class TestFinalKeyword {
public static void main(String[] args) {
//The variable of the final keyword modification is a constant. It cannot be
modified.
final double PI = 3.14;
[Link](PI);

Father f = new Father();


[Link]();

Son s = new Son();


[Link]();
}
}

class Father {
//Final keyword modification method, subclass can not be rewritten
public final void work() {
[Link]("Do hard work");
}
}

class Son extends Father {


public void study() {
[Link]("study hard, improve every day");
}
}

final class Daughter extends Father {

/*
//The final keyword modified class cannot be inherited
class GranDaughter extends Daughter {

}
*/

class GranSon extends Son {

Output Result:

3.14
Do hard work
study hard, improve every day
enum

package com.test11;

/**
enum: is a special qualified constant type
s
Topic:
Draw a variety of different circles on the drawing board
*/
public class TestEnum {

public static void main(String[] args) {


// r=5
Circle red = new Circle(5, [Link]);
[Link]();

// r=10
Circle green = new Circle(10, [Link]);
[Link]();

// r=20
Circle blue = new Circle(20, [Link]);
[Link]();
}
}

//Defining enumerated types


enum Color {
RED, GREEN, BLUE
}

class Circle {
double r; // Radius of the circle
final double PI = 3.14;
Color color; // Round color (0: red 1: green 2: blue)

public Circle(double r, Color color) {


this.r = r;
[Link] = color;
}

//Calculate the area of the circle


public double getArea() {
return PI * r * r;
}

//Drawing circle
public void draw() {
String colorName = "";
if (color == [Link]) {
colorName = "Red";
}
if (color == [Link]) {
colorName = "Green";
}
if (color == [Link]) {
colorName = "Blue";
}
[Link]("draw circle area: " + getArea() + " color: " +
colorName );
}
}

Output Result:

draw circle area: 78.5 color: Red


draw circle area: 314.0 color: Green
draw circle area: 1256.0 color: Blue

Polymorphism

package com.test12;

/**
Polymorphism:
Three types: method overload, method override, object up and down
transformation

Summary:
1. Subclass objects can be converted to parent class objects but subclass
attributes and methods are not visible after conversion.
2. When the subclass overrides the method of the parent class, the child class
is converted to the parent class and the subclass is overridden.
*/
public class TestPolymorphism {
public static void main(String[] args) {
//Upward transformation subclass attributes and methods are not visible
after conversion.
Person p = new Student("David");
[Link]();

//Object downcast Parent class


Student s = (Student) p;
[Link]();
[Link]();

}
}

class Person {
public void say() {
[Link]("Person speaking");
}
}

class Student extends Person {


private String name;

public Student(String name) {


[Link] = name;
}

public void say() {


[Link]("Student speak english");
}
public void study() {
[Link]("study");
}
}

Output Result:

Student speak english


Student speak english
study

Polymorphic Example
package com.test13;

/**
Title:
Children Eat Fruits (Apples, Grapes)

Step:
1. Class: Baby, Fruit (Apple, Grape)
2. Relationship: Fruit -> Child (apple, grape) is the classification of the
fruit
3. Attributes: Baby (name, fruit reference)
4. Methods: eat(Fruit fruit)
*/
public class TestPolymorphism3 {
public static void main(String[] args) {

Baby baby = new Baby("Gajia");

Apple apple = new Apple("Red apple");


Grape grape = new Grape("Black grape");

[Link](apple);
[Link]([Link]() + " eat " + [Link]().getName());
[Link](grape);
[Link]([Link]() + " eat " + [Link]().getName());
}
}

class Baby {
private Fruit fruit;
private String name;

public Baby(String name) {


[Link] = name;
}

public String getName() {


return [Link];
}

public Fruit getFruit() {


return [Link];
}

public void eat(Fruit fruit) {


[Link] = fruit;
}

class Fruit {
private String name;

public Fruit(String name) {


[Link] = name;
}

public String getName() {


return [Link];
}
}

class Apple extends Fruit {


public Apple(String name) {
super(name);
}
}

class Grape extends Fruit {


public Grape(String name) {
super(name);
}
}

Output Result:

Gajia eat Red apple


Gajia eat Black grape
Internal class

package com.test14;

/**
Title:
Mother is pregnant, mother's nutrition determines the healthy growth of
baby
Step:
1. Class: Mother, Baby
2. Relationship: Baby in Mother
3. Method: Mother eats (eat)
*/
public class TestInnerClass {
public static void main(String[] args) {

Mother mother = new Mother("Lucy");


[Link]("Apple");

//Baby take nutrition from apples


[Link] baby = [Link] Baby();
[Link]();
}
}

class Mother {
private String name;
private String food;

public Mother(String name) {


[Link] = name;
}

public void eat(String food) {


[Link] = food;
[Link]([Link] + " eat " + [Link]);
}

//The child is the inner class of the mother


class Baby {

public void eat() {


[Link]("Baby absorb nutrients from the mother's " + food);
}
}
}

Output Result:

Lucy eat Apple


Baby absorb nutrients from the mother's Apple
Static internal class

package com.test15;

/**
Title:
Mother is pregnant, mother's nutrition determines the healthy growth of
baby
Step:
1. Class: Mother, Baby
2. Relationship: Baby in Mother
3. Method: Mother eats (eat)
*/
public class StaticInnerClass {
public static void main(String[] args) {

Mother mother = new Mother("Lucy");


[Link]("Apple");

//Baby take nutrition from apples


[Link]();
}
}
class Mother {
private String name;
private static String food;

public Mother(String name) {


[Link] = name;
}

public String getName() {


return [Link];
}

public void setName(String name) {


[Link] = name;
}

public void eat(String food) {


[Link] = food;
[Link]([Link] + " eat " + [Link]);
}

//The child is the inner class of the mother


static class Baby {

public static void eat() {


[Link]("Baby absorb nutrients from the mother's " + food);
}
}
}

Output Result:

Lucy eat Apple


Baby absorb nutrients from the mother's Apple
Basic data Wrap class
package com.test16;

/**
Wrap class:
byte -> Byte
short -> Short
int -> Integer
long -> Long

float -> Float


double -> Double
char -> Character
boolean -> Boolean
*/
public class WrapClass {
public static void main(String[] args) {
Byte a = 1;
byte b = 10;
a = b;
[Link]([Link]());
[Link]([Link](b));

//Integer to double
int c = 100;
Integer d = new Integer(c);
[Link]([Link]());

//Integer to long
[Link]([Link]());

//Integer to string
String str = [Link](d);
[Link](str);
//String to integer
int e = [Link](str);
[Link](e);
}
}

Output Result:

10
10
100.0
100
100
100

Anonymous inner class

package com.test17;
/**
Title:
The motorcycle is equipped with an alarmer. When someone touches the
motorcycle, the alarmer sounds an alarm.
Step:
1. Class:
1.1 Motorcycle (Moto), Alarm (Alarm), Person (Person)
2. Relationship:
2.1 Motorcycle with alarm Alarm -> Moto (1 to 1)
2.2 Alarms have different brands of classification Alarm
3. Attributes:
3.1 Moto (brand, alarm reference)
3.2 Alarm (brand)
3.3 Person
4. Method:
4.1 Motorcycle with alarm Moto{load(Alarm alarm)}
4.2 Motorcycles are touched by Moto{touched(Person p)}
4.3 The alarm sounds Alarm{beep()}
*/
public class TestMoto {
public static void main(String[] args) {
Moto moto = new Moto("Moto");

[Link](new Alarm() {
public void beep(Person p) {
[Link]([Link]() + " hit the alarm ");
}
});

Person p = new Person("John");


//John accidentally bumped into the motorcycle, and the motorcycle
sounded an alarm.
[Link](p);
}
}

abstract class Alarm {


public abstract void beep(Person p);
}

class Moto {
private String brand;
private Alarm alarm;

public Moto(String brand) {


[Link] = brand;
}

public void load(Alarm alarm) {


[Link] = alarm;
}

public void touched(Person p) {


[Link](p);
}
}

class Person {
private String name;

public Person(String name) {


[Link] = name;
}

public String getName() {


return [Link];
}
}

Output Result:
John hit the alarm

package
The package is actually a folder

1. Create a new package com.pack2 Right click on the Eclipse project -> New ->
Package
2. Then create a new Wallet class under com.pack2

package com.pack2;

public class Wallet {


private double money;

public void setMoney(double money) {


[Link] = money;
}

public double getMoney() {


return [Link];
}
}

3. Create a new package com.pack1 Right click on the Eclipse project -> New ->
Package
4. Then create a new Person class under com.pack1
package com.pack1;

import [Link];

public class Person {

public Person() {
Wallet w = new Wallet();
[Link]([Link]());
}

public static void main(String[] args) {


new Person();
}
}
Thread

package [Link];

/**
1. If you want to start a thread you must call start() method
2. The thread runs at the same time, the CPU allocates to each thread for a
period of time to execute each thread sequentially.
*/
public class TestThread {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link](); // Start the thread, run() will be called automatically

for (int i = 0; i < 10; i++) {


[Link]("Main Thread " + i);
}
}
}

//Thread
class MyThread extends Thread {

public void run() {


for (int i = 0; i < 10; i++) {
[Link]("MyThread " + i);
}
}

Output Result:

Main Thread 0
Main Thread 1
Main Thread 2
MyThread 0
Main Thread 3
MyThread 1
Main Thread 4
Main Thread 5
Main Thread 6
Main Thread 7
MyThread 2
Main Thread 8
Main Thread 9
MyThread 3
MyThread 4
MyThread 5
MyThread 6
MyThread 7
MyThread 8
MyThread 9

Runnable
package [Link];

/**
Because java is a single inheritance, in order to improve scalability, the
second implementation Runnable is generally used.
*/
public class TestRunnable {
public static void main(String[] args) {
MyThread2 t = new MyThread2();
Thread thread = new Thread(t, "Car thread");
[Link](); //Start the thread, run () will be automatically called

Thread thread2 = new Thread(t, "Train thread");


[Link](); //Start the thread, run () will be automatically called

try {
for (int i = 0; i < 10; i++) {
[Link]([Link]().getName() + i);
[Link](1000); // sleep 1 second = 1000 milliseconds
}
} catch (Exception e) {
[Link]();
}

}
}

class MyThread2 implements Runnable {


@Override
public void run() {
try {
for (int i = 0; i < 10; i++) {
[Link]([Link]().getName() + i);
[Link](1000);
}
} catch (Exception e) {
[Link]();
}

Output Result:

main0
Car thread0
Train thread0
Train thread1
Car thread1
main1
Train thread2
Car thread2
main2
Train thread3
main3
Car thread3
Train thread4
Car thread4
main4
Train thread5
main5
Car thread5
Train thread6
Car thread6
main6
Train thread7
main7
Car thread7
Car thread8
Train thread8
main8
Train thread9
main9
Car thread9

Exception
Runtime exception
public class TestException {
public static void main(String[] args) {
// For runtime exceptions, we can capture or not capture
int[] scores = { 60, 70, 80 };
// [Link]
try {
[Link](scores[3]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("An array out of bounds exception occurred");
}
}
}
Output Result:

An array out of bounds exception occurred

Compile-time exception
public class TestCompileTimeException {

public static void main(String[] args) {


for (int i = 0; i < 5; i++) {
[Link](i);

//Compile-time exception, we must capture must be placed in


try{}catch{}
try {
[Link](1000); // sleep 1 second = 1000 milliseconds
} catch (InterruptedException e) {
[Link]();
}

}
}
}

Output Result:

0
1
2
3
4
finally

package [Link];

public class TestFinally {


public static void main(String[] args) {
Caculator c = new Caculator();
[Link](10, 2); // Running normally
// [Link](10, 0); // Running exception
[Link]("div finished execution");
}
}

class Caculator {

public int div(int a, int b) {


int result = 0; //Local variables need to be given initial value
try {
// Local variables defined in try catch can not be external access
// When the exception occurs in the try, the code behind it, terminate the
execution, directly transferred to the catch execution
result = a / b;
[Link]("Normal execution");
return result;

} catch (Exception e) {
[Link]("Divisor cannot be 0");
} finally {
[Link]("finally the last free release");
}
[Link]("Result return");
return 0;

}
}

Output Result:

Normal execution
finally the last free release
div finished execution
String assignment and comparison
package [Link];

public class TestStringEquals {


public static void main(String[] args) {

String str = "Dreams";


String str1 = new String("Dreams");
[Link](str);
[Link](str1);

[Link]("\n----------------");
/*
String comparison
1. == : Reference comparison
[Link]: Value comparison
*/
String str3 = "Dreams";
String str4 = new String("Dreams");
String str5 = new String("Dreams");
String str6 = "Dreams ";
[Link](str3 == str4);
[Link]([Link](str4));
[Link](str4 == str5);
[Link](str3 == str6);
}
}

Output Result:

Dreams
Dreams

----------------
false
true
false
true

Byte and string conversion

package [Link];
/**
1. byte[] getBytes() Convert a string to a byte array
2. String new String(byte[] bytes) Convert a byte array to a string
3. String new String(byte[] bytes,int offset,int length) Convert a byte array to
a string
*/
public class TestStringByte {

public static void main(String[] args) {

String str = "good";


byte[] bytes = [Link](); //Convert a string to a byte array
//Convert each character in the string to an integer corresponding to
ACSII a=97
for (int i = 0; i < [Link]; i++) {
[Link]((char) bytes[i]);
}

//Define a byte array


byte[] bytes2 = { 103, 111, 111, 100, 0, 0 };
String str2 = new String(bytes2);
[Link](str2);

String str3 = new String(bytes2, 0, 4);


[Link](str3);
}
}

Output Result:

g
o
o
d
good
String judgment operation

package [Link];
/**
1. boolean equals(Object anObject) Compare strings for equality
2. boolean equalsIgnoreCase(String antherString) Ignore case comparison
string is equal
3. int compareTo(String antherString) compares the size of two strings
4. int compareToIgnoreCase(String antherString) ignore string case to
compare size
5. boolean startsWith(String prefix) to determine whether to start with the
specified string prefix
6. boolean endsWith(String sufix) to determine whether to end with the
specified string sufix
Note:
1. When comparing strings, if the letters are compared according to the
ACSII code of the first letter and then compare the following letters in turn.
2. If the preceding characters are equal, compare the sizes by length
*/
public class TestStringCompare {

public static void main(String[] args) {


String str1 = "hello";
String str2 = "hello";
String str3 = "Hello";
[Link]([Link](str2));
[Link]([Link](str3));
[Link]([Link](str3));
String str4 = "hallow";
String str5 = "zoo";
String str6 = "zoo1";

[Link]([Link](str2)); //If equal, return 0


[Link]([Link](str3)); //If greater than return positive
[Link]([Link](str4));
[Link]([Link](str5)); //If less than return negative
[Link]([Link](str3));
[Link]([Link](str6));

String str = "Children's songs";


[Link]([Link]("Children"));

String fileName = "c:/media/amazing.mp3";


[Link]([Link](".mp3"));
}
}

Output Result:

true
false
true
0
32
4
-18
0
-1
true
true
String replacement

package [Link];

/**
1. String replace(char oldChar,char newChar) //Replace old characters with
new characters
2. String replaceFirst(String regex,String replacement); //Replace the first
string that satisfies the condition
*/
public class TestStringReplace {
public static void main(String[] args) {
String article = "The dog run under the gardenland";
[Link](article);

article = [Link]("dog", "horses");


[Link](article);

article = [Link]("gardenland", "grassland");


[Link](article);
}
}

Output Result:

The dog run under the gardenland


The horses run under the gardenland
The horses run under the grassland
String search and cut

package [Link];

/**
1. String substring(int beginIndex) The string that is Intercepted from the
beginIndex index to the end
2. int indexOf(char ch) Find the index position of the character ch in the
string from the begin, if it does not return -1
3. int lastIndexOf(char ch) Find the index position of the character ch in the
string from the end, if it does not return -1
*/
import [Link];

public class TestStringSub {


public static void main(String[] args) {
//Keyboard input file address, intercept file name and extension
[Link]("Please enter the address of the file...");
Scanner in = new Scanner([Link]);
String filePath = [Link]();

filePath = [Link](); //Remove the spaces before and after

//Intercept file extension


String fileExtension = [Link]([Link]('.'));
[Link](fileExtension);

//Determine that the file can only be in .png, .gif, .jpg format.
String checks = ".png .gif .jpg";
fileExtension = [Link]();
if (![Link](fileExtension)) {
[Link]("You are not entering an image file");
}

//Intercept the name of the file


String fileName = [Link]([Link]('\\') + 1);
[Link](fileName);
}
}

Output Result:

Please enter the address of the file...


e:\\book\music.mp3
.mp3
You are not entering an image file
music.mp3

String split

package [Link];

/**
1. String[] split(String regex) Split a string into an array with regex
*/
import [Link];

public class TestStringSplit {


public static void main(String[] args) {
//Enter a student's language, mathematics, and physics scores separated by
semicolon;
[Link]("Please enter the student name...");
Scanner in = new Scanner([Link]);
String name = [Link]();

[Link]("Enter a student's language, mathematics, and physics


scores separated by ;");
String scores = [Link]();
//Split student scores by ;
String[] scoreArray = [Link](";");

[Link](name + " language=" + scoreArray[0] + "


mathematics=" + scoreArray[1] + " physics=" + scoreArray[2]);
}
}

Output Result:

Please enter the student name...


Grace
Enter a student's language, mathematics, and physics scores separated by ;
100;98;95
Grace language=100 mathematics=98 physics=95

StringBuffer and StringBuilder


package [Link];
/**
StringBuffer StringBuilder Generally used when many strings are connected
StringBuffer Thread safe
StringBuilder Thread is not safe
*/
public class TestStringBufferStringBuilder {
public static void main(String[] args) {
String str = "";
StringBuffer strBuffer = new StringBuffer();
for (int i = 0; i < 10; i++) {
str += i + ",";
[Link](i).append(",");
}
[Link]([Link]());

//1. String append


StringBuffer buffer = new StringBuffer();
[Link]("How");
[Link](" your");
[Link]([Link]());

//2. String replacement


[Link](4, 9, "you");
[Link]([Link]());

//3. insert "are" after index 3


[Link](3, " are");
[Link]([Link]());

//4. Intercept of string


[Link]([Link](0, 4));
}
}

Output Result:

0,1,2,3,4,5,6,7,8,9,
How your
How you
How are you
How
Arrays
package com.test18;

import [Link];

public class TestArrays {


public static void main(String[] args) {

int[] arr = { 1, 4, 3, 7, 5, 6 };
[Link](arr);
[Link]([Link](arr));

//Find the specified value in an already ordered array


[Link]([Link](arr, 4));

}
}

Output Result:
[1, 3, 4, 5, 6, 7]
2
Calandar
package com.test18;

import [Link];
import [Link];

public class TestCalendar {


public static void main(String[] args) {
Calendar c = new GregorianCalendar();
//Output year, month, day, hour, minute, second
[Link]([Link]([Link]));
//Gregorian calendar starts in 0 in January, so add 1
[Link]([Link]([Link]) + 1);
[Link]([Link]([Link]));
[Link]([Link]([Link]));
[Link]([Link]([Link]));
[Link]([Link]([Link]));
[Link]([Link]([Link]));

//Get current date


[Link]([Link]());
//Get current datetime
[Link]([Link]());
//Get current timestamp
[Link]([Link]());
}
}

class DateTime {

public static String getDate() {


Calendar c = new GregorianCalendar();
StringBuffer buffer = new StringBuffer();
[Link](addZero([Link]([Link]) + 1)).append("-");
[Link](addZero([Link]([Link]))).append("-");
[Link]([Link]([Link]));
return [Link]();
}

public static String getDateTime() {


Calendar c = new GregorianCalendar();
StringBuffer buffer = new StringBuffer();
[Link](addZero([Link]([Link]) + 1)).append("-");
[Link](addZero([Link]([Link]))).append("-");
[Link]([Link]([Link])).append(" ");
[Link](addZero([Link]([Link]))).append(":");
[Link](addZero([Link]([Link]))).append(":");
[Link](addZero([Link]([Link])));
return [Link]();
}

public static long getTimeStamp() {


Calendar c = new GregorianCalendar();
return [Link]().getTime();
}

//If month, day, hour, minute, second is less than 10, add 0 in front
public static String addZero(int value) {
String str = [Link](value);
if ([Link]() < 2)
return 0 + str;
return str;
}

Output Result:

2019
3
27
11
4
58
163
03-27-2019
03-27-2019 11:04:58
1553706298165
Date
package com.test20;

import [Link];
import [Link];

public class TestDate {


public static void main(String[] args) {
//Get the current date of the system
Date date = new Date();
[Link](date);

//Get the current timestamp


[Link]([Link]());

//Get the current datetime


[Link]([Link]());

[Link]([Link]("12-12-2019 00:00:00"));

}
}

class CDate {
public static String getCurrentDateTime() {
Date date = new Date();
//Date formatting
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy
HH:mm:ss");
String dateStr = [Link](date).toString();
return dateStr;
}

public static String dateToString(Date date) {


//Date formatting
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy
HH:mm:ss");
String dateStr = [Link](date).toString();
return dateStr;
}

public static Date stringToDate(String dateString) {


try {
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy
HH:mm:ss");
return [Link](dateString);
} catch (Exception e) {
[Link]();
return null;
}
}
}

Math
package com.test20;

public class TestMath {


public static void main(String[] args) {
//Absolute value
[Link]([Link](-2));

// the smallest integer greater than the decimal


[Link]([Link](1.6));
[Link]([Link](1.1));

//the largest integer less than the decimal


[Link]([Link](1.6));
[Link]([Link](1.1));
//Fractional part rounded off
[Link]([Link](1.6));
[Link]([Link](1.1));

//Maximum of two numbers


[Link]([Link](1, 2));
//Minimum of two numbers
[Link]([Link](1, 2));

//Generate a random number between 0.0 and 1.0


[Link]([Link]());
}
}

Output Result:

2
2.0
2.0
1.0
1.0
2
1
2
1
0.36441889007455386

Comparable
package com.test20;

/**
Title:
Sorting a class of students from small to large in mathematics

Step:
1. Class:
1.1 Class (ClassSet)
1.2 Student (Student)
2. Relationship:
2.1 Students belong to class Student -> ClassSet (multiple to 1)
3. Attributes:
3.1 ClassSet ( name, size)
3.2 Student ( name, score)
4. Methods:
4.1 ClassSet{addStudent(Student s)}
4.2 ClassSet{sortByScore()}
*/
import [Link];
public class TestComparable {
public static void main(String[] args) {
ClassSet c = new ClassSet("HighClass", 4);

[Link](new Student("Lida", 90));


[Link](new Student("Mathew", 80));
[Link](new Student("Timothy", 95));
[Link](new Student("John", 70));

Student[] students = [Link]();


for (Student s : students) {
if (s != null)
[Link]([Link]() + "," + [Link]());
}

[Link]("\nSort by student grades");

[Link](students);
for (Student s : students) {
if (s != null)
[Link]([Link]() + "," + [Link]());
}

}
}

class ClassSet {
private String className;
private int maxSize;
private int currentSize;
private Student[] students;//Array of all students

public ClassSet(String className, int maxSize) {


[Link] = className;
[Link] = maxSize;
students = new Student[maxSize];
}
public Student[] getStudents() {
return [Link];
}

public void addStudent(Student s) {


for (int i = 0; i < [Link]; i++) {
if (students[i] == null) {
students[i] = s;
currentSize++;
break;
}
}
}
}

class Student implements Comparable {


private String name;
private int mathScore;

public Student(String name, int mathScore) {


[Link] = name;
[Link] = mathScore;
}

public String getName() {


return [Link];
}

public int getMathScore() {


return [Link];
}

/**
Implement the Comparable interface to override the compareTo(T o)
method
If sorted from small to large
Greater than return 1
Less than return -1
Equal to return 0
If sorted from large to small
Greater than return -1
Less than 1
Equal to return 0
*/
public int compareTo(Object obj) {
if (obj instanceof Student) {
Student s = (Student) obj;
if ([Link] > [Link]())
return 1;
if ([Link] < [Link]())
return -1;

}
return 0;
}

Output Result:

Lida,90
Mathew,80
Timothy,95
John,70

Sort by student grades


John,70
Mathew,80
Lida,90
Timothy,95
Comparator

package com.test21;

/**
Title:
Sorting a class of students from small to large in mathematics

Step:
1. Class:
1.1 Class (ClassSet)
1.2 Student (Student)
2. Relationship:
2.1 Students belong to class Student -> ClassSet (multiple to 1)
3. Attributes:
3.1 ClassSet ( name, size)
3.2 Student ( name, score)
4. Methods:
4.1 ClassSet{addStudent(Student s)}
4.2 ClassSet{sortByScore()}
*/

import [Link];
import [Link];

public class TestComparator {


public static void main(String[] args) {
ClassSet c = new ClassSet("HighClass", 4);

[Link](new Student("Lida", 90));


[Link](new Student("Mathew", 80));
[Link](new Student("Timothy", 95));
[Link](new Student("John", 70));

Student[] students = [Link]();


for (Student s : students) {
if (s != null)
[Link]([Link]() + "," + [Link]());
}

[Link]("\nSort by student's scores in ascending order");


[Link](students, new StudentAscComparator());
for (Student s : students) {
if (s != null)
[Link]([Link]() + "," + [Link]());
}

[Link]("\nSort by student's scores in descending order");


[Link](students, new StudentDescComparator());
for (Student s : students) {
if (s != null)
[Link]([Link]() + "," + [Link]());
}

}
}

class ClassSet {
private String className;
private int maxSize;
private int currentSize;
private Student[] students;//Array of all students

public ClassSet(String className, int maxSize) {


[Link] = className;
[Link] = maxSize;
students = new Student[maxSize];
}

public Student[] getStudents() {


return [Link];
}

public void addStudent(Student s) {


for (int i = 0; i < [Link]; i++) {
if (students[i] == null) {
students[i] = s;
currentSize++;
break;
}
}
}

class Student {
private String name;
private int mathScore;

public Student(String name, int mathScore) {


[Link] = name;
[Link] = mathScore;
}
public String getName() {
return [Link];
}

public void setName(String name) {


[Link] = name;
}

public int getMathScore() {


return [Link];
}

public void setMathScore(int mathScore) {


[Link] = mathScore;
}
}

// 学生升序排列
class StudentAscComparator implements Comparator {
public int compare(Object o1, Object o2) {
if ((o1 instanceof Student) && (o2 instanceof Student)) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if ([Link]() > [Link]())
return 1;
if ([Link]() < [Link]())
return -1;
}
return 0;
}
}

//Students in descending order


class StudentDescComparator implements Comparator {
public int compare(Object o1, Object o2) {
if ((o1 instanceof Student) && (o2 instanceof Student)) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if ([Link]() > [Link]())
return -1;
if ([Link]() < [Link]())
return 1;
}
return 0;
}
}

Output Result:

Lida,90
Mathew,80
Timothy,95
John,70

Sort by student's scores in ascending order


John,70
Mathew,80
Lida,90
Timothy,95

Sort by student's scores in descending order


Timothy,95
Lida,90
Mathew,80
John,70

Random
package com.test21;

import [Link];

public class TestRandom {


public static void main(String[] args) {
Random rn = new Random();
for (int i = 0; i < 10; i++) {
[Link]([Link](10));
}
}
}

Output Result:

0
8
1
5
1
0
8
5
0
0

Timer TimerTask

package com.test21;

import [Link];
import [Link];
import [Link];
import [Link];

public class TestTimer {

private Timer timer;

public TestTimer() {
timer = new Timer();
//Show current time every 1 second
[Link](new MyTask(), new Date(), 1000);
}

class MyTask extends TimerTask {

public void run() {


//Print current datetime
SimpleDateFormat df = new SimpleDateFormat("MM-dd-yyyy
HH:mm:ss");
[Link]([Link](new Date()));
}

public static void main(String[] args) {


new TestTimer();
}
}

Output Result:

03-27-2019 23:47:35
03-27-2019 23:47:36
03-27-2019 23:47:37
03-27-2019 23:47:38
List and ArrayList

/**
1. ArrayList in order of first-in, first-out.
2. ArrayList can add repeating elements
3. ArrayList can also add null value
4. ArrayList is internally implemented as an array of objects
*/
package com.test21;

import [Link];
import [Link];

public class TestArrayList {

public static void main(String[] args) {


List list = new ArrayList();
[Link](1);
[Link](1);
[Link](null);
[Link](2.5);
[Link](true);
[Link]("David");
[Link]('A');
[Link](new Cat("Persian Cat"));

Object david = [Link](3);


[Link]("get(3): "+david);

[Link]("size: "+[Link]());

[Link]("contains david: "+[Link]("David"));

[Link]("isEmpty: "+[Link]());

[Link](4, 'B');
[Link]("get(4): "+[Link](4));

//Print list all elements


for (int i = 0; i < [Link](); i++) {
Object obj = [Link](i);
[Link](obj + ",");
}

[Link](4);
[Link]("\nremove(4) --------------------");
for (int i = 0; i < [Link](); i++) {
Object obj = [Link](i);
[Link](obj + ",");
}

[Link]();
[Link]("\nclear() -------------------");
[Link]([Link]());
[Link]([Link]());
for (int i = 0; i < [Link](); i++) {
Object obj = [Link](i);
[Link](obj + ",");
}
}
}

class Cat {

private String name;

public Cat(String name) {


[Link] = name;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public String toString() {


return name;
}
}

Output Result:

get(3): 2.5
size: 8
contains david: true
isEmpty: false
get(4): B
1,1,null,2.5,B,David,A,Persian Cat,
remove(4) --------------------
1,1,null,2.5,David,A,Persian Cat,
clear() -------------------
0
true

LinkedList

/**
Title:
There are a lot of cars waiting to enter the gas station.
Print out the car information that according to the order in which the car
enters.

LinkedList is internally implemented as an link of objects


*/
package com.test21;

import [Link];
public class TestLinkedList {

public static void main(String[] args) {


Station station = new Station("Gas Station");
[Link](new Car("Car", 100));
[Link](new Car("Benz Car", 200));
[Link](new Car("Bus", 300));

LinkedList carList = [Link]();


[Link]([Link]() + " refueling car:");
for (int i = 0; i < [Link](); i++) {
Car car = (Car) [Link](i);
[Link]([Link]() + "," + [Link]());
}
[Link]([Link]());

[Link]("-------------------------------");

Car car = (Car) [Link](); // Retrieves and removes the head (first
element) of this list
while (car != null) {
[Link]([Link]() + "," + [Link]());
car = (Car) [Link]();
}
[Link]([Link]());
}
}

class Station {
private String name;
private LinkedList carList;
public Station(String name) {
[Link] = name;
[Link] = new LinkedList();
}

public void addCar(Car car) {


[Link](car);
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public LinkedList getCarList() {


return carList;
}

public void setCarList(LinkedList carList) {


[Link] = carList;
}

class Car {
private String name;
private double volume;

public Car(String name, double volume) {


[Link] = name;
[Link] = volume;
}

public String getName() {


return name;
}
public void setName(String name) {
[Link] = name;
}

public double getVolume() {


return volume;
}

public void setVolume(double volume) {


[Link] = volume;
}
}

Output Result:

Gas Station refueling car:


Car,100.0
Benz Car,200.0
Bus,300.0
3
-------------------------------
Car,100.0
Benz Car,200.0
Bus,300.0
0
Iterator

package com.test22;

/**
Title:
Printout All site information for the subway
*/
import [Link];
import [Link];
import [Link];

public class TestIterator {

public static void main(String[] args) {


List stationList = new ArrayList();
[Link](new Station("Berkeley University"));
[Link](new Station("Market Street"));
[Link](new Station("Polo Alto"));
[Link](new Station("Cuptino"));

[Link]("\nOutput as an list -----------------------------------------


");

for (int i = 0; i < [Link](); i++) {


Station station = (Station) [Link](i);
[Link]([Link]() + " -> ");
}

[Link]("\nOutput as an array ----------------------------------------


-");

Object[] stations = [Link]();


for (int i = 0; i < [Link]; i++) {
Station station = (Station) stations[i];
[Link]([Link]() + " -> ");
}

[Link]("\nOutput as an Iterator -------------------------------------


-");

Iterator iter = [Link]();


while ([Link]()) // Returns true if the iteration has more elements.
{
Station station = (Station) [Link](); // Returns the next element in the
iteration.
[Link]([Link]() + " -> ");
}
}

class Station {
private String name;

public Station(String name) {


[Link] = name;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

Output Result:

Output as an list -----------------------------------------


Berkeley University -> Market Street -> Polo Alto -> Cuptino ->
Output as an array -----------------------------------------
Berkeley University -> Market Street -> Polo Alto -> Cuptino ->
Output as an Iterator --------------------------------------
Berkeley University -> Market Street -> Polo Alto -> Cuptino ->

Vector

/**
Title:
Printout cinema movie name

Vector: thread safe


List: thread not safe
*/
package com.test22;

import [Link];
import [Link];
import [Link];
import [Link];

public class TestVector {

public static void main(String[] args) {

Vector v = new Vector();

[Link](new Movie("Deformed steel"));


[Link](new Movie("Lion king"));
[Link](new Movie("Pirates of the Caribbean"));

for (int i = 0; i < [Link](); i++) {


Movie movie = (Movie) [Link](i);
[Link]([Link]() + ",");
}

[Link]("\nEnumeration---------------------------");

Enumeration e = [Link]();
while ([Link]()) {
Movie movie = (Movie) [Link]();
[Link]([Link]() + ",");
}
}
}

class Movie {

private String name;

public Movie(String name) {


[Link] = name;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}
}

Output Result:

Deformed steel,Lion king,Pirates of the Caribbean,


Enumeration---------------------------
Deformed steel,Lion king,Pirates of the Caribbean,
Collections

/**
Title:
Sort the price of the product of the merchant by price
*/
package com.test22;

import [Link];
import [Link];
import [Link];
import [Link];

public class TestCollections {

public static void main(String[] args) {


List list = new ArrayList();
[Link](new Product("ASUS Computer",400 ));
[Link](new Product("Toshiba computer", 350));
[Link](new Product("Lenovo", 500));
for (int i = 0; i < [Link](); i++) {
Product p = (Product) [Link](i);
[Link]([Link]() + "," + [Link]());
}
[Link](list);
[Link]("After sorting result:-----------------------------------------
");
for (int i = 0; i < [Link](); i++) {
Product p = (Product) [Link](i);
[Link]([Link]() + "," + [Link]());
}

}
}

class Product implements Comparable {


private String name;
private double price;

public Product(String name, double price) {


[Link] = name;
[Link] = price;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


[Link] = price;
}

@Override
public int compareTo(Object o) {
Product p = (Product) o;
if ([Link] < [Link]()) {
return 1;
} else if ([Link] > [Link]()) {
return -1;
}
return 0;
}
}

Output Result:

ASUS Computer,400.0
Toshiba computer,350.0
Lenovo,500.0
After sorting result:-----------------------------------------
Lenovo,500.0
ASUS Computer,400.0
Toshiba computer,350.0

Set HashSet TreeSet


/**
HashSet(); //No order
TreeSet(); //In order
*/
package com.test22;

import [Link];
import [Link];
import [Link];

public class TestHashSet {


public static void main(String[] args) {

Set set = new HashSet();


[Link](new Ticket("The Matrix", 300));
[Link](new Ticket("Beautiful Soul", 100));
[Link](new Ticket("Forrest Gump", 200));
[Link](new Ticket("Firemen", 200));

Iterator iter = [Link]();


while ([Link]()) {
Object obj = [Link]();
[Link](obj + ",");
}
}
}

class Ticket {
private String name;
private double price;

public Ticket(String name, double price) {


super();
[Link] = name;
[Link] = price;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


[Link] = price;
}

public String toString() {


return name + "," + price;
}

Output Result:

Beautiful Soul,100.0,
Firemen,200.0,
The Matrix,300.0,
Forrest Gump,200.0,

Map HashMap Hashtable

/**
Hashtable // thread safe
HashMap // thread not safe
*/
package com.test22;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TestHashMap {


public static void main(String[] args) {

Map map = new HashMap();


[Link]("grace", new User("Grace","111111"));
[Link]("renia", new User("Renia","222222"));
[Link]("david", new User("David","333333"));

Set set = [Link]();


Iterator iter = [Link]();
while ([Link]()) {
[Link] entry = ([Link]) [Link]();
Object key = [Link]();
Object value = [Link]();
User user=(User)value;
[Link]([Link]() + "=" + [Link]());
}
}
}

class User {
private String username;
private String password;

public User(String username, String password) {


super();
[Link] = username;
[Link] = password;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


[Link] = username;
}
public String getPassword() {
return password;
}

public void setPassword(String password) {


[Link] = password;
}
}

Output Result:

Renia=222222
Grace=111111
David=333333
Map user login example
package com.test22;
/**
Topic:
Multiple user (User) login (1: Login 2: Print online user information 3:
Print current user -1: Exit
Keyboard input username and password
Each time a user is logged in, a user is added to a Map called an online
user.
[Link] all the usernames that have been logged in.
[Link] current login user information
*/
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class TestMapLogin {
private boolean flag = true;
private Map map = new HashMap();
private String currentUser;

public TestMapLogin() {
Scanner in = new Scanner([Link]);
while (flag) {
[Link]("Please enter : 1: Login 2: Print online user
information 3 : Print current user -1: Exit");
String action = [Link]();
if ("1".equals(action)) {
[Link]("Enter username and password");
String str = [Link]();
String[] strs = [Link](";");
String username = strs[0];
String password = strs[1];
[Link](username, password);
currentUser = username;
}

if ("2".equals(action)) {
[Link]("online user : ");
Set set = [Link]();
Iterator iter = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}

if ("3".equals(action)) {
[Link]("Current user information");
String password = [Link](currentUser).toString();
[Link](currentUser + "=" + password);
}
if ("-1".equals(action)) {
flag = false;
}
}
}

public static void main(String[] args) {


new TestMapLogin();
}
}

Output Result:

Please enter : 1: Login 2: Print online user information 3 : Print current user -1:
Exit
1
Enter username and password
yanghu;1981
Please enter : 1: Login 2: Print online user information 3 : Print current user -1:
Exit
2
online user :
yanghu
Please enter : 1: Login 2: Print online user information 3 : Print current user -1:
Exit
3
Current user information
yanghu=1981
Please enter : 1: Login 2: Print online user information 3 : Print current user -1:
Exit
-1

Stack

/**
Stack is advanced and out
Topic:
A box can put a lot of books,
Print out all book information
*/
package com.test22;

import [Link];
public class TestStack {

public static void main(String[] args) {

Stack stack=new Stack();


[Link]("Easy Learning Java");
[Link]("Oracle");
[Link]("MySQL");

String book=null;
while(![Link]())
{
book=[Link]().toString();
[Link](book);
}

}
}

Output Result:

MySQL
Oracle
Easy Learning Java

Generic
Generic : It is to pass various data types

package com.test23;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TestGeneric {

public static void main(String[] args) {


Person<String> p = new Person<String>("Grace", "30");

List<String> list = new ArrayList<String>();


[Link]("1");
[Link]("David");

Map<String, String> map = new HashMap<String, String>();


[Link]("1", "100");
[Link]("John", "Baggage");

Set<Entry<String, String>> entrySet = [Link]();


Iterator<Entry<String, String>> iter = [Link]();
while ([Link]()) {
Entry<String, String> entry = [Link]();
[Link]([Link]() + "=" + [Link]());
}
}
}

//Generic : It is to pass various data types


class Person<T> {
private String name;
private T age;

public Person(String name, T age) {


[Link] = name;
[Link] = age;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public T getAge() {
return age;
}

public void setAge(T age) {


[Link] = age;
}
}

Output Result:

1=100
John=Baggage
Generic Housing rental example

/**
Real estate company's management of rental housing information
(Housing Information: Owner Name, Price, Description)
1 . Adding a house
2. List all information about the house
3. Modify the house according to the name of the owner
4. Search for the house by the owner's name
5. Remove the house according to the owner's name
*/
package com.test23;

import [Link];
import [Link];

public class TestHouse {

public static void main(String[] args) {


Company company = new Company("Real Estate Agency");
[Link](new House("Faith", 1500, "Single Room"));
[Link](new House("Danie", 3000, "One room and one living
room"));
[Link](new House("Mathew", 4000, "Two rooms and one living
room"));

//Modify the house according to the name of the owner


[Link](new House("Mathew", 4500, "Two rooms and
one living room"));

//Search the house by owner name


House house = [Link]("Danie");
[Link]("Danie's housing information:" + [Link]() +
"," + [Link]() + "," + [Link]());

//Delete the house according to the owner's name


[Link]("Faith");

//List all information about the home


List<House> houseList = [Link]();
for (int i = 0; i < [Link](); i++) {
House h = [Link](i);
[Link]([Link]() + "," + [Link]() + "," +
[Link]());
}

}
}

class House {

private String owner;


private double price;
private String description;

public House(String owner, double price, String description) {


[Link] = owner;
[Link] = price;
[Link] = description;
}

public String getOwner() {


return owner;
}

public void setOwner(String owner) {


[Link] = owner;
}

public double getPrice() {


return price;
}

public void setPrice(double price) {


[Link] = price;
}

public String getDescription() {


return description;
}

public void setDescription(String description) {


[Link] = description;
}
}

class Company {

private String name;


private List<House> houseList;

public Company(String name) {


[Link] = name;
[Link] = new ArrayList<House>();
}

//1 . Adding a house


public void add(House h) {
[Link](h);
}

//2 . List all information about the home


public List<House> getHouseList() {
return houseList;
}
//3 . Modify the house according to the name of the owner
public boolean updateByOwner(House h) {
for (int i = 0; i < [Link](); i++) {
House house = [Link](i);
if ([Link]().equals([Link]())) {
[Link](i, h);
return true;
}
}
return false;
}

//4 . Search the house by owner name


public House findByOwner(String owner) {
for (int i = 0; i < [Link](); i++) {
House h = [Link](i);
if ([Link]().equals(owner)) {
return h;
}
}
return null;
}

//5 . Delete the house according to the owner's name


public boolean deleteByOwner(String owner) {
for (int i = 0; i < [Link](); i++) {
House h = [Link](i);
if ([Link]().equals(owner)) {
[Link](i);
return true;
}
}
return false;
}

public String getName() {


return name;
}
public void setName(String name) {
[Link] = name;
}

public void setHouseList(List<House> houseList) {


[Link] = houseList;
}
}

Output Result:

Danie's housing information:Danie,One room and one living room,3000.0


Danie,3000.0,One room and one living room
Mathew,4500.0,Two rooms and one living room
Generic about school examples

/**
Topic:
Implemented with a collection framework generic:
1. There are many classes in the school, and there are many students in
each class.
2. Output student information corresponding to each class
*/
package com.test23;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class TestClassStudent {

public static void main(String[] args) {


School school = new School("Primary School");
//Add classes and corresponding students
List<Student> studentList1 = new ArrayList<Student>();
[Link](new Student("David", 10));
[Link](new Student("Grace", 11));
[Link]("CLASS1", studentList1);

List<Student> studentList2 = new ArrayList<Student>();


[Link](new Student("Luke", 9));
[Link](new Student("Sala", 11));
[Link]("CLASS2", studentList2);

//Output student information corresponding to each class


Map<String, List<Student>> schoolMap = [Link]();
Set<Entry<String, List<Student>>> set = [Link]();
Iterator<Entry<String, List<Student>>> iter = [Link]();
while ([Link]()) {
Entry<String, List<Student>> entry = [Link]();
String className = [Link]();
[Link](className + " student information:");
List<Student> studentList = [Link]();

for (Student student : studentList) {


[Link]([Link]() + "," + [Link]());
}
}
}
}

class School {

private String name;


private Map<String, List<Student>> schoolMap = new HashMap<String,
List<Student>>();

public School(String name) {


[Link] = name;
}

//Add classes and corresponding student collections


public void add(String className, List<Student> studentList) {
[Link](className, studentList);
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public Map<String, List<Student>> getSchoolMap() {


return schoolMap;
}

public void setSchoolMap(Map<String, List<Student>> schoolMap) {


[Link] = schoolMap;
}

class Student {

private String name;


private int age;

public Student(String name, int age) {


[Link] = name;
[Link] = age;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


[Link] = age;
}
}
Output Result:

CLASS1 student information:


David,10
Grace,11
CLASS2 student information:
Luke,9
Sala,11
File
package com.test23;

import [Link];
import [Link];

public class TestFile {

public static void main(String[] args) {

File f = new File("[Link]");


try {
//Create a new empty file if the file does not exist
[Link]();

//Get the absolute path to the file


[Link]([Link]());

//Get the file name


[Link]([Link]());

//Get the size of the content in the file


[Link]([Link]());

//Rename file
[Link](new File("[Link]"));

//Determine if it is a file
[Link]([Link]());

//Determine if this file exists


[Link]([Link]());

//Delete Files
[Link]([Link]());
} catch (IOException ex) {
[Link]();
}
}
}

Output Result:

E:\Workspace\[Link]
[Link]
0
false
false
false

File and Folder


package com.test23;
import [Link];

public class TestDirectory {

public static void main(String[] args) {

File dir = new File("dir2/test");// File also indicates the directory

[Link]();//Create a directory

[Link]();//Can create multiple levels of directories

[Link]([Link]());//Get absolute path to a


directory
[Link]([Link]()); //Get the file name of the directory

[Link](new File("dir2/newtest")); //Rename a directory

//Determine if it is a directory
[Link]([Link]());

//Determine if a file or directory exists


[Link]([Link]());

//Can only delete empty directories


File dir3 = new File("dir");
[Link]();
File dir4 = new File("dir2");
[Link]();
}
}

Output Result:

E:\Workspac\dir2\test
test
false
false

FileInputStream reads a file


1. Create a text file

C:/Users/tim/Desktop/[Link]

every day is good day

[Link] read the [Link]

package com.test23;

import [Link].*;

public class TestInputStream {


public static void main(String[] args) {
InputStream is = null;
try {
//Established a connection to the file [Link]
is = new FileInputStream(new
File("C:/Users/tim/Desktop/[Link]"));
//Read data
byte[] data = new byte[1024];
//Read all the data from the file into the data byte array
[Link](data);

[Link](new String(data));

} catch (Exception e) {
[Link]();
} finally {
//Close file
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}

Output Result:

every day is good day

FileOutputStream writes to file


package com.test23;

import [Link].*;

public class TestOutputStream {


public static void main(String[] args) {
OutputStream os = null;
try {
os = new FileOutputStream(new File("c:/res/[Link]"));//File path
directory must exist
//Write data to a file
String content = "good morning";
byte[] data = [Link]();
[Link](data);
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();//Close the output stream
} catch (IOException e) {
[Link]();
}
}
}

}
FileWriter writes characters

package com.test23;

import [Link].*;

public class TestFileWriter {


public static void main(String[] args) {
Writer writer = null;
try {
writer = new FileWriter(new File("C:/Users/tim/Desktop/[Link]"));
//Directory must exist
//Write data to a file
String content = "At this moment, you will dream";

[Link](content);
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
FileReader reads files as characters

1. Create a text file

C:/Users/tim/Desktop/[Link]

At this moment, you will dream

2. FileReader read the [Link]

package com.test23;

import [Link].*;
public class TestFileReader {
public static void main(String[] args) {
Reader reader = null;
try {
//Established a connection to the file [Link]
reader = new FileReader(new
File("C:/Users/tim/Desktop/[Link]"));
// Each time a character is read, the return value is the integer type
value of the ACSII.
//if there is still a character in the file, continue reading until read the
end of the file. Return -1
int l;
while ((l = [Link]()) != -1) {
[Link]((char) l);
}
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}

Output Result:

A
t

t
h
i
s

m
o
m
e
n
t
,

y
o
u

w
i
l
l

d
r
e
a
m
InputStreamReader byte to character

1. Create a text file

C:/Users/tim/Desktop/[Link]

At this moment, you will dream

2. FileInputStream read [Link] and then InputStreamReader Convert to Reader

package com.test23;

import [Link].*;

public class TestInputStreamReader {


public static void main(String[] args) {
InputStream is = null;
try {
is = new FileInputStream("C:/Users/tim/Desktop/[Link]");
//inputStream InputStreamReader Convert to Reader
Reader reader = new InputStreamReader(is);
int l;
while ((l = [Link]()) != -1) {
[Link]((char) l);
}
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}

Output Result:

A
t

t
h
i
s

m
o
m
e
n
t
,

y
o
u
File copy

1. Prepare an image file [Link]

c:/res/[Link]

FileInputStream read and then FileOutputStream copy to c:/res/[Link]

package com.test23;

import [Link].*;

public class TestCopy {


public static void main(String[] args) {

InputStream is = null;
OutputStream os = null;
try {
//Read file [Link]
is = new FileInputStream(new File("c:/res/[Link]"));

//Copy [Link] to [Link]


os = new FileOutputStream(new File("c:/res/[Link]"));
int l;
//Write while reading
while ((l = [Link]()) != -1) {
[Link](l);
}
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
[Link]();
} catch (IOException e) {
[Link]();
}

}
}
}

TCP protocol
1. Server-side

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class Browser {

public static void main(String[] args) {


try {
ServerSocket ss = new ServerSocket(8888);
[Link]("The server is listening on 8888. . .");
while (true) {
Socket socket = [Link]();
InputStream is = [Link]();
byte[] b = new byte[1024];
int l = [Link](b);
String message = new String(b, 0, l);
[Link](message);

PrintWriter pw = new PrintWriter([Link](), true);


[Link]("<h1>hello</h1>");

} catch (IOException e) {
[Link]();
}
}
}

1. Client-side

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class IE {

public static void main(String[] args) throws Exception {


Socket socket = new Socket("localhost", 8888);
PrintWriter pw = new PrintWriter([Link](), true);
[Link]("GET /[Link] / HTTP/1.1");
[Link]("Accept: */*");
[Link]("Host: localhost:8888");
[Link]("Connection: Keep-Alive");
[Link]("");
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()));
String str = null;
while ((str = [Link]()) != null) {
[Link](str);
}

}
}

[Link] run Browser and then run IE

Output Result:

<h1>hello</h1>
UDP protocol

1. Server-side

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class UDPServer {

public static void main(String[] args) {


try {
DatagramSocket ds = new DatagramSocket(9001);
[Link]("The server listens on port 9001...");

byte[] b = new byte[1024];


DatagramPacket dp = new DatagramPacket(b, 0, [Link]);

[Link](dp);
byte[] data = [Link]();
String content = new String(data, 0, [Link]());
[Link](content);

byte[] b2 = "ok".getBytes();
DatagramPacket dp2 = new DatagramPacket(b2, 0, [Link]);
[Link]([Link]());
[Link]([Link]());
[Link](dp2);

[Link]();

} catch (SocketException e) {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}

1. Client-side

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class UDPClient {

public static void main(String[] args) {


try {
DatagramSocket ds = new DatagramSocket(9000);
[Link]("The client listens on port 9000...");
String content = "hello";
byte[] b = [Link]();
DatagramPacket dp = new DatagramPacket(b, 0, [Link]);
[Link](9001);
[Link]([Link]("localhost"));

[Link](dp);

byte[] b2 = new byte[1024];


DatagramPacket dp2 = new DatagramPacket(b2, 0, [Link]);
[Link](dp2);
byte[] data2 = [Link]();
content = new String(data2, 0, [Link]());
[Link](content);

[Link]();

} catch (SocketException e) {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}

[Link] run UDPServer and then run UDPClient

Output Result:

The server listens on port 9001...


hello

The client listens on port 9000...


ok

You might also like