Java basics 1

Source: Internet
Author: User
Tags arithmetic operators

Java basics 1
I. java Development Tools

Editplus: Connection Configuration between Editplus and jdk, such as javac (Compilation), java (running), and javap (view bytecode)
A) configuration content:
I. javac (Compilation): the parameter is-d. (FileName); initial directory (FileDir)
Ii. java (run): the parameter is (CurSel ). (FileNameNoExt); initial directory: (FileDir) iii. javap (view bytecode): the parameter is (FileNameNoExt); initial Directory: $ (FileDir)

Ii. java Initialization

:
A) explains keywords, naming conventions, and modifiers through the HelloWorld class;
Pubic class HelloWorld {
Public static void main (String [] args ){
System. out. println ("Hello World !");
}
}
B) differences between jdk and jre; content, scope // development, run // contains various class libraries and tools, java program runtime environment JVM
Jar; compressed files in java
Javac; Compile
Javadoc; to form a help document
Total: java; run
Native2ascii; change local code to ASCII code
Javap; view bytecode files
C) bytecode. It is a cross-platform mechanism of java. It is a piece of binary code, including the execution program,
A binary file consisting of a sequence of op code (operation code)/data pairs. A bytecode is an intermediate code that is more abstract than a machine code. It is a binary file (. class) that contains an execution program)
The data unit is in hexadecimal notation; K is MB, G is GB, and G is GB. T is too pulling 8 bit (BIT) = 1 Byte (Byte)
1024 Byte (bytes) = 1KB 1024KB = 1 MB 1024 MB = 1 GB 1024 GB = 1 TB
In java, bytecode is a portable machine language of the CPU architecture (JVM.
D) four goals;
1. java introduction; history and position-cross-platform object-oriented language-third-generation language: inheritance, encapsulation, polymorphism: method with the same name, different body
C ++-Class Functions
. NET-Cross-Language Platform
SQL-Structured Query Language-fourth generation language
Lisp and Prolog Artificial Intelligence Language-fifth generation language
Self-Development: 95 years later, it will become javaSE
Java System: javase, javaee, javame
Features: Object-oriented, platform-independent, and robust: no pointer, memory application and release (memory allocation)
2. Working Principle
I Java Virtual Machine
Java Virtual Machine (JVM) is a system that uses bytecode as machine instructions. The Instruction Set for compiling a virtual machine is very similar to that for compiling a microprocessor.
The Java Virtual Machine includes a set of bytecode instruction sets, a set of registers, a stack, a garbage collection heap, and a storage method domain. -- Stack, stack, local method stack, method zone, pc register
. Java-. class
Ii garbage collection mechanism (GC); memory space that is no longer used should be recycled
Java's garbage collection mechanism: Java's garbage collection mechanism is the capability provided by java virtual machines. It is used to dynamically reclaim the memory space occupied by non-referenced objects in an irregular manner during idle time. Note that garbage collection is the memory space occupied by objects without any reference, rather than the object itself.
1. Garbage collection is automatically executed by virtual machines and cannot be artificially intervened.
2. The system is relatively idle (garbage collection thread) for execution
3. The object is not referenced. The object is in the isolated island State of reference (isolated reference), and the object has the condition for recycling.
4. gc () method. It is recommended that the virtual machine perform garbage collection, but it cannot be determined whether garbage collection will be performed.
Iii. Development Environment Construction
Tools: JCreator \ Eclipse \ MyEclipse \ Jbuilder \ NetBeans

Iv. The first java program
Java source file;. java
The basic composition is class. Only one public class can be created, and the name is the same
Java Runtime (JVM): Class Loader, bytecode verification, Interpreter
In java, only values are passed.

Iii. Data Type and conversion

(Identifier and keyword, constant and variable, basic data type, automatic conversion, forced conversion, escape character, expression)
A) identifier: the format requirements of the identifier:
I. Definition: The character sequence used by java to name various variables, methods, classes, and other elements must comply with the rules of the identifier
Ii. Rules:
1. It consists of letters, underscores (_), dollar signs ($), and numbers.
2. It cannot start with a number.
3. Case Sensitive, unlimited length (difference C)
4. The first letter of a class name is generally in upper case, and the method name is generally in lower case, and follows the naming rules of camels, such as ActiveDemo.
B) KEYWORDS
I. Definition: some strings in java with specific meanings for special purposes
Ii. All keywords must be in lower case
Iii. Common keywords
1. Used for data types: int, long, short, String, byte, char, float, double, boolean
2. for process control: if, else, for, switch, case, do, while, break, and continue
3. access controllers: public, protected, default, and private
4. For exceptions: try, catch, finally, throw, and throws
5. return type: native, super, null, void, return, synchronized (synchronous)
6. instance: instanceof, this, new
7. Object-oriented: class, extends, interface, abstract, final, implements, import, package, static
8. goto and const are used to destroy the program entry. They are also keywords.
C) constants and variables
I. Constant: (public static final constant name ;)
1. Definition: constant value, which can be a value, character, or string
2. Rules: naming conventions should be capitalized.
Ii. Variable: (type varName [= value];)
1. Note: local variables must be initialized before use or compilation fails!
Iii. Call format:
1. The variable/constant format for calling other classes in the same file is: object. Variable
2. For instances of the same type that call other functions, the variable/constant format is: new object (). variable name
3. The class variable/constant format for calling other functions in the same type is: Class Name. variable name
D) Data Type
I. Basic data types: byte, short, int, long, char, float, double, boolean
1. Default Value (range:-2 ^ (n-1) limit 2 ^ (n-1)-1)
A) Byte // 1, short // 2, int // 4, long // 8 -- the default value is 0.
B) char // 2 --- character 0 -- the range is 0 ~ 65535-unicode Encoding
C) float // 4, double // 8---0.0
D) Boolean // 2 ----- false
Ii. Reference Data Types: arrays, classes, and interfaces
E) automatic conversion (implicit conversion) (from small to large)
I. Definition: automatic type conversion, also known as implicit type conversion, refers to type conversion that is automatically completed by the system without the need to write code.
Ii. conversion rules: byte? Short (char )? Int? Long? Float? Double
Iii. Sample Code:
1. int I = 4;
2. float n = I;
F) forced conversion (from large to small)
I. conversion rules: double → float → long → int → short (char) → byte
Ii. Format: (type to be converted) value to be converted
Iii. Sample Code:
1. double d = 3.10;
2. int n = (int) d;
Iv. Note: forced conversion usually results in loss of precision.
G) escape characters
I. \ B Return
Ii. \ n newline
Iii. \ r press ENTER
Iv. \ 'single quotes
V. \ "double quotation marks
Vi. \ backslash
H) Operator -- Expression
I. Definition: an expression is a combination of numbers, operators, numerical grouping symbols (parentheses), free variables, and constraint variables that can be obtained by meaningful permutation of values. The constraint variable has been specified in the expression, while the free variable can be specified outside the expression.
Ii. arithmetic operators:
1. Single Object: ++ (auto-plus 1),-(auto-minus 1), + (take positive),-(take negative)
2. binocular: +,-, *,/, %
3. Category 3 :? : For example, a> B? A: B
Iii. Relational OPERATOR: --- return result true/false
1. equal to the symbol: =
2. Not equal to the symbol :! =
3. Greater than the symbol:>
4. Less than symbol: <
5. symbol greater than or equal to:> =
6. less than or equal to the symbol: <=
Iv. Logical OPERATOR: -- return result true/false
1. And (&): false Short Circuit
2. Or (|): True short circuit
3. Non (!) :
V. bitwise OPERATOR: -- convert the original number into binary Computation
1. sum (&): for example, 1100 & 1010 = 1000
2. Or (|): for example, 1100 | 1010 = 1110
3. Non (!) : For example! 1100 = 0011
4. Exclusive or (^): for example, 1100 ^ 1010 = 0110
5. <shift left with a symbol -- equivalent to multiplying by 2
6.> shift right with a symbol --- divide by 2
7. >>> no number shifted to the right
8. Exclusive or rule:
A) a ^ a = 0
B) a ^ B = B ^
C) a ^ B ^ c = a ^ (B ^ c) = (a ^ B) ^ c;
D) d = a ^ B ^ c can be used to release a = d ^ B ^ c.
E) a ^ B ^ a = B
Vi. assignment operator:
1. =, + =,-=, * =,/=, % =, & =, ^ =, |=, <=, >>=
Vii. Intanceof: -- ownership
1. Definition: binary operator. The operator on the left is an object and a class on the right. Returns true if the object on the left is the object of the right class.
2. Format: result = object instanceof class such as: a = B instaceof B; // true
Viii. Priority: (from high to low, from left to right)
1. () []
2 .! + (Positive)-(negative )~ ++-
3. */%
4. + (plus)-(minus)
5. <>>>>>
6. <=> = instanceof
7. =! =
8. & (bitwise AND)
9. ^ (bitwise OR)
10. | (bit is not)
11 .&&
12. |
13 .? :
14. = + =-= * =/= % = & = | = ^ = ~ = <<=>=>>>>=

Iv. Process Control statements (branches and loops)

A) If... Else: Example 1.1:
I. If (a> B ){
Ii. System. out. println ();
Iii.} else if (B> c ){
Iv. System. out. println (B );
V.} else {
Vi. System. out. println (B );
Vii .}
B) Branch: (switch)
I. Format: switch (Condition Statement ){
Case:
Case:
.....
Default:
}
Ii. Example 1.2: switch (month ){
Case 1: System. out. println ("spring"); break;
Case 1: System. out. println ("spring"); break;
Case 1: System. out. println ("spring"); break;
Case 1: System. out. println ("spring"); break;
Default: System. out. println ("spring"); break; // the statement that will be executed.
}
C) For Loop
I. Format: For (initialization statement; Condition Statement; control statement ){
Loop body;
}
Ii. Example 1.3: for (int I = 1; I <101; I ++ ){
Int sum = 0;
Sum + = I;
}
D) while
I. Format: while (Condition Statement ){
// Initialization statement;
Loop body;
// Control statement;
}
Ii. Example 1.4: int I = 1;
While (I <101 ){
Int sum = 0;
Sum + = I;
}
E) Do .... While ()
I. Format: do {
Loop body;
} While (Condition Statement );
Ii. Example 1.5: int I = 1;
Do {
Int sum = 0;
Sum + = I;
} While (I> 101 );
F) enhanced for loop ---- mainly used to print array elements
I. Format: for (e: array name ){
Loop body
}
Ii. Example 1.6: int [] a = new int [10];
For (e: ){
System. out. println (e );
}

V. Method and Recursion

A) method-Function
I. Definition: A piece of code snippet used to complete a specific function
Ii. Declaration format: [modifier] return type method name (form parameter list ){
Method body;
}
Iii. Syntax explanation:
1. Formal parameters: used to receive external input data when a method is called
2. Real parameters: data actually transmitted to the method when a method is called
3. Return Value: The data returned to the environment that calls the method after the method is executed.
4. Return Value Type: the data type of the previously agreed return value. If no return value exists, the return type void must be provided.
5. The return statement aborts the method and specifies the data to be returned.
Iv. Call format:
1. Call of static methods (also called class methods): Class Name. Method Name (actual parameter)
2. Call an instance method: Object Name. Method Name (actual parameter)
3. when passing a parameter in a call, the following rule is followed: the basic data type is the data itself, and the reference data type is the reference (address) of the object, not the object itself-the basic data type: value transfer; reference data type: Address Transfer.
V. Example 1:
Public class DemoMethod {
Public static void main (String [] args) {// call of a static method (also called a class method): Class Name. Method Name (actual parameter)
Show ("I am a girl ");
// Call an instance method: Object Name. Method Name (actual parameter) // how to generate an Object, format: new Constructor ()
// A method with the same name as a class is called a constructor.
// What is Constructor )? Each class has a constructor with the same class name and is automatically generated.
// New DemoMethod (). display ();
New DemoMethod (). visiable (12, "aaa", 3.0f );
}
// Static method definition [static modification method with keyword]
Public static void show (String s) {// custom Method
System. out. println (s );
}
// Instance method definition [method without static keyword modification]
Public int display () {System. out. println ("welcome to jiangxi"); return (85); // return the result. You can use arc brackets or skip them}
// Instance method with multiple parameters
Public void visiable (int x, String y, float f) {System. out. println ("=========================== ");}
}
B) recursion ---- there must be an exit
I. Definition: recursion is used to allow a function to call itself from within it
Ii. features:
1. The program code is concise, easy to understand, but a waste of memory
2. There must be a return type
3. There must be if ....... Else ...... And if has termination conditions

Vi. Category (Object-Oriented Technology basics, class declaration and use, object declaration and use, and constructor)

A) Object-oriented Technology Basics
I. object-oriented design methodology [OOA (analysis )? OOD (Design )? OOP (programming )? Test )? Deployment]
Ii. Object Oriented (OO) features:
1. Object uniqueness: each object has its own unique identifier. Through this identifier, you can find the corresponding object. The identifier of an object remains unchanged throughout its lifecycle. Different objects cannot have the same identifier (address ).
2. encapsulation (abstraction): encapsulates objective objects into abstract classes, and classes can only operate trusted classes or objects on their own data and methods, hide untrusted information.
3. Inheritance: inheritance is the mechanism by which child classes automatically share the data structure and method of the parent class. This is a relationship between classes. Classes in java only support single inheritance, and interfaces support multiple inheritance.
4. Polymorphism: Polymorphism means that the same operation or method and process can act on multiple types of objects and obtain different results. Different objects receive the same message to produce different results. This phenomenon is called polymorphism.
5. Summary: encapsulation can hide implementation details to modularize the code. inheritance can expand existing code modules (classes). They are all for the purpose of code reuse. Polymorphism aims to achieve another purpose-interface reuse! Polymorphism is used to ensure that a certain attribute of an instance of any type in the family tree is called correctly when the class is inherited and derived.
Iii. Basic Features of object-oriented (OO)
1. package)
2. inheritance-Association
A) inherit (generalized generalize)
I. Implement inheritance
Ii. Visual inheritance
B) combination (aggregation)
I. interface inheritance
3. Polymorphism (Polymorphism)
A) override)
I. Method
Ii. interface)
B) overload)
I. functions with the same name
B) Class description and usage
I. Declaration format:
[Modifier] class [class name ]{
Method body;
}
Ii. Example 1:
Public static class Demo {
System. out. println ();
}
C) object declaration and use
I. Format: reference variable of the class name object = new Class Name ();
Ii. Example 2: Demo d = new Demo ();
D) Comparison between classes and objects
I. A class is an object template, and an object is a class instance.
E) constructor
I. Definition: defines the method in the class used to initialize the member variables of the object. The returned memory address is
Ii. format:
1. [modifier] Method Name (){}
2. Example 3: public Demo (){}
Iii. Requirements:
1. the same name as the class; 2. No return value (without void modification); you must first create an object and call it on the object (new)

VII. UML

A) UML definition: (uniied Modeling Language) Unified Modeling Language, a visual Modeling Language for the analysis and design phase of Object-Oriented Software Engineering
B) UML relationship (relationship between classes): Associate with attributes and dependency on Methods
I. Correlation: Diamond points to overall has
1. Join relationship-if logically A is a part of B, B is not allowed to be born from A, but to combine A with other things to B.
2. aggregation-solid-line hollow Diamond
3. Combination-the whole and part cannot be separated, solid line solid diamond
Ii. Generalization (inheritance): Use a solid hollow triangle to point to the parent class is
1. If B is A logical "One" of A, and all functions and attributes of A are meaningful to B, B is allowed to inherit the functions and attributes of.
Iii. Implementation relationship (Interface): dotted line
Iv. Dependency relationship: A "---->" B (A depends on B) use a dotted arrow
C) modifier Image
I. + public-private # protected ~ Default access
D) Modeling graphics (9 types ):
I. Use Case divisor: displays the relationship between various executors outside the system and various Use cases provided by the system.
Ii. Class digraphs: displays the static structure of classes in the system (Class refers to objects with the same attributes and behaviors). Class diagrams are used to describe the static structure of classes in the system.
Iii. Object digraphs: An instantiated graph in a class graph (instantiate a class graph)
Iv. sequence Diagram: displays a dynamic cooperative relationship between objects (composed of a group of objects, the process of exchanging messages between objects over time, highlighting the time relationship)
V. Collaboration Diagram: displays the dynamic Collaboration between objects from another perspective (dynamic Collaboration between objects, highlighting the relationship between sending and receiving information)
Vi. Statechart di: Describes all possible states of a class of objects and their transfer relationships (displays all possible states of an object and the transfer of States when a specific event occurs)
Vii. Activity digraphs: displays the execution processes of various activities in the system (the execution sequence and execution process of various activities)
Viii. Component Diagram: displays the physical structure of program code (describe the organizational structure of program code and dependencies between various components)
Ix. deployment Diagram: displays the configuration relationships of software in hardware environments (especially in distributed and network environments) (physical configurations and system architecture of hardware and software in the System)

8. Custom classes

A) Class Definition: a class is a set of objects with the same attributes and operations. a class is an object template. a class can generate objects, the single-instance mode is used to generate a single object. A class is an abstraction of the real-world entity, and an object is an instance of the real-world entity.
B) Composition of classes: field (member variable) + method + initialization block (static initialization block + object initialization block)
C) Naming rules: the first letter of the class name is in upper case, the first letter of the variable name and method name (except the method construction method) is in lower case, and the camel name is used for naming.
D) Definition Format of fields (instance variables + class variables (static variables:
[Modifier (4 p, static, final)] Data Type attribute name [= default value ];
E) Definition Format of the method: [modifier (4 p, static, final, abstract)] Return Value Method Name ([parameter list]) {code block ;}
F) initialization sequence: static initialization block? Class variable, instance variable initialization? Initialize object initialization blocks and member variables (in the order of program code )? Constructor
G) JavaBean specifications:
I. It must be a public class and set its access attribute to public, such as: public class Stu {}
Ii. There must be an empty Constructor (public, no parameter): there must be a public constructor without Parameters
Iii. The field (instance variable) must be private, and the first letter must be in lower case. use private to modify it, for example, private int id;
Iv. fields should be accessed through a set of access methods (getter and setter). Generally, the getter and setter methods are generated using tools such as Eclipse, JBuilder, and IDE.
V. setter and getter specifications: lowercase letters of a field -- for example:
1. public class Demo {
A) private String name;
B) public Demo (){}
C) public Demo (){
System. out. println ("good ");
D )}
E) public void setName (String name ){
This. name = name;
F )}
G) public String getName (){
Return name;
H )}
}

9. Array (one-dimensional array, two-dimensional array, sorting, Arrays. sort)

A) one-dimensional array
I. Definition: An array is a set of elements of the same type.
Ii. The array variable is a reference type. stack (FILO, automatic recycle) references the data in heap (new, tree structure, JVM recycle;
Iii. Format: int [] a = new int [3];
Int [] a = {1, 2, 4 };
Iv. Use the for loop to traverse the output to obtain the length of the array and access elements.
For... Each: enhanced for Loop
For (String I: a) {// enhanced for loop System. out. println (I );}
// Bubble sort
Public class SortTest {
Public void sort (int [] args ){
System. out. println ("Before sorting");
For (int m: args) {System. out. print (args [m] + ",");}
Int time1 = 0, time2 = 0;
For (int I = 0; I <args. length-1; I ++) {for (int j = I + 1; j <args. length; j ++) {int temp; if (args [I]> args [j]) {temp = args [j]; args [j] = args [I]; args [I] = temp ;}} System. out. println (); System. out. println ("sorted"); for (int n: args) {System. out. print (n + ",") ;}} public static void main (String [] args) {int [] arg = new int, 9,0}; new SortTest (). sort (arg );}
}
B) two-dimensional array -- actually one-dimensional array references another one-dimensional array
I. Declaration: Int [] [] arr; // 4 bytes
Ii. A row must be created during creation. Initialization is to initialize each element and use the enhanced for loop.

10. Object Class

A) The Object class is the superclass of all classes;
B) Common method: HashCode () -- hash value, for example:
I. IntegertoHexString (p1.hashCode (); // convert the unsigned hexadecimal format of the hash code to decimal
C) getClass () // get the class at runtime
D) toString () // return character, equivalent to getClass (). getName () + "@" + Integer. toHexString (HashCode ());
E) clone () // create an object that is exactly the same as the source object, but the new object is not the same as the source object
I. Subclass rewrite clone () requirements: 1. Create A Class A to implement the cloneable interface; 2. Rewrite the Object clone () and call super. clone ()
Ii. Code implementation: as shown in Figure
Public class Person implements Cloneable {
Int;
Protected Object clone () throws CloneNotSupportedException {Person p = (Person) super. clone ();
}
}
Public class PersonDemo {public static void main () throws CloneNotSupportedException {Person p = new Person (); p. as = 11; System. out. println ("Before clone" + p. as); Person p1 = (Person) p1.clone (); p1.as = 22; System. out. println ("After clone" + p. as );}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.