Java BASICS (4)

Source: Internet
Author: User
Tags bitwise operators

This blog post summarizes some Java interview questions, focusing on the Java interview book by Dr. Zhang Xiaoxiang.

 

1. & Differences

1)& And & can both be used as operators for logic and, Indicating the logic and (and). When the expression results on both sides of the operator are true, the entire operation result is true. Otherwise, if either of them is false, the result is false.

2)& Short circuitsThat is, if the first expression is false, the second expression is no longer calculated. For example, if (str! = Null &&! Str. equals ("") expression. When str is null, the following expression is not executed, so NullPointerException is not thrown if & is changed. If (x = 33 & ++ y> 0) y will increase, If (x = 33 & ++ y> 0) will not increase

3)& Can also be used as bitwise operatorsWhen the expressions on both sides of the & operator are not of the boolean type, & indicates bitwise AND operation. We usually use 0x0f to perform & operation with an integer, for example, 0x31 & 0x0f returns 0x01.

 

2. How to jump out of the current multi-nested loop in JAVA?

1) in Java, to jump out of multiple loops, you canDefine a label before the loop statement, and then use the break statement with the label in the code of the loop body in the layer.To jump out of the outer loop. For example:

1 ok:2 for(int i=0;i<10;i++){3   for(int j=0;j<10;j++){4        System.out.println("i="+i+",j="+j);5        if(j==5)6           break ok;7     }8 }

2) I personally do not use the label method,The result of the outer loop condition expression can be controlled by the loop body code in the lower layer.For example, you need to find a number in a two-dimensional array.

 1 public class Test { 2     public static void main(String[] args) { 3         int arr[][]={{1,2,3},{4,5,6,7},{9}}; 4         boolean found=false; 5         for(int i=0;i<arr.length&&!found;i++){ 6             for(int j=0;j<arr[i].length;j++){ 7                 System.out.println("i="+i+",j="+j); 8                 if(arr[i][j]==5){ 9                     found=true;10                     break;11                 }12             }13         }14     }15 }

 

3. Can the switch statement be applied to byte, long, or String?

In switch (expr1), expr1 can only be an Integer expression or enumeration constant (larger font). The Integer expression can be of the int basic type or Integer packaging type, because, byte, short, char can be implicitly converted to int. Therefore, these types and their packaging types are also acceptable. Obviously, the long and String types do not comply with the switch syntax and cannot be implicitly converted to the int type. Therefore, they cannot be applied to swtich statements.

 

4. How many times is 2 multiplied by 8 in the most efficient way?

2 <3, because if a number is shifted to n places, it is equivalent to multiplying the n power of 2. Therefore, if a number is multiplied by 8, it only needs to be shifted to three places.Bit computing CPUs are directly supported, with the highest efficiencyTherefore, the most efficient method of multiplying 2 by 8 and so on is 2 <3.

 

5. When a variable is modified using the final keyword, can the reference not be changed, or can the referenced object not be changed?

  When you use the final keyword to modify a variable, it is suggested that the variable cannot be changed, and the content in the object to which the referenced variable points can still be changed.

For example, for the following statement: final StringBuffer a = new StringBuffer ("immutable"); execute the following statement to report a compilation error: a = new StringBuffer (""); however, execute the following statement to compile:. append ("broken! "); When someone defines a method parameter, they may want to use the following form to prevent the method from modifying the passed parameter object: public void method (final StringBuffer param) {} Actually, this cannot be done. In this method, you can add the following code to modify the parameter object: param. append ("");

1 public class Test {2 public static void main (String [] args) {3 final StringBuffer a = new StringBuffer ("Hello "); 4 // a = new StringBuffer ("hello"); // compilation error 5. append (", world"); 6 System. out. println (. toString (); // Hello, world7} 8}

 

6. Differences between "=" and equals Methods

1)The "=" operator is used to compare whether the values of the connected variables are equal., That is, to compare whether the values stored in the memory corresponding to the variable are the same, to compare two basic types of data or two reference variables are equal, only the = operator can be used.

2)The equals method is used to compare whether the content of two independent objects is equal.

3) if a class does not define its own equals method, It inherits the equals method of the Object class. The implementation code of the equals method of the Object class is as follows:

1 public boolean equals(Object obj) {2     return (this == obj);3 }

  The following conclusions can be drawn from the code: If a class does not have its own equals method defined, its default equals method (inherited from the Object class) uses the = Operator, it is also to compare whether the objects pointed to by two variables are the same object. At this time, the equals method and the = Operator will get the same result, if two independent objects are compared, false is always returned. If you want to write a class to compare the content of the two instance objects created by the class to be equal, you must overwrite the equals method, it is up to you to write the code to determine when the content of the two objects is the same.

 

7. Differences between Integer and int

1) int is one of the eight original data types provided by java. java provides an encapsulation class for every un data type, and Integer is the encapsulation class provided by java for int (Encapsulation class = Data + operation).

2) The default value of int is 0, while the default value of Integer is null. That is, Integer can be distinguished as the difference between value assignment and value 0. int cannot express the value assignment. For example, if you want to express the difference between not taking the test and 0, you can only use Integer. In JSP, the default Integer value is null. Therefore, when an EL expression is used to display it in a text box, the value is an empty table string, and the default value of int is 0, so when the EL expression is displayed in the text box, the result is 0. Therefore,Int is not suitable for form data types on the WEB layer.

3)Integer provides a series of int-related operation methods.

 

8. Math. round, Math. float, Math. ceil

The Math class provides three methods related to rounding: ceil, floor, and round.

Ceil: rounded up. For example: Math. ceil (11.5), the result is 12; Math. ceil (-11.5), and the result is-11.

Floor: round down. For example, Math. floor (11.5), the result is: 11; Math. floor (-11.5), and the result is-12.

Round: rounding. The algorithm is Math. floor (x + 0.5 ). Math. round (11.5), the result is 12; Math. round (-11.5), and the result is-11.

 

9. abstract classes can have static main methods

1 public abstract class AbstractClass {2 public static String name; 3 4 public abstract void eat (); 5 6 public static void main (String [] args) {7 System. out. println ("this is the main method... "); 8} 9}

 

10. Can Constructor be overwritten?

Constructor cannot be inherited, so it cannot be Override, but can be Overload.

1 public final class Constructor<T> extends AccessibleObject implements GenericDeclaration, Member {2     //...  ...  3 }

 

11. Access Permissions: public, private, protected, and default

The current class is the same package, and other packages of the Child class are

Public Y

Protected Y N

Friendly Y N

Private Y N

Note: friendly is not a java keyword. friendly is used as the access permission by default only when no access permission modifier is specified before the variable.

Protected and friendly can only access other classes in the same package, but protected can access the parent classes in other packages through subclass inheritance, but friendly cannot, this is the only difference between the two.

 

12. When writing the clone () method, there is usually a line of code. What is it?

  Super. clone (); because the Members in the parent class must be copied first, and then the members of the parent class should be copied.

  Http://www.cnblogs.com/o-andy-o/archive/2012/04/06/2434904.html

In the actual programming process, we often encounter this situation: there is an object A, which contains some valid values at A time point, in this case, you may need A new object B that is exactly the same as A, and any subsequent changes to B will not affect the value in A. That is to say, A and B are two independent objects, however, the initial value of B is determined by object. In Java, simple assignment statements cannot meet this requirement. Although there are many ways to meet this requirement, the clone () method is the simplest and most efficient method.

  By default, all classes in Java inherit the java. lang. Object class, and there is a method clone () in the java. lang. Object Class (). This method returns a copy of the Object.There are two points to note: first, yesCopying an object returns a new object instead of a reference.. Second, the difference between copying an object and the new object returned using the new operator is that this copy already contains information about the original object, rather than the initial information of the object.

A typical clone () code is as follows:

 1 class CloneClass implements Cloneable{ 2  public int aInt; 3  public Object clone(){ 4   CloneClass o = null; 5   try{ 6    o = (CloneClass)super.clone(); 7   }catch(CloneNotSupportedException e){ 8    e.printStackTrace(); 9   }10   return o;11  }12 }
1 public class CloneClass implements Cloneable {2     3 }
1 public class Object{2     ... ...3     protected native Object clone() throws CloneNotSupportedException;4     ... ...    5 }

There are three notable points: first, the CloneClass class that can implement the clone function implements the Cloneable interface, which belongs to java. lang Package, java. the lang Package is already in the default import class, so you do not need to write it as java. lang. cloneable. The clone () method is overloaded. Finally, super is called in the clone () method. clone (), which also means no matter what the clone class's inheritance structure is, super. clone () directly or indirectly calls java. lang. object Class clone () method. The following is a detailed explanation of these points.

The third point is the most important. Take a closer look.The clone () method of the Object class is a native method. The efficiency of the native method is generally much higher than that of the non-native method in java.This also explains why to use the clone () method in the Object instead of creating a new class, and then assigning the information in the original Object to the new Object, although this also implements the clone function. Observe the second point.The clone () method in the Object class is also a protected attribute method. This also means that if you want to apply the clone () method, you must inherit the Object class. All classes in Java inherit the Object class by default, so you don't need to care about this.Then rewrite the clone () method. Another thing to consider is to allow other classes to call the clone () method of this clone class,After rewriting, set the clone () method attribute to public..

Why should the clone class implement the Cloneable interface? Pay attention to the following,The Cloneable interface does not contain any method.!In fact, this interface is only a flag, and this flag is only for the clone () method in the Object class. If the clone class does not implement the Cloneable interface, it calls the clone () method of the Object () method (that is, the super. clone () method), the Object's clone () method will throw a CloneNotSupportedException exception.

  Note: Cloneable is a classic Mark interface in java, and there is no way to serialize the Serializable serialization interface! Their role is to tell the virtual machines that they are already marked and can be processed accordingly!

 

13. Object-oriented features

Object-Oriented Programming Languages have four main features: encapsulation, inheritance, abstraction, and polymorphism.

1) Encapsulation: encapsulation is the basis for ensuring excellent controllability of software components. The purpose of encapsulation is to achieve high cohesion and low coupling of software components ", prevents changes caused by program dependency. In an object-oriented programming language,Objects are the basic unit of encapsulation. Object-oriented encapsulation is to encapsulate the code that describes the attributes and behaviors of an object into a "module ".Is a class. As long as you put the variables together with the method to access this variable, all the member variables in a class are defined as private, and only the methods of this class can be accessed, this basically achieves object encapsulation.

2) Abstraction: abstraction is to find similarities and commonalities of some things and classify these things into a class. This class only considers the similarities and commonalities of these things, in addition, it ignores the parts irrelevant to the current topic and goal and focuses on the aspects related to the current goal.

3) Inheritance:Inheritance is a mechanism by which child classes automatically share parent class data and methods.This is a relationship between classes and improves the reusability and scalability of software.

4) polymorphism: Polymorphism refers to the specific type pointed to by the referenced variable defined in the program and the method call sent through the referenced variable. It is not determined during programming, it is determined only when the program is running, that is, the Instance Object of the class to which a referenced variable directs, and the method called by the referenced variable to which class is implemented, it can be determined only when the program is running. This is because the specific class can be determined only when the program is running. In this way, you can bind reference variables to different class implementations without modifying the source code, as a result, the specific method of the Reference call changes accordingly, that is, without modifying the program code, you can change the specific code bound to the program running, so that the program can select multiple running states, which is polymorphism.Overriding and Overloading are different manifestations of Java polymorphism. Overriding is a manifestation of the polymorphism between the parent class and the subclass, and Overloading is a manifestation of the polymorphism in a class.

 

14. Differences between abstract class and interface

All methods in the interface must be abstract. The method definition in the interface defaults to the public abstract type, and the member variable type in the interface defaults to the public static final type.

Syntax differences:

1. abstract classes can have constructor methods, and interfaces cannot have constructor methods.

2. abstract classes can contain common member variables, and interfaces do not contain common member variables.

3. abstract classes can contain non-Abstract Common methods. All methods in an interface must be abstract and cannot have non-Abstract Common methods.

4. The access type of abstract methods in the abstract class can be public or protected. However, all abstract methods in the interface can only be public, and the default type is public abstract.

5. An abstract class can contain static methods. An interface cannot contain static methods.

6. the abstract class and interface can contain static member variables. The access type of static member variables in the abstract class can be arbitrary, but the variables defined in the interface can only be of the public static final type, the default value is public static final.

7. A class can implement multiple interfaces, but can inherit only one abstract class.

 

15. String s = "a" + "B" + "c" + "d"; how many objects have been created together?

Only one String object is created.

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.