30 FAQs for beginners of Java and FAQs for beginners of java
This article answers 30 common questions for beginners of Java beginners. Can I use % to divide it by a decimal number? Is the effect of a + = B different from that of a + B? Why does it take a lot of time to declare an array? Why does the JAVA library not need to be quickly sorted by random sort?
1.2 Basic Data Types
Q. Why is the result of-0/3 0 and-0.0/3.0-0.0? (Note that the result 0 is followed by a negative number)
A. in Java, integers are represented by supplementary codes. In the complement code, 0 has only one representation method. On the other hand, floating point numbers are represented in the IEEE Standard. For 0, there are two Representation Methods: 0 and-0.
Q. Can I use % to divide it by a decimal number?
A. Of course. For example, ifAngleIs a non-negative number, thenAngle % (2 * Math. PI)The angle is converted to 0 to 2 π.
Q. When a B is a basic type variable,A + = BAndIs the effect of a = a + B different?
A. When the types of a and B are different, the effects of the two statements may be different.A + = BEquivalentA = (int) (a + B). In this case, a can be int type and B can be float type.But under the same circumstancesA = a + BAn error will be reported during compilation.
1.3 conditional and cyclic statements
Q. Why can't I use the same string?=?
A. This reflects the basic type (Int,Double,Boolean) And the reference type (String.
Q. Is there any situation where the curly braces of a statement block cannot be omitted?
A. In the following example, the first part of the code is valid, and the second part of the code will cause A compilation error. Technically speaking, the statement is a variable declaration, not a statement, so an error is reported.
// legalfor (int i = 0; i <= N; i++) { int x = 5;}// illegalfor (int i = 0; i <= N; i++) int x = 5;
Q. Are there any situations in the following two sections of code that have different effects?
for (<init stmnt> <boolean expr>; <incr stmnt>) { <body statements>}<init stmnt>;while (<boolean expr>) { <body statements> <incr stmnt>}
A. Yes. If you use the continue statement in the loop block. In the for code, the counter will add one. In the while code, because the while code is skipped by the continue, the counter does not add one.
Array 1.4
Q. Some Java developers useInt a []InsteadInt []Declare an array. What is the difference between the two?
A. in Java, these two usage methods are both legal, and their functions are the same. The former is the method for defining arrays in C. The latter is the method recommended by JAVA, because its writing method int [] can better indicate that this is an array of int.
Q. Why does the array subscript start from 0 instead of 1?
A. This traditional programming method originated from machine language. In machine language, the array subscript is used to calculate the offset between the element position and the first element. If the offset is calculated from 1, a subtraction operation is required, which is a waste.
Q. What will happen if I use a negative number as the array subscript?
A. When the subscript is smaller than 0 or greater than or equal to the array length, JAVA will throwArrayIndexOutOfBoundsExceptionException, and stop running the program.
Q. Are there any other traps to be aware of when using arrays?
A. Remember that JAVA initializes an array when you create it, so it takes O (N) Time to declare an array.
Q. SinceA []Is an array, why?System. out. println ()A hexadecimal number is printed, just like@ F62373, instead of printing the elements of the array?
A. Good question. This statement prints the address of the array in the memory. Unfortunately, in most cases, this is not what you need.
1.5 Input and Output statements
Q. Can I re-read the data from the standard input?
A. No. You can only read it once.
Q. How do I enter the end-of-file (eof) symbol?
A. The operating system automatically includes it.
Q. UseWhat are the usage of printf?
A. For integers, useOOutput gossip, useXThe output hexadecimal format. For floating point numbersEOrGOutput scientific notation form.
Q. What is the end symbol of a row?
A. Different file systems use different symbols. On Unix systems, the symbol of a new line is'\ N'; inOn Windows, each line ends with a string consisting of two characters."\ R \ n"; inOn Macs, The Terminator is"\ N \ r ". To print the row number, you can use System. out. println ()Or use the following statement to get the row terminator of the current operating system:
String NEWLINE = System.getProperty("line.separator"); |
Q. Which of the following two statements is more efficient?
String s; while (!StdIn.isEmpty()) { while (!StdIn.isEmpty()) { s = StdIn.readString(); String s = StdIn.readString(); ... ...} } |
A. There is no difference between the two in terms of efficiency. But the second method is better, because it limits the scope of the variable.
2.1 function call
Q. I am often confused when I use arrays as parameters for function calls?
A. Yes. Remember the difference between passing value parameters (the parameter is the basic variable type) and passing reference parameters (such as arrays.
Q. Why don't we use the value-passing method for all parameters, including treating arrays?
A. However, when an array is large, copying an array requires A lot of performance overhead. For this reason, the vast majority of languages support the input of arrays into functions, except for the MATLAB language, which does not copy a copy.
2.3 recursive call
Q. Can I use loops instead of recursion?
A. No. All loops can be replaced by recursion, although in most cases, recursion requires additional memory.
Q. Can I only use recursion instead of loops?
A. No. All recursive calls can be expressed in A loop. For example, you can use the while method to implement the stack.
Q. Which method should I choose, recursive or loop?
A. weigh between the readability and efficiency of the Code.
Q. I am worried about the space overhead and repeated computing when using recursive Code (for example, using recursion to solve Fibonacci. Are there other concerns?
A. when creating a big data type (such as an array) in recursive code, you need to note that as recursion advances, memory usage will increase rapidly. As memory usage increases, the time overhead for operating system memory management will also increase.
4.2 sorting and searching
Q. Why should we spend a lot of time proving that a program is correct?
A. To prevent incorrect results. Binary Search is an example. Now that you understand the principle of binary search, you can rewrite binary search in recursive form to binary search in a circular form. Professor Knuth published a binary search paper in 1946, but the first correct binary search program appeared in 1962.
Q. Are there any sorting and searching functions in the JAVA library?
A. Yes. InJava. util. ArraysContainsArrays. sort ()AndArrays. binarySearch ()Method. ForFor the Comparable type, it uses Merge Sorting, and for the basic data type, it uses quick sorting. Because the basic type is value transfer, fast sorting is faster than Merge Sorting, and no additional space is required.
Q. Why does the JAVA library not need to be quickly sorted by random sort?
A. Good question. Some programmers may need deterministic code implementation when debugging code. Using Random distinct violates this principle.
4.3 stack and queue
Q. Are there implementations of stacks and queues in the Java library?
A. built-in Java LibraryJava. util. Stack, but you should avoid using it if you need a real Stack. Because it implements additional functions, such as accessing the nth element. In addition, it also supports inserting elements from the bottom of the stack, so it looks more like a queue. Although implementing these additional features is a plus for programmers, we use the data structure not just to use all the features, but the structure we just need. JAVA stack implementation is a typical wide interface Example.
Q. I want to use arrays to indicate a stack containing generics, but the following code compilation reports an error. Why?
private Item[] a = new Item[max]; oldfirst = first; |
A. A good attempt. Unfortunately, creating a generic array is not supported in Java 1.5. You can use cast, as shown in the following code:
private Item[] a = (Item[]) new Object[max]; oldfirst = first; |
The root cause is that arrays in JAVA are covariant, But generics are not. For example,String []YesA seed type of Object [],Stack <String>NotA seed type of Stack <Object>.Many Programmers think that the "covariant" array is a disadvantage of JAVA in terms of data types. However, if we do not consider generics, the "covariant" array is useful, such as implementationArrays. sort (Comparable [])Method, and then when the parameter isString [] can also be called normally.
Q. Can I use the foreach Method on an array?
A. Yes (although the array is not implementedIteratorInterface ). See the following code:
public static void main(String[] args) { for (String s : args) StdOut.println(s);} |
Q. Is using iterator on the linked list more efficient than loop or recursion?
A. During translation, the compiler may translate the form of "tail recursion" into an equivalent loop form. Therefore, the performance may not be improved.
Tail recursion is a programming technique. In a recursive function, the result returned by a recursive call is always directly returned, which is called tail recursion. Tail recursion is extremely important, and does not require tail recursion. The Stack Consumption of functions is immeasurable and the stacks of many intermediate functions need to be saved. For example, f (n, sum) = f (n-1) + value (n) + sum; stores n function call stacks, and uses tail recursion f (n, sum) = f (n-1, sum + value (n); in this way, only the last function stack is retained, and the previous optimization can be deleted.
Q. What can I do with the automatic packing mechanism?
Integer a = null;int b = a; |
A. It returns A runtime error. The base type does not allow the value of its corresponding packing type to be null.
Q. Why is the first group printed?TrueBut the following two groups printFalse?
Integer a1 = 100;Integer a2 = 100;System.out.println(a1 == a2); // trueInteger b1 = new Integer(100);Integer b2 = new Integer(100);System.out.println(b1 == b2); // falseInteger c1 = 150;Integer c2 = 150;System.out.println(c1 == c2); // false |
A. The second group of code printingFalseBecauseB1AndB2Point to different Integer object references. The first and third groups depend on the automatic packing mechanism. The surprising first group prints true because the values between-128 and 127 are automatically converted to the same immutable type.IntegerObject. For the number that exceeds that range, Java creates a new Integer object for each number.
Notes for learning Java !!!
If you have any questions or want to obtain learning resources during the learning process, join the Java learning exchange group: 159610322 let's learn Java together!