1. Which of the following statements about the program is true?
public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub byte a = 3,b=2; //1 byte c = a+b; //2 System.out.println(c); }}
A. Compiled and printed 5 at runtime
B. The compilation is successful, and 23 is printed at runtime.
C. If compilation fails, an error occurs in // 2 because f must be a byte type variable.
D. If the compilation fails, an error occurs at // 1. Variables cannot be defined in this way.
Parsing: operations involving byte, short, and char Types in java will first convert these values to the int type, then perform operations on the int type values, and finally get the result of the int type. Therefore, if two bytes are added, an int value is obtained. To obtain the byte type result, you must explicitly convert the result of this int type to the byte type.
Correct the code at Step 2: byte c = (byte) (a + B); // 2
2. The following program errors: A, short s = 1; s = s + 1; B, short s = 1; s + = 1;
Resolution: s + 1 is int and cannot be directly assigned to short. In B, the address of read right s is + 1.
3. Will the following program be executed incorrectly? If something is wrong, what is the error?
public class PerttyTest { public static void main(String[] args){ String i="123",s; s=getStr(i); System.out.println(s); } public String getStr(String s){ StringBuffer sb=new StringBuffer(); for(int i=s.length()-1;i>=0;i--){ sb.append(s.charAt(i)); } return sb.toString(); }}
Resolution: The main function is a static function. getStr is not a static function and cannot be called in the main function. You can declare getStr as a static function or instantiate a PerttyTest class to call it.
4. Differences between final, finally, and finalize. (1) final modifier (keyword)
If a class is declared as final, it means that it cannot generate a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared both abstract and final.
Declare variables or methods as final to ensure that they are not changed during use. It can be initialized in two places: one is its definition, that is, it is assigned a value directly when the final variable is defined; the other is in the constructor. You can only choose one of these two places. Methods declared as final can only be used and cannot be overwritten)
(2) finally
Finally blocks are provided for troubleshooting to clear any exceptions. If an exception is thrown, the matched catch clause is executed, and the control enters the finally block.
(3) finalize
Finalize is the method name. Java technology allows you to use the finalize () method to clear objects from the memory before the Garbage Collector clears them. This method is called by the garbage collector when it determines that this object is not referenced.
5. Which of the following will happen when you compile and run the following code?
class ExBase{ abstract public void martley(){ }}public class MyEx extends ExBase{ public static void main(String argv[]){ DataInputStream fi =new DataInputStream(System.in); try{ fi.readChar(); }catch(IOException e){ System.exit(0) } finallly{Sytemt.out.println("Doing finally");} }}
A. Compilation Error
B. When the program runs, wait for a keyboard input and then jump out.
C. When the program is running, wait for a keyboard input, "Doing finally" is displayed on the screen, and then jump out
D. Jump out immediately during running
Analysis: this is a typical misleading question. In fact, the program will generate errors, just think that the local method and the abstract method are not the same method body. In addition, the class of the abstract method must be modified using abstract. Note that abstract methods may not exist in abstract classes. Abstract classes cannot generate objects. abstract classes are inherited by nature. Abstract class abstract methods can only be modified using public and abstract methods. The same is true for interface methods.
6. What is the difference between shallow replication and deep replication? (1) shallow copy (shallow clone)
All variables of the Copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, the shortest copy only copies the objects to be considered, rather than the objects referenced by the shortest copy.
(2) Deep replication (deep cloning)
All variables of the Copied object contain the same value as the original object, except those variables that reference other objects. Variables that reference other objects will point to new objects that have been copied, instead of the original referenced objects. In other words, deep replication copies all the objects referenced by the objects to be copied.
Example:
class ShallowCopy implements Cloneable{ private Date begin; public Date getBegin() { return begin; } public void setBegin(Date begin) { this.begin = begin; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); }}class DeepCopy implements Cloneable{ private Date begin; public Date getBegin() { return begin; } public void setBegin(Date begin) { this.begin = begin; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub DeepCopy obj=null; obj=(DeepCopy) super.clone(); obj.setBegin((Date) getBegin().clone()); return obj; }
7. Implement a copy constructor:
public class Test1 {public int i;public Test test;public Test1() {// TODO Auto-generated constructor stub}public Test1(Test1 t){i=t.i;test = new Test();test.i=t.test.i;}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub//A a = new B();Test1 t = new Test1();t.i=9;t.test=new Test();t.test.i=10;Test1 t1=new Test1(t);System.out.println(t1.i);System.out.println(t1.test.i);}}class Test{public int i;public Test(){}public Test(Test t){i=t.i;}}
8. What are the differences between public, protected, private, and default in Java? Public, protected, and private are used to define the access permissions of members in Java. The other is "default", that is, no permission modifier is added before a member.
The access permissions of these four modifiers are as follows:
-----------------------------------------------
Class internal package subclass outside package
Public allow
Protected allowed not allowed
Allow by default or not
Private: Not allowed. Not allowed.
-----------------------------------------------
The access control of Java stays at the compilation layer, that is, it does not leave any trace in the class file, and only checks the access control during compilation.
In fact, reflection can be used to access members of any class under any package. For example, it is also possible for private members of the category class.
9. Methods of interfaces in Java can only be of the public abstract type, but can be omitted. variables can only be of the final static type and can be omitted. 10. What is the difference between equal and = in Java? First, let's look at a piece of code:
public class Test1{ public static void main(String args[]){ String a="1234"; String b="1234"; String c = new String("1234"); System.out.println(a==b); System.out.println(a==c); System.out.println(a.equals(c)); }}
Result:
True
False
True
First, you should first understand the difference between String new and direct value assignment in java.
The second is false because a and c point to different objects. = When using the basic data type, compare their actual values to determine whether they are equal, while when used to compare the reference type, it is to compare whether the two referenced addresses are equal, that is, whether to point to the same object. The string created through new generates an object separately, so a and c point to different objects.
The equal () method is the java. lang. object method, that is, all Java classes will have methods. It can be overwritten and overwritten by programmers and determined whether two objects are equal in a custom way. For the String class, its equal method is used to compare whether the character sequences of strings are completely equal.
11. What is the char value range in Java?
In Java, char adopts the Unicode encoding format and uses two bytes to represent a single character. A total of 16 bits can represent a maximum of 16 to the power of 2.
12. Can char in Java store Chinese characters?
Char can store Chinese characters, and each Chinese character has a corresponding Unicode encoding.
13. The difference between Overload (Overload) and Override (Override) in Java is a means for classes to process different types of data in a unified manner. Multiple Functions with the same name exist at the same time and have different parameter numbers/types, regardless of the return value type.
Overwrite indicates that a method of the parent class is redefined in the subclass. The method name, parameter location, number, and return value of the subclass are the same as those of the parent class, therefore, the method of the parent class is not executed when this method of the subclass is called. If the methods defined in final are in the parent class, they cannot be overwritten in the subclass.
14. What is the output of the following code?
public class Test1 {public Test1() {// TODO Auto-generated constructor stub}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubA a = new B();System.out.println("----------------");B b = new B();}}class A{static{System.out.println("AAAAAAAAAAAAAA static");}public A() {//super();System.out.println("AAAAAAAAAAAAAA");// TODO Auto-generated constructor stub}}class B extends A{static{System.out.println("BBBBBBBBBBBBBBB static");}public B() {//super();System.out.println("BBBBBBBBBBBBBB");}}
Result:
Aaaaaaaaaaaa static
Bbbbbbbbbbbbbbbbb static
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
----------------
AAAAAAAAAAAAAA
BBBBBBBBBBBBBB
Static {} (static block) is executed only once when the class is loaded. It is generally used to initialize static variables and call static methods.
15. How many references are supported in Java: strong reference, soft reference, weak reference, and virtual reference? In versions earlier than JDK, when an object is not referenced by any variable, the program will no longer be able to use this object. That is to say, the program can use the object only when it is reachable. This is like in daily life, after buying an item from a store, if it is useful, keep it; otherwise, it will be thrown into the garbage bin and taken away by the cleaners. Generally, if an item has been thrown into a garbage bin, it is impossible to pick it up and use it again.
However, sometimes the situation is not that simple, and you may encounter items similar to chicken ribs. This kind of item is useless now. It will take up space to keep it, but it is not worthwhile to discard it immediately because it may be useful in the future. A compromise solution for such dispensable items is: if the Home Space is sufficient, keep it at home first. If the home space is insufficient, even if all the household items are cleared, they still cannot accommodate the essential necessities, and then they are discarded.
Since JDK1.2, the object reference is divided into four levels, so that the program can control the object lifecycle more flexibly. The four levels are from high to low: strong reference, soft reference, weak reference, and virtual reference.
1) strong references
In normal programming, for example, Object object = new Object (); that object is a strongly referenced Object. If an object has a strong reference, it is similar to an essential necessities. The Garbage Collector will never recycle it. When the memory space is insufficient, the Java Virtual Machine would rather throw an OutOfMemoryError to terminate the program abnormally and does not recycle strongly referenced objects to solve the problem of insufficient memory.
2) SoftReference)
If an object only has soft references, it is similar to the necessities that can be used. If the memory space is sufficient, the garbage collector will not recycle it. If the memory space is insufficient, the memory of these objects will be recycled. The object can be used by the program only if the garbage collector does not recycle it. Soft references can be used to implement memory-sensitive high-speed cache. Soft references can be used together with a ReferenceQueue, the Java virtual machine adds this soft reference to the reference queue associated with it.
3) WeakReference)
If an object only has weak references, it is similar to a necessities that can be used. The difference between weak references and soft references is that only objects with weak references have a shorter life cycle. When the Garbage Collector thread scans the memory area under its jurisdiction, its memory will be recycled no matter whether the current memory space is sufficient or not. However, since the garbage collector is a thread with a low priority, it may not soon find objects with weak references. Weak references can be used together with a ReferenceQueue, the Java virtual machine adds this weak reference to the reference queue associated with it.
4) PhantomReference)
As the name implies, "virtual references" are just the same as virtual ones, which are different from other types of references. Virtual references do not determine the object lifecycle. If an object only holds a virtual reference, it is the same as no reference and may be recycled at any time. Virtual references are mainly used to track the activity of objects being reclaimed by garbage collection. A difference between virtual and soft references and weak references is that virtual references must be used together with the reference Queue (ReferenceQueue. When the garbage collector is preparing to recycle an object, if it finds that it has a virtual reference, it will add this virtual reference to the reference queue associated with it before it recycles the object's memory. The program can determine whether the referenced object has been added to the reference queue to check whether the referenced object is to be recycled. If the program finds that a virtual reference has been added to the reference queue, it can take necessary actions before the memory of the referenced object is recycled.
16. What are the differences between String str1 = "abc" and String str2 = new String ("abc?
When executing this code, the Java Virtual Machine encounters the double quotation mark operator, it will automatically create a String object, the value represented by this String object is abc, and then return a reference to this object.
For the str1 string, the creation process is described above. In Java and later versions, before creating this object, JVM will search for whether the String object has been created in the String object pool. If it has been created, a reference is directly returned, otherwise, a reference is returned after creation.
The creation process of str2 string variable requires one more step. It creates a new String object, that is, the role of the new Keyword, and returns a reference to str2.
Java has the object pool concept. When the Java Virtual Machine starts, nine object pools will be instantiated, which are used to store 8 basic packaging classes and String objects respectively. The object pool is used to frequently create and destroy objects, which affects system performance.
Str1 is an object in the object pool. The str2 method directly generates a new object.
In any case, as long as a new String object is created.
Therefore, the result of expression str1 = str2 is false.
17. String cannot be inherited. When a String is used as a method parameter, it is passed as a value instead of a reference.