java-basic Knowledge (1)

Source: Internet
Author: User

1. What are the aspects of object-oriented features?

A: Object-oriented features are mainly in the following areas:

Abstract: Abstraction is the process of constructing classes by summarizing the common features of a class of objects, including both data abstraction and behavioral abstraction. Abstractions focus only on what properties and behaviors the object has, and do not care what the details of those behaviors are.

Inheritance: Inheritance is the process of creating a new class from an existing class to get inherited information. The class that provides the inheritance information is called the parent class (the superclass, the base class), and the class that gets the inherited information is called the subclass (derived class). Inheritance allows for a certain degree of continuity in a changing software system, and inheritance is also an important means of encapsulating the variables in the program (if not understood, read Dr. Shanhong's "Java and Patterns" or "Design pattern Refinement" section on Bridge mode).

Encapsulation: Encapsulation is generally considered to be the binding of data and the method of manipulating data, and access to data can only be achieved through defined interfaces. The essence of object-oriented is to portray the real world as a series of completely autonomous and closed objects. The method we write in the class is a encapsulation of the implementation details, and we write a class that encapsulates the data and data operations. It can be said that encapsulation is to hide everything can be hidden, only to the outside world to provide the simplest programming interface (can think of the difference between ordinary washing machine and automatic washing machine, it is obvious that the automatic washing machine package is better, so it is easier to operate; The smart phones we use are also well-packaged, Because of a few buttons to get everything done).

Polymorphism: Polymorphism means that objects of different subtypes are allowed to respond differently to the same message. The simple thing is to invoke the same method with the same object reference but do something different. Polymorphism is divided into compile-time polymorphism and run-time polymorphism. If the method of an object is treated as a service to the outside world, then the runtime polymorphism can be interpreted as: when a system accesses the services provided by B system, B system has a variety of ways to provide services, but everything is transparent to a system (like an electric shaver is a system, its power supply system is B, b system can use battery power or AC power, and possibly even solar energy, a system only through the Class B object call power supply method, but do not know what the bottom of the power supply system to achieve what is the way to get the momentum. Method overloads (overload) implement compile-time polymorphism (also known as pre-binding), while the method override (override) implements runtime polymorphism (also known as post-bind). Runtime polymorphism is the most essence of object-oriented things, to achieve polymorphism need to do two things: 1). Method overrides (subclasses inherit the parent class and override existing or abstract methods in the parent class); 2). Object styling (referencing a subtype object with a parent type reference, so that the same reference calls the same method and behaves differently depending on the subclass object).

2, access modifier public,private,protected, and do not write (default) when the difference

current class
modifier same   package sub   class Other Package
public √ √ √ √
protected √ √ √ x
default √ √ x x
private √ x x x

Defaults to default when members of a class do not write access adornments. The default is equivalent to exposing (public) to other classes in the same package, and for other classes that are not in the same package are equivalent to private (private). A protected (protected) subclass is equivalent to exposing a class that is not a parent-child relationship in the same package as private. In Java, the modifiers of an outer class can only be public or default, and the members of the class (including inner classes) can have the four modifiers.

3. Is String the most basic data type?

Answer: No. There are only 8 basic data types in Java: Byte, short, int, long, float, double, char, Boolean, except for the base type (primitive type) and the enumeration type (enumeration type). All that is left is the reference type (reference type).

4. Float f=3.4, is it correct?

Answer: not correct. 3.4 is a double, assigning a double type (double) to a float (float) belonging to the lower transformation (down-casting, also known as narrowing) will result in a loss of precision, so you need to force the type conversion of float F = (float) 3.4; or write a float f =3.4f;.

5, short S1 = 1; S1 = s1 + 1; Is it wrong? short S1 = 1; S1 + = 1; wrong?

Answer: for short S1 = 1; S1 = s1 + 1; since 1 is an int type, the result of the s1+1 operation is also an int type, which requires a cast type to be assigned to the short type. and short S1 = 1; S1 + = 1; can be compiled correctly because s1+= 1, equivalent to S1 = (short) (S1 + 1), which has an implicit coercion type conversion.

6. Java has no goto

A: Goto is a reserved word in Java and is not used in the current version of Java. (in the appendix to the Java programming Language, written by James Gosling (the father of Java), is a list of Java keywords with goto and const, but these two are keywords that are not currently available, So in some places it is called a reserved word, in fact, the word reserved word should have more extensive meaning, because the familiar C language programmers know that in the System class library used in the special meaning of the word or word combination is considered a reserved word)

7. What is the difference between int and integer

A: Java is a nearly pure object-oriented programming language, but for the convenience of programming or the introduction of basic data types, but in order to be able to use these basic data types as Object operations, Java for each basic data type has introduced the corresponding wrapper type (wrapper class), The wrapper class for int is integer, and the automatic boxing/unpacking mechanism is introduced from Java 5, allowing the two to be converted to each other.

Java provides the wrapper type for each primitive type:

Original type: boolean,char,byte,short,int,long,float,double

Package Type: Boolean,character,byte,short,integer,long,float,

8, the difference between & and &&

The:& operator is used in two ways: (1) bitwise and; (2) Logical AND. The && operator is short-circuiting and arithmetic. The difference between the logic and the short-circuit is very large, although both require that the Boolean value on both sides of the operator is true the value of the entire expression is true. && is called a short-circuit operation because if the value of the expression on the left side of && is false, the expression on the right will be shorted out directly and will not be evaluated. Most of the time we may need to use && instead of &, for example, to verify that the user's name is not NULL and is not an empty string when validating the login, it should be written as: Username! = null &&!username.equals ("") , the order of the two cannot be exchanged, not the & operator, because if the first condition is not true, the equals of the string cannot be compared, otherwise a nullpointerexception exception will be generated. Note: Logical OR operator (|) and short-circuit or operator (| | The difference is also true.

Add: If you are familiar with JavaScript, you may be more able to feel the power of short-circuit operations, want to become a master of JavaScript first from the play to the short-circuit operation began.

9. Explain the usage of the in-memory stack (stack), heap, and static area.

A: Usually we define a variable of a basic data type, a reference to an object, and a field save for a function call that uses the in-memory stack space, while the object created by the new keyword and the constructor is placed in the heap space; the literal in the program (literal) is 100, "Hello" written directly And constants are placed in the static zone. Stack space is the fastest, but the stack is small, usually a large number of objects are placed in the heap space, in theory, the entire memory is not used by other processes in the space or even the hard disk virtual memory can be used as a heap space.

String str = new string ("Hello");

In the above statement, the variable str is placed on the stack, the string object created with new is placed on the heap, and the literal "hello" is placed in the static area.

Add: The newer version of Java (starting with an update to Java 6) uses a technique called escape analysis, which allows you to put some local objects on the stack to improve the performance of the object.

10, Math.Round (11.5) equals how much? How much does Math.Round (-11.5) equal?

Answer: The return value of Math.Round (11.5) is the return value of 12,math.round (-11.5) is-11. Rounding is done by adding 0.5 to the parameter and then taking the next rounding.

11. Does switch function on a byte, can it function on a long, and can it function on a string?

A: Before Java 5, in switch (expr), expr can only be a byte, short, char, Int. Starting with Java 5, the enumeration type is introduced in Java, and expr can be an enum type, starting with Java 7, expr can also be a string (string), but long is not available in all current versions.

12. Calculate 2 times 8 with the most efficient method

A: 2 << 3 (left 3 is the equivalent of multiplying by 2 by 3, and the right shift 3 is equivalent to dividing by 2 3).

Add: When we rewrite the Hashcode method for a class we write, we may see code like the following, in fact we do not understand why we use such multiplication to generate hash code (hash code), and why this number is a prime, why usually choose 31 this number? The answer to the first two questions you can Baidu, choose 31 is because you can use SHIFT and subtraction operation instead of multiplication, so as to get better performance. You may have thought about it here: * num is equivalent to (Num << 5) –num, the left 5 is the equivalent of multiplying by 2 by 5 and subtracting itself by the equivalent of multiplying by 31, now the VM can automatically complete this optimization.

13. Does the array have the length () method? String has no Length () method

Answer: The array does not have the length () method and has the length property. String has the length () method. In JavaScript, getting the length of a string is obtained through the long property, which is easily confused with Java.

14. In Java, how to jump out of the current multiple nested loops

A: Before the outermost loop, add a tag such as a, and then use break A; You can jump out of multiple loops. (Java supports tagged break and continue statements that are somewhat similar to goto statements in C and C + +, but like avoiding goto, avoid using tagged break and continue, because it doesn't make your program more elegant, Many times even have the opposite effect, so this grammar actually does not know better)

15. Whether the constructor (constructor) can be overridden (override)

A: The constructor cannot be inherited and therefore cannot be overridden, but can be overloaded.

16, two object values are the same (x.equals (y) = = true), but can have different hash code, this sentence is right

A: No, if two objects x and y satisfy x.equals (y) = = True, their hash code (hash code) should be the same. Java for the Eqauls method and Hashcode method is this: (1) If two objects are the same (the Equals method returns True), then their hashcode values must be the same, (2) If two objects have the same hashcode, they are not necessarily the same. Of course, you may not have to do as required, but if you violate the above principles you will find that when using containers, the same objects can appear in the set set, while the efficiency of adding new elements is greatly reduced (for systems using hash storage, if the hash code conflicts frequently, the access performance will be drastically reduced).

Add: About Equals and Hashcode methods, many Java programs are known, but many people just know, in Joshua Bloch's masterpiece "Effective Java" (Many software companies, "effective Java", " Java Programming Ideas and refactoring: Improving existing code quality is the Java programmer must read books, if you have not seen, then quickly go to the Amazon to buy a copy of it is described in this way: first the Equals method must satisfy the reflexivity (x.equals (x) Must return True), symmetry (x.equals (Y) returns True when Y.equals (x) must also return true), transitivity (X.equals (y) and y.equals (z) all return True when X.equals (z) must also return true) and consistency (when the object information referenced by x and Y is not modified, multiple calls to X.equals (y) should get the same return value), and a reference to any non-null value x,x.equals (NULL) must return FALSE. The tips for achieving a high-quality Equals method include: 1. Use the = = operator to check if the parameter is a reference to this object; 2. Use the instanceof operator to check if the parameter is the correct type; 3. For the key properties in the class, check that the properties of the parameter's incoming object match; 4. After writing the Equals method, ask yourself whether it satisfies symmetry, transitivity, consistency; 5. Overriding equals always overrides Hashcode;6. Do not replace object objects in the Equals method argument with other types, and do not forget the @override annotations when overriding.

17. Whether the string class can be inherited

A: The String class is the final class and cannot be inherited.

Add: Inheriting a string is itself a bad behavior, and the best way to reuse the string type is the association relationship (HAS-A) and the dependency (use-a) rather than the inheritance relationship (IS-A).

18, when an object is passed as a parameter to a method, this method can change the properties of the object, and can return the changed results, whether this is a value or a reference to pass

A: The value is passed. Method calls in the Java language only support value passing of parameters. When an object instance is passed as a parameter to a method, the value of the parameter is a reference to the object. The properties of an object can be changed during the call, but changes to the object reference do not affect the caller. In C + + and C #, you can change the value of an incoming parameter by passing a reference or transmitting a parameter.

19, the difference between string and StringBuilder, StringBuffer

A: The Java platform provides two types of strings: string and Stringbuffer/stringbuilder, which can store and manipulate strings. Where string is a read-only string, meaning string content referenced by string cannot be changed. The string object represented by the Stringbuffer/stringbuilder class can be modified directly. StringBuilder is introduced in Java 5, and it is exactly the same as the StringBuffer method, except that it is used in a single-threaded environment because all aspects of it are not synchronized decorated. Therefore, it is also more efficient than stringbuffer.

20. The difference between overloading (overload) and overriding (override). Whether overloaded methods can be differentiated by return type

A: The overloads and overrides of a method are implemented in a polymorphic way, except that the former implements the polymorphism at compile time, while the latter implements the runtime polymorphism. Overloads occur in a class, and methods with the same name are considered overloaded if they have different parameter lists (different parameter types, different number of arguments, or both); Overrides occur between subclasses and parent classes, and overrides require subclasses to be overridden by methods that have the same return type as the parent class, which is better accessed than the overridden method of the parent class. You cannot declare more exceptions than the parent class is overridden by the method (the Richter substitution principle). Overloads do not have special requirements for return types.

java-basic Knowledge (1)

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.