Re-learning Java-Basic Java programming structure (2)

Source: Internet
Author: User
Tags case statement

The previous section briefly reviewed some basic Java programming knowledge. This section will continue to review and explore this knowledge based on the book Java core technology.

1. String

The Java string is actuallyUnicode Character Sequence. For example, the string "Java \ u2122" consists of five Unicode characters J, a, v, a, and™. JavaNo built-inIn the standard Java class library.Every String enclosed in double quotation marks is an instance of the String class.. String operations are also one of the most important basic components in Java.

1.1 substrings

The substring method of the String class can extract a substring from a large String.

String greeting = "Hello"= greeting.substring(0, 3

The first parameter of the substring method isThinkThe first position of the copy, and the second parameter isNoThe first copy location. The substring method has an advantage that it is easy to calculate the length of the substring. The length of s. substring (a, B) is B-. For example, the length of the sub-string "El" is 3-0 = 3.

1.2 stitching

Like most programming languages, Java allows+Connects two strings. Between wordsNo space. When a string is concatenated with a non-string value, the latter is converted to a string.

 age = 13= "PG" + age; 
1.3 immutable string

The String class does not provide a method for modifying strings. If you want to change the greeting ("Hello") content to "Help! ", You cannot directly modify the last two positions. In Java, you must extract the required characters and splice them.

greeting = greeting.substring(0, 3) + "p!";

Because the characters in the Java string cannot be modifiedThe String class object becomes an immutable String.. "Hello" always contains the code unit sequences of characters H, e, l, l, and o, but cannot modify any of them. Of course, you can modifyString variableGreeting, let it referenceIn additionA string.

The Java compiler operates strings in a shared manner. As you can imagine, various strings are stored in the public storage pool, and string variables point to the corresponding location in the storage pool. If you copy a string variable, the original string shares the same character with the copied string.

Java designers think that the efficiency brought by sharing is better than the efficiency brought by string extraction and concatenation. In a program, there are few strings that need to be modified, but Strings need to be compared. (In an exception, a single character or short string originating from a file or keyboard needs to be integrated into a string, for this reason, Java provides a separate class ).

1.4 check whether the strings are equal

You can use the equals method to check whether two strings (string variables or string constants) are equal. If they are equal, true is returned. Otherwise, false is returned. Use the case-insensitive signorecase method to check whether the strings are equal.Must not use =Checks whether two strings are equal, because it can only determine whether the two strings are placed in the same position. If the JVM always shares the same string, you can use = to check whether the strings are equal. But actually onlyString constantIs shared, and the + or substring results are not shared. Therefore, do not use = for comparison.

1.5 code points and code units (not clear) 1.6 build strings

If you need to construct a string with many small strings, follow the steps below.

StringBuilder builder = String completedString = builder.toString();

The StringBuilder class is introduced in JDK5.0. The predecessor of this class isStringBuffer, The efficiency is somewhat low, but multi-thread execution is allowed. Use StringBuilder to operate strings in a single thread.

2. Input and Output 2.1 read input

As we know, printing to the "standard output stream" (that is, the console window) is a simple task. You only need to call System. out. println. However, reading System. in is not easy.

Scanner in = "What is your name?"= in.nextLine(); String firstName = in.next();  age = in.nextInt();  money = in.nextDouble(); 

Because the input is visible, the hosts class is not suitable for reading passwords from the console. Java SE 6 introduces the Console class to implement this function.

Console cons == cons.readLine("User name: "[] passwd = cons.readPassword("Password:  "); 
2.2 format the output

Use System. out. print (x) to print x to the console.Which of the following data types are allowed by x?The maximum number of non-0 digits is x. Java follows the printf method in the C language library function to modify and format the output.

 x = 10000.0 / 3.0"%8.2f", x); = "Jack" age = 18"Hello, %s. Next year, you'll be %d", name, age); 

In the code above, the first program prints8Characters in width and decimal pointTwoCharacterFloating Point TypeX; the first s of the second program represents a string, and d represents a decimal integer. In the printf sentence, the type after "%" is replaced with the type after "%. Therefore, the first % s is replaced by the name variable, and % d is replaced by age.

Conversion character Type For example   Conversion character Type For example
D Decimal integer 159   S String Hello
X Hexadecimal integer 9f   C Character H
O Octal integer 237   B Boolean True
F Fixed Point floating point number 15.9   H Hash code Listen 28b2
E Exponential floating point number 1.59e + 01   Tx Date and Time See the following table.
G General floating point number -   % Percent sign %
A Hexadecimal floating point number 0x1. fccdp3   N Platform-related line delimiters -

 

 

 

 

 

 

 

 

System.out.printf("%,.2f", 10000.0 / 3.0); 
Logo Object For example
+ Print the symbols of positive and negative numbers + 3333.33
Space Add a space before a positive number | 1, 3333.33 |
0 Add 0 before the number 003333.33
- Left aligned | 1, 3333.33 |
( Enclose Negative Numbers in parentheses (3333.33)
, Add group Separator 3,333.33
# (For f format) Contains decimal point 3,333
# (For x or 0 format) Add prefix 0x or 0 0 xcafe
$ Specify the formatted parameter index. For example, % 1 $ d, % 1 $ x will print 1st parameters in decimal and hexadecimal format 159 9F
< Format the preceding value. For example, % d % <x prints the same value in decimal and hexadecimal notation. 159 9F

 

 

 

 

 

 

 

 

 

 

 

 

 

The printf method can print the time format, starting with t, and ending with two letters in the table.

System.out.printf("%tc",  Date()); 
Conversion character Type For example
C Complete Date and Time Sunday, October 13, 13:31:11 CST 2013
F Date of IOS 8601 2013-09-22
D Date in the U.S. format (month/day/year) 09/22/13
T 24 hours 13:31:46
R 12 hours 01:31:56 pm
R 24 hours without seconds 13: 33
Y The year of the four digits (add 0 before) 2013
Y The last two digits of the year (the first digit is 0) 13
C Number of the first two years of the Year (add 0 before) 20
B Complete monthly spelling September)
B or h Abbreviation of month Sept)
M Month with two digits (0 in front) 09
D Day with two digits (0 in front) 22
E Day with two digits (not 0) 22
A Complete spelling of the day of the week Sunday)
A Abbreviation of day of the week Sunday (Sun)
J The day of a three-digit year (0 in front), between 001 and 366 265
H The hour with two digits (supplemented by 0 before), between 0 and 23 13
K Two-digit hour (not supplemented with 0), between 0 and 23 13
I The hour with two digits (supplemented by 0 before). The value ranges from 0 to 12. 01
L The hour with two digits (not 0 in front), between 0 and 12 1
M Minutes with two digits (0 in front) 37
S Second with two digits (add 0 before) 50
L The millisecond value of the three digits (the first digit is 0) 346
N The microseconds of the nine-digit number (the first digit is 0) 032000000
P Uppercase signs in the morning or afternoon PM
P Lowercase sign in the morning or afternoon Pm
Z RFC822 digital shift from GMT + 0800
Z Time Zone CST
S Number of seconds from 00:00:00 GMT 1379828369
Q Number of milliseconds since 00:00:00 GMT 1379828377563

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

System. out. printf ("% 1 $ s % 2 $ tB % 2 $ te, % 2 $ tY", "Due date:", Date ());

You can also choose to use the <flag, which indicates that the parameters in the preceding format description will be used again.

System. out. printf ("% s % tB % <te, % <tY", "Due date:", Date ());
2.3 input and output of Files
Scanner in =  Scanner( File("myfile.txt")); =  PrintWriter("myfile.txt"):  
3. 3.1 Scope of the control process

BlockIt refers to several Java statements enclosed by a pair of curly braces. The block determines the scope of the variable. A block can be nested in another block. However, the same variables cannot be declared in two nested blocks and cannot be compiled. But in C ++, the declared variables will overwrite the previous ones, but Java does not allow them, which may lead to program design errors.

3.2 condition statements

In Java, the condition statement format is if (condition) statement1 else statement2. Here, else is optional, and else and the nearest neighbor if constitute a group.

3.3 cycles

When the condition is true, the while loop is executed. If the start condition is false, it will not be executed once. The structure is: while (condition) statement. If you want to execute a loop at least once, you can use the do/while statement to perform this operation. The structure is do statement while (condition ).

3.4 definite cycle

It is the traditional for loop structure. Although Java allows any expressions to be placed inside the for loop, there is an unwritten rule that the three parts of the for statement should initialize the same counter variable, detection and update, otherwise it will be obscure. DetectionFloating Point NumberSometimes it is possible that the conditions cannot be accurately reached due to binary problems, and thus the failure fails.

3.5 multiple options: switch statement

When processing multiple options, using multiple if/else structures is a bit clumsy and unclear. You can use the switch statement to create such a structure.

 1 2 3

If no corresponding case statement exists, the default statement is executed. If the case statement does not have a break, the next case statement is executed directly.

3.6 interrupt control flow statement

In Java, although the goto statement is a reserved word, It is not functional. Java uses the break statement with labels to exit the loop.

 i = 1 ( (i == 100 read_data;  i++

Using break separately, you can jump out of the current block, and there is a continue, which breaks the normal cycle and transfers it to the header of the innermost loop. There is also a label-based continue, to the loop header that matches the tag.

4. Large Value

If the precision of the basic integer and floating-point numbers cannot meet the requirements, you can use two useful classes in the java. math package: BigInteger and BigDecimal. YesArbitrary LengthThe numerical value of the numerical sequence.

BigInteger a = BigInteger.valueOf(100); 

However, you cannot use familiar Arithmetic Operators to process large numbers. You need to use the methods of the object, such as add and multiply. Because JavaOperator overload not providedBut the Java designer isThe string connection is overloaded. +Operator.

lotteryOdds = lotteryOdds  * (n - i + 1) /lotteryOdds = lotteryOdds.multiply(BigInteger.valueOf(n - i + 1).divide(BigInteger.valueOf(i));
5. Array

An array is a data structure used to storeSame type valueThrough subscript, you can access each value in the array.

[] a; [] a =  [100]; 

The array subscript starts from 0. If 100 elements are created and a [100] is accessed, an exception is thrown (normally, only 0-99 can be accessed ). You can use arratName. length to obtain the array length.

5.1 For each loop

Java SE 5.0 adds this loop to process each element in the array in sequence (other types of element sets are also supported) without worrying about subscript. Format: for (variable: collection) statement. Defines a variable for saving each element in the set. The object to be operated must beArray or an object that implements the Iterable interface.

If you only want to print each value in the array, you can use the Arrays. toString (s) method to print.

5.2 array initialization and anonymous Array
[] smallPrimes = {1, 2, 3};  [] {1, 2, 3, 4}; 

In Java, the array length is allowed to be 0.

5.3 copy an array

In Java, an array variable can be copied to another array variable. This is, the two variables willReference the same Array. To copy all values of an array to a new array, use the copyOf method of Arrays. If the array is of the numeric type, the value of excess elements is 0, and the value of Boolean is false. If the length is smaller than the original length, only the first element is copied.

5.4 command line parameters

Each Java has its own main method of the String [] args parameter, indicating that the main receives the String array, that is, the command line parameter.

If java Message-g cruel world; args array is used, it will contain {"-g", "cruel", "world "}.

5.5 array sorting

You can use the sort method in the Arrays class to sort relative Arrays. This method usesQuick sortingAlgorithm.

5.6 multi-dimensional array

Multi-dimensional arrays use multiple tables to access the arrays. For example, double [] [] balances = new double [a] [B]; for each loops cannot automatically process two-dimensional arrays. They must use two nested loops. To quickly print a two-dimensional array, you can use: System. out. println (Arrays. deepToString ());

5.7 irregular Array

Java actually does not have multi-dimensional arrays, but only one-dimensional arrays. Multi-dimensional arrays are interpreted as "arrays". Therefore, each row is a separate array, which can be used to construct irregular 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.