Java Face question 03

Source: Internet
Author: User
Tags arithmetic operators finally block message queue semaphore static class thread class

1. Can a ". Java" source file contain more than one class (not an inner class)? What are the restrictions?
Can I include more than one class (not an inner class) in a ". Java" source file? What are the restrictions?
This is OK, a ". Java" source file can contain multiple classes, but only one public class is allowed, and the class name must match the file name.

Each compilation unit can have only one public class. This means that each compilation unit can have only one exposed interface, and this interface is represented by its public class.
You can add as many classes as you need to the file that provide accessibility package permissions. However, if there are two or more public classes in the compilation unit, the program will not know where to import, the compiler will error.


2, switch can function on a byte, can function on a long, can function on a string?

The expression in the switch statement can only be byte,short,char, int, and enum (enum), so when the expression is byte it is implicitly convertible to the int type, and the long byte is more than the int byte and cannot be implicitly converted to the int type. So the switch statement can be used on byte and not on long, and because of the introduction of new features in JDK7.0, the Witch statement can receive a string value, string can act on the switch statement

3, talk about final, finally, finalize the difference between the three.
1.final: If a class is final decorated, it means that the class cannot derive a new subclass and cannot be inherited as a parent class. Therefore, a class cannot be declared abstract and is declared final. Declares a variable or method to be final. Can guarantee that they will not be changed when they are in use. It can be initialized in two places: the first is where it is defined, that is, when the final variable is defined, and the second is in the constructor. These two places can only choose one of them, either at the time of definition, or give values in the constructor. A method that is declared final can only be used and cannot be overridden.

2.finally: In exception handling, provide a finally block to perform any cleanup operations. If an exception is thrown, then the matching catch is executed, and then the control enters the finally block, provided there is a finally block.

3.finalize:finalize is the method name, and Java technology allows the use of the Finalize () method to do the necessary cleanup before the garbage collector clears the object from memory. This method is called when the garbage collector confirms that an object is not referenced. It is defined in the object class, so all classes inherit it. The subclass override Finalize () method has collated system resources or performed other cleanup work. The Finalize () method is called on the object before the object is deleted by the garbage collector.


4, Math.Round (11.5) and Math.Round (-11.5) respectively equal how much?
The result of Math.Round (11.5) is that the result of 12,math.round (-11.5) is-11

5, talk about the difference between string, StringBuffer, StringBuilder.
01. Difference

The main performance difference between the string type and the StringBuffer type is that the string is an immutable object, so each time a change is made to the string type, it actually equals a new string object, and then points the pointer to the new string object. Therefore, it is best not to use string to change the content of the strings, because each generation of objects will have an impact on system performance, especially when there is no reference object in memory, the JVM's GC will start to work, the speed will be quite slow.

02. Execution Speed:

Comparison of the three in the speed of execution: stringbuilder>stringbuffer>string

03, the use of the scene:

A, if you want to manipulate a small amount of data with string

B, single-threaded operation string buffer operation of large amounts of data using StringBuilder

C, multi-threaded operation string buffer operation of large amounts of data using StringBuffer


6. Why not recommend logging when using System.out.println ().
I'm sure a lot of Java novices are very fond of using the System.out.println () method to print logs, and don't know if you'd like to do the same. However, in real project development, it is extremely not recommended to use the SYSTEM.OUT.PRINTLN () Method! If you use this method frequently in your company's projects, you are likely to be scolded.
Why would the System.out.println () method be so despised by everyone? After careful analysis, I found that this method is useless except for the convenience of use. Where is the convenience? In eclipse you only need to enter SYSO, and then press the code hint key, this method will automatically come out, I believe this is also a lot of Java novice love for it reasons. And where is that shortcoming? This is too much, such as the log printing is not controllable, printing time is not determined, cannot add filters, log no level discrimination ...
Listen to me, you probably don't want to use the System.out.println () method, so log put all the shortcomings mentioned above all done? Not all, but I think the log has done quite well. I'm going to show you the strength of the log and Logcat mates right now.
First of all, in Logcat you can easily add filters, and you can see all of our current filters in Figure 1.21.


7. What is the difference between a run-time exception and a common exception?
Java provides two main types of exceptions: Runtime exception and checked exception. The checked exception is the IO exception that we often encounter, and the SQL exception is the exception. For this exception, the JAVA compiler enforces that we must catch the exceptions that occur. So, in the face of such anomalies whether we like it or not, we can only write a lot of catch blocks to deal with possible exceptions.
But another exception: Runtime exception, also known as runtime exception, we can not handle. When such an exception occurs, it is always taken over by the virtual machine. For example: No one has ever dealt with a nullpointerexception exception, which is a run-time exception, and this exception is one of the most common exceptions.


8. What is the difference between thread.sleep () and object.wait ()?
1. The two methods come from different classes, namely, sleep comes from the thread class, and wait comes from the object class.

Sleep is the static class method of thread, who calls to sleep, even if the a line thread calls the sleep method of B, actually still a goes to sleep, to let the B thread sleep to call sleep in B's code.


2, the most important is that the sleep method does not release the lock, and the wait method frees the lock, so that other threads can use the synchronization control block or method.

Sleep does not sell system resources; Wait is the thread waiting for the pool to wait, to assign system resources, and other threads to consume the CPU. The general wait does not add a time limit, because if the wait thread runs out of resources, it is useless to wait for all threads in the Notify/notifyall wake-up waiting pool to be called by other threads before it enters the ready queue to wait for the OS to allocate system resources. Sleep (milliseconds) can be specified by time to wake it up automatically, if the time is less than the interrupt () force interrupt.

The role of Thread.Sleep (0) is "triggering the operating system to immediately re-compete with the CPU".


3, use range: Wait,notify and notifyall can only be used in synchronous control method or synchronization control block, and sleep can be used anywhere
Synchronized (x) {
X.notify ()
or wait ()
}


4. Sleep must catch exceptions, while wait,notify and notifyall do not need to catch exceptions


9. When a thread enters an synchronized method of an object, can other threads enter other synchronized methods and common methods of this object?
1. Whether the Synchronized keyword was added before other methods, if not added, it can.
2. If wait is called internally by this method, you can enter another synchronized method.
3. If all other methods add the Synchronized keyword and no wait is called internally, you cannot.

10, how to traverse HashMap.
public static void Main (string[] args) {
Map<string,string> map=new hashmap<string,string> ();
Map.put ("1", "value1");
Map.put ("2", "value2");
Map.put ("3", "Value3");
Map.put ("4", "Value4");

The first type: normal use, two times value
System.out.println ("\ n traverse key and value by Map.keyset");
For (String Key:map.keySet ())
{
System.out.println ("Key:" +key+ "Value:" +map.get (key));
}

The second Kind
System.out.println ("\ n map.entryset using iterator to traverse key and Value:");
Iterator Map1it=map.entryset (). Iterator ();
while (Map1it.hasnext ())
{
Map.entry<string, string> entry= (entry<string, string>) Map1it.next ();
System.out.println ("Key:" +entry.getkey () + "Value:" +entry.getvalue ());
}

The third type: recommended, especially when the capacity is large
System.out.println ("\ n traverse key and value through Map.entryset");
For (map.entry<string, string> entry:map.entrySet ())
{
System.out.println ("Key:" + entry.getkey () + "Value:" +entry.getvalue ());
}

Fourth type
System.out.println ("\ n map.values () iterates through all the value, but cannot traverse key");
For (String v:map.values ())
{
System.out.println ("The value is" +v);
}
}


11, set of elements can not be repeated, what method to distinguish whether or not to repeat it? Is it used = = or equals? What is the difference between them?
The difference between = = and Equals ()
= = is the memory address of the object to be judged, and the object referenced by S1==s2,s2 is the same as S1.
The Equals of the object class is also the memory address of the judgment object. The bottom is also used = =.
There are some classes that replicate equals () to determine the specific contents of this object
The elements in the set cannot be duplicated, and the repetition of the elements is judged using the Equals () method.
The Equals () and = = methods Determine whether the reference value points to the same object Equals () is overwritten in the class so that when the contents and type of the two detached objects match, the truth is returned


12. Write a method to calculate the Fibonacci sequence (1,1,2,3,5,8,... ) The value of the 100th item, the method parameter is the nth item,
The value of item 100th is 3736710778780434371

Method:
public long shu (int t) {
int d =t-3;
Long x=2;
Long Y=1;
for (int i=0;i<d;i++) {
Long r=x;
X=x+y;
Y=r;
}
return x;
}

@Test
public void Ku () {
Long u= Shu (100);
SYSTEM.OUT.PRINTLN (U);
}
}

13, talk about your understanding of the Java.math.BigDecimal class.

Java provides operation classes for large numbers (more than 16 significant bits), namely the Java.math.BinInteger class and the Java.math.BigDecimal class, for high-precision computations.
Where the BigInteger class is a processing class for large integers, and the BigDecimal class is a processing class for the size number.
The implementation of the BigDecimal class is used in the BigInteger class, and the difference is that the BigDecimal adds a decimal concept.
float and double can only be used for scientific calculations or engineering calculations; In business computing, the need for digital precision requires the use of the BigInteger class and the BigDecimal class, which supports the fixed-point number of any precision that can be used to accurately calculate currency values.
The BigDecimal class creates an object that cannot be mathematically calculated directly using the traditional + 、-、 *,/and arithmetic operators, but must call its corresponding method. The parameter of the method must also be an object of type BigDecimal.

The following methods are commonly used to construct BigDecimal objects:
BigDecimal BigDecimal (double D); Not allowed to use
BigDecimal BigDecimal (String s); Commonly used, recommended
Static BigDecimal valueOf (double D); Commonly used, recommended


which
1. The method of constructing a double parameter is not allowed to use the!!!! Because it can not accurately get the corresponding value;
2. The String construction method is fully predictable: writing new BigDecimal ("0.1") will create a BigDecimal, which is exactly equal to the expected 0.1; Therefore, it is generally advisable to use the String construction method first;
3. Static method ValueOf (double val) is implemented internally, and the double type is still converted to String type; This is usually the preferred method of converting a double (or float) to BigDecimal;

BigDecimal adouble =new BigDecimal (1.22);
System.out.println ("construct with a Double value:" + adouble);
Results: Construct with a doublevalue:1.2199999999999999733546474089962430298328399658203125

BigDecimal astring = new BigDecimal ("1.22");
System.out.println ("construct with a String value:" + astring);
Result: Construct with a String value:1.22

"Details: http://blog.csdn.net/jackiehff/article/details/8582449"

14. What are the ways to communicate between Java processes?
(1) Pipes: Pipelines can be used to communicate between affinity processes, allowing one process and another to communicate with a process that has a common ancestor to it.
(2) Named pipe (named pipe): Named pipe overcomes the limitation that the pipe has no name, in addition to having the function of the pipeline, it also allows the communication between unrelated processes.
(3) signal (Signal): signal is a more complex mode of communication, used to inform the receiving process of an event occurred, in addition to inter-process communication, the process can also send signals to the process itself.
(4) Message queue: Message Queuing is a linked table of messages, including POSIX Message Queuing system V Message Queuing.
(5) Shared memory: Allows multiple processes to access the same piece of memory space, is the fastest available IPC form. is designed for inefficient operation of other communication mechanisms.
(6) Memory mapping (mapped memories): Memory mapping allows any number of interprocess communication, and each process that uses the mechanism implements it by mapping a shared file to its own process address space.
(7) Semaphore (semaphore): primarily as a means of synchronization between processes and between different threads of the same process.
(8) Socket: A more general inter-process communication mechanism that can be used for inter-process communication between different machines.


15, CSS rules style= "padding:0 0 3px 3px Sets the number of elements within the padding.

Upper right Down left

padding:0px 1px 2px 3px on 0, right 0, Bottom 3, left 3

16. Tell the difference between the get and post methods of the HTTP request.
1, GET request, the requested data is appended to the URL, to split the URL and transfer data, multiple parameters with & connection. The encoding format of the URL is encoded in ASCII rather than Uniclde, meaning that all non-ASCII characters are encoded before being transmitted.

POST request: The POST request places the requested data in the package body of the HTTP request packet. The item=bandsaw above is the actual transfer data.

Therefore, the data for the GET request is exposed in the address bar, and the POST request does not.

2, the size of the transmitted data

In the HTTP specification, there is no limit to the length of the URL and the size of the data being transmitted. However, in the actual development process, for get, the specific browser and server to the length of the URL is limited. Therefore, when you use a GET request, the transfer data is limited by the URL length.

In the case of post, it is theoretically not restricted because it is not a URL, but in fact each server will have a limit on the size of the post submission data, and Apache and IIS have their own configuration

3. Security
The security of post is higher than get. The security here refers to real security, and unlike the security methods mentioned above, the security mentioned above is simply not modifying the server's data.
For example, in the sign-in operation, the user name and password will be exposed to the URL by a GET request, because the login page is likely to be cached by the browser and other people can view the browser's history.
This time the user name and password is easy to get someone else. In addition, data submitted by get requests may also cause Cross-site request Frogery attacks
17, the forward of the servlet and the redirect difference.
Redirect:
Response.sendredirect ("Address");
A. Page address display final page
B. Parameters cannot be passed backwards
C. Skip to the external site

Server forwarding:
Request.getrequestdispatcher ("Address"). Forward (request, response);
A. Page Address display request page
B. Parameters can be passed backwards
C. Cannot jump to external site

Redirect makes two requests, forwards only one request at a time
18. Write a JDBC Query code for Oracle data.
Connection conn = null;
ResultSet rs = null;
Load Driver
Clas sensitive word orname ("oracle.jdbc.OracleDriver");
Get Connected
conn = Drivermanager.getconnection (
"Jdbc:oracle:thin: @localhost: 1521:orcl",
"Scott",
"Tiger");
Statement stat = conn.createstatement ();
SQL statements
String sql = "SELECT * from EMP";
Execute statement to get result set
rs = stat.executequery (SQL);
Traversing result Sets
while (Rs.next ()) {
String name = rs.getstring ("name");
SYSTEM.OUT.PRINTLN (name);}
Close link
Conn.close ();

19. The benefits of PreparedStatement in JDBC compared to statement
I. Readability and maintainability of the code.
While replacing statement with PreparedStatement will make the code a few more lines, this code is both readable and maintainable.
are more than the direct use of statement code high grade;

Two. PreparedStatement the maximum possible performance improvement.
Each database will do its best to provide maximum performance optimizations for precompiled statements. Because precompiled statements are likely to be called repeatedly. So the statements are cached after the compiler compiles the DB compiler.
Then the next call, as long as the same precompiled statement will not need to compile,
As long as the parameters are passed directly into the compiled statement execution code (equivalent to a function, which is done without rewriting one), it will be executed.

Three. The most important point is a significant increase in security.
Use precompiled statements. Any content you pass in will not have any matching relationship with the original statement.
As long as you're using precompiled statements all the time, you don't have to worry about the incoming data (because it's only used for arguments, not compiling,
Then the arguments to the SQL-containing statement are not compiled again, leaving the SQL stitching security hole

20. Select the database you are familiar with and write the following SQL statements:
Set up Table library:
CREATE TABLE Library if not exists (

ID Int (TEN) NOT null primary key auto-increment comment "id",
Age Int (TEN) NOT null comment "ages",
Sex varchar () default "male" comment "gender",

) Charset=utf-8 default Engine=innodb;

Java Face question 03

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.