Java Basic Knowledge Secondary Learning--chapter II Basic Grammar and recursive supplement

Source: Internet
Author: User
Tags logical operators switch case truncated

chapter II Basic Grammar and recursion supplement   Date: April 24, 2017 10:39:18 Chapters: 02 Chapters _01, 02 chapters _02 Festival Video Length: 49:21 + 15:45 content: Identifiers, keywords and data typesExperience: Composed of letters, underscores, $, numbers, should be preceded by letters, underscores $, and should avoid Java reserved characters

A variable is a small area in memory that uses the variable name to access the area

Memory management during execution ( question: Is the memory here the same as the JVM? The code segment stores the data segment static variable string constant stack stack local variable heap new out of the thing Order 1. Load to memory Area 2. Find the Main method to start executing Java variables including member variables and local variables local variables: variable member variables defined inside a method or statement block: External to the method, variables defined internally by the class previously understood as global variables (in fact, Java is an object-oriented language, and variables are hooked to objects, so only the member variables that belong to the object and the following local variables so there is no global variable)The classification of Java data types is divided into basic data types and reference data types basic data type numeric character type (char) Boolean type (Boolean) numeric type (byte,short,int,long) floating-point type (float,double) Reference data type class interface (interface) array Boolean type Boolean in Java allows only true or false, not 0 or 0 (this differs from the C language) Char type Java characters are Unicode encoded, each character is two characters, so it can be represented by a 16 binary encoding, and the default is to take the ' \ ' as an escape character in Utf-16java. <java Core Technology volume 1> supplement:\u0000 to \uffff Unicode encoding units can be represented as 16 binary values include special escape characters in Java, char type describes a unit of code with UTF-16 encoding starting from JDK5.0 A code point refers to a character in an encoded table that corresponds to the code value of the first level code for the basic multi-language level, from u+0000 to u+ffff including the classic Unicode code the remaining 16 levels of code points from u+10000 to U+10FFFF, including some auxiliary characters Integer type (byte,short,int,long)
Type Occupy Storage space Table Count Range
Byte 1 bytes -2 of 7 square to 2 7 square-1
Short 2 bytes Ibid., and number of digits related
Int 4 bytes Ibid., and number of digits related
Long 8 bytes Ibid., and number of digits related
In Java there is no unsigned integer, all the numbers are signed, so the number of bits to be taken out alone to make a symbol so, for example, byte,1 bytes, 8 bits is 2 7 to +2 7 square-1 (because there is a 0, So to-1) Java each integer type and fixed number of table range and field length, not affected by the specific operating system, to ensure the portability of Java programs The Java language's shaping constants default to int type declaration long type constant can be added "L" or "L" generally l because lowercase l looks like 1 Floating-point type (float,double) in Java floating-point type generally two representations 1. Decimal, such as 3.14 314.0.3142. Scientific notation such as 3.14e2 3.14E2 default to double type if you want to declare a float type, To add F For example float =12.3 This is wrong because double float belongs to large turn small cannot be cast need to declare is F float=12.3f For example float 4 bytes Double 8 bytes Float precision is 7 bits, Double precision is 15 bits Date: April 24, 2017 13:33:06 Chapters: Chapter 02 _03 Festival Chapter 02 _04 Festival Video Length: 20:00 + content: Identifier keywords and data typesExperience: Boolean: Unlike C + +, the Boolean type in Java can be converted to other types of char: When a character type is used, a type with a small size of ASC encoding is automatically converted to a large data type (rather than a byte length) from small to large in order to: Byte, Short,char-->int-->long-->float-->double where Byte,short,char Three do not convert to each other, they will first convert int type int into byte,short, Char, if no more than their range is able to turn directly if it exceeds the need to cast and will be truncated <java Core Technology volume 1> supplement:

, a solid arrow represents a loss-free conversion, a virtual arrow indicates that there may be a loss of conversion, such as the 123456789 conversion of int to float type, the number of bits is more than the number of bits that float can express, so the size is the same after the conversion, but the loss of a certain precision big turn small, To join the cast, but may result in the reduction or overflow of precision, when using the need to pay extra attention to a variety of data types for mixing operations, the system first automatically convert all data to the largest capacity of the data type, and then calculate the real number constants default to double integer constant default to int Example int to byte when 4 bytes to 1 bytes, the preceding 3 bytes directly truncated, the remaining bytes are a few double float floating point number in the computer in a special form, the middle of a decimal point to calculate the decimal point after a few So you can't just truncate beyond the range. Display Infinity Decimal type conversion to an integer, such as float converted to long, will force discarding the fractional part (not rounding) Date: April 24, 2017 14:31:15 Chapters: Chapter 02, section _05 Video Length: 13:27 content: Program formatNote: Roughly is the specification of some program format 1. Brace Alignment 2. The Brace indentation 3 is encountered. Method and method, add a blank line between the program blocks 4. Add a space between the statements by 5. The operator adds a space int i = 8 and (except for special cases) 6. {Preceded by a space 7. A pair of programming purposes is: let others see more clearly, let others see more comfortable   Date: April 24, 2017 14:42:54 Chapters: Chapter 02, section _06 Video Length: 20:42 Content: OperatorsExperience:

self-increment operatori++, the first value and then the Operation ++i, the first operation and then the value (generally not recommended--<java Core Base volume 1>) logical Operators& and | Or! Non-^ xor or dissimilarity is true, different for true&& and | | If the front conditions are set, the back will not be shipped. Assignment OperatorsIf the data types on both sides of the "=" are inconsistent, you can apply the default type conversions or apply the coercion type conversion principle. Note: You can directly assign the shape constants directly to types such as Byte,short,char, without forcing type conversions, as long as the range of tables is not exceeded +=,-=,*=,/ =,%= String Connectorint id = 800 + 90; string s = "Hello" + "world"; note: only one of the operands on either side of the "+" operator is a string (string) type, and the system automatically converts the other operand to a string and then connects when the SYSTEM.OUT.PRINTLN When the statement is printed, it is automatically converted to a string for printing int c = 12, regardless of any type; System.out.println (c); The interior will first convert 12 to a string and then print out An expressionThe expression is the type of the sequence expression value of the operator and operand that conforms to a certain syntax rule the type of expression is the operation order of the expression from high to low (known as the main), generally less certain operations plus () can

Three mesh operatorX? Y:z recalled that there was a question about the three-mesh operation of the El expression ${(Requestscope.userid > 5)? "Greater than 5": "Less than 5"} Multilevel Trinocular operator, from inside to outside calculation Date: April 24, 2017 15:07:53 Chapters: Chapter 02, section _07 Chapter 02 _08 Festival Chapter 02 _09 Festival Video Length: 20:01 5:00pm content: If branch and for Loop job Section Job Section SupplementExperience: If statementIf Else,else if,...... There is only one sentence that needs to be executed, you can omit {} (but personally think it's best not to omit it, easy to structure) Looping Statements For Loop (i=0;i>5;i++) {}The first one is initialization, the second is the judging condition, and the third is the judgment after the execution of the statement, where I is scoped to the Foreach Loop after JDK 1.5 in the For loop, which iterates through the collection or array, for example: for (Student s:studentlist <Student>) {System.out.println (S.getstudentname ())}

public static void Main (string[] args) {
int result=0;
for (int i = 0; i <; i + = 2) {
result + = i;
}
SYSTEM.OUT.PRINTLN ("The result is" +result);} Date: April 24, 2017 15:37:05 Chapters: Chapter 02, section _10 Video Length: 11:42 5:55 content: Whlie & Do While statements break& continue statements and some examplesExperience: While first to judge the execution of Do-while first execution and then judge the break statement is used to terminate the execution of a block of statements, you can forcibly jump out of the loop to terminate this round of loop error instance: if (i = = stop); In a sense, it can actually be understood to be an empty statement. if (i = = stop) {;} Break, so when using break or continue loop, do not add a semicolon after the if (), or the code is much less likely to discharge this error continue statement is used to terminate this cycle remember seeing a problem before how to jump out of multiple loops at once? Just vaguely remember that you can jump to a mark with break For example, you can jump to OKOk:while () {for () {-() {Break OK;}}} example for (int i = 1; I <= 5; i++) {//When I equals skip, skips the secondary loop if (i = = Ski     p) Continue; System.out.println ("i =" + i);} Two examples 1. The top 5 of the output 1~100 can be divisible by 3. The idea is to traverse 1-100 each plus 1, to find a number num on +1,num==5 when the break jumps out of public static void main (string[] args) {int num = 0;//used to calculate the number found Syst    Em.out.println ("The first 5 numbers divisible by 3 1~100");            for (int i = 1; i < i++) {if (i% 3 = = 0) {System.out.print (i+ "");        num++;        } if (num = = 5) {break; }    }}

 2. The idea of prime numbers in the output 101~200 is first of all the number of prime numbers that are divisible by only 1 and themselves   so all the even numbers are not prime so you can reduce the number of iterations by half the first is to cycle through all the odd-numbered in the 101~200 for each of these odd, Will each be less than his number to him, if the remainder is 0, then the representative can be divisible, meaning that the number is not prime, jump out of the number of factors to look for the loop, and mark the number as non-prime (define a Boolean) if all the remainder is not 0, then it means that the entire number is prime, then print out    /*** 2. Output 101~200 within the prime number */public static void Problem2 () {    Boolean flag = true;    for (int i = 10 1; I <= 200; i + = 2) {        flag = true;//The following is the factor search loop, which goes into the if condition to find the factor, also                 means this is not a prime number         for (int j = 2; J < I; j + +) {          &N Bsp if (i% j = 0) {                flag = false;          & nbsp     break;           }       }        IF (flag) {            SYSTEM.OUT.PRINTLN ("Find a prime number, this prime number is" + i);       }  &nbs P }}

Originally this is written, only the red, and later found that as long as a prime number after a Boolean did not reset, and then added a blue reset, and later found that since this Boolean type value is only used in the loop, why I do not directly defined in the loop, anyway, is a local variable, used to complete automatic recovery. /*** 2. Output 101~200 within the prime number */public static void Problem2 () {for (int i = 101; I <=; i + = 2) {Boolean flag = TR        Ue                The following is the factor search loop, which goes into the if condition to find the factor, also means that this is not a prime number for (int j = 2; J < I; J + +) {if (i% J = = 0) {                Flag = false;            Break        }} if (flag) {System.out.println ("Find a prime number, this prime number is" + i); }    }}

Date: April 24, 2017 16:35:47 Chapters: Chapter 02 _12 Video Length: 09:03 content: Related use of switch statementsExperience: switch (i) {case 1:system.out.println ("1"); Break;case ......} A switch (expression) expression can only be an int or a data type of equivalent int (byte,short,char,int) (before JDK 1.6 (including 1.6)) Note: (Since the video tutorial version is 1.5, the fact that java1.7 started to support the string string in the switch expression)For example: Output "My name is Little red" String name = "Little Red"; switch (name) {case "Little Red": System.out.println ("My name is" + name); break;} And, when using the switch case, pay attention to the break, otherwise it will be executed until the next break; just jump out, this error compiler does not complain and multiple case statements can be combined such as the case "Little Red": "Case" small green: Syst     EM.OUT.PRINTLN (123); Break     Default can be omitted, but it is not recommended to omit, so that the program is more robust default:xxxx; Break Date: April 24, 2017 16:52:11 Chapters: Chapter 02 _13 Video Length: 20:08 content: Java methodsExperience: This is actually a Java package, I want what, the program will give me what, do not need to let the user care how to do it for example: you give me money, I give you rice, do not need to let customers care about how the meal is made out of (money is the parameter, rice is the return value, this method is called to buy rice in At the level of code can reduce the use of repetitive code, forget who said, writing code is best not to have any line of duplicate code, although the actual situation is difficult to do, but to try to this aspect of the function call in Java to pass parameters, follow the principle of value passing: The basic type is passed the data value itself. A reference type passes a reference to an object, not the object itself. A good question and explanation about this value pass. The question is: Why is the string class designed to be final? Answer in a separate note sheet.     Date: April 24, 2017 17:03:32 Chapters: 02 Chapters _ Recursion Supplement Video Length: 4:17+8:52+6:15+1:43+10:18+2:30 Content: Introduction and explanation of recursionExperience: public static void Main (string[] args) {System.out.println (Method (4))}, public static int method (int n) {if (n    = = 1) {return 1; } else return n * method (n-1);}

It is important to note that a method will return only if the operation is finished.then for recursion, it can be understood as multiple calls to itself, multi-layered nesting, until all methods run to the endas the above exampleMethod (4)--Return 4*method (3)--Return 4*3*method (2) and so on: Fibonacci sequence 1,1,2,3,5,8,.... 40 is the nth number of the N-1 and the number of N-2 and, (1th and 2nd numbers are 1) recursion is one of the solutions.//The method enters the number of Fibonacci numbers, returns the value of the change number public static int f (int n) {if (n = = 1 | | n = = 2) {return 1; //The first number and the second number are 1}else{return (f (n-1) + f (n-2)); //Otherwise it is the first 2 numbers and}} Classroom exercises: The first response to this problem is to use a loop to construct a sequence of this type, try public static int x (int n) {int[] array = new Int[n]; //For the values in the array in order to assign a value, first construct the series, and then return the corresponding valuefor (int i = 0; I <array.length; i++) {if (i = = 0 | | i = = 1) {Array[i] = 1;        }else {Array[i] = Array[i-1] + array[i-2]; }} return array[n-1];}

Another workaround: Use the For loop to construct 3 numbers directly, that is, the number that the user needs to return, and the first 2 digits of the entire count, after all, any value in the Fibonacci sequence is only linked to his top 2 numbers, so you can just keep updating the 3 numbers.     /** * Another way of thinking, the direct use of circular construction, but also the video teacher's solution * @param index * @return */public static long F2 (int index) {//1th and 2nd are 1 if (index = = 1 | | Index ==2) {return 1; } //Starting from the 3rd number of constructs, the default 1th number F1 is 1, the second number F2 is also 1 //f is the final number to be output.Long f1 = 1L;    Long F2 = 1L; Long f = 0; //Because it starts with the 3rd, so the number of constructs is 2 (minus the 1th and 2nd numbers, the default value has been given)for (int i = 0; I <index-2; i++) {f = f1 + f2;//f is the first 2 numbers and f1=f2;//updates the F1,F2, because F1,F2 refers to the top 2 numbers of the number of F users want, so according to    The situation of cyclic structure should be updated continuously f2=f; } return F;

Chapter II End time: April 24, 2017 17:49:13Summary, easy to use when reviewing

Java Basic Knowledge Secondary Learning--chapter II Basic Grammar and recursive supplement

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.