Java Basics (Interview questions)

Source: Internet
Author: User
Tags finally block

1: Object-oriented programming has many important features:

Encapsulation, inheritance, polymorphism, and abstraction.

2: What is a Java virtual machine? Why is Java called a "platform-agnostic programming language"?

(1) A Java Virtual machine is a virtual machine process that can execute Java bytecode. The Java source file is compiled into a bytecode file that can be executed by the Java virtual machine.

(2) Java is designed to allow applications to run on arbitrary platforms without requiring programmers to rewrite or recompile each platform individually.

The Java Virtual machine makes this possible because it knows the instruction length and other features of the underlying hardware platform.

What is the difference between 3:JDK and JRE?

The Java Runtime Environment (JRE) is the Java virtual machine that will execute the Java program. It also contains the browser plug-in needed to execute the applet. Java Open

The toolkit (JDK) is a complete Java software development package that contains the JRE, compilers, and other tools (such as the Javadoc,java debugger) that can

Let developers develop, compile, and execute Java applications.

4: What does the "static" keyword mean? Is it possible to overwrite (override) a private or static method in Java?

Static "keyword indicates that a member variable or a member method can be accessed without an instance variable of the class to which it belongs.

The static method in Java cannot be overridden because method overrides are dynamically bound based on the runtime, while the static method is statically bound at compile time.

5: Can I access non-static variables in the static environment?

The static variable belongs to the class in Java, and it has the same value in all instances. When the class is airborne into Java virtual, the static variable is

Initialization of the row. If your code tries to access a non-static variable without an instance, the compiler will make an error because the variables have not been created yet

is associated with any instance.

What types of data are supported by 6:java? What is auto-unboxing?

The 8 basic data types supported in the Java language are:

    • Byte
    • Short
    • Int
    • Long
    • Float
    • Double
    • Boolean
    • Char

Auto-Boxing is a conversion of the Java compiler between the base data type and the corresponding object wrapper type. For example: Convert int into integer,double conversion

into double, and so on. The reverse is automatic unpacking.

What does the method overlay (overriding) and method overloads (overloading) in 7:java mean?

Method overloads in Java occur when the same class has two or more methods with the same name but different parameters. In contrast to this, method overrides are said to be subclasses

A method that redefined the parent class. Method overrides must have the same method name, parameter list, and return type. The override may not restrict access to the methods it covers.

In 8:java, what is a constructor function? What is a constructor overload? What is a copy constructor?

When a new object is created, the constructor is called. Each class has a constructor function. The Java compiler creates a default constructor for this class in cases where the programmer does not provide a constructor for the class.

Constructor overloading and method overloading are similar in Java. You can create multiple constructors for a class. Each constructor must have its own unique argument list.

Java does not support copy constructors like in C + + because Java does not create a default copy constructor if you do not write the constructor yourself.

Does 9:java support multiple inheritance?

Not supported, Java does not support multiple inheritance. Each class can inherit only one class, but it can implement multiple interfaces.

10: What is the difference between an interface and an abstract class?

    • All methods in an interface are implicitly abstract. Abstract classes can contain both abstract and non-abstract methods.
    • A class can implement many interfaces, but only one abstract class is inherited
    • Class if you want to implement an interface, it must implement all the methods that the interface declares. However, a class can not implement all methods of an abstract class declaration, and of course, in this case, the class must also be declared abstract.
    • An abstract class can implement an interface without providing an interface method implementation.
    • The variables declared in the Java interface are final by default. An abstract class can contain non-final variables.
    • The member functions in the Java interface are public by default. The member functions of an abstract class can be private,protected or public.
    • An interface is absolutely abstract and cannot be instantiated. An abstract class can also not be instantiated, but it can be called if it contains the main method.

11: What is value passing and reference passing?

An object is passed by value, which means that a copy of the object is passed. Therefore, even if you change the object copy, the value of the source object is not affected.

object is passed by reference, meaning that it is not the actual object, but the reference to the object. Therefore, changes made externally to the referenced object are reflected on all objects.

12: What is the difference between a process and a thread?

A process is an application that executes, and a thread is an execution sequence within a process. A process can have multiple threads. Threads are also called lightweight processes.

13: How do I create threads in several different ways? Which one do you like? Why?

There are three ways to create threads:

    • Inherit the thread class
    • Implementing the Runnable Interface
    • Applications can use the executor framework to create a thread pool

Implementing the Runnable interface is more popular because this does not require inheriting the thread class. This requires multiple inheritance in cases where other objects have already been inherited in the design of the application

(while Java does not support multiple inheritance), only interfaces can be implemented. At the same time, the thread pool is very efficient and easy to implement and use.

14: Generalized explanation of several available states of the thread.

  

    • Ready (Runnable): The thread is ready to run, not necessarily immediately start execution.
    • Running (Running): The code of the thread that the process is executing.
    • Waiting (Waiting): The thread is in a blocked state, waiting for the external processing to end.
    • Sleep (sleeping): The thread is forced to sleep.
    • I/O blocking (Blocked on I/O): Waits for I/O operation to complete.
    • Synchronous blocking (Blocked on synchronization): Waits for a lock to be acquired.
    • Death (Dead): The thread completed execution.

15: What is the difference between a synchronization method and a synchronized code block?

In the Java language, each object has a lock. A thread can use the Synchronized keyword to obtain a lock on an object. The Synchronized keyword can be applied at the method level (coarse-grained locks) or at the code block level (fine-grained locks).

16: How does thread synchronization work inside the monitor? What level of synchronization should the program do?

Monitors and locks are used in Java virtual machines. The monitor monitors a block of synchronization code to ensure that only one thread executes the synchronized code block at a time. Each of the monitors is

An object reference is associated. The thread does not allow synchronization code to be executed until the lock is acquired.

17: What is deadlock (deadlock)?

A deadlock occurs when two processes are waiting for the other party to execute until execution is complete. As a result, two processes are trapped in infinite waiting.

18: How do you make sure that n threads can access n resources without causing a deadlock?

When using multithreading, a very simple way to avoid deadlocks is to specify the order in which locks are acquired and force threads to acquire locks in the order specified. Therefore, if all the

Threads lock and release locks in the same order, and there is no deadlock.

What are the basic interfaces of the 19:java collection class framework?

The Java Collection class provides a set of well-designed interfaces and classes that support the manipulation of a set of objects. The most basic interfaces within the Java Collection class are:

  

    • Collection: Represents a set of objects, each of which is its child element.
    • Set: A collection that does not contain duplicate elements.
    • List: A sequence of collection, and can contain repeating elements.
    • Map: You can map a key (key) to an object with a value, and the key cannot be duplicated.

20: Why does the collection class not implement the cloneable and serializable interfaces?

The collection class interface specifies a set of objects called elements. Each specific implementation class of the collection class interface can optionally save and sort the elements in its own way.

Some collection classes allow duplicate keys, some are not allowed.

21: What is an iterator (Iterator)?

The iterator interface provides many ways to iterate over a collection element. Each collection class contains an instance of the iterator that can be returned
Iterative methods. Iterators can delete elements of the underlying collection during the iteration.

What is the working principle of hashmap in 22:java?

HashMap in Java is a key-value pair (Key-value) that stores elements. HashMap requires a hash function, which uses hashcode () and Equals ()

method to add and retrieve elements from the collection/collection. When the put () method is called, HashMap calculates the hash value of the key, and then stores the key-value pairs in the collection

On the appropriate index. If the key already exists, value is updated to the new value. Some of the important features of HashMap are its capacity (capacity), load factor (loading factor)

and expansion limits (threshold resizing).

Where does the importance of the 23:hashcode () and Equals () methods manifest?

HashMap in Java uses the hashcode () and Equals () methods to determine the index of key-value pairs, which are used when the values are obtained by key. If not

The correct implementation of these two methods, two different keys may have the same hash value, therefore, may be considered equal by the collection. Moreover, these two methods are also used to discover

repeating elements. So the realization of these two methods is very important to the accuracy and correctness of hashmap.

What's the difference between 24:hashmap and Hashtable?

  

    • HashMap and Hashtable both implement the map interface, so many features are very similar. However, they have the following different points:
    • HashMap allows keys and values to be null, while Hashtable does not allow keys or values to be null.
    • The Hashtable is synchronous, while HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is suitable for multithreaded environments.
    • HashMap provides a collection of keys that can be used for iteration, so HashMap is a quick failure.

25: What is the difference between arrays (array) and list (ArrayList)? When should I use array instead of ArrayList?

The different points of the array and ArrayList are listed below:

  

    • An array can contain primitive types and object types, and ArrayList can only contain object types.
    • The array size is fixed, and the size of the ArrayList is dynamically changing.
    • ArrayList provides more methods and features, such as AddAll (), RemoveAll (), iterator (), and so on.
    • For basic type data, the collection uses automatic boxing to reduce the coding effort. However, this approach is relatively slow when dealing with fixed-size base data types.

What's the difference between 26:arraylist and LinkedList?

ArrayList and LinkedList all implement the list interface, they have the following different points:

(1) ArrayList is an index-based data interface, and its underlying is an array. It can randomly access elements with an O (1) time complexity. Corresponding to this, LinkedList is a meta-

Store its data in the form of a vegetarian list, each element is linked to its previous and subsequent elements, in which case the time complexity of finding an element is O (n).

(2) The insertion, addition, and deletion of arraylist,linkedlist are faster because when the element is added anywhere in the collection, it is not necessary to recalculate the size as an array or to update the index.

(3) LinkedList accounts for more memory than ArrayList because LinkedList stores two references for each node, one to the previous element, and one to the next.

27: How do I trade out an unordered array or an ordered array?

The greatest benefit of an ordered array is that the time complexity of the lookup is O (log n), and the unordered array is O (n). The disadvantage of an ordered array is that the time complexity of the insert operation is O (n) because the value is large

Elements need to be moved backwards to give new elements a place to move. Instead, the insertion time complexity of an unordered array is constant O (1).

What's the difference between 28:hashset and TreeSet?

HashSet is implemented by a hash table, so its elements are unordered. The time complexity of the add (), remove (), contains () method is O (1).

On the other hand, TreeSet is implemented by a tree-shaped structure in which the elements are ordered. Therefore, the time complexity of the add (), remove (), contains () method is O (Logn).

What is the purpose of garbage collection in 29:java? When does garbage collection take place?

The purpose of garbage collection is to identify and discard objects that the app is no longer using to free and reuse resources.

What will 30:system.gc () and RUNTIME.GC () do?

These two methods are used to prompt the JVM for garbage collection. However, starting or delaying a garbage collection immediately depends on the JVM.

When is the 31:finalize () method called?

The garbage collector calls the object's Finalize () method before releasing the memory occupied by the object. It is generally recommended that the resources held by the object be disposed of in this method.

32: If the object's reference is set to NULL, will the garbage collector immediately release the memory occupied by the object?

No, in the next garbage collection cycle, this object will be recoverable.

What is the structure of the 33:java heap like? What is the permanent generation in the heap (Perm Gen space)?

The JVM's heap is the run-time data area, and all instances and arrays of classes are allocated memory on the heap. It is created when the JVM is started. The heap memory that the object occupies is reclaimed by the automatic memory management system, which is the garbage collector.

Heap memory is made up of surviving and dying objects. The surviving objects are accessible to the app and are not garbage collected. The object of death is the object that the app is inaccessible and has not been reclaimed by the garbage collector. One until

Before the garbage collector reclaims these objects, they will occupy a heap of memory space.

34: In Java, when can objects be garbage collected?

This object can be recycled when the object becomes inaccessible to applications that currently use the object.

Will garbage collection occur in the permanent generation of 35:JVM?

Garbage collection does not occur in a permanent generation, and if it is permanently full or exceeds the threshold, a full GC is triggered. If you look closely at the output of the garbage collector, you will find that the permanent generation is also returned

It's closed. This is why the correct permanent generation size is very important for avoiding full GC.

Is 36:string the most basic type of data?

No. There are only 8 basic data types in Java: Byte, short, int, long, float, double, char, Boolean, except the base type (primitive type)

And the enumeration type (enumeration type), the remainder is the reference type (reference type).

37:float f=3.4, is it correct?

Not correct. 3.4 is a double, assigning a double type (double) to a floating-point (float) belonging to the lower transformation (down-casting, also known as narrowing) can result in a loss of precision,

It is therefore necessary to force the type conversion of float F = (float) 3.4; or write a float f =3.4f;.

38:short s1=1;s1=s1+1, wrong? S1=1;s1+=1: Wrong?

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.

What is the difference between 39:& and &&?

There are two ways to use the & operator: (1) bitwise and; (2) Logic and. The && operator is short-circuiting and arithmetic. The difference between the logic and the short-circuit is very large, although both require the operator to the left and right sides of the

The Boolean value is true if 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, not

will perform the operation. 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

can produce nullpointerexception exceptions. Note: Logical OR operator (|) and short-circuit or operator (| | The difference is also true.

40: Explain the use of the In-memory stack (stack), heap (heap), static zone (statically area)?

Usually we define a variable of a basic data type, a reference to an object, and a field save for a function call to use the in-memory stack space, whereas the new keyword and the constructor create a

The object is placed in the heap space, and the literal (literal) in the program, such as 100, "Hello" and constant, are placed in the static area. The stack space is the fastest but the stack is small, usually a large number of objects

is placed in the heap space, in theory the entire memory is not used by other processes and even the virtual memory on the hard disk can be used as 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.

41: Does the array have the length () method? Does the string have the length () method?

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.

42: How do I jump out of the current multiple nested loops in Java?

Add a tag such as a before the outermost loop, then use break A; You can jump out of multiple loops.

43: Can the constructor (constructor) be overridden (override)?

Constructors cannot be inherited and therefore cannot be overridden, but can be overloaded.

44: Two object values are the same (X.equals (y) ==true), but can have different hash code, this sentence right?

No, if two objects x and y satisfy x.equals (y) = = True, their hash code (hash code) should be the same. Java for Eqauls method and Hashcode method is this

stated: (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.

Use the = = operator to check if the parameter is a reference to this object.

45: Can I inherit the String class?

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

46: When an object is passed into a method as a parameter, this method can change the properties of the object and return the changed result, is this a value pass or a reference pass?

is a value pass. 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.

The difference between 47:string,stringbuilder,stringbuffer?

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,

This means that string content referenced by string cannot be changed. The string object represented by the Stringbuffer/stringbuilder class can be modified directly.

48: What are the similarities and differences between abstract classes and interfaces?

Abstract classes and interfaces cannot be instantiated, but they can define references to abstract classes and interface types. A class that inherits an abstract class or implements an interface requires all of its abstract methods to be implemented.

Otherwise, the class will still need to be declared as an abstract class. Interfaces are more abstract than abstract classes, because constructors can be defined in abstract classes, can have abstract methods and concrete methods, and interfaces cannot define constructors and their

Methods are all abstract methods. Members in an abstract class can be private, default, protected, public, and members of the interface are all public. A member variable can be defined in an abstract class, while a connector

The member variables that are defined are actually constants. Classes with abstract methods must be declared as abstract classes, and abstract classes may not necessarily have abstract methods.

Is there a memory leak in the 49:java, please briefly describe it?

In theory, Java has no memory leaks due to garbage collection (GC) (which is an important reason why Java is widely used in server-side programming); However, in actual development, there may be useless

But the objects that can be reached, these objects cannot be recycled by GC, and therefore can also cause memory leaks to occur. For example, the object in Hibernate session (first-level cache) is a persistent state, and the garbage collector does not recycle this

objects, however, there may be useless garbage objects in these objects, and memory leaks can occur if you do not close (close) or empty (flush) The first-level cache in a timely manner. The code in the following example also causes a memory leak.

50: Can abstract methods be static at the same time (static)? Can it be local at the same time? Can the syhcronized be modified at the same time?

Can not. Abstract methods require subclasses to rewrite, and static methods cannot be overridden, so they are contradictory. A local method is a method implemented by local code (such as C code), and the abstract method is not implemented and is

Contradictory. Synchronized is related to the implementation details of the method, and the abstract method does not involve implementation details, and therefore is contradictory to each other.

51: Describe the difference between a static variable and an instance variable?

A static variable is a variable modified by the static modifier, also known as a class variable, which belongs to a class, not to any object of the class, and a class has no matter how many objects are created, static variables have in memory and only one copy; instance

A variable must be dependent on an instance, and the object needs to be created before it can be accessed through an object. Static variables can be implemented to allow multiple objects to share memory.

52: Can I make a call to a non-static method from within the static method?

No, static methods can only access static members, because calls to non-static methods create objects first, and when static methods are called, they may not be initialized.

53:string str=new string ("xyz"), how many string objects are created?

Two objects, one is the "xyz" of the static zone, and the other is the object created on the heap with new.

What are the uses of the final keyword in 54:java?

(1) Modifier class: Indicates that the class cannot be inherited, (2) The Modification method: Indicates that the method cannot be overridden, (3) A modifier variable: Indicates that the value cannot be modified (constant) after the variable can be assigned only once.

55: How do I convert a base data type to a string? How do I convert a string to a base data type?

Calling the method Parsexxx (string) or valueof (string) in the wrapper class corresponding to the base data type can return the corresponding base type;
One way to do this is to concatenate the base data type with an empty string ("") to get its corresponding string, or to call the ValueOf () method in the string class to return the corresponding string.

The difference between 56:error and exception?

Error indicates system-level errors and exceptions that the program does not have to handle, a serious problem in situations where recovery is not impossible but difficult, such as memory overflow, which cannot be expected to be handled by the program;

Exception represents an exception that needs to be captured or handled by a program, which is a design or implementation problem, that is, if the program is running normally, it never happens.

57: List Some of your common runtime exceptions?

ArithmeticException (Arithmetic exception)
ClassCastException (class conversion exception)
IllegalArgumentException (illegal parameter exception)
Indexoutofboundsexception (Subscript out-of-bounds exception)
NullPointerException (null pointer exception)
SecurityException (Security Exception)

58: Explain the difference between final,finally,finalize?

(1) Final: modifier (keyword) has three uses: If a class is declared final, it means that it can no longer derive a new subclass, i.e. it cannot be inherited, so it and abstract are antonyms. Declare the variable as final,

It is guaranteed that they will not be changed in use, and that the variable declared as final must be given the initial value at the time of declaration, whereas in subsequent references it can only be read and not modifiable. A method that is declared final can also be used only and cannot be overridden in a subclass.

(2) Finally: usually put in try...catch ... The subsequent construct always executes the code block, which means that the program executes either normally or unexpectedly, the code here can be executed as long as the JVM is not closed, and the code that frees the external resource is written in the finally block.

(3) The method defined in the Finalize:object class allows the use of the Finalize () method in Java to do the necessary cleanup before the garbage collector clears the object from memory. This method is called by the garbage collector when the object is destroyed.

You can defragment your system resources or perform other cleanup tasks by overriding the Finalize () method.

What is the difference between the sleep () method of the 59:thread class and the Wait () method of the object that allows the thread to pause execution?

The Sleep () method (Hibernate) is a static method of the thread class (threads) that calls this method to suspend execution of the specified time by the current thread, giving the execution opportunity (CPU) to other threads, but the lock of the object remains.

Therefore, after the sleep time is restored automatically (the thread returns to the ready state, refer to the Thread state transition diagram in question 66th). Wait () is a method of the object class that causes the current thread to discard the object by invoking the Wait () method

Lock (the thread pauses execution), enter the object's wait pool, and only call the object's Notify () method (or Notifyall () method) to wake the thread in the waiting pool into the lock pool,

If the thread re-obtains the lock on the object, it can enter the ready state.

Add: Probably a lot of people to what is the process, what is the thread is also more ambiguous, for why multi-threading programming is not a special understanding. Simply put: A process is a program with certain independent functions on a data set

A running activity is an independent unit of the operating system for resource allocation and scheduling; a thread is an entity of a process, a basic unit of CPU dispatch and dispatch, and a smaller unit that can run independently than a process. Thread's Stroke

The sub-scale is less than the process, which makes the multi-threaded procedure highly concurrency, and the process typically has independent memory units at execution time, while the threads can share memory. Programming with multithreading often leads to better performance and user experience,

But multithreaded programs are unfriendly to other programs because they may consume more CPU resources. Of course, it is not the more threads, the better the performance of the program, because scheduling and switching between threads can also waste CPU time.

  

  

Java Basics (Interview questions)

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.