Java Common interview Basic problem collation

Source: Internet
Author: User
Tags bitwise exception handling float double garbage collection

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

Answer: S1 = s1+1; Will prompt "cannot convert from int to short", 1 is itself an int type, and S1 is a short integer, so they are the int type, and for the expression to be valid, you need to cast the result to the shorter type
S1+=1 is equivalent to S1 = (short) (S1 + 1), which has implied coercion type conversions. So there's no problem with compiling.

2, the difference between int and integer.

Answer: 8 Large data types: (data in the stack can be allocated directly memory is the basic data type)

        Integer: char, short, int, long floating-point type: float, double logical: Boolean: Char basic data type and reference data type:

        Basic data type: The data in the stack that can be allocated directly to the memory is the basic data type.

        Reference data type: the reference to the data is in the stack, but its object is in the heap. Corresponding bytes: BOOLEAN:1/8 (a byte has a 8bit (bit) Boolean only true and false two logical values, in the compiled value of 0 and one to indicate that they are in memory by bitwise, only need one to be able to represent) byte:1 (word Char:2 (character type, a char can store only one kanji) short:2 (short int) int:4 (integer type) long:8 (Long integer) float : 4 (floating-point) Double:8 (double-precision type) The default integer type in Java is int, and if you want to define a float, you need to add the default floating-point type in L or L Java to be double, if you want to define

        Float type, need to add F or F in the back of small size to large, large turn will lose precision. Corresponding encapsulation class: Boolean→boolean char→character byte→byte short→short int→inte

        Ger Long→long float→float double→double: The difference between int and integer. (1) integer is the encapsulated class provided by Int.

        int is one of the basic data types. (2) The default value for integer is null.

        The default value for int is 0.

        (3) An integer is an object that requires a reference to point to the object, int is the basic data type, and is stored directly in memory. (4) SoundVariables that are declared as integers need to be instantiated, and variables that declare int do not need to be instantiated.
 

3, Java in the heap and stack.

Java is divided into two types of memory, one is heap memory, one is stack memory.

Static storage allocation: refers to the ability to determine at compile time the storage space requirements for each data target at run time, that is, the corresponding fixed memory space can be assigned to it at compile time.

Stack storage allocation: Known as dynamic storage allocation, is implemented by a stack of stacks. In contrast to the static storage allocation, in the stack storage scenario, the program is unknown to the memory space required at compile time, and only when it is run can the corresponding memory space be allocated according to the required size of the data area. (Stack memory is allocated in accordance with advanced principles.) )

Popular point of the heap and stack difference: The heap is mainly used to store objects, the stack is mainly used to execute the program.

Some of the basic types of variables and objects referenced in Java that are defined in a function are allocated in the stack memory of the function. When a variable is defined in a block of code, Java allocates memory space for the variable in the stack, and when the scope of the variable is exceeded, Java automatically releases the memory space allocated for the variable, which can be used as an immediate alternative.

Heap memory is used to store objects and arrays created by new. The memory allocated in the heap is managed by the automatic garbage collector of the Java Virtual machine. After generating an array or object in the heap, you can also define a special variable in the stack so that the value of the variable in the stack equals the first address of the array or object in the heap memory, and the variable in the stack becomes the reference variable for the array or object.

A reference variable is equivalent to a name that is an array or an object, and you can later use the reference variable in the stack to access the array or object in the heap.

Summarize:

Stacks and heaps are places where Java is used to store data in memory (unlike C + + Java Automatic management stacks and heaps, programmers cannot directly set stacks and heaps)

Heap: (object)

The Java heap is a run-time data area, the heap is responsible for garbage collection, the advantage of the heap is the dynamic allocation of memory size, the lifetime does not have to tell the compiler in advance, because it is dynamically allocating memory at runtime, the Java garbage collector will automatically take away these no longer used data. But the disadvantage is that the access speed is slow due to the dynamic allocation of memory at run time.

Stack: (Basic data)

The advantage of the stack is that the access speed is faster than the heap, and the stack data can be shared. But the disadvantage is that the data size and lifetime in the stack must be fixed and inflexible. Some basic types of variables are stored in the stack.

4, the principle of Math.Round ().
Math.Round (11.5) The result is 12,
Math.Round (11.4) The result is 11,
Math.Round (11.6) The result is 12
Math.Round (-11.5) The result is-11
Math.Round (-11.4) The result is-11
Math.Round (-11.6) The result is-12
The principle is to add 0.5 to the required value and then to the next rounding.
5, String, StringBuffer, StringBuilder the difference.
They can both manipulate and store strings.
String is a read-only string, and string references to strings cannot be changed.
The string objects represented by the StringBuffer and StringBuilder classes can be modified directly.
StringBuilder is introduced after Java5, and StringBuffer is the difference between StringBuilder it is used in a single-threaded environment, so the efficiency is higher than the stringbuffer.
6, the difference between overloading (overload) and overriding (override). Whether the overloaded method can be distinguished by the return type.
Both overloads and overrides are Polymorphic embodiments, and the difference is:
Overload says: Compile-time polymorphism. It occurs in the same class, meaning that in a class, a method with the same name has a different parameter type or a different number of parameters or a parameter type and number. Note: There is no special requirement for the return type for overloading.
The rewrite says: Run-time polymorphism. It occurs between the parent class and the subclass, the return type is the same when the subclass inherits the parent class and the methods in the subclass and the methods in the parent class have the same method name, number of parameters, and parameter types (although this can be different after java5, but it must be a subclass of the return value of the parent class, If the parent class returns the object class, the return value of the subclass can be a string, and so on.
7, the difference between & and &&.
And: Bitwise AND, the left and right sides first converted into binary, and then the operation with.
&&amp: Logical And, both left and right expressions are true to return true, with one false result false
8. The difference between an abstract class and an interface.
When to use an abstract class, and when to use an interface.
If you have some methods and want some of them to have a default implementation, you can use an abstract class.
If you want to implement multiple inheritance, you need to use interfaces (Java does not support multiple inheritance, subclasses cannot inherit multiple classes, but you can implement multiple interfaces)

An interface is an abstraction of an action, and an abstract class is an abstraction of the root cause.
An abstract class represents what this object is, and the interface represents what the object can do.
For example: The person is an abstract class, the pig is also an abstract class, the person has eats and drinks pulls the sleep the movement, the pig also has eats and drinks pulls the sleep the movement, then may eat and drink pulls sleeps these movements to make an interface, then separately goes to concretely realizes them.

The purpose of using abstract classes is to improve the reusability of code. You can override the methods in the abstract class to achieve what you want.
The purpose of using interfaces: to embody polymorphism, so that the object implementing the interface can implement the same method in different ways.

Abstract method: An abstract method must be decorated with an abstract keyword. If an abstract method exists in a class, the class must be an abstract class, and the abstract class must be decorated with the abstract keyword before the class. Because an abstract class contains methods that do not have a specific implementation, you cannot create an object with an abstract class. (Note: If a class does not contain abstract methods, it is also an abstract class if it is modified with abstract.) That is, an abstract class does not necessarily have to contain abstract methods. )

The meaning of an abstract class exists is to inherit. If an abstract class is defined, it is not inherited. Then it is tantamount to creating this abstract class in vain.

The class that contains the abstract method is an abstract class, but it does not mean that there can be only abstract methods in an abstract class, which, like ordinary classes, can also have member variables and ordinary member methods.

The main difference between an abstract class and an ordinary class:
(1) The abstract method must be public or protected, and the default is public because private cannot be inherited.
(2) An abstract class cannot be used to create an object.
(3) If a class inherits from an abstract class, the subclass must implement the abstract method of the parent class. If the subclass does not have an abstract method that implements the parent class, the subclass must also be defined as an abstract class.

The interface can contain variables and methods. In fact, the variables in the interface are implicitly specified as public static final variables (only) methods that are implicitly specified as public abstract methods and can only be public-abstract methods.
Difference:
(1) The interface can be more inherited, the abstract class can only be inherited, abstract classes may implement multiple interfaces.
(2) All the methods in the interface are abstract (the default public abstract decoration) and cannot have a specific implementation. An abstract class can have a normal method, an abstract method, or a static method to define.
(3) The member variable in the interface can only be public static final (static variable), and the variables in the abstract class can be of various types.
(4) There is no constructor in the interface, there is a constructor in the abstract class, but the constructor here cannot be used for the new object, and his role is primarily to initialize the operation of the abstract class.

Example:
An interface with an alert. There is an abstract class of doors. Then write a security door class words only need to inherit the abstract class, the implementation of the alarm interface can be.

Interfaces can inherit interfaces, and interfaces can inherit multiple interfaces, an abstract class can implement interfaces, and multiple interfaces can be implemented, and abstract classes can inherit concrete classes.

9, whether the abstract method can be static (static) at the same time, and whether it can be a local method. Can be synchronized decorated at the same time.
Answer: The abstract method is to be rewritten in the future, and static methods cannot be overridden, so this is wrong. The local method is implemented by native code, and the abstract method is not implemented, so this is also a mistake. The
synchronized function is mainly embodied in the specific method implementation, the same abstract method is not the amount of implementation, so this is also wrong.
10, use of the final keyword.
Answer:
(1) Cosmetic class: Indicates that the class cannot be inherited.
(2) Cosmetic method: Indicates that the method cannot be overridden.
(3) modifier variable: a constant that indicates that the value cannot be modified after the variable is assigned.
11, the order in which the object constructor is called. The
Initializes a static member variable-> and then calls the parent constructor – and then initializes the non-static member variable –> the last call to its own constructor
12, and whether it is possible to emit a call to a non-static method from within a static (static) method.
Answer: No, static methods can access only static members, and calls to Non-static methods create objects first.
13, about GC?
Answer: GC is the meaning of garbage collection, and the Java GC feature detects whether an object exceeds the scope to automatically reclaim memory. The
effectively protects against memory leaks, and the GC acts as a single, low-priority thread that cleans and reclaims objects that are not used for a long time in the memory heap.
14, conversion between data types.
Convert a string to a basic data type:
Call the Parsexxx () of the encapsulated class corresponding to the base data type ()
Replace the base data type with a string:
to invoke the string.valueof (XXX) method;
15, how to implement the inversion and conversion of strings.
Answer:

 public static string reverse (String a) {string newstr = "";
          if (a = = NULL | | a.length () <= 1) {return A; 
              }else{Newstr=reverse (a.substring (1)) +a.charat (0);
          return newstr; }
      }

16, Java Common exception handling keywords "throws", "throw", "try", "catch", "finally".
Answer: Every exception in Java is an object that is an instance of the Throwable class or its subclasses. When a method has an exception, an exception object is thrown, which contains exception information, and the method that invokes the object can catch the exception and handle the exception.
Throw: That's when we know what's going to happen when we develop, and we throw that exception explicitly.
Throws: Used to declare a variety of exceptions that a method might throw.
Try: To specify a segment or a program that needs to prevent an exception, and if there is an exception object, you can catch it by its type or by always executing a code block (finally).
17, a common run-time exception.
ArithmeticException (arithmetic anomaly)
ClassCastException (class conversion exception)
IllegalArgumentException (illegal parameter exception)
Indexoutofboundsexception (following table out of bounds exception)
NullPointerException (null-pointer exception)
SecurityException (Security Exception)
18, final, finally, finalize the difference.
Final: Modifiers (keywords) have three uses:
If a class is declared final, it means that it cannot derive a new subclass, that is, it cannot be inherited, so it is opposite to abstract.
Declaring variables final can guarantee that they will not be changed in use, and that a variable declared final must be given an initial value at the time of declaration, and can only be read in future references.
If the method is also used only by the final decoration, it cannot be overridden in a subclass.

Finally: Usually the structure behind the Try......catch always executes a block of code, which means that the code will be executed regardless of whether the program executes correctly or abnormally.

Finalize:object the method defined in the class, Java allows you to use the Finalize () method to do the necessary cleanup before the garbage collector clears the object out of memory. This method is invoked by the garbage collector when destroying objects, by overriding the Finalize () method to organize system resources or perform other cleanup work.

19, the use and difference of list,set,map.
List,set are inherited from the collection interface, and map is not.

List: Elements are stored in a linear fashion and can contain duplicate elements.

List Main Implementation classes:
ArrayList (): An array of lengths that can be changed, and insertion and deletion elements are more efficient. Retrieval efficiency is fast.
LinkedList (): The linked list data structure storage, inserts and deletes the element to be efficient, the retrieval access efficiency is slow.
Set (SET): An element does not have a specific order, it holds an object reference, and there is no repeating element.

Set main implementation class:
HashSet: Accesses the objects in the collection according to the hashing algorithm, and the access speed is faster.
TreeSet: Implements the SortedSet interface, the ability to sort objects in a collection.

Map (map): A set of key objects and value object mappings, each of which has a corresponding key and value object, and when retrieving elements from the map, only the key object can be returned to the corresponding value object.
A map cannot contain the same key, and each key can map only one value

Main implementation class:
HASHMAP: Bottom use data + linked list implementation, the same key can put multiple values, but take out the last value. (asynchronous) allows nulls null keys.
Hashtable:hashtable and HashMap, the only difference is that it is thread safe, put and get operations are locked, and do not allow NULL values and NULL keys.
Linkedhashmap and Linkedarraylist principle similar, can vent value null key. (asynchronous) compared to HashMap is a one-way linked list, it is a two-way linked list. (The disadvantage is that the original value will be preserved)

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.