Java-error-prone knowledge points

Source: Internet
Author: User
Tags bitwise operators set time

Purely personal opinion. If you have any mistakes, please correct them!

I. Switch

1. it can accept four data types: Char, byte, short, int
2. Default can be placed anywhere in the switch, but it will be executed only when the given condition does not match.
3. If the 'case' and 'default' statement is to be jumped out after execution, break must be used. Otherwise, the statement will continue to be executed (if the 'case' statement is met, it will directly go into execution)
Instance 1:

        int i = 1, j = 0;        switch (i) {        case 2:            j += 6;        case 4:            j += 1;        default:            j += 2;        case 0:            j += 4;        } 

What is the value of J?
A.0
B .1
C.2
D.4

E.6

What is the acceptable type for the variable I?
A. byte
B. Long
C. Float
D. Double
E. Object
F. A and B
G. C and D

Ii. String and stringbuffer

A string defines a String constant, and its struct does not change once defined as follows:
String S = "ABC ";
S = S. substring (2); // A New String object is generated.
After the preceding two statements are executed, "two" strings are generated in the memory, one is "ABC", and the other is "AB" (note that s no longer points to "ABC ")
Stringbuffer defines a string variable, and its variable value can be changed as follows:
Stringbuffer S1 = new stringbuffer ("ABC ");
S1 = s1.substring (2 );
After the preceding two statements are executed, only "one" String object is generated in the memory: "AB" pointed by S ";

Iii. String S = new string ("XYZ") produces several objects

This statement generates two string objects:
One method is generated during compilation and stored in the constant pool.
One is generated at runtime using the new method and stored in heap memory.
However, only one object is generated in the new mode during running.

4. Parameters in Java can only be transferred by worker, and the copy of worker is passed.

If the basic type is used, a copy of the basic type is passed.
If it is a reference type, a copy of the reference itself is passed.

5. Conditions for method overloading and overwriting

The following conditions are met:
1. In the same class
2. There are multiple methods with the same name,
3. Different method parameters (different numbers of parameters or different types of parameters)
Instance:

public class MethodOver {     public void setVar (int a, int b, float c) {     }} 

Which two overload the setvar method? (Choose two)
A. Private void setvar (int A, float C, int B ){}
B. Protected void setvar (int A, int B, float c ){}
C. Public int setvar (int A, float C, int B) (return ;)
D. Public int setvar (int A, int B, float C) (return ;)
E. Protected float setvar (int A, int B, float C) (return C ;)

The following conditions are met:
1. In inheritance
2. The method name in the subclass is the same as that in the parent class.
3. The method parameters in the subclass are the same as those in the parent class.
4. The return type of the method in the subclass is the same as that of the parent class.
5. The subclass method cannot throw more exceptions than the parent class.
6. The access range of the subclass method is greater than or equal to that of the parent class.
Override it is worth noting that if there is a method name in the subclass that is the same as the parent class, but the parameters are different, it is not called overwrite, so it is not subject to overwriting conditions (note that this method can exist)

6. Knowledge about variable initialization in Java classes

6-1. The initialization sequence is divided into three steps:
1. initialize static variables and static blocks during class loading, first parent class and then subclass
2. When a new object is generated during running, allocate space for the object and initialize the instance variable. The first parent class and then subclass
3. when calling a constructor, first execute the constructor of the parent class, and then execute the constructor of the Child class. The specific process is when the constructor of the Child class is called, in the first line, the constructor of the parent class is called (explicit or implicit)

6-2. Initialization of various types of variables:
Reference Type: NULL
Basic Type:

  boolean : false  char:\u0000  byte: 0  short: 0  int: 0  long: 0  float: 0.0  double: 0.0 

6-3. array Initialization
When we generate an array of storage objects, we actually generate an array that stores references. After the array is created, each reference is automatically set as a special value. This value is expressed by the keyword null. When Java sees the null value, it regards this reference as "not pointing to any object ". Before using any reference, you must assign an object to it. If you use a reference and its value is null, an error will occur during the execution period.
Array initialization starts when space is allocated. Initialization rules are applied. The basic types are initialized according to the 6-2 rules, and all reference types are initialized to null.

6-4. All instance variables in Java are initialized by default. All method variables are initialized by the method itself, and the variables in the method must be initialized before they can be applied.

VII. constructor in Java

1. constructor cannot be inherited
2. Each class has at least one constructor, which is not defined by itself. The Compiler also assigns a default constructor without parameters.
3. the constructor of the subclass must call the constructor of the parent class. The constructor of the parent class must be called either explicitly or implicitly through Super; if no explicit call is made, the compiler automatically adds the implicit call of super () to the first line of the constructor of the subclass, at this time, the parent class must have constructors without parameters (if the parent class defines the constructor but has parameters, an error will be reported during compilation)
Example:

Class super1 {public int I = 0; Public super1 (string text) {I = 1 ;}} public class sub1 extends super1 {public sub1 (string text) {// super (text); I = 2; // the implicit superconstruction super1 () is undefined. Must explicitly cite another constructor} public static void main (string ARGs []) {sub1 sub2 = new sub1 ("hello"); system. Out. println (sub2. I );}}
8. Exception Handling in Java

1. exception in Java is a sub-run exception or non-runtime exception. The runtime exception is captured and processed by the runtime system (compilation is normal). Non-runtime exceptions must be handled (throw or captured)

2. Must catch be followed after try {} in the exception mechanism?
* Not necessarily, but it must be followed by finally. That is, catch and finally.
* Must catch be followed after try {} in the exception mechanism?
* Not necessarily, but it must be followed by finally. That is, catch and finally.
* Try {
*} Finally {}
* This is okay, and it doesn't make sense, because it ensures that the code in finally will be executed even if an exception occurs.
* Sometimes, this is very useful.
* For example, it can be used to release some resources occupied by the caller and then let the caller handle exceptions.
3. Finally in the exception will be executed. Even if a return statement exists in a method, it will be returned only after Exception Processing.
4. if an exception is thrown, the Child class can be first added to the parent class. If the child class is captured, the parent class will not be captured;
However, the parent class cannot be used as a subclass, which may cause compilation errors.
5. After exception handling, the program continues to execute
Instance:

/** If a non-runtime exception is thrown, either catch block capture or throw */import Java. io. ioexception; public class exceptiontest {// public static void methoda () {public static void methoda () throws ioexception {// throw new nullpointerexception (); // try {Throw new ioexception (); // system. out. println ("method exit"); //} catch (ioexception e) {}// finally {}} public static void main (string [] ARGs) {try {methoda (); // throw new ioexception ();} catch (ioexception e) {system. out. println ("caught1 ioexception");} catch (nullpointerexception e) {system. out. println ("caught1 nullpointerexception");} catch (exception e) {system. out. println ("caught exception");} system. out. println ("main exit ");}}

9. bitwise AND logical operations

Bitwise operators (&, |) must be calculated on both sides.
If the left side of the operator (&, |) is true, it is not on the right side of the calculation.

Instance:

public class test {    private static int j = 0;    private static boolean methodB(int k) {        j += k;        return true;    }    public static void methodA(int i) {        boolean b;        b = i < 10 | methodB(4);        b = i < 10 || methodB(8);    }    public static void main(String args[]) {        methodA(0);        System.out.println(j);    }}

What is the result?
A. The program prints "0"
B. The program prints "4"
C. The program prints "8"
D. The program prints "12"
E. The Code does not complete

10. For (;) Meaning

It is equivalent to while (true). I don't know why Java is going to create this strange and confusing thing?

11. Equals, =

Equals checks whether the content of two objects is equal.
= Compare whether two references point to the same object
The storage feature of string will have an impact on the above Judgment Rules (essentially the rules remain unchanged, and changes on the surface ):
Objects generated by string using the "" method are stored in the constant pool. A major feature of the constant pool is sharing, such as string S = "X "; before placing "X" in the constant pool, the JVM checks whether the constant pool has the same object as "X". if it already exists, it directly points the reference to an existing object, no space is allocated for "X". The advantage is that space is saved.

When to rewrite equals ()

When a class has its own unique concept of "logical equality" (different from the concept of object identity ).

2. design equals ()

[1] use the instanceof operator to check whether the real parameter is of the correct type ".

[2] for each "key field" in the class, check the field value in the real parameter and the corresponding field value in the current object.

[2.1] for non-float and double primitive type fields, use = for comparison;

[2.2] recursively calls the equals method for the object reference domain;

[2.3] for float domains, use float. floattointbits (afloat) to convert to int, and then use = for comparison;

[2.4] for double fields, convert double. doubletolongbits (Adouble) to int and then use = for comparison;

[2.5] For array fields, call the arrays. Equals method.

3. When you rewrite equals (), you always need to rewrite hashcode ()

According to the equals method of a class (after rewriting), two different instances may be logically equal. However, according to the object. hashcode method, they are only two objects. Therefore, the violation of "equal objects must have equal hash codes ".

4. Design hashcode ()

[1] store a non-zero constant value, such as 17, in the result of the int variable;

[2] for each key field F in an object (each field considered in the equals method ):

[2.1] boolean type, computing (F? 0: 1 );

[2.2] Byte, Char, short type, calculation (INT );

[2.3] long type, calculation (INT) (f ^ (F >>> 32 ));

[2.4] float type, computing float. floattointbits (afloat );

[2.5] Double type, calculate double. doubletolongbits (Adouble) to get a long value, and then execute [2.3];

[2.6] references an object and recursively calls its hashcode method;

[2.7] array field, which calls its hashcode method for each element.

[3] Save the hash code calculated above to int variable C, and then execute result = 37 * result + C;

[4] Return result.

12. Assign the initial sequence to the variable of the basic type

The byte range is-128 ~ 127
When we give an integer without the l sign, the compiler automatically treats it as an int type, such
Int I = 1; is true
When we give a decimal number without the f flag, the compiler automatically treats it as a double type, such
Double D = 1.0; is true

13. Conversion of Basic Types

Rules: small ones can be automatically converted to large ones. Large ones must be mandatory to be converted to small ones. For example:
Double D = 1.0f; // correct, small to large, automatic
Float F = 1.0d (or 1.0); // error, large to small, need to force float F = (float) 1.0d;

14. servlet Operating Mechanism

Servlet is a technology introduced by Java to process dynamic web pages in the B/S architecture. Its essence is a Java class that inherits httpservlet and is interpreted and run by the Web container, the Mechanism is as follows:
(First request)
The customer makes a request-> the Web Container parses the request to find the request URL, according to the Web. find the corresponding servlet in xml configuration-> load servlet-> instantiate-> call init initialization-> call service method-> automatically match doxxx method by service method-> disable Web Container/servlet Length if the time is not requested, call its destroy method to destroy the servlet instance.

Uncertain: how long will the servlet be destroyed before it is called? Can I set it? Different Web servers should be different.

15. Differences between Servlet and JSP

All technologies are used to process dynamic web pages. After JSP is compiled, it is converted to servlet. a jsp page is essentially a servlet. After JSP is requested for the first time, it is converted to Servlet and then compiled, so the first time is slower than Servlet
Servlet is embedded with HTML in Java code and is good at logic control.
JSP is embedded with Java code in HTML and is good at page processing.

16. Difference between forward and redirect

(Forward is a server-side request and a technology provided by Servlet. The server finds the requested page based on the request URL. For the browser, this process is not transparent, as if nothing happened, the address bar of the browser will not display the requested URL page address (which is still the URL address of the server side of the last request). From the HTTP perspective, only one request response process occurs
Redirect is a client request. The client sends a new request to the server based on the address returned by the server. The address bar of the browser displays the URL of the new request, two request responses occurred)
-------------------
1. redirection is a function defined by the HTTP protocol. It takes two HTTP Communication processes to obtain the actual address of the resource for the first time and send a request with the previous address for the second time, this process is visible to the browser;
Request Forwarding is a feature of Servlet technology. The forwarding process is performed inside the server and is not transparent to the browser. It considers that the address it sends actually gets the content; from the HTTP perspective, there is only one communication process

2. redirection can only be switched to new resources, with a single function. Request forwarding can not only switch to new resources, but also combine other resources with the content generated by itself.

17. Thread

16-1. Thread Synchronization
1. Concept of synchronization: when multiple threads use an object at the same time, the uncertainty of the thread itself may cause operation integrity. Therefore, synchronization is introduced.
2. There are two synchronous methods in Java: synchronized and lock.
3. when a thread enters the synchronization method of an object, it will lock the object and other threads cannot use the object (including any methods and attributes of the object ), this object is not available to other threads until the thread releases the lock.
4. Conditions for a thread to release the synchronization lock:
A. After running properly (exit the synchronized block)
B. Use the wait () method
5. synchronous method: Wait (), Y ()/notifyall (), used for thread communication in synchronization
Wait (): releases the synchronization lock and enters the lock wait state. Because multiple threads "operate simultaneously" in the thread, the operating conditions may not be met, when the conditions are not met, the thread itself needs to enter the waiting state (release the lock), and wait for other threads to change the conditions before it can continue to execute.
Yyall (): Wake up the lock wait thread. When an object holding the thread lock calls this method, other threads in the lock wait are awakened, however, the lock itself will not be immediately released. You need to wait until the running ends (exit the synchronized block) to release the lock, and other threads will have the opportunity to execute the lock.
16-2. Methods in the thread
6. Sleep (): The current thread slews at a set time, and enters the thread readiness queue after the time arrives, waiting for execution.
7. Join (). This method enables the thread that calls this method to complete execution before that, that is, wait until the thread that calls this method finishes execution before continuing execution. Note that this method also needs to capture exceptions.
Instance:

class A implements runable {    int i;    public void run() {        try {            thread.sleep(5000);            i = 10;        } catch (InterruptedException e) {        }    }}public class Test {    public static void main(string args[]) {        try {            A a = new A();            Thread t = new Thread(a);            t.start();            int j = a.i;        } catch (Exception e) {        }    }}

Which statement Al line 17 will ensure that J = 10 at line 19?
A. A. Wait ();
B. T. Wait ();
C. T. Join ();
D. T. Yield ();
E. T. Policy ();
F. A. 127y ();

G. T. Interrupt ();

8. yield () is similar to sleep (), but it cannot be specified by the user for how long to pause. Therefore, after a thread executes the yield () method, it may also be executed immediately (JVM is still assigned to it for execution). The yield () method can only give threads with the same priority a chance to execute.

For example:

// Example 1 synchronization class syncstack {// synchronization Stack class private int Index = 0; // the initial value of the stack pointer is 0 private char [] buffer = new char [6]; // The stack has 6 Characters in space: Public synchronized void push (char c) {// Add the mutex lock while (Index = buffer. length) {// the stack is full. Do not press the stack try {This. wait (); // wait until there is data output stack} catch (interruptedexception e) {}} this. Y (); // notify other threads to export data to the stack buffer [Index] = C; // data into the stack index ++; // pointer move up} public synchronized char POP () {// Add mutex lock while (INDE X = 0) {// The stack has no data and cannot output the stack try {This. wait (); // wait for other threads to put data into the stack} catch (interruptedexception e) {}} this. Y (); // notify other threads to go to the stack index--; // the pointer moves down the return buffer [Index]; // data output stack} class producer implements runnable {// producer class syncstack thestack; // The letters generated by the producer class are saved to the synchronized stack public producer (syncstack S) {thestack = s;} public void run () {char C; For (INT I = 0; I <20; I ++) {c = (char) (math. random () * 26 + 'A'); // generates a random value of 20 thestac characters. K. push (c); // Add characters to the stack system. out. println ("produced:" + C); // print the character try {thread. sleep (INT) (math. random () * 1000);/* sleep every time a thread generates a character */} catch (interruptedexception E) {}}} class Consumer implements runnable {// consumer class syncstack thestack; // The characters obtained by the consumer class are all from the synchronized stack public consumer (syncstack s) {thestack = s ;} public void run () {char C; For (INT I = 0; I <20; I ++) {c = thestack. pop (); // read the character system from the stack. out. println ("consume D: "+ C); // print the character try {thread. sleep (INT) (math. random () * 1000);} catch (interruptedexception e) {}}} public class synctest {public static void main (string ARGs []) {syncstack stack = new syncstack (); // The consumer class objects and producer class objects under the same synchronization stack object operate on the same runnable source = new producer (stack ); runnable sink = new consumer (stack); thread T1 = new thread (source); // thread instantiation thread t2 = new thread (sink); // thread instantiation t1.start (); // thread Start t2.start (); // thread start} // Example 2. The following code runs normally most of the time. Under what circumstances will the problem occur? Where is the root cause of the problem? Import Java. util. synchronized list; public class Stack {synchronized list = new synchronized list (); Public synchronized void push (Object X) {synchronized (list) {list. addlast (x); y () ;}} public synchronized object POP () throws exception {synchronized (list) {If (list. size () <= 0) {Wait ();} return list. removelast ();}}}

Analysis of Example 2 [user ]:
When a thread executes the following method:

public synchronized void push(Object x) {  synchronized(list) {      list.addLast( x );    notify();  }} 

At this time, he gets two locks, one is the lock of the stack object, and the lock of the list object, while notify releases the lock of the stack object and does not release the lock of the list object, so long as the size of the List detected in the pop method is 0, the thread executing the pop operation will keep controlling the list lock, making the push unable to be executed. The reason why the program runs successfully most of the time is that push is always faster than pop, and list is not 0.

// Example 3. thread public class synctest {public static void main (string [] ARGs) {final stringbuffer S1 = new stringbuffer (); Final stringbuffer S2 = new stringbuffer (); new thread () {public void run () {synchronized (S1) {s2.append ("A"); synchronized (S2) {s2.append ("B"); system. out. print (S1); system. out. print (S2 );}}}}. start (); New thread () {public void run () {synchronized (S2) {s2.append ("C"); synchronized (S1) {s1.append ("D "); system. out. print (S2); system. out. print (S1 );}}}}. start ();}}

Analysis of Example 3 [user]
If no deadlock occurs, the output result must be: "ababcd"; if this result is not output; then the deadlock occurs.
Cause: T1 is started first, T2 is started later, and step 1 of T1 is synchronized (S1)
1. because T1 execution is too slow ---> T2 needs to execute Step 1: synchronized (S2) ---> Search For S1, lock wait by T1 ---> T1 for S2, lock wait by T2; deadlock
2. T1 execution is too fast --> S1, S2 are locked ---> T2 execution, wait --> T1 execution: "AB" --> T2 execution: "ABCD"

18. Web Server

To put it bluntly, the web server provides the basic functions of Web applications:
1. It is a server program that complies with the HTTP protocol and provides basic request parsing and response processing according to HTTP.
2. It provides the most direct environment for web programs to run. For example, Tomcat is a servlet container.
3. It provides thread management, including creation, scheduling, and revocation.
4. It provides the corresponding processing between the request address and the specific address
...
B/S is a technology developed based on the C/S architecture. Compared with C/S, B/S has the following differences, in addition, whether it is superior or not is associated with a specific environment. You cannot tell which one is better,
1. B/S follows the HTTP protocol, that is, the standard protocol is used,
2. the B/S client has been developed (a browser that complies with the HTTP protocol) and does not need to be developed by programmers.
3. The server side of B/S also provides the implementation of basic functions (various web containers)

A c/s example (multithreading), hoping to better understand the Web server based on it
1. Client Program: multitalkclient. Java

Import Java. io. *; import java.net. *; public class multitalkclient {public static void main (string ARGs []) {try {Socket socket = new socket ("127.0.0.1", 4700 ); // send the customer request bufferedreader sin = new bufferedreader (New inputstreamreader (system. in); // The bufferedreader object printwriter OS = new printwriter (socket. getoutputstream (); // get the output stream from the socket object and construct the printwriter object bufferedreader is = new buffere Dreader (New inputstreamreader (socket. getinputstream (); // obtain the input stream from the socket object and construct the corresponding bufferedreader object string Readline; Readline = sin. readline (); // read a string from the system standard input while (! Readline. equals ("bye") {// If the string read from the standard input is "bye", the cyclic OS is stopped. println (Readline); // outputs the string read from the system standard input to the Server OS. flush (); // refresh the output stream so that the server immediately receives the string system. out. println ("client:" + Readline); // print the read string system on the system standard output. out. println ("server:" + is. readline (); // read a string from the server and print it to the standard output. Readline = sin. readline (); // read a string from the system standard input} // continue loop OS. close (); // close the socket output stream is. close (); // close socket input stream socket. close (); // close socket} catch (exception e) {system. out. println ("error" + E); // print the error message when an error occurs }}}

2. server-side program: multitalkserver. Java

Import Java. io. *; import java.net. *; import serverthread; public class multitalkserver {static int clientnum = 0; // static member variable, which records the number of current customers. Public static void main (string ARGs []) throws ioexception {serversocket = NULL; Boolean listening = true; try {serversocket = new serversocket (4700); // create a serversocket to listen to customer requests on port 4700} catch (ioexception E) {system. out. println ("cocould not listen on port: 4700. "); // error, print error information system. exit (-1); // exit} while (Listening) {// listens to new serverthread (serversocket. accept (), clientnum ). start (); // listen to the customer request, create a service thread Based on the socket object and customer count, and start the clientnum ++; // increase the customer count} serversocket. close (); // close serversocket }}

3. The program serverthread. Java

Import Java. io. *; import java.net. *; public class serverthread extends thread {Socket socket = NULL; // Save the socket object int clientnum related to this thread; // Save the customer count of this process public serverthread (socket Socket socket, int num) {// constructor this. socket = socket; // initialize the socket variable clientnum = num + 1; // initialize the clientnum variable} public void run () {// thread body try {string line; bufferedreader is = new bufferedreader (New inputstreamreader (socket. getinputstream ()));/ /Obtain the input stream from the socket object and construct the corresponding bufferedreader object printwriter OS = newprintwriter (socket. getoutputstream (); // obtain the output stream from the socket object and construct the printwriter object bufferedreader sin = new bufferedreader (New inputstreamreader (system. in); // The bufferedreader object system is constructed by the system standard input device. out. println ("client:" + clientnum + is. readline (); // print the string line = sin. readline (); // read a string from the standard input while (! Line. equals ("bye") {// If the string is "bye", the cyclic OS is stopped. println (line); // output the string OS to the client. flush (); // refresh the output stream so that the client immediately receives the string system. out. println ("server:" + line); // print the string system on the system standard output. out. println ("client:" + clientnum + is. readline (); // read a string from the client and print it to the standard output line = sin. readline (); // read a string from the system standard input} // continue loop OS. close (); // close the socket output stream is. close (); // close socket input stream socket. close (); // close socket server. close (); // close serversocket} catch (exception e) {system. out. println ("error:" + E); // error, print error message }}}

19. understanding of resource pools

1. Purpose (Benefit) of resource pool Introduction)
Improve Performance
2. Resource Pool Operation Mechanism
The resource pool manager provides a certain number of target resources. When a resource is requested, the resource pool is allocated to one resource, and the resource is marked as busy. The resources marked as busy cannot be allocated and used, after a resource is used up, the resource pool clears the busy mark of the resource to indicate that the resource can be used by the next request.
3. Common Parameters in the resource pool
1. Number of initial resources: the number of resources created at a time when the resource pool is started. The minimum number of resource pools must be guaranteed.
2. Maximum number of resources: When the requested resources exceed this number, wait
4. Common resource pools
1. Database Connection Pool
2. Request and response Object pool in the Web Container
3. Web Container Thread Pool

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.