Two years of Java programming experience

Source: Internet
Author: User

I have been studying Java for two years. I never dare to say how proficient I am, but I also want to talk about my feelings and write it to my colleagues at the Software Institute, this helps you avoid detours on the technical road. If I speak louder, I hope everyone will compete for the Software Institute. In fact, the most important thing is the improvement of everyone's own progress ??

1. What about the dynamic loading mechanism ??
Learning Java is easier to understand the idea of OOP than C ++. After all, C ++ has a lot of process-oriented components. Many people can back up the features of the Java language, the so-called dynamic loading mechanism, and so on. Of course, the concept is often first remembered and then digested. How many people have actually realized the dynamic loading mechanism and tried to find details? You can use the following methods:
When running a Java program in the command line window, add this useful parameter:

Java-verbose *. Class

This will clearly print the loaded class files, most of which are required for JDK's own operation. The last few lines will clearly see the order in which the class files used are loaded. Even if you declare a class object, it will not be loaded without instantiation. This means that the class will be loaded only when the class instance is actually used. In this case, do you understand a little bit about dynamic loading? Pai_^

2. How does one find a class file ??
It is recommended that you compile and run in the command line window at the beginning, instead of using jcreator, eclipse, and other ide To help with those tasks. Try to do this yourself:
Javac-classpath yourpath *. Java
Java-classpath yourpath *. Class
Many people may understand that the purpose of setting classpath is to tell the compiler where to find your class file. however, at least I understand the principle of JVM to query classes today. The compiler must load classes by classloader. The classloader has three levels, from high to low, which are bootclassloader (the name may be inaccurate ), extclassloader, appclassloader.

These three loaders correspond to the compiler to find the class file priority and different paths: bootclassloader corresponds to the JRE/classes path, which is the place where the compiler first looks for the class
Extclassloader corresponds to the JRE/lib/EXT path, which is the place where the compiler first looks for the class.
Appclassloader corresponds to the current path, so it is also the place where the compiler finds the class by default.

In fact, you can write a simple program for testing, for any class, such as,
Call New A (). getclass (). getclassloader (). tostring () to print it out. If you put the class file in a different path and execute it again, you will see the difference. Note that if it is printed as null, it indicates the highest level of bootclassloader, because it is written in C ++ and does not have the name of the Class Loader corresponding to Java.

The order of search is a kind of thought, that is, if this level cannot be found, it can only be found above this level, rather than looking down. However, it seems that the features from jdk1.4 to jdk1.6 have changed and no details are found. So we will not give an example. I would like to tell you that sun designed this system as a technology core Mr. Gong Li, a purebred Chinese! Pai_^

In this way, we hope that you will not be confused why class files cannot be found in the general error reports, whether written by yourself or imported third-party jar files (which often needs to be imported in J2EE ).

3. About JDK and JRE ??
You must choose whether to install a separate JRE when installing JDK. It is usually installed together. I also recommend that you do this. This helps you better understand the differences between them:

JRE is the Java Runtime Environment and the runtime environment of Java programs. Since it is running, of course it should contain JVM, that is, the familiar virtual machine, and all the class files of Java class libraries are packaged into jar in the lib directory. You can verify it by yourself. Which file is the virtual machine on windows? Anyone who has learned MFC knows what DLL files are. So let's see if there is a JVM. dll in JRE/bin/client? That is, virtual machines.

JDK is a Java development kit and a Java development kit that contains various class libraries and tools. Of course, it also includes another JRE. So why should we include another JRE? In addition, JDK/JRE/bin contains both the client and server folders and a JVM. dll. There are two virtual machines. I don't know if you have noticed this yet?

I believe everyone knows that JDK's bin contains the commands required by various Java programs. The most obvious difference with the bin directory of JRE is that javac is available under JDK, which is very understandable, because JRE is just a runtime environment. It has nothing to do with development. Because of this, JDK's own JRE with the development function will have a client JVM and a server JVM, in the JRE environment, only client JVM is required. DLL is enough.

Do you remember to set the JDK/bin path in the environment variable path? This should be the first step for everyone to learn java. The teacher will tell everyone that javac and Java will not be used if they are not set. The JDK/bin directory contains all the commands. But have you ever wondered whether the Java commands we use are not under the JDK/bin directory but under the JRE/bin directory? Do not believe that you can create an experiment. You can cut the java.exe file in the JDK/bindirectory to another place and run the Java program. What did you find? Everything is OK!

So someone will ask? I have not set the JRE/bin directory to the environment variable?

If Java is provided to most people, they don't need JDK for development, but they only need JRE to run the Java program, so every customer needs to manually set the environment variable. How troublesome is it? When jreinstallation is used, the installation program automatically adds jrejava.exe to the system variables. The verification method is very simple. You can see that the system environment variable path is prefixed with "% SystemRoot %/system32; % SystemRoot %, so let's go to Windows/system32 and see what we found? There is a java.exe.

If JDK/bin can be forcibly moved to the front of the System32 variable, of course, the Java in JDK/JRE can also be forced. However, unless necessary, I do not recommend that you do this. Using a separate JRE to run a Java program is also a test in the customer environment.

Now, we should be more clear about the connection and differences between JDK and JRE?

PS: In fact, I still have many feelings to sum up. I am afraid that everyone will throw bricks to death at a time, and I am so sorry. We should be more steadfast and more pragmatic in doing some research and sharing experiences with each other. The general direction and too-cutting technology discussions are necessary, but we 'd better not be too many. After all, we have not laid a solid foundation yet, talking about the latest version is actually a major obstacle to progress!

Java learning Miscellaneous (2)
In view of the feelings of the last write-back, We all encouraged our younger brother to continue writing, so it was hard to wait until the National Day Golden Week, and the internship finally had a rest phase, so we started to write the second article. I hope this writing will still be helpful to like-minded friends. Last, I talked about the Java Dynamic Loading Mechanism, classloader principle, and three questions about JDK and JRE. What are some specific class libraries ??

1. About the set framework class
I believe that those who have learned Java are familiar with this term and are certainly familiar with Java. util. * package. I don't know how to review or analyze a package when querying an API. The two most important parts of each package are interfaces and classes. The interface represents what it can do, the implementation class represents how it is implemented. Before paying attention to the Implementation class, we should first understand its source interface, whether in j2se or J2EE, it should be like this. First, let's look at these three interfaces: List, set, and map.
Some people may not be familiar with these three names, but I believe most people are familiar with the names of implementation classes such as arraylist, rule list, treeset, hashset, hashmap, and hashtable. The differences between them are easy to understand. You can put a set of repeated objects in the list, set a combination of non-repeated objects, and map a name-Value Pair such as <key, value>, key cannot be repeated, and value can. There are several confusing issues:

What is the difference between vector, arraylist, hashtable, and hashmap?
Many interviewers like to ask this question. In fact, they should be more professional and ask: what are the differences between the new collection framework and the old collection framework? For the new collection framework, you can find since jdk1.2 in these packages. Previous classes such as vector and hashtable are included in the old collection framework. What is the difference?
A. the naming of the new collection framework is more scientific and reasonable. For example, arraylist and rule list under List
B. All of the new collection frameworks are non-thread-safe. We recommend that you go to the source code contained in JDK and check the differences between vector and arraylist. Of course, after JDK, it would be a little ugly because the generic syntax is added, similar to the C ++ template syntax.

Have you ever wondered why you should lock all the old collection framework by default to prevent multi-thread access from being updated to cancel all the locks in the new collection framework? By default, multithreading is supported? (Of course, you can use the static method of collections to lock the thread when needed)
In my opinion, the development of any technology may not follow their original intention. Many major changes are influenced by the objective environment. Do you know why Java was originally developed? Is developed for embedded programs. Do you remember the classloader mechanism mentioned in the previous article? It is designed to save memory in the embedded development environment. Today, Java has become the language for the birth of the Internet. What does Internet mean? Multithreading is an inevitable trend. The objective environment is changing, and Java technology is also developing rapidly, which leads to an increasing departure from its original intention. It is said that sun is actually focusing on j2se, and the result is that due to objective environmental impact, j2se is almost forgotten. It is always focused on J2EE.

The technical details are not mentioned here. Only when used can we truly understand them. This is to help you understand the technologies you are learning and want to learn. We will discuss it later when talking about J2EE.
The IT giant was IBM a few decades ago, and the mainframe market was incomparable. How does Microsoft beat IBM? It is precisely because of the rapid development of hardware that the objective environment for personal PC needs makes Microsoft the second giant through OS. What about the next defeat of Microsoft? Google. How to do it? If Microsoft does not compete with IBM for a mainframe, Google uses the objective environment of rapid Internet development as a decisive factor to avoid competing with Microsoft for OS, but uses the search engine path, known as 3rd giants. So who are the 4th giants? Many experts predict that things will appear in Asia or China. Whatever and objective environment change trends are the key to determining the general direction. Of course, I also hope it will appear in China, ^ _ ^ ~~

2. Java Design Patterns
Many of them are looking at the 23 Design Patterns of gof. It seems that they have become a popular style to learn about gof at school or in the workplace. I don't want to list and explain the 23 design patterns. My original intention of writing these patterns is to talk about my own experiences and opinions, hoping to help you understand them.
First of all, I think the design pattern is only a general solution to a type of problem. As long as it is object-oriented programming predictions, these 23 kinds can be used. The best way to understand them is to write each method in person, even a simple application is enough. If the code implementation cannot be remembered, remembering the corresponding UML diagram will be a good way. Of course, the premise is that you must understand UML.
At the same time, it is best to use Java's own class libraries to help with memory, such as the commonly used observer mode, in Java. util. * There is a ready-made observer interface and Observable implementation class. If you look at the source code, it is sufficient to understand the observer mode. For example, in the decorator mode, you only need to write a few Java. Io. * programs to fully understand what the decorator mode is. Many people think that they should not be connected to design patterns when they get started. The famous java Design Patterns in beiling design series are written by Steven John metsker, I am also confused by most examples. However, I still don't agree that there is any conflict between getting started and learning design patterns, but we only need to know the concepts and typical applications of each pattern, in this way, when writing fileoutputstream, bufferedreader, and printwriter for the first time, we can feel that the original design pattern is so close to us, and it is not so mysterious.

In addition, while learning some patterns, it helps us better understand some characteristics of Java class libraries. For example, when you compile the prototype mode, you must understand the java. Lang. cloneable interface and the clone () method of the base class object of all classes. That is, the difference between deep copy and light copy:
Object. by default, clone () implements shortest copy, that is, copying an object copy. However, if the object contains references of other objects, it does not copy references, so the original object and the copy share the referenced object.
Deep copy, of course, involves copying all references of objects. In this way, both the original object and the copy object have a reference object. To implement deep copy, you must first implement the java. Lang. cloneable interface, and then rewrite the clone () method. Because the clone () method in the object is signed by protected, and the function of the cloneable interface is to enlarge protected to public so that clone () can be overwritten.

So there is another problem? What if the referenced object references another object? Is it very troublesome to keep judging and copying it? Some predecessors once told me that the method is to serialize the original object to the disk and then deserialize it when rewriting the clone method, so that a deep copy result can be obtained without judgment. If you do not know the serialization method, we suggest you take a look at objectoutputstream and objectinputstream.

In the final analysis, a pattern is just an ideological thing. It is actually nothing more than an experience summed up by our predecessors. We encourage you to write your own data, such as the proxy mode. You can simply write a Child class and an adult class. Child needs to buy anything and is implemented by adult proxy. In short, the buy () in adult actually calls the child buy (), but the main function is exposed to adult. Buy (). Such a simple program is enough to understand the basic meaning of the proxy mode.
Java Miscellaneous (3)
This is the third Java note I have written. I am glad that the first two articles have been supported and encouraged by Forum friends. I hope you can continue to correct the shortcomings. I have always been eager to use this method to find technical shortcomings and hope to improve it with my colleagues who are interested in Java.
The first two articles respectively describe self-understanding about JVM, JDK, JRE, collection, classloader, and some design pattern. We are still not prepared to start the transition to J2EE this time, because we think there are still some trivial j2se problems that have not been summarized.

1. Understanding about object classes
As we all know, object is the base class of all Java classes, meaning that all Java classes inherit the 11 methods of the object. We recommend that you check the source code of the 11 member functions of the object to see the default implementation method. For example, in the equals method, the default implementation is to use "=" to compare, that is, to directly compare the memory address, return true or false. The tostring () method returns the string composition method ??
"Getclass (). getname () +" @ "+ integer. tohexstring (hashcode ())"
In fact, you can understand the composition of this string without having to explain it too much. Next let's take a look at hashcode ():
Public native int hashcode ();

Because the native method is related to the OS processing method, there is only one declaration in the source code. If we are interested, we can fully explore how its hashcode is generated by the OS? However, I suggest that you remember to use the principles first! First, if the equals () method has the same hashcode for the same object, but the equals () object is not the same, it is not guaranteed that the hashcode () method returns different integers. In addition, when you run the same program next time, the same object may not be the original hashcode.
What about other methods? Nofigy (), policyall (), clone (), and wait () are all native methods, which indicate that they depend on the implementation of the operating system. The last interesting method is finalize (). Similar to the C ++ destructor, the signature is protected, which proves that the method can be used only after the inheritance extension, and the method body is empty, do nothing. It serves to notify the JVM that the object is no longer used and can be destroyed at any time. The actual destruction right lies in the virtual machine. So does it really do nothing? Not necessarily, in fact, if it is a thread object, it will lead to a higher priority of the thread within a certain range, leading to faster destruction to save memory and improve performance. In fact, from a common sense, we can probably guess the purpose of JVM practice.

2. Relationship between heavy load hashcode () and collection framework
I once heard from a senior who has been engaged in Java training for many years that in his opinion the hashcode method has no significance, just to prove that the same hashcode will lead to equal equals methods. Even some predecessors have made such a mistake, which means it is easy to be ignored. So what is the purpose of the hashcode () method?

After learning the Data Structure Course, You will know that there is a structure called hash table, which aims to improve the query efficiency by assigning a unique index to each object. Therefore, Java will not modify this concept at will, so the only function of hashcode is to support the hash table structure in the data structure. In other words, that is, the hashcode () method must be reloaded only when hashtable, hashmap, and hashset of the Collection framework are used,
In this way, we can control whether the indexes in the hash structure are equal. Here is an example:
In order to write a solution program, we need to randomly list different permutation and combinations composed of 1, 2, 3, and 4. Therefore, I wrote an array class to store the combination result with int, then, we add the randomly generated combination to a hashset, which is to take advantage of the characteristics that hashset does not include repeated elements. But how does a hashset determine whether it is a repeated element? The result returned by hashcode () is equal. You can perform this experiment:
Int [] A = {1, 2, 4 };
Int [] B = {1, 2, 4 };
System. Out. println (A. hashcode ());
System. Out. println (B. hashcode ());

This is clearly the same combination, but it is different hashcode. When you add a set, it will be treated as different objects. At this time, we need to rewrite the hashcode () method by ourselves. How can we write it? Actually, it is based on the original hashcode (). After all, it is the implementation of the operating system. There are many implementation methods to find the unique identifier of the same object. The implementation method is as follows:
First, override the tostring () method:
Return a [0] "+" a [1] "+" a [2] "+" a [3]; // intuitive display
Then use tostring () to calculate hashcode ():
Return this. tostring (). hashcode ();
In this way, both A and B will return "1234" in the test tostring (). hashcode (), because the string copies in the memory are the same, "1234 ". hashcode () must return the same result.

Speaking of this, I believe everyone can understand it better than me. Do not misunderstand the role of the hashcode () method in the future.

3. About the member functions of the class and the Java reflection mechanism
I have been familiar with Java for a long time and have heard many teachers talk about the dynamic runtime mechanism and reflection mechanism of Java. Indeed, they are all notable features of Java. I have introduced them in the first article during runtime loading. Now I want to talk about the reflection mechanism. In Java, the class and method class in the Java. lang package are used to implement the memory reflection mechanism.
People familiar with C ++ must know that the following cannot be done in C ++: When a class name is passed as a string parameter during runtime, all information of this class can be obtained, including all its methods and detailed information about the methods. You can also instantiate an object and call any method of the object by finding the method name. This is because the Java class in the memory contains a description of the class itself in addition to the static dynamic data zone in c ++, and through the information in this description, in order to help us read the content and get all the information of the target class, so as to implement the reflection mechanism. Have you ever thought about how to know the attributes of a JavaBean instance when we need it? A simple example is to write a an Parser:

A. Get the class object through class. forname ("Bean class name"), for example, abeanclass
B. Use the getmethods () method of abeanclass to obtain the method [] Object
C. According to the specification, all the words after the get method name represent an attribute of the bean.
D. if you already know a method name, you can call newinstance () to obtain an instance, and then pass the method name and parameters required by the method through the invoke () method, you can call this method dynamically.

Of course, there are more complex applications. We will not go into details here. You can refer to the class and method class methods.

4. Acknowledge the nature of synchronize
Synchronize everyone knows that synchronize means synchronization and locking. In fact, its nature is far less complex than everyone thinks. When the synchronize method is called, the lock actually loads the object. Of course, if it is a static class, the lock is applied to the class, and the call stop lock is released. Its implementation principle is very simple, just to prevent the second lock from being added to the same object or class again, that's all. A simple example is enough to illustrate the problem:
Class {
Synchronized void F (){}
Void g (){}
}

When an object A of A is called by the first thread for its F () method, the second thread cannot call the Synchronized Method of A, for example, F (), because it is trying to add a second lock to the object. However, calling g () is acceptable, because it is not produced by adding two locks to the same object.
So that everyone can understand? Understanding its principles can help you better design synchronization mechanisms and avoid misuse of locks.

PS: in the next article, I plan to summarize all aspects of J2EE and talk about my experiences and ideas. I hope you will continue to support the writing and correct the shortcomings.
 
 
Java Miscellaneous (4)

I have already written the fourth article without knowing it. Some friends on the Forum encouraged me to write it. Stick to your own style of work, tell all confusing and difficult-to-understand knowledge, and let everyone understand it. Then you will understand it. During my internship at the company recently, trainer told me a lot of classic stories. It is a great fortune for me who have not yet graduated. My belief is: people are growing at a far faster rate than they are in adversity. In this way, everything can be readily accepted.
Well, I will not talk about it. The third part is about the reflection mechanism Collection framework and so on. This time I want to talk about my understanding of deserialization and multithreading. Hope to help you learn Java ??

1. About serialization and deserialization
Everyone should probably know the meaning of serialization and deserialization in Java. serialization is to convert a Java object to binary for disk transmission or network stream transmission, deserialization means re-assembling the received binary stream into the original object inverse process. In Java, they are implemented through objectinputstream and objectoutstream (hereinafter referred to as OIS and OOS ).

The writeobject () method of OOS is used to execute the serialization process. The readobject () method of OIS is used to execute the deserialization process. Before transmitting the binary stream, the two high-level stream objects are connected to the same channel. The channel can be a disk file or a socket bottom layer. Therefore, no matter which method is used, the bottom flow object is transmitted to the OOS and OIS high-level streams in the form of constructor parameters. binary data transmission can be performed only after the connection is complete. Example:
It can be a file Channel
File = new file ("C:/data. dat ");
Oos = new objectoutputstream (New fileoutputstream (File ));
Ois = new objectinputstream (New fileinputstream (File ));

Or network stream channel
Oos = new objectoutputstream (socket. getoutputstream ());
Ois = new objectinputstream (socket. getinputstream ());

I wonder if you have noticed that OOS is always defined before Ois. Do you not want to misunderstand that the order is fixed? The answer is no. Are there any order requirements? The answer is yes. What is the principle?
The principle is that the output stream must be initialized before the input stream initialization. Otherwise, an exception is thrown. You will certainly ask why? You just need to take a look at the source code files of these two classes. The task of the output stream is very simple. You only need to convert the object to binary and write it into the channel, however, the input stream requires a lot of preparation to accept and ultimately reorganize the object. Therefore, the objectinputstream constructor needs to use the output header information to initialize the sent header. This method is called readstreamheader (), it will read two short values to determine the size of the cache to store the binary stream sent by the channel. The size of the cache varies with the JRE version. Therefore, if the output is not initialized first, the input constructor cannot run correctly first.

For the above two examples, the first order is strict, and the second is because the OOS and OIS are connected not to the other end, but to the stream at the other end of the socket, the output stream to be connected by another party must be opened before the input stream to run smoothly.

The writeobject and readobject are thread-safe, and concurrent access is not allowed during transmission. Therefore, objects can be continuously transmitted one by one. Many people may encounter eofexception during operation, and they may not be able to solve the problem and go to various forums to ask for solutions. In fact, I want to say that this exception does not have to be declared. That is to say, although it is an exception, it is actually a sign of the end of normal operation. EOF indicates that the final part of the file is read, and the natural connection will be disconnected after the sending ends. If this affects the correctness of your program, please calm down and look at the business logic of your program, rather than focusing on the method of sending and receiving. This is because I have been plagued by such bugs for a whole day, and many posts on the Forum have misunderstood the last lessons learned many times. If readobject is removed in the while loop, there is no problem in nature. If the object data is available, it will be read, and automatic blocking will occur if the object data is not available. Therefore, the eofexception must be thrown because the connection is disconnected and the read continues. What causes the connection to be disconnected? It must be an error in the business logic, such as nullpoint, classcaseexception, and arrayoutofbound. Even if the program is large, it doesn't matter. You only need to adjust it once to quickly discover and solve the bug.

No wonder a programmer said: 90% rely on experience to solve problems, 5% rely on technology, and 5% rely on luck! Jin yuliangyan: I have probably reviewed no less than 30 posts about using readobject to throw eofexceptionde IN THE while loop, everyone is blindly paying attention to interpreting this term, deserialization behavior, or opposing such writing, and no one thinks that EOF is a correct behavior. In fact, it is actually very honest in its work. Why do people ignore the real errors? Two words, experience!

2. multi-thread programming in Java
Some basic concepts can be known for Java threads that are beginner or not deeply touched, and at the same time, they will be confused about what the thread is like? If someone thinks they have understood it, answer the following questions:
A. A Object implements the runnable interface. Who is the so-called thread object after a. Start () runs? Is it?
B. When is the thread's wait () and notify () Methods used?
C. Why is the thread's suspend method outdated and not recommended for use? Can the thread be suspended?
D. in order to synchronize, we will declare synchronized to lock the thread method on the object. If the F () method of the parent class is added with synchronized, must the F () method be overwritten by the subclass with synchronized? If the F () method of the subclass declares synchronized and calls super. F (), how many locks are there on the subclass object? Will deadlock occur due to competition?

How many answers can you give me? If you can answer all these questions, the concept of the thread is still full and clear, although it is far from proficient. I will answer the questions one by one here. Due to space reasons, I would like to give a brief introduction as much as possible. If you have any questions, please join us.

First, thread and object are two different things, although we often say thread objects. But after you start a thread using run () and start (), the thread actually has nothing to do with the object that inherits the thread or implements runnable, objects can only be counted as available resources in the memory, while objects can only be counted as code segments that can be executed in the memory body area. Since resources and code segments can be accessed by another thread, the main function will start at least two threads. One is called the main thread and the other is the garbage collector thread, when the main thread ends, the program ends. The Garbage Collector thread may be working.

Second, wait () and sleep () are similar in that they are used to suspend the thread for a period of time. The difference is that wait will release all the locks occupied by the current thread, but not sleep. We know that the only way to obtain the lock is to enter the synchronized protection code segment, so we will find that wait only appears in the synchronized method, and the direct write will give a warning that the lock of the current object is not obtained. Therefore, notify is used with wait, and notify will re-return the lock to the blocked thread for re-execution. When multiple objects are wait, notify cannot determine which one to wake up, only one lock is required. Therefore, policyall () is generally used to allow them to compete for the only lock based on their priorities. Other threads only need to continue wait.

Previously, Java allowed the thread to be suspended outside of a thread, that is, the suspend method is called. This operation is extremely insecure. According to the object-oriented thinking, each object must be responsible for its own behavior, and encapsulate its own power. If any external step object can cause a thread to be suspended and blocked, the program will often crash due to confusion, so this method will naturally be destroyed.

The last question is interesting. The first answer is that the subclass rewrite F () method can be added with synchronized or not. If so, super is also called internally. F () should be used to add two locks to the same object in theory, because each call to the synchronized method requires one, and the F that calls the subclass adds one first, add another pair of F for calling the parent class inside the method. Isn't it mutex for adding two? Then, do I have to wait forever for the lock to be released and cause a deadlock when the parent class F is locked? Actually, this mechanism is called Re-entry. When the F method of the parent class tries to add a lock to this object, because the current thread has the Lock of this object, it can also be understood as the key to enable it. Therefore, adding a second lock before the same thread is released on the same object will not cause problems. In fact, this lock is not added at all, it has a key, no matter how many or can enter the lock protection code segment, unblocked, so that re-entry, we can simply think that the second lock is not added.

All in all, the essence of synchronized is to prevent other threads from adding a lock to the same object.
######################################## ######################################## #########################
Java Miscellaneous (5)

Originally, j2se was expected to end with only the fourth article, but the moderator likes to stick the post for a long time so that everyone can browse and make the younger brother feel more responsible, and be sure to pursue the best and better, therefore, I decided to write a few more articles about some of the commonly used experiences for discussion and discussion. This article will introduce the XML parsing package and Java swing, and then the next article will introduce Java. the security package is about the Java sandbox security mechanism and RMI mechanism, and then enters the J2EE part. This plan is made for the moment. If the update is a little slow due to busy internships, I hope you will forgive me!

1. parse XML in Java
I believe everyone is familiar with XML, meaning a scalable markup language. It is also a data carrier that appears in a tree. Later, the data gradually becomes information, the difference is that information can include variable states, so that the practice of hard encoding for the program is changed to hard encoding for the unified interface, and the variable state is stored as information in XML. In this way, the only task to implement scaling by changing the state is to add a piece of text information to the XML, and the Code does not need to be modified or re-compiled. This flexibility was unexpected when XML was born.

Of course, if the interface needs to be able to extract the information configured in XML, the program needs to be able to parse the standard XML file. in Java, of course, we need to improve the support for this behavior. The two packages I intend to talk about are org. W3C. Dom and javax. xml. parsers and. (You can browse the interfaces and class definitions in these packages)

The javax. xml. parsers package is simple and has no interfaces. The two factories have two Resolvers. Obviously, there are two ways to parse XML: Dom parsing and sax parsing. In essence, no one is good or not, but the idea of implementation is different. Example of an XML file:
<? XML version = "1.0" encoding = "UTF-8">
<Root>
<Child name = "kitty">
A cat
</Child>
</Root>

The idea of Dom Parsing is to store the entire tree chart into the memory. You only need to search for the node on the tree to read its attributes and content, the advantage is that all nodes can be repeatedly searched and used in the memory. The disadvantage is that the corresponding memory space needs to be consumed.

The idea of natural sax Parsing is to overcome the disadvantages of Dom. Based on the basic idea of event triggering, we searched down in sequence and encountered what events were triggered before the element and what actions were taken afterwards. Because you need to write the processing scheme to trigger the event, you need to use another Custom Handler in the org. xml. Sax. helpers package. Its advantage is of course that it does not need to read the entire package into the memory. The disadvantage is that it can only be searched in sequence, and it has to be repeated after it is completed.

You can easily guess which J2EE framework is used, obviously Dom. Similar to struts, The Hibernate framework configuration file is a small part of configuration information after all, and needs to be searched frequently to read, of course, the DOM method will be used (in fact, the DOM structure is used internally to store node information ). No matter what framework is used, it is really difficult to find the technology to parse XML using sax. If anyone knows, please let me learn.

Now that the resolution method is available, a storage location for resolution is required. I don't know if you have found that the org. W3C. Dom package does not implement all classes with interfaces. Here I want to talk about how Java parses XML, which is the responsibility of JDK. The W3C organization maintains and defines XML standards. Therefore, the W3C determines what an XML structure is like and does not care how Java implements it, this defines the rules that should be followed by all XML storage structures. This is Org. w3C. the purpose of all interfaces in the Dom. In my opinion, a simple understanding of interfaces is the principle that implementers must abide.

The structure of the entire XML file is called document, the child element is called element, and node, nodelist, text, entity, characterdata, cdatasection, and other interfaces related to nodes are also called, they can all find the corresponding meaning in the middle of the XML syntax. Because the basic XML syntax is not explained here, we will not introduce it much. If you are interested, I can also write a special post on XML syntax rules to share with you.

2. Java swing
Swing is a love-and-hate thing. The cute thing is that it is easier to get started. It is more powerful than AWT, the hateful thing is that the complicated interface compilation workload is huge. I have written over 3000 lines of swing interfaces, and I feel that the user experience is not so good. More than 6000 lines have been written recently. As there are more functional modules, the overall effect is just as general. The most profound word is: tired! As a result, swing is not widely used in real-world projects, and too many interface technologies can replace it. I was forced to write this article, but no one wrote it in the helpless group. Who did not enter the region?

Although swing is slowly being ignored, especially as B/S is slowly drowning C/S, I am very willing to stand out as swing. The knowledge of each technology is by no means a follow-up of fashion. Those who really like Java should have a good understanding of swing. I believe many students are learning about it. Most of the university teachers who have come from JDK 1.1 and 1.2 may be the least familiar with it.
Swing provides a set of light components collectively referred to as jcomponent. The biggest difference between them and AWT components is that jcomponent is all container, which is characterized by the ability to load other components. Any other components can be loaded in swing components, such as jbutton, jlabel, jpanel, and jlist. The advantage is that programmers can "redevelop" Swing components and build their own buttons, labels, artboards, lists, and other specific components based on specific requirements.

What is the difference between light components and heavy components? The forms shown by heavy components vary with operating systems. The light components are provided by swing's own GUI to maximize consistency across platforms.
So what should I pay attention to during programming? I will talk about some of my experiences:

A. it is a clear concept that only the frame component can be displayed separately. Some people may say that the static method in joptionpane implements the appearance of a separate window, however, if you search for the source code, you will find that the actual dialog also needs to rely on a frame form. If you do not specify it, a dialog will be generated by default and then loaded to display it.

B. jframe is composed of the following parts:
The bottom layer of jrootpane consists of glasspane (A jpanel) and layeredpane (A jlayeredpane), while layeredpane consists of contentpane (A jpanel) and menubar. All our components are added to contentpane, while the background image can only be added to layeredpane. Glasspane is a transparent layer that covers contentpane and will be used to record mouse coordinates or hide components in a specific effect.

C. To enhance the user experience, we will add shortcut keys on some buttons. However, in swing, only the Alt key of the keyboard can be recognized. To add other shortcut keys, you must implement an actionlistener by yourself.

D. setlayout (null) allows all components to precisely locate their respective sizes and positions using the four parameters of setbounds (), but it is not recommended to use it, because a good programming style should not be hard-coded with specific numbers in swing code, all numbers should be stored in a static, non-instance resource file in the form of constants. This static no-instance class is responsible for the swing interface style, including fonts and colors.

E. A good interface design has a golden rule: you can learn to use the software without using any manual. Therefore, try to present the buttons in the menu form (either right-click menu or the top menu of the form) to the customer, unless the button is frequently clicked, it is necessary to directly present the button in the interface.

In fact, swing is quite powerful, but it is not widely used now. It may take a lot of time to study it. The author browsed articles on Swing skills on various forums on various websites, but he learned a lot from them. His understanding of swing components is a process of practice accumulation. I have only used the above, so I can only talk about some ideas. I hope you will forgive me!
 
 

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.