Java Interview Bible answer detailed and sentiment (first day)

Source: Internet
Author: User

First, the Java Foundation part

The order of the underlying parts: basic syntax, class-related syntax, internal class syntax, inheritance-related syntax, exception syntax, thread syntax, collection syntax, IO syntax, virtual machine aspect syntax.

 1. Can I include more than one class (not an inner class) in a ". Java" source file? What are the restrictions?

Answer: There can be multiple classes, but only one public class, and the class name of public must match the file name.

  2. Is there a goto in Java?

Answer: reserved words in Java are not currently used in Java .

Parsing: The goto statement is also known as an unconditional transfer statement, which is generally formatted as follows: A goto statement designator, where the statement designator is a symbol written by an identifier, placed before a line of a statement, followed by a colon (:). The statement label acts as an identity statement and is used in conjunction with a goto statement.

3, talk about the difference between & and && .

 Answer:&and the&&can be used as the logical AND operator, representing the logical and ( and), when the result of an expression on either side of the operator istrue, the result of the entire operation istrue, otherwise, as long as one party isfalse, the result isfalse. &&also features a short circuit, i.e. if the first expression isfalse, the second expression is no longer evaluated, for example, for aif (str! = null&&!str.equals (""))expression, whenStrto beNULL, the subsequent expression does not execute, so it does not appearNullPointerExceptionif the&&instead&, you will throwNullPointerExceptionexception. If (x==33 &++y>0) ywill grow,If (x==33 && ++y>0)does not grow&can also be used as a bitwise operator when&an expression on either side of the operator is notBooleantype,&represents bitwise and operations, which we typically use0x0fto do with an integer&operation to get the minimum of the integer4abitbits, for example,0x31 & 0x0fThe result is0x01.

Analysis: A, &:and and B, && short circuit with; C, |:or or; D, | | : Short circuit or; This problem first says the similarities between the two, and the special points of && and & , and lists some classic examples to show that they understand thoroughly, practical experience.

Bitwise -and operation:

For example: 1010 0011
& 0000 1111
------------------------
0000 0011
That is, with the 0 equivalent to the number of 0, and 1 is equivalent to the retention of the position

  4. How do I jump out of the current multiple nesting loops in JAVA?

  Answer: In Java, to jump out of multiple loops, you can define a label in front of the outer loop statement, and then use a labeled break statement in the code of the inner loop body to jump out of the outer loop. For example

Ok:

for (int i=0;i<10;i++) {

for (int j=0;j<10;j++) {

System.out.println ("i=" + i + ", j=" + j);

if (j = = 5) break OK;

}

}
In addition, I personally do not usually use the label this way, but let the outer loop condition expression results can be controlled by the inner Loop body code, for example, to find a number in a two-dimensional array.

int arr[][] ={{1,2,3},{4,5,6,7},{9}};

Boolean found = false;

for (int i=0;i<arr.length&&!found;i++) {

for (int j=0;j<arr[i].length;j++) {

System.out.println ("i=" + i + ", j=" + j);

if (Arr[i][j] ==5) {

Found = true;

Break }    } }

5. Can the switch statement function on a byte, can it function on a long String?

Answer: in Switch (EXPR1), EXPR1 can only be an integer expression or enumeration constant (larger font), an integer expression can be an int primitive type or an integer wrapper type, because, Byte,short , char can be implicitly converted to int, so these types, as well as the wrapper types of these types, are also possible. Obviously, long and String types do not conform to the syntax of switch, and cannot be implicitly converted to int types, so they cannot be used in Swtich statements.

Parsing: Note that the selection value in a switch statement can only be a character or a constant.

 6, short S1 = 1; S1 = s1 + 1; what's wrong? Short S1 = 1; S1 + = 1; what's wrong?

Answer: for short S1 = 1; S1 = s1 + 1; Because the type of the expression is automatically promoted by the s1+1 operation, the result is of type int, and when assigned to the short type S1, the compiler reports an error that requires a cast type.

for short S1 = 1; S1 + = 1; since + = is a Java-language-defined operator, the Java compiler will treat it specially, so it compiles correctly.

Parsing: Basic Data type: Long (Long integer) size 64 bit, int (integer) size 32 bit, short (shorter integer) size 16 bit, byte (bit) size 8 bit, char (character) size 2 bit, float (single precision) size 32 bit ; double (double) size 64 bits; Boolean type Boolean;

7. Can I store a Chinese character in char type?

Answer: Char type variable is used to store Unicode encoded characters, Unicode encoding character set contains Chinese characters, so, of course, char variable can store Chinese characters. However, if a particular Chinese character is not included in the Unicode encoding character set, then this char variable cannot store this particular character.

Supplemental Note: Unicode encoding consumes two bytes, so variables of type char are also two bytes.

Note: The latter part of the answer, although not in the positive answer, but, in order to show their knowledge and performance of their own understanding of the depth of the problem, can answer some relevant knowledge, do sparing, liker.

  8, the most efficient way to calculate 2 times 8 is equal to a few?

Answer: 2 << 3, because moving a number to the left n bit, is equivalent to multiplying by 2 of the N-square, then, a number multiplied by 8 to move it to the left 3 bits, and the bit operation CPU directly supported, the most efficient, so, 2 times 8 and the most efficient method is 2 << 3.
Parsing: Left shift << and right shift >> are available in Java. The left-shift operation is to move the binary code of the operand to the left of the specified number of digits, and the empty space after the left is filled with zeros.

9, please design a 10 billion of the calculator

Answer: First of all to understand the topic of the test point is what, first of all, we have to understand the basic principles of the computer, to know the principle of the bit operation and know that the arithmetic operations in the computer will be out of bounds, the second is to have a certain object-oriented design ideas.

First, the computer in a fixed number of bytes to store the numeric value, so the computer can be represented by a certain range of values, in order to facilitate interpretation and understanding, we first use a byte type integer as an example, it is stored with 1 bytes, representing the maximum value range of 128 to +127. 1 the corresponding binary data in memory is 11111111, if two-1 add, do not consider the Java operation when the type promotion, the operation will produce a carry, the binary result is 1, 11111110, because the carry after more than the byte type of storage space, so the carry part is discarded, That is, the final result is 11111110, that is, 2, which is exactly the way of using overflow to achieve the operation of negative numbers. 128 the corresponding binary data in memory is 10000000, if two-128 add, do not consider the Java operation when the type promotion, the operation will produce a carry, the binary result is 1, 00000000, because the carry after more than the byte type of storage space, so the carry part is discarded, That is, the final result is 00000000, that is, 0, the result is obviously not what we expected, this shows that the arithmetic operation in the computer will be out of bounds, the results of two can not exceed the numerical range of the type in the computer. Since the types in Java that are involved in expression arithmetic are automatically promoted, we cannot use the byte type to do experiments that demonstrate this problem and phenomenon, and you can use the following example program to experiment with integers:
int a = Integer.max_value;

int b = Integer.max_value;

int sum = a + b;

System.out.println ("a=" +a+ ", b=" +b+ ", sum=" +sum ");

Regardless of the long type, since int has a positive range of 2 to 31, the maximum value represented is approximately equal to 2*1000*1000*1000, which is the size of 2 billion, so to implement a 10 billion calculator, we have to design a class that can be used to represent a large number of integers, and provides the function of subtraction with another integer, the approximate function is as follows:

(1) There are two member variables within this class, one representing the symbol and the other using a byte array to represent the binary number of the value

(2) There is a construction method that converts a string containing a multi-digit value into an internal symbol and byte array

(3) Provide the function of subtraction

public class biginteger{

int sign;

Byte[] Val;

Public Biginteger (String val) {

sign =;

val =;

}

Public BigInteger Add (BigInteger other) {

}

Public BigInteger Subtract (BigInteger other) {

}

Public BigInteger Multiply (BigInteger other) {

}

Public BigInteger Divide (BigInteger other) {

}

}

Note: To write this class of complete code, is very complex, if interested, you can see the JDK in the Java.math.BigInteger class source. The interviewer also knows no one can write this kind of complete code in a short time, he wants to be you have this aspect of concept and consciousness, his most important is to examine your ability, so, you do not because you cannot write the complete final result to give up this problem, you have to do is you write more than others, Prove that you are stronger than others, you have this aspect of the ideological consciousness can be, after all, others may even the meaning of the topic do not understand, what has not written, you have to dare to answer this question, even if only a part, that also with those who do not understand the difference out of the person, opened the distance, is the dwarf in the tall, In addition, the framework code in the answer is also very important, embodies a number of object-oriented design skills, especially the method named very professional, with the English word is very accurate, this is the ability, experience, professionalism, English level and other aspects of the embodiment, will give people a good impression, In the case of programming ability and other conditions, English is good except for you to get more opportunities, salary can be 1000 yuan higher.

  10. When a variable is decorated with the final keyword, is the reference immutable or does the referenced object not change?

 Answer: When you use the final keyword to decorate a variable, it means that the reference variable cannot be changed, and the contents of the object to which the reference variable is pointing can be changed. For example, for the following statement:

Final StringBuffer a=new StringBuffer ("immutable");

Executing the following statement will report a compile-time error:

A=new StringBuffer ("");

However, the following statements can be executed by compiling:

A.append ("broken!");

When someone defines a method's parameters, you might want to block the method from modifying the passed-in Parameter object in the following form:

public void method (final stringbuffer param) {}

In fact, this cannot be done, and the following code can still be added inside the method to modify the Parameter object:

Param.append ("a");

  11. What is the difference between "= =" and Equals method?

  Answer: (Make a single thing clear, and then another, so that their differences naturally come out, mixed together to say, it is difficult to understand)

The = = operator is specifically used to compare the values of two variables, that is, whether the value stored in the memory used to compare the variables is the same, to compare two basic types of data or two reference variables equal, only with the = = operator.

If the data that a variable points to is an object type, then this time involves two blocks of memory, the object itself occupies a chunk of memory (heap memory), and the variable occupies a chunk of memory, such as Objet obj = new Object (); the variable obj is a memory, and new object () is another memory, At this point, the value stored in the memory of the variable obj corresponds to the first address of the memory that the object occupies. For variables that point to the object type, if you want to compare whether the two variables point to the same object, that is, to see if the values in memory for the two variables are equal, then you need to compare them with the = = operator.

The Equals method is used to compare the contents of two separate objects, as compared to two people whose looks are the same, compared to the two objects that are independent of each other. For example, for the following code:

String A=new string ("foo");

String B=new string ("foo");

Two new statements create two objects, and then use a/b to point to one of the objects, which is two different objects, their first address is different, that is, the values stored in a and B are not the same, so the expression a==b will return false, and the contents of the two objects are the same. Therefore, the expression a.equals (b) returns True.

In real-world development, we often have to compare whether the string content passed in is, for example, string input = ...; Input.equals ("Quit"), many people do not pay attention to use = = to compare, this is wrong, casually from the Internet to find a few project real-life teaching video to see, there are a lot of such errors. Remember that the comparison of strings is basically using the Equals method.

If a class does not define its own Equals method, it inherits the Equals method of the object class, and the implementation code for the Equals method of the object class is as follows:

Boolean equals (Object o) {

return this==o;

}

This means that if a class does not define its own Equals method, its default Equals method (inherited from the object class) is using the = = operator, and whether the object pointed to by the two variables is the same object, using equals and using = = will get the same result. If the comparison is two independent objects, the total return is false. If you are writing a class that wants to compare the contents of the two instance objects created by the class, then you must override the Equals method, and write your own code to determine at what time that the contents of the two objects are the same.

  12. The difference between a static variable and an instance variable

  Answer: The syntax definition is the difference: static variables to add the static keyword before the instance variable is not added.

The difference when the program runs: instance variables belong to an object's properties, and an instance object must be created where the instance variable is allocated space before the instance variable can be used. Static variables are not part of an instance object, but belong to a class, so also known as class variables, as long as the program loads the class's bytecode, without creating any instance objects, static variables will be allocated space, static variables can be used. In summary, an instance variable must be created before it can be used by the object, and a static variable can be referenced directly using the class name.
For example, for the following program, no matter how many instance objects are created, only one Staticvar variable is always assigned, and each instance object is created, the Staticvar adds 1; However, each instance object is created with a instancevar, which may be assigned multiple Instancevar, and the value of each instancevar is only added 1 times.

public class varianttest{

public static int staticvar = 0;

public int instancevar = 0;

Public Varianttest () {

staticvar++;

instancevar++;

System.out.println ("staticvar=" + Staticvar + ", instancevar=" + Instancevar);

} }

Note: This solution in addition to clear the difference between the two, and finally with a specific application examples to illustrate the difference between the two, showing that they have a good explanation of the problem and the ability to design cases, quick thinking, more than the general programmer, have the ability to write

   13. Is it possible to make a call to a non-static method from within a static method?

  Answer: No, you can't. Because the non-static method is to be associated with an object, you must create an object before you can make a method call on the object, and the static method call does not need to create the object, which can be called directly. That is, when a static method is called, there may not be any instance objects created, and if a call to a non-static method is emitted from a static method, which object does that non-static method relate to? This logic cannot be set up, so a static method is issued inside a call to a non-static method.

 14, the difference between Integer and int

 Answer: Int is one of the 8 raw data types provided by Java. Java provides encapsulation classes for each primitive type, and integer is the wrapper class provided by Java for Int. The default value for int is 0, and the default value for integer is null, that is, integer can differentiate between unassigned and value 0, and int cannot express an unassigned condition, for example, if you want to express the difference between not taking an exam and the test score of 0, you can only use integer. In JSP development, the default for Integer is null, so when displayed in a text box with an El expression, the value is a blank string, and the default value of int defaults to 0, so when the El expression is displayed in the text box, the result is 0, so that int does not work as a type of form data for the Web tier. In Hibernate, if the OID is defined as an Integer type, hibernate can determine whether an object is temporary based on whether its value is null or not, and if the OID is defined to be of type int, it also needs to be set in the HBM mapping file Unsa The Ved-value property is 0.

In addition, the integer provides multiple integer-related action methods, such as converting a string to an integer, and also defining constants that represent the maximum and minimum values of integers.

  15, Math.Round (11.5) how much? Math.Round (-11.5) how much?

 Answer: The Math class provides three methods related to rounding: ceil, Floor, round, which correspond to the meanings of their English names, for example, the English meaning of Ceil is the ceiling, which means rounding up, Math.ceil (11.3) The result of 12,math.ceil (-11.3) is the result of -11;floor is the English meaning of the floor, the method is to represent a downward rounding, the result of Math.ceil (11.6) is the result of 11,math.ceil (-11.6) is-12; the hardest thing to master is Round method, which means "rounding", the algorithm is Math.floor (x+0.5), the original number is added 0.5 and then rounded down, so the result of Math.Round (11.5) is 12,math.round (-11.5) The result is-11.

  16. What's wrong with the code below?

  1. if (Username.equals ("Zxx") {}

Username may be null, the null pointer error is reported, and instead "Zxx". Equals (username)

2. int x = 1;

return x==1?true:false;

This is changed to return x==1;

  17, please say the scope public,private,protected, and do not write when the difference

  Answer: The visible range of these four scopes is shown in the following table.

Description: If no access modifier was written above the decorated element, the friendly

The scope is currently similar to a package (pack) descendant class other packages (package)
Public√√√√
Protected√√√x
Friendly√√xx
Private√xxx
Note: As long as you remember that there are 4 access rights, 4 access range, and then the full selection and the range in the horizontal and vertical direction of the order from small to large or from large to small, it is easy to draw the above diagram.

 18, the difference between overload and Override. Can the Overloaded method change the type of the return value?

  Answer: Overload is overloaded meaning, override is the meaning of overwrite, that is, rewrite.

Overloaded overload means that there can be more than one method with the same name in the same class, but the parameter lists of these methods vary (that is, the number of arguments or the type differs).

overriding override means that a method in a subclass can be exactly the same as the name and parameters of a method in the parent class, and invoking the method from an instance object created by the subclass invokes the definition method in the subclass, which is equivalent to overwriting the exact same method defined in the parent class. This is also a representation of the polymorphism of object-oriented programming. When a subclass overrides a method of a parent class, it can only throw fewer exceptions than the parent class, or a child exception that throws an exception thrown by the parent class, because subclasses can solve some problems with the parent class and cannot have more problems than the parent class. The subclass method can only be accessed more than the parent class, and cannot be smaller. If the method of the parent class is private, then the subclass does not have an override limit, which is equivalent to adding a new method to the subclass.

As to whether the Overloaded method can change the type of return value, it depends on what you want to ask. The subject is very vague. If several Overloaded methods have different parameter lists, their type of returnees can of course be different. But I guess the question you want to ask is: if the parameter list of the two methods is exactly the same, can you make them different from the return values to implement the overloaded overload. This is not possible, we can use contradiction to illustrate this problem, because we sometimes call a method can also not define the return result variable, that is, do not care about its return results, for example, when we call the Map.Remove (key) method, although the Remove method has a return value, However, we usually do not define a variable to receive the return result, when it is assumed that the class has two names and the parameter list is exactly the same method, only the return type is different, Java will not be able to determine the programmer's bottom is to invoke which method, because it can not be judged by the return result type.

Override can be translated as an overlay, literally knowing that it is covering a method and rewriting it to achieve different effects. The most familiar overlay for us is the implementation of the interface method, which is generally just a declaration of the method in the interface, and we need to implement all the methods of the interface declaration when we implement it. In addition to this typical usage, we may also overwrite methods in the parent class with the subclass in the inheritance. Be aware of the following points in the overlay:

1, the mark of the method of covering must match with the mark of the method that is covered completely, can reach the effect of coverage;

2. The return value of the overridden method must be the same as the return of the overridden method;

3. The exception that is thrown by the overridden method must be the same as the exception thrown by the overridden method, or its subclass;

4. The overridden method cannot be private, otherwise only a new method is defined in its subclass, and it is not overwritten.

Overload may be more familiar to us, can be translated as overloaded, it means that we can define some of the same name, by defining different input parameters to differentiate these methods, and then call, the VM will be based on different parameter styles, to choose the appropriate method of execution. The following points are to be noted in using overloading:

1. You can only pass different parameter styles when using overloads. For example, different parameter types, different number of parameters, different parameter order (of course, several parameter types within the same method must not be the same, such as can be Fun (int,float), but not fun (int,int));

2, can not be overloaded by access rights, return type, thrown exception;

3, the method of the exception type and number will not affect the overload;

4, for inheritance, if a method in the parent class is the access permission is PRIAVTE, then it can not be overloaded in the subclass, if defined, but also only defined a new method, but not to achieve the overloaded effect.

Java Interview Bible answer detailed and sentiment (first day)

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.