Java Learning Notes

Source: Internet
Author: User

Java Knowledge Module:
1. Basic knowledge, arrays, strings, regular expressions;
2. Classes and objects, interfaces, inheritance, polymorphism, abstract classes, inner classes, generics, Java Common class libraries.
3. exception handling; 4.IO; 5. event handling;
6. Multithreading; 7. Collection Class 8. network communication; 9.JDBC Operational database

First, Idea skills
1. Set the font size:
setting, Colors&font, editor, file-------Edit size sizes with Save As and font-with custom
Change the background color:
Colors&font, General-----text-----setting, editor, File----
2.alt+enter automatic import class;

Eclipse Tips
1.alt+/can be corrected quickly.
Enter Sysout, then press alt+/, and you can print.
Enter Main and press alt+/to display the main method directly.
2.ctrl+/Comment whole line
3. Debugging skills. Double-click the blue vertical bar to set breakpoints, F11 for debugging, F6 Single step, F8 stepping in.
4. Open a Java project with Eclipse: File->import->general->existing project into workspace-> (just select your project)


II. Classes and objects
1. A class is an abstract concept that describes an object of the same type, and an object is a concrete instance of the class.
2. Objects can be considered as wrappers for static attributes (member variables) and dynamic properties (methods).
3. When a class is created, it is the appearance and behavior of the object that describes that class. When you execute new to create an object, the data storage space is allocated and its methods are called by the outside world.
4. The name of the construction method must be exactly the same as the class name. The construction method does not return a value.
5. Initialization remember that the order of initialization is a static object and then a "non-static" object.
For static variables, static initialization blocks, variables, initialization blocks, constructors,
They are initialized sequentially (static variables, static initialization blocks) > (variables, initialization blocks) > constructors.
6. Stack memory: Some basic types of variables and object reference variables defined in the function are allocated in the function's stack memory.
Some of the basic types of variables and object reference variables defined in the function are allocated in the stack memory of the function.
Heap Memory: Heap memory is used to hold objects and arrays created by new.
7. The Get and set methods are used to ensure the closure and security of the program.
If you set the data directly to public, the data is likely to be confusing and impossible to maintain.
8. Generate random numbers 0 to 100
Random rand = new Random ();
int m = rand.nextint (100);
9. Input data from the keyboard example:
Scanner scanner=new Scanner (system.in); When the program is done here you will be asked to enter something from the keyboard if you type in and a number of numbers such as 150
int S=scanner.nextint (); With check function
10. Static Factory Method: The more popular specification is to name the static factory method valueof or getinstance.
Calendar cal=calendar.getinstance (Locale.china);
11. Modifier Range
Private: Only available in the current class; public: Fully exposed; protected: subclasses can access.
Static: When a property or method is decorated, it represents a class-wide public, equivalent to a global variable.
The 12.java has an automatic garbage collection mechanism.


Three, single case mode
Lazy Type: private static single single=null;
Lazy Type:
public Class A single {
private static single single=null;
Private single () {}
public static single getinstance () {
if (single==null) single=new single ();
return single;
}
}
Bad Han style: private static single single=new single ();
Bad Han style:
public class single{
private static single single=new single ();
Private single () {}
public static single getinstance () {
return single;
}
}

Four, generic type
1. Generics: Defines the type of the object in the collection at the same time as the collection is defined.
2. List <?>
List<?> so to define the words and list<object> is a meaning, so that you can avoid the time to take the value from the list when using the runtime exception occurs,
In addition to generics, after the definition, when adding elements to the list must be defined elements, or compile will be error, such as the definition of list<string> a=new arraylist<string> ();
In this case, a can only be added to the string, the other types are not added, the special role is to avoid runtime exceptions

V. Abstract class
1. When a class is declared abstract, it is called an abstraction class.
public abstract class leader{}
2. Abstract classes cannot be instantiated, and methods in abstract classes have only method names and no method bodies.
public abstract void Worker ();
3. Classes that contain abstract methods must be abstract classes.

Vi. Internal Classes
1. Each inner class can inherit itself from one (interface) implementation independently, so no matter whether the perimeter class has inherited an implementation or not, there is no effect on the inner class.
An anonymous inner class is an inner class without a name, and because there is no name, the anonymous inner class can only be used once, which is often used to simplify code writing.
But there is also a precondition for using anonymous inner classes: You must inherit from a parent class or implement an interface

Java reflection mechanism: through reflection, you can access the description of Java objects already loaded in the JVM in the program, and implement the ability to access, detect, and modify the information describing the Java object itself.
Class Clazz=object.getclass (); Get class objects representing classes
StringBuilder sb=new StringBuilder ();
Package Packagename=clazz.getpackage (); Gets the package name where the class resides
Method[] Methods=clazz.getdeclared
Methods (); Get method An array group
for (Method method:methods) {
String modifier=modifier.tostring (Method.getmodifiers ()); Get modifier
if (Modifier.contains ("public")) {Sb.append (method.togenericstring () + "\ n");}
}

Vii. inheritance
1. Inheritance is an indispensable component of all object-oriented languages, including the Java language.
When you create a class, you implicitly inherit from the Java standard to class object unless you explicitly indicate that you want to inherit from another class.
2. In order to inherit, the general rule is to designate all data members as private and all methods as public.
The 3.this keyword can only be used inside a method, representing a reference to the "object that called the method".
Super appears in subclasses that inherit from the parent class. Super must be placed in the first row of the class.
Super.xxx ();(xxx is the method name) meaning, directly accessing and calling methods in the parent class.
4. Combination: Simply place the object reference in the new one. An object of an existing class that is embedded in a new class is generally private.
5. The relationship of "is-a" is expressed by inheritance. The "has-a" relationship is expressed in combination.
If a class inherits from another class, then they are "is-a" relationships, and if another class is referenced in a member of a class, they are "has-a" relationships.

Viii. polymorphic
1. polymorphic, as the name implies, there are many forms of expression.
Dog jack=new Animal ();
2. There are two forms of polymorphism: overloading and rewriting.
A. Overloading (overload), a class can have two or more functions, called the same name and their parameters are different.
They are not related to each other, they are different functions, just maybe they function similarly, so just name it, increase readability.
B. Rewrite (override), which occurs in subclasses, where inheritance occurs. Inherit a class, you have the parent class all the way,
If you feel that the function of the method changes, then the function is re-implemented in the subclass. When this method is called again, the procedure in the subclass is executed.

Nine, interface
1.Java because multiple inheritance is not allowed, you can implement multiple interfaces if you want to implement the functionality of multiple classes.
2. One of the biggest differences between interfaces and abstract classes is that Java abstract classes can provide partial implementations of some methods, while Java interfaces are not.

Ten, array
1. Creation and initialization of arrays:
int month[]=new int[12]; int month[] is the declaration part, new int[] is allocated memory.
int Arr[]=new int[]{1,2,3,12,24};
The use of 2.length.
Int[] A=new int[10];int len=a.length;
This is the length property of the array
String str= "abc"; int len=str.length ();
This is the length method of string
3. Two-D array initialization, the number of rows can not be written, but the number of columns must be written.
4. The foreach usage of the array. for (int k:arr).
Int[] arr= {1,2,3,4,5};
for (int K:arr) System.out.println (k); The k here is the array element a[0],a[1] ....
Equivalent:
Int[] arr= {1,2,3,4,5};
for (int i=0; i<arr.length; i++)
{
int k = Arr[i];
System.out.println (k);
}
5. Sorting arrays, you can use the sort () method;
You can use the copyof () method to copy the array.
6.

Xi. string
The ToString method can be used to convert a 1.StringBuffer type to string.
The append is used to add strings to the StringBuffer object. Deletecharat deletes the character at the specified position.
Insert is used for inserting. Delete Deletes. The reverse is used to invert strings.
2.toString () is a method in the object class. All classes inherit from object, so all classes have the ToString () method, which can be overridden.
The ToString () method converts an object to a string type, and the converted algorithm depends on the type and actual needs.
3.split is used to divide the Chaizi character, which returns a zero-based array of characters that contains the specified number of substrings.
The 4.trim () method is used to remove spaces before and after the string.
5.indexOf (int ch) returns the index of the specified character at the first occurrence of this string.
6.setCharAt (int index, char ch): Modifies the character of the index value in the object to be the new character Ch.
7.toUpperCase (); Convert to uppercase. toLowerCase (), which becomes lowercase.
8. The comparison operator "= =" compares the memory location, not suitable for comparing strings;
The Equals () method compares the contents of a two string.
9.StringBuffer and StringBuilder difference: StringBuilder performance is good, time is low, stringbuffer thread safety, time consuming.
The difference between String and StringBuffer:
The string class provides strings that cannot be changed by numeric values. The string provided by this StringBuffer class can be modified.
You can use StringBuffer when you know that character data is going to change. Typically, you can use Stringbuffers to dynamically construct character data.

10.indexOf (char a)//Gets the index position of the specified character
LastIndexOf (char a)//Gets the last index position of the specified character
charAt (int index)//Gets the character of the index position
Both 11.CharSequence and string can be used to define a string, but the value of charsequence is a readable, writable sequence, and the value of string is a read-only sequence.
12.int i=integer.parseint (str); Convert a string to a corresponding number
13. When overriding Equals, you must override Hashcode.
The relationship between equals and Hashcode is as follows:
A, if two objects are the same, then their hashcode values must be the same;
b, if the hashcode of two objects are the same, it is not necessarily the same with the Eqauls method.

12, the regular expression;
1. In order to check whether the input data satisfies a certain format, you can use the matches method in the regular expression.
2. The qualifier for the regular expression, in the regular expression,//d{3} indicates that the number appears 3 times.
3.java.util.regex is a class library package that matches strings by using regular expression-ordered patterns.
It consists of two classes: pattern and matcher. Pattern a pattern is a pattern of expressions compiled by a regular expression.
Matcher a Matcher object is a state machine that matches a string to a matching pattern based on pattern objects.
First, a pattern instance is used to customize a compiled pattern of a similar regular expression using the same syntax as Perl.
Then a Matcher instance matches the string in the pattern control of the given pattern instance.
The pattern compile (String regex) indicates that the given regular expression is compiled and given to the pattern class.

13. Exception Handling
1.try {Possible error code block} catch (Exception e) {code to process};
Declaration of an object variable
In this way, if the code is correct, then the program runs straight down without a catch statement;
If the code is incorrect, the returned exception object and e are matched, and if the match succeeds, the exception handling code after it is processed. (If you use exception to declare E, because exception is the parent class for all exception objects, all of them are successful).
After the code has been processed, the exception is completely processed, and the program goes down from where it happened (from where the exception occurred or behind the catch). Validation using the program). Finally the program exits normally.
If an error is found in the try, which jumps out of the try to match the catch, then the statement after the try is not executed.
2.e.printstacktrace () Method: Print exception information at the command line where and why the error occurred in the program

14. Input/Output
1. Byte input stream: InputStream
BYTE output stream: OutputStream
File input stream: FileInputStream (provides only read methods for byte and byte arrays)
Create files: File File=new file ("E:/io operation");
method to obtain file information: File.getname (); Get file name
File.exists (); Determine if a file exists
Character Stream: Write,read
2. The byte stream itself does not use the buffer (memory) in the operation, it is directly manipulated by the file itself,
The character stream uses a buffer to manipulate the file through the buffer.
3. What is a stream? Flow has directionality, as to whether it is an input stream or an output stream is a relative concept, which is generally referenced by the program,
If the flow of data is program-to-device, we become the output stream, which we call the input stream.
4. File format, you can right click on the file, the properties, find the path. such as F:\\io operation \\fileStream.txt
When the 5.read () method reads to the end, the return value is-1.
6. Check if the file exists.
File File=new file ("D:\\mywork\\work.txt");
if (file.exists ()) {//
File.delete (); System.out.println ("file deleted");
} else {
try{
File.createnewfile (); System.out.println ("file created");
} catch (Exception e) {e.printstacktrace ()}

}
7. The byte array is placed in the file output stream for the data to be written. After the operation, remember to close the stream.
Also, when you do an IO operation, you add exception handling.
File File=new file ("F:/io operation", "FileStream.txt"); To create a file object
try {
FileOutputStream out=new fileoutputstream (file); Creating an output Stream object
System.out.println ("Please enter content:");
Scanner sc=new Scanner (system.in); Getting data from the keyboard
Byte Byte1[]=sc.nextline (). GetBytes (); Gets the byte. File stream and byte stream for IO operations "
Out.write (BYTE1); Writes a byte array to the file output stream.
Out.close (); Remember to close the stream.

FileInputStream in=new fileinputstream (file); Creating an input Stream object
Byte[] Byte2=new byte[1024];
int len =in.read (byte2); Gets the file length.
System.out.println ("The content in the destination file is:" +new String (Byte2,0,len)); Convert a byte array to a string
}catch (Exception e) {
E.printstacktrace ();
}
8. Examples of character streams:
public class Writedemo {
public static void Main (string[] args) {
File File=new file ("F:\\io operation", "Work.txt");
try{
Writer out=new FileWriter (file);
String str= "Hello World";
Out.write (str); Character streams can be written directly to a string without a byte array
Out.close (); A character stream exists in a buffer and must be closed.
}catch (IOException e) {
E.printstacktrace ();

}
}
}

XV, multithreading
There are two ways to implement multi-threading in 1.java, one is to inherit the thread class and one is to implement the Runnable interface; the thread class is defined in the Java.lang package.
A class that inherits the thread class to overwrite the run () method in this class can implement multithreaded operations, but only one parent class can inherit from a class, which is the limitation of this method.
2. The object "Mutex" guarantees the integrity of the shared data operation, and the "mutex" token guarantees that only one thread can access the object at any one time.
3. Keyword synchronized the mutex used for an object, when an object has a synchronized adornment, it indicates that the object can only be accessed by one pure pass at any one time. (Program Lock)
The difference between 4.Wait and sleep: Wait for other threads to access the locked object, while sleep does not allow other threads to access the locked object.
5.notify is used to wake the wait process. Thread.yield () pauses the currently executing thread object and executes other threads


16. Collection
Both 1.ArrayList and vectors use arrays to store data, find data fast and insert data slowly, LinkedList use a doubly linked list for storage, and insert faster.
2.List refers to the set .<> is generic, which specifies what data is stored in this set.
List<string> list=new arraylist<string> ();
<?> is a wildcard character,list<?> equivalent to List<object>.
The 3.Collection interface defines a method for accessing a set of objects whose sub-interfaces define how they are stored. Collection are the parent interface for various collection structures.
Set: unordered and non-repeating. List: Ordered and can be duplicated.
The ordering of the list is consistent in the order of the output collection data and in the order in which the collection data is entered.
Common methods of 4.List: Add (), remove (), iterator ().
Example code:
List<string> list=new linklist<string> ();
List.add ("a");  List.add ("B");         List.add ("C"); Adding elements to the collection
Iterator<string> Iterator=list.iterator (); To create an iterator for a collection
while (Iterator.hasnext ())//hasnext () indicates that there is a next one.
{System.out.println (Iterator.next ());} Iterating through the list with iterators
The elements in the 5.Map collection are stored by Key,value (key-value pairs).
To add elements to a map, you must use put ();
Map<string,string> map=new hashmap<string,string> ();
Map.put ("Key", "value"); To add a key-value pair
Map.Remove ("key");

Java Learning Notes

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.