30 FAQs for beginners of JAVA

Source: Internet
Author: User
Tags comparable

This article is translated from 《Introduction to Programming in JavaQ & A in some chapters of this book. Original address http://introcs.cs.princeton.edu/java/home/

 

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-0/3 result 0, and-0.0/3.0 result-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 a and B are of different types, 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 code is valid, and the second code may 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.In the following two sections of code, is there any situation where they 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, both of these are valid and have the same role. 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 happens 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.From the perspective of efficiency, there is no difference between the two. 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.So why not use the value-passing method for all parameters, including the treatment of 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.Is it possible to use loops instead of recursion?

A.Impossible. All loops can be replaced by recursion, although in most cases, recursion requires additional memory.

Q.Can we 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 one should I choose? Is the recursive or loop method?

A.Weigh between code readability and efficiency.

Q.I am worried about the space overhead and repeated computing when using recursive Code (for example, using recursion to solve the problem of 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 do we need to 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.Is there any implementation 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 error is returned. 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 the array in JAVA is "covariant (Covariant )",However, 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 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 recursionIt 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.How does the automatic packing mechanism handle the following situations?

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 printedTrueBut 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.Second set 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.

 

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.