Core Java 1~4 (HelloWorld & identifiers | keywords | data types & Expressions | Process Control & arrays)

Source: Internet
Author: User
Tags bitwise operators class definition float double keyword list shallow copy uppercase letter

MODULE 1

Compilation and operation of Java
----------------------------
Compilation: Javac-d bin Src\helloworld.java
-D: Specify the storage path for the compiled class file
If you call the class of another file in the class of this. java file, you need to compile the called class first, and then enter
javac-d Bin-cp bin Src\helloworld.java
or compile all. java files javac-d bin Src\*.java

Run: Java-cp bin Com.briup.ch01.HelloWorld
-CP: Specify the search path for the class file

Three elements in the Java source file:
-------------------------
1) package
Syntax: Package com.briup.ch01;
Appears as a directory after compilation
Package is not a directory
Complete class name after compilation: Package name + class name Com.briup.ch01.HelloWorld
2) Import
Dispensable
Classes in the Java.lang package or classes in the same package do not need import
3) class definition
Class Name {...}
Class name requires an uppercase letter; Keep good habits
A Java source file allows you to define multiple classes, but only one class that is public decorated
The class name of the public class must be the same as the name of the source file

BYTE-code Checker
--------------------------------
1) Verify the compatibility of the JVM version
2) Verify that the code does not compromise the integrity of the system
3) does not cause stack overflow or underflow in memory
4) parameter types are checked during method invocation
5) data type conversion to be correct


Class loading process
---------------------------
1. Class Loader classification
1) Start class Loader Bootstrap class loader
Loading the JDK's core class library
%java_home%jre/lib/rt.jar
2) Extension class loader extensible class Loader
Load some third-party extension class libraries
%java_home%/jre/lib/ext/*.jar
3) System class loader (loader)
Loading a custom class
2. Class loading process
--Start class loader--Extend ClassLoader--system ClassLoader
Parental delegation mechanism
Java Com.briuch01.HelloWorld

Advantages: 1) You can avoid repeated loading of classes, and when the previous level has been loaded, the class with the same name will not be loaded to the next level
2) Consider security and avoid any custom classes overriding the core class library of Java

Hit Jar bag
JAR-CVF helloworld.jar com
-C creat
-V Display procedure
-F Specify File name
Unpack the jar package
JAR-XVF Helloworld.jar

Common packages in the JDK
----------------------
Java.lang Common Classes
Java.awt/javax.swing/java.awt.event
Development of graphical user interface
java.io input, output
java.net Network Programming
Common tool classes provided by the Java.util JDK

MODULE 2 identifier keyword data type
---------------------------------------------------------------

Comments:
------------------
Single-line Comment
Comment Content
Multi-line comments
/*
Multi-line Comment content
*/
Javadoc Document Comments (recommended in source program)
/**
Comment Content
*/
Generate HTML-formatted Javadoc documents
Common syntax:
@author author
@version version
@since which version of the JDK is labeled
@param parameters
@return return type
Description of @throws @Exception exception information
Command: javadoc-d Doc Src\*.java
Generate author and version number: javadoc-d doc-author-version Src\*.java

Coding considerations
----------------
1) each statement with ";" End, it is recommended to write only one statement per line, note the indentation
2) All the code in Java to write in the code block {}
3) split between Code: Space tab TAB line break continuation

Identifier
----------------------------
Naming classes, methods, variables
1) Start with a letter, "$", and cannot begin with a number
2) Case sensitive
3) No length limit
4) Avoid using keywords

Key words
-----------------------------
1) Goto const is not a keyword list, called a reserved word, to avoid using
2) True false null has a special meaning, also avoid using the


1. Basic data types
-----------------------
Four types of eight types: integer floating-point Boolean character type

Boolean
True/false
Cannot be 0 and 1

Char
unsigned 16bit integral type
1) Single quotation marks indicate char c= ' A ';
2) The ASCII code denotes char c=97;
3) Unicode encoding means char c= ' \u0060 '

String:
is not a basic data type, it belongs to a reference type
A collection that represents multiple characters

Integral type
byte short int long
The default is int type, long type to be appended with L or L
1) Octal octal
Front plus 0 as 010===> 0*8^0 +1*8^1 ===> 8
Convert to binary: 0---> 1----> 001 ===>001000---->8
2) Decimal Decimals
Integer number in Java defaults to decimal int type data
3) Hex Hexadecimal
Front plus 0x as 0x10
Convert to decimal: 0*16^0 + 1*16^1 ===>16
Converted into binary: 0--->0000 1--->0001 ===>00010000---->16

Floating point Type
Float double
3.1415
1) default is double type
2) Float type one "F" or "F" end
3) Double type ends with "D" or "D"


Conversions between data types
1. Implicit conversions
Byte/short/char----> Int-----> Long ======> float----> Double
The Byte/short/char is a lateral one and cannot be converted automatically.
Short i=99;
Char c=i;//Error
Char c= (char) i;
---------------
Short s1=1;
s1=s1+1;//Error
2. Forcing type conversions
Large types are converted to small types and require coercion of type conversions
Syntax: (target type of conversion) original data type
Problem: There is a loss of precision


Naming rules
1) class name/Interface name: Start with uppercase
2) Method: Start with lowercase and capitalize on the first letter
3) Variable: Start lowercase
4) Constants: All caps


Memory Allocations in Java
---------------------------
Heap area: All programs are shared, space is not continuous, capacity is slow
Typically used to store created objects (new), member variables, etc.
Stack area: Advanced after-out allocation principle, storage space continuous, small capacity speed fast
Typically used to store local variables and basic data type variables, etc.
Code Area: Store code block, method body, etc.
static/constant zones: storing static variables, constants, etc.


int i= (int) (char) (short) (byte)-1;
How to store negative numbers: complement


Class:
Real-World Object---(abstract)----> class
1) in life:
Common characteristics and common behaviors of a group of the same type
2) in the program
Class person{
Common Features--member variables
int age;
Common behavior--common methods
public void Eat () {}
}

Objects Object
1) in life
A separate individual in the group
2) in the program
An instantiated object of the class
Person zhangweiwen;//declares a reference variable
Zhangweiwen=new person ();//Create a Person class object and return a reference
Zhangweiwen.eat ();

If a class file outside the file is called in Cattest.java
Compile Cattest.java:
Compile the called class first
Then javac-d BIN-CP bin Src\cattest.java


Constructors
Initializes a member variable in a class that does not belong to the class's behavior
The definition is the same as the class name, and there is no return type
Public Cat (String atype,string aname,int aage,string acolor) {
Type=atype;
Name=aname;
Age=aage;
Color=acolor;
}

Reference type variable
To use an object, give the object a unique identity
Variable name. member Variables---> Accessing properties of Objects
Variable name. Method ()----> Access object behavior


Homework:
Custom Rectangle Class Rectangular.java
Member Variable: Length width
Constructor: no parameter constructor
A parametric constructor
Method: Calculate perimeter, print output
Calculate area, print output
Define Test class Rectangletest.java
Main
Create multiple Rectangle objects (created by constructor)
Call method print output perimeter and area separately

MODULE 3 Expressions and Process Control
----------------------------
Local variables: Variables defined inside a method, without default initialization values, must be assigned before use
Scope scope is only within the method, and the method executes the space to reclaim

Reference type initialization
Student li=new Student ();
String Str1=new string ("Hello");
String str= "Hello";//Special, allows the assignment of a value in basic type mode
New String ("Hello");

Member variables
Defined outside of the inner method of the class
has a default initialization value
Integral type: 0
Floating-point type: 0.0
Character type: ' \u0000 '
Boolean:false
Reference type (reference type): null


Class person{
Member variables
String name;
in age;
void addage (int n) {
Age +=n;
}
}

Operators operator
-----------------------
Arithmetic operator: Subtraction
The data types are consistent on both sides of the operator, otherwise the small type is converted to a large type by default

Assignment operators

Comparison operator result is Boolean type True or False

Shift operator: operation on binary string of data
Right shift >> negative number max bit 1 is the highest bit complement sign bit
3>>2 3 binary number right 2 bits
Shift left <<
Unsigned right shift >>> highest bit sign bit complement 0

Bitwise operators
--------------------------
Bits and & two are 1, the result is 1 otherwise the result is 0
Bit or | As long as there is one for 1, the result is 1
Xor ^ Same as 0, different 1
Take counter ~


Logical operators participate in the operation of Boolean data
---------------------
Logic and &&
A && b A and B are true when the result is true
Short-circuit rule: When A is false, B does not participate in the operation
Logical OR | |
A | | As long as there is a true in B A or B, the result is true
Short-circuit rule: When A is true, B does not participate in the operation

Conditional operators
A? B:c
If A is true, the expression result is B, otherwise C
Note: When data types are inconsistent on both sides of a colon, the small type is automatically converted to a large type, and the final result is a large type

Process Control Statements
---------------------------------
Switch & Case
Switch (temp)
1. Require temp to be a byte short char int, enumeration (jdk1.5)
2.case is the entrance to the conditional branch, and once entered, it is executed until break
3.default can be placed anywhere in the switch

Looping statements
-----------------------
1.for Cycle
2.while Cycle
3.do-while Cycle


MODULE 4 Array
------------------------
An array is a data structure
A collection of the same type of data that is used to store the specified length
1) same type of data
The type of the elements in the array must be specified when declaring
2) Specify length
Once the array length is defined, it can no longer be changed.
3) belongs to reference type
Must be created using new, attribute stone length


Statement
--------------------------
1. Elements are basic data types
Int[] IArray; int iarray[];
Declares that only the element type is specified and the array length is not specified
2. Element is a reference type
Student[] IArray; Student iarray[];

Create
--------------------------
1) Create an array object using the New keyword
2) Specify the length of the array (maximum number of elements allowed)
3) elements in the array need to be created separately
4) The elements in the array have default initialization values
Grammar:
1) Basic Data type
Int[] Iarray=new int[3];
2) Reference type
Creates an array, but the student objects inside are not created
Student[] Iarray=new student[5]
Create a Student object
Student s1=new Student ();

Initialization of the element
-------------------
Default initialization:
Explicit initialization
1) declaring, creating and initializing separate
2) simultaneous declaration, creation and initialization
int[] Iarray=new int[]{2,3,4};//correct

Int[] IArray; Iarray=new int[]{5,6,7};//Correct

int[] Iarray=new int[3]{2,3,4};//Error

Int[] iarray={5,6,7};//Correct

Int[] IArray; iarray={5,6,7};//Error
Reference type
Student[] Iarray=new student[3];
Student s1=new Student ("Jeffrey");
Iarray[0]=new Student ("Jeffrey");

Student[] Iarray=new student[]{
New Student ("Jim"),
New Student ("Ann")};
Student[] iarray={
New Student ("Jim"),
New Student ("Ann")};

Student[] IArray;
iarray={
New Student ("Jim"),
New Student ("Ann")};

Access to array elements
----------------------------------
Syntax: array name [element subscript]
The range of the element subscript: 0~length-1

Traversal of an array
-----------------------------------
Int[] Iarray=new int[100];
Algorithm: for (int i=0;i<iarray.length;i++) {iarray[i]=i;}


How arrays are stored in memory
A contiguous linear storage space for an address
1) Basic Data type
Variables and data are stored in the stack area
Int[] Array=new int[]{1,5,23,35};
2) Reference type
Variables are stored in the stack area, and the element objects reside in the heap area

Multidimensional arrays
-----------------
The arrays in Java are all one-dimensional arrays, and the so-called multidimensional arrays represent arrays of arrays
Dimensions can define up to 255 dimensions
One-dimensional arrays represent linear data
Two-dimensional array representation plane


Two-dimensional array classification:
1. Symmetric arrays (matrices)
Int[][] Array=new int[2][3];//Create a two-dimensional array with three columns
2. Asymmetric Array (serrated)
1) The first dimension must be determined at the time of creation
Int[][] Array=new int[3][];
2) Each element is a one-dimensional array that needs to be created separately
Array[0]=new Int[3];
Array[1]=new Int[5];
Array[2]=new int[2];
***
*****
**
3) array.length=3;//= number of rows = First dimension
array[0].length=3;//the number of elements in each row
array[1].length=5;

Access each element of a two-dimensional array
Array[0] represents the first row
Array[0][0] array[0][1] array[0][2]

Traversing a two-dimensional array
for (int i=0;i<array.length;i++) {
for (int j=0;j<array[i].length;j++) {
System.out.print (Array[i][j]);
}
}


Copy of array
-------------------------
Extending the array length indirectly

Source array----------> dest array

System.arraycopy (From,fromindex,to,toindex,length)

Knowledge Points:
Shallow copy, for reference types, copy only the reference address of the object, rather than recreating the new object, so the copied object cannot be independent of the original object

Core Java 1~4 (HelloWorld & identifiers | keywords | data types & Expressions | Process Control & arrays)

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.