Java Basic interview Review one

Source: Internet
Author: User
Tags bitwise

Java business Development for a long time, some technology quickly forget?

Come on, let's start again from the basics.

1. Can I include more than one class (not an inner class) in a ". Java" source file? What are the restrictions?
There can be multiple classes, but only one public class, and the class name of public must match the file name.

2. Does Java have goto?
Reserved words in Java are not currently used in Java.

3, talk about the difference between & and &&.
Both & and && can be used as the logical AND operator, representing logic and (and), when the result of an expression on either side of the operator is true, the entire result is true, otherwise the result is false if one of the parties is false.
&& also has a short-circuit function, that is, if the first expression is false, the second expression is no longer evaluated, for example, for an if (str! = null&&!str.equals (")) expression, when STR is NULL, The following expression does not execute, so the nullpointerexception will not appear if you change && to & NullPointerException exception will be thrown. if (x==33 &++y>0) y grows, 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 not a Boolean,,& represents bitwise AND operation.
We usually use
0x0f to perform an & operation with an integer to get the minimum 4 bit bits of the integer, for example, 0x31 & 0x0f results in 0x01.
Note: This topic first said the similarities between the two, and the special points of && and &, and cited some classic examples to show that they understand thoroughly deep, practical experience.

4. How do I jump out of the current multiple nesting loops in Java?
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?
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 these types of wrapper types, are also available. Obviously
Both long and string types do not conform to the syntax of switch, and cannot be implicitly converted to int types, so they do not work in Swtich statements.

6, short S1 = 1; S1 = s1 + 1; what's wrong? Short S1 = 1; S1 + = 1; what's wrong?
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.

7. Can I store a Chinese character in char type?
Char-type variables are used to store Unicode encoded characters, and the Unicode encoding character set contains Chinese characters, so the char type can of course 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?
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.

9, please design a 10 billion of the calculator
First of all to understand the question of the test point is what, first of all, we have to understand the underlying details of the computer principle, to know the bit operation principle of addition and subtraction, 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?
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?
(Make one thing clear, and then another, so that the difference naturally comes out, and it's hard to say for sure) the = = operator is specifically used to compare the values of two variables for equality, that is, the value stored in the memory used to compare variables is the same, To compare two basic types of data or two reference variables for equality, use the = = operator only.
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, what is the difference between a static variable and an instance variable? The
differs from the syntax definition by adding the static keyword before the instance variable.
The difference when a program is run: an instance variable is a property of an object, 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, a Instancevar is assigned. That is, multiple instancevar may be assigned, and each Instancevar value 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);
}
}
Remarks: 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, reflecting their own 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?
No. 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
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 displayed in a text box with an El expression, the result is
0, therefore, 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 for the int type, It is also necessary to set its Unsaved-value property to 0 in the HBM mapping file.
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?
The Math class provides three methods related to rounding: Ceil, floor, and round, which correspond to the meanings of their English names, for example, the English meaning of Ceil is the ceiling, the method represents an upward rounding, the result of Math.ceil (11.3) is 12, The result of Math.ceil (-11.3) is that the English meaning of -11;floor is the floor, the method is to take the rounding down, the result of Math.ceil (11.6) is the result of 11,math.ceil (-11.6) is-12; the most difficult thing to Master is the round method, It 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) of 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
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 is represented.
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?
Overload is the meaning of overloading, override is the meaning of overrides, that is, rewriting.
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.

19. Can the constructor constructor be override?
The constructor constructor cannot be inherited and therefore cannot override override, but can be overloaded with overload.

20. Can interfaces inherit interfaces? Can an abstract class implement (implements) interfaces? Can an abstract class inherit a concrete class (concrete Class)? Is there a static main method in the abstract class?
Interfaces can inherit interfaces. Abstract classes can implement (implements) interfaces, and abstract classes can inherit concrete classes. There can be static main methods in an abstract class.
Note: As long as you understand the nature and role of interfaces and abstract classes, these questions are good answers, and you think, if you are the Java language Designer, will you provide such support, if not provided, what is the reason? If you have no reason not to provide, then the answer is yes.
Just remember that the only difference between an abstract class and a normal class is that you cannot create an instance object and allow an abstract method.

Java Basic interview Review one

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.