Questions on Java basic plane

Source: Internet
Author: User
Tags stream api stringreplace try catch

1 Object-oriented features
Encapsulating inherited polymorphism
Package: 1. Hide the content that does not need to be provided externally;
2. Hide the attributes and provide access to public methods;
Inheritance: 1. A parent class is a method or property that has a common characteristic, and we take it out separately into a class;
2. Inheritance is the more specific the sub-class, the more common the parent class;
3. Can implement code reuse;
Polymorphic: The reference of the parent class points to the object of the subclass;


2 Override and Overload
1 override overrides between parent class and subclass 1 Method Name parameter return type consistent 2 modifier permission greater than or equal to parent class 3 exception less than equals parent class
2 overload overloaded Similar methods 1 method names are identical, parameter order or type, number is inconsistent, cannot be overloaded by return value difference


3 Abstract classes and interfaces
1 abstract classes can implement methods, interfaces cannot have implementation methods
2 interfaces can implement multiple, abstract class single inheritance
3 abstract classes can have construction methods, interfaces cannot have
The variables in the 4 interface are public static final


4 string with Stringbuffter StringBuilder
1 string is the final class, in order to secure the immutable allocation of memory, the concatenation of strings will open up a new memory
String s= "ABC"; s= "XXX"
2 stringbuffter variable Use the same piece of memory, so the string addition is more efficient than string
3 Stingbuffterst StringBuilder StringBuilder thread is unsafe and highly efficient


5 Tell the difference between Arraylist,vector, LinkedList, HashMap and Hashtable,list,set, and speak of their underlying realization

The list element is ordered and can be repeated.
Set element: Unordered and non-repeatable
Map: Key-value pair form keys cannot be duplicated

ArrayList vector ArrayList thread is not safe and efficient; vector is synchronous
ArrayList LinkedList: Array query Fast increase delete slow list instead

HashMap and Hashtable 1 HashMap thread unsafe efficiency 2 HashMap allow NULL as key 3 Contains API change


HASHMAP: The underlying implementation: Array + linked list, that is, the element in the array is a linked list, key to calculate its hashcode as the subscript of the array, because hashcode may be repeated, the list of elements entry (Key,value), according to key to get your value

ArrayList: The underlying uses the array linkedlist to use the linked list

Set: Use the HashMap key to store the HashMap key as the Set element

6 parsing methods of XML
Dom Sax (push parsing) Stax (pull-Parse)
1 DOM Document Object model
2 Sax Simple API for XML
3 Stax Stream API for XML
DOM parsing: XML is loaded into memory in a tree-structured way, easy to use, easy to modify, but more memory. It is not suitable for large files, and it can be used in most applications under normal circumstances.
Sax parsing: Parsing XML based on a push-mode event, less memory-intensive, faster than DOM parsing, and adapting to large files.
Stax parsing: Parsing XML based on the event stream of the pull mode, the speed is the fastest in 3 kinds of parsing methods, the operability is also the best.
Pull and push differences:
Push-trigger events are fixed, write our code in fixed events
Pull trigger event into int type, write code according to event of int type, control event is more flexible


7 Talk about final and finally finalize static
1 Final class cannot be inherited
Final method cannot be overridden
The final variable value cannot be modified if the reference variable is modified, the reference cannot be changed, and the object to which the reference is directed can be modified
The 2 finally try Catch finally finally executes regardless of whether there is an exception, one case does not execute, in the code calls the System.exit (0);
3 Finalize the garbage collection method to be executed when this object resembles servlet dying before calling destroy
4 static: Do not use new directly through the class name, only once
1 limiting the scope of a variable global
2 storage domain for the specified variable is stored in the static zone


8 Multi-Threading has several implementations, how to synchronize, what types of threads
1 Inheriting thread 2 implementation runnable
Difference 1 single Inheritance multi-Implementation 2 implement Runnable resource sharing
2 How to Sync
1 Synchronized
2 Wait (waits for the next thread) notify (wakes a thread that is waiting for a sync lock) Notifyall (wake All) producers and consumers
3 Sprite Thread (daemon thread background such as garbage collection thread) and user thread (normal thread)
If the application exits, the application exits as long as no user thread is running, but the daemon thread is running (the garbage collection mechanism is running)
The sprite thread does not have a lifecycle and ends with the end of the virtual machine, and if you want to turn the thread into a sprite thread, you must call it before start
Setdaemon (Boolean) method, once the thread becomes a daemon thread, it cannot become a user thread.


9 talking about thread pools and connection pools
1 Why use a thread pool? The practice of space-changing time
If it takes 3 seconds to create and destroy a thread and only 1 seconds to use it, it is not necessary to create it each time, you can use the thread pool

Create 3 + Destroy 3 > Use time 1 Use the thread pool to create a few threads into the pool, use one out to execute, throw after execution (how to throw) back into the pool, reuse.
The time spent on creating and destroying threads and the amount of system resources consumed are more than the time and resources spent processing actual user requests
A. Reducing the time spent on creating and destroying threads and the overhead of system resources
B. Without a thread pool, it is possible that the system creates a large number of threads that consume system memory and "over-switch".
2 then how to create a thread pool use the methods in executors to create thread pools Executorservice
Newfixedthreadpool creating a fixed-size thread pool
Newcachedthreadpool to create a cacheable thread pool
Newscheduledthreadpool (int corepoolsize): Creates a regularly executed thread pool of a given size
Executorservice Pool=executors.newfixedthreadpool (5);
Pool.execute (thread);
Pool.shutdown

Common Connection pools: dbcp,c3p0,prox001

There are several types of streams in Java? Please name some IO classes?
Direction Division: In relation to the program, it is divided into the input stream and the output stream
Unit Division: Byte Stream and character stream
Functional partitioning: node flow and filter flow (wrapper flow)

FileInputStream ObjectInputStream buffedinputstream bytearrayinputstream (Memory stream) PipedInputStream (pipeline flow)
Datainpustream (read eight basic data types, network read data)

The conversion stream is the adapter mode, and the filter stream is the adorner mode

One-to-one Java exception types, how to do exception handling, keyword: throws,throw,try,catch,finally what is the meaning of each
1 Exception types
Throwable
/            \
Error exception
/                \
Uncheced exception checked exception (must be caught or thrown)
(Runtime exception, system exception) compile-time exception, common exception
Error causes app to exit memory overflow power off
Unchecked exceptions differ from checked exceptions checked exceptions must be caught or thrown, otherwise the compilation does not pass
Unchecked exception: Nullpointerexcption arrayindexoutofexcption classcastexception Arithmetic Exception nosuchmethoderror
2 try,catch,finally Try must have, catch,finally a combination of both
3 throws method declaration on the inside of the throw method

principle of the JVM
1. Java (source program)---Compiler---. class bytecode file----ClassLoader loaded into memory----bytecode Checker (Security check)---interpreter (interpreted as
Operating system--CPU)--Operating system
class loader with 3 types of ClassLoader in Java
1 Application class Appclassloader loads the class under our application's Classpath
2 Extension class loader Extclassloader loading Jre/lib/ext under JDK
3 Bootstrap loader loads the jre/lib under the JDK

The loading mechanism is loaded with the class's delegate mechanism
First, the Appclassloader class loader---The parent class---the parent class, the topmost parent class loader loads, if the class is not found, the subclass loads, the original path returns, and finally
All the ClassLoader have found all the paths or the class is not found, and will throw classnofoundexception

java modifier scope public,protected, default, Private
Current class current Bun class other package
Public y-y y y
Protected y y y N
The default y y n n
Private y-n n N

Java Serialization
Serializable is an identity interface that functions as a
1. Transferring objects on the network;
2. Save the data to the hard drive;

UML Diagram of the Java Collection Framework

16 Talk about reflection
1 reflection is a set of classes and APIs that obtain information about itself, and this set of APIs can get the properties of the class and its parent class, or method invocation methods, and so on class-related API class
API method for the API Field and methods of the properties
2 Filed getdeclaredfields All properties (old Lee says violent access) GetFields public
3 Method
Getdeclaredmethods: Methods of this class
GetMethods: Methods for this class and for all parent classes

Call the method method of the class. Invoke (instance, parameter list); Original instance. Method (Parameter list)
private static void InvokeMethod () {
Class C=domain.class;
Method Methods[]=c.getdeclaredmethods ();
Method Method=null;
for (int i = 0; i < methods.length; i++) {
if (Methods[i].getname (). Equals ("SetName")) {
Method=methods[i];
}
}
Domain d= (domain) c.newinstance ();
Method.invoke (D, "AAA");
System.out.println (D.getname ());
}

How to implement polymorphism in Java
1 parent class reference to child class instance
2 Overloading of methods

18 Sort Bubbles
for (int i=0;i<a.length;i++) {
for (int j=i+1;j<a.length;j++) {
if (A[i]<a[j]) {
int Temp=a[i]
A[I]=A[J]
A[j]=temp
}
}
}
47000 188
19 Inheriting class execution order results
The delegate mechanism of a class
First, the Appclassloader class loader---The parent class (Extclassloader)---The parent class (BootStrap), and the topmost parent class loader loads, if
Cannot find the class, the subclass to load, the original path to return, and finally all the ClassLoader have found all the paths or not found the class, will throw Classnofoundexception

20 Local variables must be initialized before they are used
public class foo{

public static void Main (String args[]) {
String s;
System.out.println ("s=" +s);
}
}
What is the result?

21 variable and immutable transfer values and references
Pass value: The eight basic types are transmitted values, that is, the actual parameter is copied to a formal parameter;
Reference: Reference the memory address of the argument to the parameter, the reference is immutable, the reference to the content is mutable
public class test{
public static void StringReplace (String text) {
Text=text.replace (' J ', ' l ');
}
public static void Bufferreplace (StringBuffer text) {
Text=text.append ("C");
}
public static void Main (String args[]) {
String Textstring=new string ("Java");
StringBuffer textbuffer=new StringBuffer ("Java");
StringReplace (TextString);
Bufferreplace (TextBuffer);
System.out.println (Textstring+textbuffer);
}
}
What is the output?
Java Javac

22 What are the three ways to get class?
Class name The. Class object. getclass
Class.forName ("CMA.A") reads the. class file into memory

the socket and UDP
Socket: Three-time handshake is equivalent to calling safe
UDP: Stateless insecure equivalent to mailing
Socket: Divided into server and client
Service side
ServerSocket serversocket=new ServerSocket (1099)//Start service on 1099 port number
Socket socket=serversockeet.accept ()//Monitor the customer
Socket.getinputstream

Client socket socket=new socket ("IP address", 1099);
Socket.getoutputstream (). Write ("Output information")

Communication via IO Stream

UDP: Point-to-point communication, does not require server relay, who can be a server, can also be a client

is there a memory leak in Java?
Memory leaks: When an object is not being used in a program, but is not recycled by the garbage collector, this phenomenon is known as a memory leak, which often occurs in
Long life cycle variables that refer to short life cycle variables
Object O1=new object ();
Object O2=o1;
o1=null;//

For example, if the stack is in the popup element, if we do not remove the element from the array at the same time, there will be a memory leak;

25 How to read a large file such as a 4GB file
1 segment read, first processing the incoming data (such as first read 100m, first storage), then the 100m occupied resources released, and then read down
while ((str = br.readline ()) = null) {
i++;
APP=APP+STR;
if (i%100 ==0) {//Suppose to read 100 rows

Here you first operate on these 100 lines, then continue reading
App=null;
}
}
Br.close ();
}
2 NiO reads large files in a block-efficient way

the super and this
1 This represents the current object, which is the current class object, and super represents the parent class of the current class
Note the point:
1 call Super () must be written on the first line of the subclass construction method, otherwise the compilation does not pass. Each subclass constructs the first statement of the method, which is implicitly called by the
Super (), if the parent does not have this form of constructor, then it will be error-free at compile time.
2) Super () and this () are similar, except that super calls the constructor of the parent class from the subclass, this () calls other methods within the same class.
3) Super () and this () must be placed in the first line of the construction method.
4) Although you can call a constructor with this, you cannot call two.
5) This and super can not appear in a constructor at the same time, because this is bound to call other constructors, the other constructors will inevitably have a super statement exists, so in the same constructor has the same statement, it loses the meaning of the statement, the compiler will not pass.
6) This () and super () all refer to objects, so they cannot be used in a static environment. Includes: static variable, static method, static statement block.

27 = = with equals
The basic data type can only be compared by "= =", the comparison is the value;
The reference type compares the memory address with "= =", and equals compares the value
String overrides the Equals method, which is more than the content

Comparable is the natural comparison method of interface Java.lang natural sort CompareTo
Comparator is the overall ordering of interface Java.util

Questions on Java basic plane

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.