JAVA 8 отмечает исследование - Глава первая

Глава 1 Java Строительные блоки

1 Комментарий

//: однострочный комментарий

/ *

*

* /: Многострочный комментарий

/ **

*

* /: Комментарий JavaDoc

 

2. класс

Классы имеют два основных элемента: методы и поле, классы являются основными строительными блоками.

Имя файла должно совпадать с именем класса, и имеет расширение .java.

компиляции javafile в командной строке: Javac xxx.java

запустить JavaClass: Java XXX

Основной метод: государственной статической силы основных (String [] арг) {}

Без основного метода (), класс может скомпилировать, но не может работать.

 

3. импорт

Импортирует только классы в указанном пакете, он не импортирует классы в дочерних пакетов в назначенный.

Пакет java.lang автоматически импортированы.

Явный импорт занимает precedure по шаблону настоящего времени.

Используйте полное имя класса, чтобы исправить конфликт имен

импорт java.util.Date;

импорт java.sql *.

Имя Явная класс:

 дата java.util.Date; // новый построенный объект типа java.util.Date назвал дату

 java.sql.Date sqldate; //

 

4. Объект создания

1) Конструктор

- совпадает с именем класса без возвращаемого типа.

- для инициализации полей

2) экземпляр инициализатор

Коды блоки {}, которые появляются вне метода, называются экземпляр инициализаторы.

3) порядок инициализации

Поля и экземпляр инициализатор блоки выполняются в том порядке, в котором они появляются в файле.

Тогда конструктор работает.

 

4. Тип данных

1) примитивные типы

восемь Bulit-в: байт, короткие, Int, длинные, с плавающей точкой, двойной, символ, логическое.

По умолчанию Java предполагает , что вы определяете  Int  с буквальным.

длиной макс = 3123456789; // не компилируется

длиной макс = 3123456789L;

С плавающей точкой литералов предполагаются дважды, так что поплавок требует Буква F следующее число.

float f = 2.2;  // doesn't compile

float f = 2.2f;

Undercore can be added into a number except at the beginning of a literal, the end of a literal, right before the decimal point , or right after the decimal point.

2) reference types

A reference type refers to an object (instance of a class).

Test s = new Test();

3) key differences

- A reference type can be asigned null, while primitive type can't.

- A reference type have methods, while primitive type don't.

 

6. Variables

Declare a variable: state the type and give a name.

Initialize a variable: give a value.

Multiple variables of defferent types can't be declared in the same statement.

String s, int num;  //doesn't compile

1) identifiers

- Can be combinations of letter, number, _ and $.

- Can't begin with numbers.

- Can't use java-reserved words.

- Java is case-sensitive.

Method and variable names begin with an lowercase letter followed by ComelCase.

Class names begin with an uppercase letter followed by ComelCase.

Package names use only lowercase.

Constant names use only uppercase.

2)initialization

Local variables is a variable defined within a method. Local variables must be initialized before use.

Instance variables are also called fields.

Class variables hava a keyword static before it, and shared by multiple objects.

As soon as you declare a class variable or instance variable, it's given a default value.

Default value:

boolean: false

byte, short, int, long: 0

float, double: 0.0

char: '\u0000'

reference type:  null

3) variable scope

Local variables can NEVER have a scope larger than the method they are defined in.

Local variables---in scope from declaration to the end of the block{};

Instance variables--in scope from declaration until object garbage collected

Class variables (static) -- in scope from declaration until program ends.

 

7. elements orders in class

1) package

2) import

3) class

mutiple classes can be defined in the same file, but only one of them is allowed to be public.  The public class matches the name of the file.

A file is also allowed to have neither classes be public.

 

8. garbage collection

1) System.gc(): suggests garbage collection to run, but java is free to ignore the request.

2) finalize(): is only run when the object is eligible for garbage collection. it could run zero or one time.

 

9. benefits of java

Object - Oriented: code defined in classes and instantiated into objects.

Encapsulation: Java supports access identifiers to protect data from unintended access and modification.

Platform Independent: compiled to bytecode and can be run on different systems.

Robust: Java manage memory on its own and does garbage collection automatically, proventing memory leaks.

Simple: get rid of operator overloading

Secure: Java code runs inside the JVM.

рекомендация

отwww.cnblogs.com/shendehong/p/11703043.html