Java entry (2) -- it is true that the break is still punished... java is punished.

Source: Internet
Author: User

Java entry (2) -- it is true that the break is still punished... java is punished.

After more than a month of disconnection, the reading volume immediately drops from 100 + to 10-although it is not very important, after all, it is only when this is your study notes, but some people see, some people comment, some people agree and criticize the situation, especially those who have been deprived before.

Write it well.

The current "business" is developed in PHP and Android.

The former tends to be in three directions, summing up the previous (reading books and coding implementation), the development of e-commerce websites, and the implementation of some skills;

In the early stage of the latter, I learned Java and made things by hand. I want to give an explanation within a week.

Today, I am still a bit confused. I uninstalled what I got yesterday. The Virtual Interface in AS is not used. Use Genymotion recommended by my friends. At least someone will bring it. This is better than PHP (tears rush ).

The schedule is always a problem, so you have to enable and reduce traffic. Come on!

1. Java (2)

2. constants and variables

2.1 keywords in Java

Some special-purpose words in Java are called keywords. Keywords have special significance for Java compilers. Be careful when using them in programs !!

Common keywords in Java:

Q: You can't remember that much ...... -_-|

A: You do not need to remember all of them now,Just mix your eyesIn the course of learning, you will gradually find the feeling and remember them

By the way, I almost forgot about the major event. The Java keyword isCase SensitiveOh! Therefore, void is a keyword, but Void is not ~~

PS: I can turn off the case sensitivity in AS. In fact, I don't recommend it.

2.2 Java identifier Recognition

Q: What is the identifier?

A: An identifier is a symbol used to name variables, classes, and methods in a Java program.

When using identifiers, follow the following rules:

1. identifierYesByLetters, numbers, underscores (_), dollar signs ($)But cannot contain other special characters such as @, %, and space., Cannot begin with a number. For example, 123 name is invalid.

2. identifierIt cannot be a Java keyword or a reserved word.(Keywords reserved in Java may be used as keywords in later versions), but they can contain keywords and reserved words. For example, void cannot be used as an identifier, but Myvoid can

3. The identifier isCase Sensitive. Therefore, it must be clear that imooc and IMooc are two different identifiers!

4. The name of the identifier is best to reflect its effect.Mingzhiyi.

What is the 2.3 variable?

Simply put, we can regard variables as a box where keys, mobile phones, drinks, and other items can be stored, you can also replace it with the new items we want to store as needed.

In Java, we use three elements to describe variables:Variable type, variable nameAndVariable value.

If we compare variables to the hotel room, the data to be stored is like the guests who want to stay, we can arrange for the guests to stay in the "Standard Room" or "presidential suite" according to their requirements ", you can quickly find the information of the guests Based on the room name. Similarly, in a Java program, we can save the data in the specified variable space based on the format of the data to be saved, and quickly locate it using the variable name!

For example, we have defined a variable "love" to save a string "imooc". Once the variable "love" is found in the program, we can find the "imooc" stored in it "! Of course, we can also replace the value in love with the new string "I love imooc "!

Running result:

Everyone should pay attention to the following:Punctuation Marks in Java are in English.. For example, the end of a statement is a semicolon (;), which is an English symbol. If you write tens of millions of tables in Chinese ~~

2.4 how to name Java Variables

Just as the hotel will give a personalized name to each room, variables in the program also need to be managed with a reasonable name-variable name!

Note that the name of a hotel room can be a number, such as "802" or an interesting name, such as "Peony", "President of the United States", and "Water Curtain Cave, but it is required to give the variable a name.Comply with certain rules, As shown below:

The names of the following variables comply with the specifications:

But please refer to the following code, you know:

Habits of excellent city siege teachers:

1. When a variable name is composed of multiple words,Lowercase letters of the first word,The first letter of the subsequent word is capitalized., Also known as the camel naming method, such as myAge

2. When naming variables, express the role of variables as short and clear as possible to achieveMingzhiyi. For example, define the variable name stuName to save the "Student name" information.

PS: Java variable nameNo limit on LengthBut the Java languageIs case sensitiveSo price and Price are two completely different variables!

2.5 Data Types in Java

In general, to facilitate the storage of items, we will specify the types of items that can be stored in each box. Just like in the box with smelly socks, we will not put "Bread! Similarly, variable storage also focuses on "classification "!

Java isStrong typeLanguage. In general, the data stored in Java is of a type and must be determined at compilation. Java has two types of data:

In the Java Field, Basic data type variableSaved isData itself, AndReference Type VariableSaveData Space address. To put it bluntly, the basic data type variables store things directly in the drawer, and the reference data type variables store the keys of the drawer. The keys correspond to the drawers one by one.

Common basic data types include:

You may have noticed:

For example
Public class HelloWorld {
Public static void main (String [] args ){
String name = "love course ";
Char sex = 'male ';
Int num = 18;
Double price = 120.5;
Boolean isOK = true;
System. out. println (name );
System. out. println (sex );
System. out. println (num );
System. out. println (price );
System. out. println (isOK );
}
}

2.6 rules for using variables in Java

UnacceptableSmall temper:

1. Variables in Java need to be declared first and then used

2. When using a variable, you can declare the variable and initialize it at the same time.

,

You can also declare and assign values first.

3. Only one value can be assigned to a variable at a time, but it can be modified multiple times.

4. variables defined in the main method must be assigned values before output.

5. Although no errors are prompted in the syntax, it is not recommended to use Chinese characters for variable names during actual development, which may cause security risks, such as garbled Characters During later cross-platform operations.

String: indicates that the data stored in the variable is of the String type. It will be detailed in the following sections ~~

2.7 automatic type conversion in Java

In Java programs, data of different basic data types often needs to be converted to each other. For example:

,

In the code, the int-type variable score1 can directly assign values to the double-type variable score2. The running result is:82.0

This type of conversion is calledAutomatic type conversion.

Of course, automatic type conversion is requiredMeet specific conditionsOf:

1. The target type can be compatible with the source type. For example, the double type is compatible with the int type, but the char type is not compatible with the int type.

2. Target typeGreaterSource Type. For example, the length of the double type is 8 bytes, And the int type is 4 bytes. Therefore, variables of the double type can directly store int type data, but in turn cannot.

2.8 forced type conversion in Java

I believe our friends have also discovered that, although automatic type conversion is very convenient, it cannot meet all programming needs.

For example, how can I implement the function of assigning the value of the double variable to an int variable in a program?

Obviously, this conversion will not be performed automatically! Because the storage range of the int type is smaller than that of the double type. In this caseForced type conversion.

Syntax:(Data Type) Value

Running result:

It can be seen that after 75.8 is assigned to the int type variable through forced type conversion, the result is 75, and the numeric value is not rounded, but the decimal place is truncated directly.

Understand,Forced type conversion may cause data loss.You must be careful when using the app!

2.9 application of Java Constants

The so-called constant can be understood as a special variable. After its value is setIt cannot be changed during program running.

Syntax:Final constant name = value;

Using constants in the program can improve the CodeMaintainability. For example, during project development, we need to specify the user's gender. In this case, we can define a constant SEX with a value of "male". You can directly call this constant where the user's gender needs to be specified, this avoids program errors caused by user non-standard assignment.

Note: constant names are generally used.Uppercase characters

2.10 how to use annotations in Java

When writing a program, you often need to add some comments to describe the role of a piece of code.

In general, for a standard program source code, comments should account for more than 1/3 of the source code. Therefore, annotations are an important part of the program source code and must be paid attention!

There are three types of annotations in Java:Single line comment, multi-line comment, document comment

Running result:Hello Imooc!

View: The annotated code block will not be executed when the program is running ~~

We can useJavadocCommand to extract content from the document comment and generate the program's API help document.

Open the home page to view the generated API documentation

PS: You can also useJavadoc flagTo generate more detailed document information:

@ Author indicates the author of The development class module

@ Version indicates the version of the module.

@ See references, that is, related topics

@ Param description of a parameter in the other method

@ Return description of the return value of the Method

@ Exception describes possible exceptions thrown by methods.

Iii. Operator-related

3.1 Arithmetic Operators

Public class HelloWorld {

Public static void main (String [] args ){

Int age1 = 24;

Int age2 = 18;

Int age3 = 36;

Int age4 = 27;

Int sum = age1 + age2 + age3 + age4;

Double avg = sum/4;

Int minus = age1-age2;

Int newAge = -- age1;

System. out. println ("Total Age:" + sum );

System. out. println ("Average age:" + avg );

System. out. println ("age difference:" + minus );

System. out. println ("age after auto-subtraction:" + newAge );

}}

Note:Differences between the two methods of self-increment and auto-SubtractionOkay.
3.2 comparison Operators

Public class HelloWorld {
Public static void main (String [] args ){
Int a = 16;
Double B = 9.5;
String str1 = "hello ";
String str2 = "imooc ";
System. out. println ("a equals B:" + (a = B ));
System. out. println ("a greater than B:" + (a> B ));
System. out. println ("a less than or equal to B:" + (a <= B ));
System. out. println ("str1 equals str2:" + (str1 = str2 ));
}
}

The output is

A is equal to B: falsea is greater than B: truea is less than or equal to B: falsestr1 is equal to str2: false


In short, return boolean, and = ......

3.3 conditional operators in Java

Conditional operators (? :) Is also called the "ternary operator ".

Syntax format:Boolean expression? Expression 1: expression 2

Operation Process: if the value of a Boolean expression isTrue, ReturnsExpression 1OtherwiseExpression 2Value

For example:

Because the value of expression 8> 5 is true, return:8> 5

Public class HelloWorld {
Public static void main (String [] args ){
Int score = 68;
String mark = (score> = 60 )? "Pass": "fail ";
System. out. println ("How is the test score:" + mark );
}
}

The rest are relatively basic and will not be detailed.

Remember one thing about priority: () the highest priority.

Ps: The result of the expression (11 + 3*8)/4% 3 is () -- 2

Iv. Loop

Master the following example

Public class HelloWorld {
Public static void main (String [] args ){

System. out. println ("print right triangle ");

// Number of rows in the outer loop
For (int I = 1; I <= 3; I ++ ){

// The number of * numbers in each row is cyclically controlled in the inner layer.
// The maximum value of the inner loop variable is equal to that of the outer loop variable.
For (int j = 1; j <= I; j ++ ){

System. out. print ("*");
}

// Line feed after each line is printed
System. out. println ();
}
}
}

Then we can determine the number of digits for the for statement.

Public class HelloWorld {

Public static void main (String [] args ){

Int num = 999;

Int count = 0;

For (int I = 0; I <10; I ++ ){

Int test = 10 ^ I;

If (num % test = 0 ){

Break;

}

Count = count + 1;

}

System. out. println ("it is the number of" + count + "bits! ");

}}

 

 

 

 

 

 

Related Article

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.