Learn Java Programming Basics
Learn Java Programming Basics
YANG HU
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
[Link]
[Link]
[Link]
[Link]
Unzip [Link]
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]
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.
*/
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;
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);
}
}
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.
//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.
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);
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);
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 {
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 {
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];
//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:
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:
/**
do{
statements;
}while (expression):
until the while expression evaluates to false exit loop
*/
import [Link];
Output Result:
Do while loop 2
/**
Enter the student's name continuously, enter "q" to exit the system
*/
import [Link];
Output Result:
Please enter the student name until enter q to quit the system
grace
q
Exit System
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
Output Result:
********
********
********
********
********
********
********
********
One-dimensional array
[Link]("\n-------------------------------");
Output Result:
90,70,50,80,60,85,
-------------------------------
90,70,50,80,60,85,
/**
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 };
}
}
Output Result:
90,70,50,80,60,85,75,
/**
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];
}
}
Output Result:
/**
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:
sort(scores);
}
}
Output Result:
50,60,70,80,85,90,
Two-dimensional array
[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];
Output Result:
/**
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]()
*/
/*
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;
Output Result:
package [Link];
/**
The encapsulation attribute:
privatize the attributes of the class and then provide a public method to
access it.
*/
class Person {
//private attribute
private String name;
private int age;
[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
*/
//Anonymous object
new Person("David", 23).say();
}
}
class Person {
private String name;
private int age;
}
/**
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:
package com.test2;
}
}
/**
Method overload:
In the same class, there is a method name with the same name, different
parameter numbers or parameter types.
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) {
}
}
class Utils {
public void increment(int count) {
count++;
}
class Count {
private int value;
Output Result:
1
1
1
2
Static keyword
package com.test4;
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");
}
Output Result:
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)
*/
class Person {
protected String name;
protected int age;
public Person() {
[Link]("parent class Person instantiation");
}
/**
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");
}
Output Result:
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) {
class Person {
public void say() {
[Link]("Person speaking");
}
}
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) {
[Link]("Fruit");
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");
}
}
Output Result:
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";
interface PrimeMinister
{
String name="PrimeMinister";
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);
class Father {
//Final keyword modification method, subclass can not be rewritten
public final void work() {
[Link]("Do hard work");
}
}
/*
//The final keyword modified class cannot be inherited
class GranDaughter extends Daughter {
}
*/
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 {
// r=10
Circle green = new Circle(10, [Link]);
[Link]();
// r=20
Circle blue = new Circle(20, [Link]);
[Link]();
}
}
class Circle {
double r; // Radius of the circle
final double PI = 3.14;
Color color; // Round color (0: red 1: green 2: blue)
//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:
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]();
}
}
class Person {
public void say() {
[Link]("Person speaking");
}
}
Output Result:
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) {
[Link](apple);
[Link]([Link]() + " eat " + [Link]().getName());
[Link](grape);
[Link]([Link]() + " eat " + [Link]().getName());
}
}
class Baby {
private Fruit fruit;
private String name;
class Fruit {
private String name;
Output Result:
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) {
class Mother {
private String name;
private String food;
Output Result:
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) {
Output Result:
/**
Wrap class:
byte -> Byte
short -> Short
int -> Integer
long -> Long
//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
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 ");
}
});
class Moto {
private String brand;
private Alarm alarm;
class Person {
private String name;
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;
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 Person() {
Wallet w = new Wallet();
[Link]([Link]());
}
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
//Thread
class MyThread extends Thread {
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
try {
for (int i = 0; i < 10; i++) {
[Link]([Link]().getName() + i);
[Link](1000); // sleep 1 second = 1000 milliseconds
}
} 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:
Compile-time exception
public class TestCompileTimeException {
}
}
}
Output Result:
0
1
2
3
4
finally
package [Link];
class Caculator {
} 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];
[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
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 {
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 {
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);
Output Result:
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];
//Determine that the file can only be in .png, .gif, .jpg format.
String checks = ".png .gif .jpg";
fileExtension = [Link]();
if () {
[Link]("You are not entering an image file");
}
Output Result:
String split
package [Link];
/**
1. String[] split(String regex) Split a string into an array with regex
*/
import [Link];
Output Result:
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];
int[] arr = { 1, 4, 3, 7, 5, 6 };
[Link](arr);
[Link]([Link](arr));
}
}
Output Result:
[1, 3, 4, 5, 6, 7]
2
Calandar
package com.test18;
import [Link];
import [Link];
class DateTime {
//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];
[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;
}
Math
package com.test20;
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](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
/**
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
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];
}
}
class ClassSet {
private String className;
private int maxSize;
private int currentSize;
private Student[] students;//Array of all students
class Student {
private String name;
private int 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;
}
}
Output Result:
Lida,90
Mathew,80
Timothy,95
John,70
Random
package com.test21;
import [Link];
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 TestTimer() {
timer = new Timer();
//Show current time every 1 second
[Link](new MyTask(), new Date(), 1000);
}
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];
[Link]("size: "+[Link]());
[Link]("isEmpty: "+[Link]());
[Link](4, 'B');
[Link]("get(4): "+[Link](4));
[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 {
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.
import [Link];
public class TestLinkedList {
[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();
}
class Car {
private String name;
private double volume;
Output Result:
package com.test22;
/**
Title:
Printout All site information for the subway
*/
import [Link];
import [Link];
import [Link];
class Station {
private String name;
Output Result:
Vector
/**
Title:
Printout cinema movie name
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("\nEnumeration---------------------------");
Enumeration e = [Link]();
while ([Link]()) {
Movie movie = (Movie) [Link]();
[Link]([Link]() + ",");
}
}
}
class Movie {
Output Result:
/**
Title:
Sort the price of the product of the merchant by price
*/
package com.test22;
import [Link];
import [Link];
import [Link];
import [Link];
}
}
@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
import [Link];
import [Link];
import [Link];
class Ticket {
private String name;
private double price;
Output Result:
Beautiful Soul,100.0,
Firemen,200.0,
The Matrix,300.0,
Forrest Gump,200.0,
/**
Hashtable // thread safe
HashMap // thread not safe
*/
package com.test22;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class User {
private String username;
private String 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;
}
}
}
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 {
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 T getAge() {
return 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];
}
}
class House {
class Company {
Output Result:
/**
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];
class School {
class Student {
import [Link];
import [Link];
//Rename file
[Link](new File("[Link]"));
//Determine if it is a file
[Link]([Link]());
//Delete Files
[Link]([Link]());
} catch (IOException ex) {
[Link]();
}
}
}
Output Result:
E:\Workspace\[Link]
[Link]
0
false
false
false
[Link]();//Create a directory
//Determine if it is a directory
[Link]([Link]());
Output Result:
E:\Workspac\dir2\test
test
false
false
C:/Users/tim/Desktop/[Link]
package com.test23;
import [Link].*;
[Link](new String(data));
} catch (Exception e) {
[Link]();
} finally {
//Close file
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
Output Result:
import [Link].*;
}
FileWriter writes characters
package com.test23;
import [Link].*;
[Link](content);
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
}
FileReader reads files as characters
C:/Users/tim/Desktop/[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
C:/Users/tim/Desktop/[Link]
package com.test23;
import [Link].*;
Output Result:
A
t
t
h
i
s
m
o
m
e
n
t
,
y
o
u
File copy
c:/res/[Link]
package com.test23;
import [Link].*;
InputStream is = null;
OutputStream os = null;
try {
//Read file [Link]
is = new FileInputStream(new File("c:/res/[Link]"));
}
}
}
TCP protocol
1. Server-side
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
} catch (IOException e) {
[Link]();
}
}
}
1. Client-side
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class IE {
}
}
Output Result:
<h1>hello</h1>
UDP protocol
1. Server-side
package [Link];
import [Link];
import [Link];
import [Link];
import [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];
[Link](dp);
[Link]();
} catch (SocketException e) {
[Link]();
} catch (IOException e) {
[Link]();
}
}
}
Output Result: