4 Java Fundamentals

Source: Internet
Author: User
Tags array length assert exit in object object sql injection thread class try catch concurrentmodificationexception

4.1 Basic Concepts 4.1.1  Java language a bit 4.1.2      Java interpreted language      C + + compiled language 4.1.3 The main method can be the same name but the type cannot be repeated 4.1.5 static initialization order: The parent class static variable, the parent class static code block, the subclass static variable, the subclass static code block, the parent non-static variable, the parent class non-static code block, the parent class constructor, the subclass non-static variable, the subclass non-static code block, Subclass constructor Code does not need to load the scope public in 4.1.6 Java: can be accessed by all other classes protected: it can be accessed by itself, by subclasses, and by classes under the same package. Default: Can be accessed by itself and by classes in the same package. Private: can only be accessed by itself. 4.1.8      constructors cannot be overwritten 4.1.9      NULL interfaces are often used as identity interfaces 4.1.10 clone () o = (OBJ) super.clone ( 4.1.11 reflection mechanism Class c = class.forname ("ClassName"); ClassName name = (className) c.newinstance ();  a.method (); 4.1.12 Package4.1.13 using interfaces to achieve pointer-like functionality 4.2 Object-oriented technology 4.2.1 What is the difference between object-oriented and process-oriented      1. Different starting points      2. Different levels of logical relationships      3. Data processing methods and control procedures are different.      4. Analysis design and encoding conversion modes different 4.2.2 Object-oriented features     encapsulation, inheritance, polymorphism, abstraction 4.2.3 What are the advantages of object-oriented development     1. High development efficiency     2. Guaranteed software robustness     3. Guaranteed high maintainability of the software 4.2.6 polymorphic Implementation Mechanism     method overloads, method overrides 4.2.8 abstract class and interface    & nbsp; contains abstract methods, which are abstract class variables, the default static final type      interface means that a collection of methods has no method body 4.2.9 inner class static inner class (can be used directly without first implementing the outer Class), member inner class, local inner Class 4.2.10 get Parent class name     This.getclass (). Getsuperclass (). GetName () 4.2.11 This and super4.3 keywords 4.3.2 Brea, continue, return interrupt multilayer loop out:    Code     for ()           for ()                break out;4.3.3 final, finally, finalize    once the garbage collector is ready to release the space occupied by the object, first call its Finalize () method. What is the role of 4.3.4 assert     assert condition: error 4.3.5 static keyword 4.3.7 volatile every time it is used for the Chenyuan variable it modifies, it is taken from memory, not the cache 4.3.8 Instanceof is not an instance of a class (interface, abstract class, parent class) 4.3.9 strictfp decorated class or interface or method precise floating point 4.4 basic types and Operations 4.4.1 basic data type int, short, long, byte, float, double, Char, boolean4.4.2 immutable class 4.4.3 value passing and reference passing 4.4.4 conversion of different data types what are the rules for automatic conversion rules  
Type of operand 1 Type of operand 2 The converted Type
Long byte short char int Long
Int byte Short Char Int
Float byte short int char long Float
Double byte short int long char float Double
Casting rules
The type of the original operand Type of operand after conversion
Byte Char
Char byte Char
Short byte Char
Int byte Short Char
Long byte short char int
Float byte short char int long
Double byte short char int long double
4.4.7 Math class round plus 0.5 down rounding floor down rounding up Ceil rounding up 4.4.8 ++i and i++4.4.9 >> and >>> 4.4.10 char and string encoding Q Problem Java Unicode encoding char one character occupies two characters string English takes one byte, Chinese characters occupy two bytes4.5 strings and Arrays4.5.1 New String ("abc") creates one or two constant and heap areas to see if the previous constant area has an original "abc" string 4.5.2
    • = = Determines whether the two variable values are equal or not suitable for judging the base type or reference of the object
    • Equals Object object provides methods to determine whether content is equal
    • Hashcode convert Address to int
    public boolean equals (Object anobject) {    if (this==anobject) {         return True;    }    if (anObject instanceof String) {        string anotherstring = (string) anObject;         int n = value.length;        if (n = = anotherString.value.length) {            char v1[] = value;             char v2[] = anotherstring.value;             int i=0;             while (n--! =0) {                 if (V1[i]!=v2[i])        &nbsP;            return false;                 i++;             }             return true;        }    }     return false;} 4.5.3 
    • Character for a single string
    • String
      • Value is not variable
      • Can be directly assigned to initialize or constructor function class.
      • The StringBuffer method is called when the value is modified
      • Thread safety because value is immutable (constant)
    • StringBuffer (String buffer)
      • Variable Value
      • constructor-only initialization
      • Thread safety (synchronization with synchronized)
    • StringBuilder
      • Similar to StringBuffer
      • But thread is not secure
4.5.4 arrays are objects with attribute (length) and method (clone) callable 4.5.5 Array Declaration and initialization
    • Declaration type[] Arrayname or type arrayname[] (not recommended)
    • The array will have an initial value after it is created
    • Memory is not allocated after declaration
    • Arrayname = new Type[arraysize] How to allocate memory
    • Initialization method int[] A = new int[5] or int[] a = {1,2,3,4,5}
    • can also be written separately
      • Int[] A; A = new int[5];
      • Int[] A; A = new int[]{1,2,3,4,5};
    • Two-dimensional arrays
      • Can int[][] A = new int[2][]; Variable length in array
      • A[0] = new int[]{1,2,3};
      • A[1] = new Int[]{1};
4.5.6
    • Stringname.length () Gets the length of the string
    • Arrayname.length getting the array length
    • Size Calculates object sizes
4.6 Exception HandlingWhen is the 4.6.1 finally called?
    • Finally executes before the return method is executed
    • The finally return will overwrite the return inside the try or catch
    • The return value is stored in a location so finally can have an effect on the return value operation (can be used as a pointer)
      • When the return type is the base data type, there is no effect
      • When referencing a type (changing the value of the reference type is not changing the reference) there will be changes
    • Finally is not necessarily executed
      • An exception occurred before entering the try
      • Force exit in Try catch (System.exit (0))
4.6.2 Exception Handling principle
    • Exception occurs when the program runs at run time, and the JVM throws
    • The Java language treats exceptions as objects
    • There are two cases of violation of semantic rules
      • One is the semantic checking of the values in the Java class Library
      • The other is that developers extend this semantic check
    • Exception inheritance Diagram

4.6.3 the difference between runtime exceptions and common exceptions
    • Error
      • is a particularly serious error that occurred during operation
      • Will cause the program to terminate
      • is caused by a logical error.
      • Not recommended capture
      • Should resolve the error
    • Exception
      • Represents a recoverable error
      • The compiler can capture the
      • Two types of
        • Check for exception compiler forced capture
        • Runtime exception compiler does not force it to capture
    • Exception Handling Considerations
      • Catching an exception should capture the subclass before capturing the parent class
      • Throw an exception early
      • Custom exceptions can be customized according to actual requirements
      • Exception can be handled on processing, can not be processed on the throw
4.7 input/output stream4.7.1 implementation mechanism of Java IO stream
    • Two major classes of flow
      • BYTE stream (8 bit units) does not use the cache
        • InputStream (Input stream)
        • OutputStream (output stream)
      • Character stream (-bit) one-time readability multiple byte caching mechanism
        • Reader (Input stream)
        • Writer (output stream)
    • Read file FileInputStream ("Test.txt");
4.7.2 managing files and directory classes
Method Role
File (String pathname) Create a file object based on the path you developed
CreateNewFile () Returns False if the directory exists, otherwise wears a file or folder
Delete () Delete a file or folder
Isflie () Determines whether the object represents a file
Isdirectory () Determine if the object represents a folder
Listfiles () If folder, list all files
mkdir () Creates a directory based on the path specified by the current object
Exists () Determine if the file that the object object should exist
4.7.3 Java Socket
    • Network Seven layer structure
    • Sockets can be divided into two types
      • TCP connection-oriented socket communication protocol
      • UDP for non-connected socket communication protocol
4.7.4 Java NIO non-blocking IO 4.7.5 What is the way Java serialization implements persistence
    • Serialization of
      • Implementation of the Serializable interface using the method
      • Two features of serialization
        • If a class is serialized, its subclasses can also be serialized
        • static, transient (temporary data), cannot be serialized
      • When to serialize
        • The object needs to be sent over the network, or the state of the object needs to be persisted into the database or file.
        • Serialization enables deep replication, which is to copy reference objects.
    • External serialization
4.7.6 System.out.println () precautions
    • The output is a string
    • You need to define the ToString () method to output an object
4.8 Java platform and memory management4.8.1 Java Platform Independence language
    • Environment Order Java program, JRE/JVM, operating system, hardware
The principle mechanism of 4.8.3 JVM home in class file
    • Three-class loaders (System class loader, extension classloader, custom ClassLoader)
      • Bootstrap Loader-Responsible for home in the System class (Jre/lib/rt.jar Class)
      • Extclassloader-Responsible for loading the extension class (Jar/lib/ext/*.jar Class)
      • Appclassloader-Responsible for loading the application class (Classpath the specified directory or the class in the jar)
    • Loader first loaded by the upper loader, if not found down degraded
    • Loader loading steps
      • Loading. Locate the relative class file based on the lookup path, and then import.
      • Link. A link is divided into three small steps.
        • Check. Check the correctness of the class file to be loaded.
        • Get ready. Allocates memory space to static variables in the class.
        • Analytical. Converts a symbolic reference to a direct reference. (optional)
      • Initialization Perform initialization work on static variables and static blocks of code.
4.8.4 what is a GC
    • Garbage collection algorithm
      • Reference counting algorithm: When there is no reference, the JVM is not used because it cannot solve the problem of mutual references.
      • Tracing Recovery algorithm: Use object reference graph without referenced recycle.
      • Compression Reclamation algorithm: Moves the active object in the heap to the other end of the heap.
      • Replication Reclamation algorithm: divides the heap into identical extents, and copies the active object to another area when it is full.
      • According to the collection algorithm: Youth generation, old age, lasting generation.
    • System.GC () notifies garbage collection to run, but does not necessarily run garbage collection immediately.
4.8.5 If there is a memory leak in Java
    • Two scenarios for memory leaks
      • Heap requested memory not released (Java has been resolved)
      • The object is not being used but remains in memory.
    • Why a memory leak is thrown
      • Static collection classes, such as hsahmap and vectors. These are static containers that are as long as the life cycle and the program.
      • The various links are not closed.
      • Listener, there is no corresponding delete listener when deleting an object.
      • The scope of the variable is unreasonable.
      • A singleton mode may cause a memory leak.
3.8.6 What is the difference between heap and Stack in Java
    • Heap
      • Local base types and references to objects
    • Stack
      • Variables referenced by memory
      • Object includes variable references within the object (base type also exists in heap area)
4.9 containers4.9.1 what is the Java collections framework
    • Set Set
      • HashSet
      • TreeSet
    • List lists
      • LinkedList
      • ArrayList
      • Vector
    • Map
      • HashMap
      • TreeMap
      • Linkedhashmap using lists to maintain internal order
      • Weakhashmap
      • Identityhashmap
4.9.2 what is an iterator
    • No internal details are exposed
    • Precautions for use
      • Returns Iterator,next () by using the iterator () method to get the next.
      • Hasnext () to determine if there are new elements
      • Remove () removes the returned element
    • Single thread resolves concurrentmodificationexception exceptions, saves the elements that you want to delete into a collection, and then removes them all using the RemoveAll () method
    • multithreading resolves concurrentmodificationexception exceptions, using synchronized synchronization or Concurrenthashmap security containers.
    • The difference between iterator and Listiterator, iterator only forward traversal, applicable to modification; Listiterator can support both bidirectional and modified
What is the difference between 4.9.3 ArrayList, vector, and linkedlist?
    • are all scalable arrays
    • ArrayList, vector based on object[] Array
      • Vectors are expanded by default to twice times the original (you can set the extension method) Most methods use synchronization synchronization, thread safety
      • ArrayList default extension to 1.5 times times the original (no extension method) thread is unsafe
    • LinkedList with two-way list implementation, non-thread safe
What are the differences between 4.9.4 HashMap, HashTable, TreeMap and Weakhashmap?
    • HashMap non-thread safe, allow null for key value, use iterator traversal, default size is 11 increase by old*2+1
    • HashTable thread safe, disallow null for key value, use enumeration traversal, default size is 16 and must be 2 exponent
    • Weakhashmap and HashMap similar, weakhashmap use weak reference, when key is no longer external reference can be garbage?? Recovery.
    • HashMap for thread safety, Map m = Collections.synchronizedmap (New HashMap ());
4.9.5 Map Considerations
    • Key cannot be duplicated
What's the difference between 4.9.6 collection and collections?
    • Collection is a collection interface.
    • Collections is a wrapper class for collections. It provides a series of static methods to implement operations on various collections.
4.1 Multi-Threading4.10.1 What is multithreading
    • Program execution is the smallest unit (process is the basic unit of resource allocation)
    • The stack is independent and the others are shared
    • A process can have multiple threads
    • Four states of a thread: run, ready, suspend, and end.
    • New State (new), Ready State (Runnable), running State (Running), blocking state (Blocked), death status (Dead)
    • Multithreading Benefits:
      • Reduce program Response time
      • Less thread creation and switching overhead
      • Multi-CPU with multi-thread execution capability
      • Simplified program Structure
4.10.2 What is the difference between synchronous and asynchronous 4.10.3 how to implement multithreading
    • Inherit the thread class, overriding the run () method.
Thread myThread = new Thread () {public void run () {//do something}};mythread.start ();
    • Implement the Runnable interface and implement the run () method of the interface. Recommended
public class Testmain {public static void main (string[] args) {MyThread thread = new MyThread (); Thread t = new thread (thread); T.start ();}} Class MyThread implements Runnable{public void Run () {//do Something}}
    • Implement the callable interface, overriding the call () method.
      • Callable is more powerful than runnable.
      • Callable can return a value after the task has ended
      • The call () method in callable can throw an exception
      • At run time callable can get a future object.
public class Testmain {public static void main (string[] args) {Executorservice ThreadPool = executors.newsinglethreadexec Utor ();//start thread future<string> future = Threadpool.submit (New MyThread ()); try {System.out.println ("wating!"); System.out.println (Future.get ());//wait for thread to end return result set} catch (Exception e) {e.printstacktrace ();}}} Class MyThread implements callable<string> {public String call () throws Exception {System.out.println ("go"); Return "Hello World";}}
    • It is recommended to implement the Runnable interface method.
      • Using inherited thread also requires rewriting the run () method.
      • Abuse of inheritance is a bad habit.
    • You can inherit both the thread class and the Runnable interface, and you do not have to write the run () method, because the run () method is inherited from the thread class;
What is the difference between the 4.10.4 run () method and the Start () method
    • Start () begins a thread, calling the run () method asynchronously
    • Direct call to run () is considered a normal function call
4.10.5 Multi-thread synchronization implementation method
    • Synchronized keywords
      • Synchronized method
        • Public synchronized void Mutithreadaccess ()
      • Synchronized block
        • Synchronized (SyncObject) {
Access code for the SyncObject object}
    • Wait () and notify ()
      • Wait () stop scrambling for threads, freeing up resources
      • Notify () wakes the first thread in the wait queue
      • Notifyall () wakes up all the waiting threads
    • Lock
      • Lock () Gets the lock in a blocked way, if it is not acquired to wait, gets to return immediately.
      • Trylock () try, get to return True, no return false
      • Trylock (long timeout,timeunit unit) tried for some time
      • Lockinterruptibly () is similar to lock () but can be interrupted by another thread, and you receive an interruptedexception exception.
        • Demonstrate
What is the difference between the 4.10.6 sleep () method and the Wait () method
    • Sleep () not recommended
      • is a static method of thread,
      • Suspend execution give the execution opportunity to other threads, time to auto-wake,
      • Does not involve inter-threading communication
      • Do not release locks
      • can be placed anywhere
      • Exception must be caught
    • Wait ()
      • Is the method of object,
      • You can use Notify () to wake up or set time,
      • For thread communication
      • Release lock
      • Wait () can only be placed in a synchronous method or in a synchronization block
    • Yield () pauses the currently executing thread object and executes other threads. Let the higher priority thread run
    • The difference between yield () and sleep ()
      • Sleep () does not consider priority yield ()
      • Sleep () will not be executed within the time, yield () No time limit may be executed immediately
      • Sleep () throws a Interruptedexception exception.
      • Sleep () has better portability.
4.10.7 What are the methods for terminating threads
    • Not recommended
      • Stop () Frees resources
      • Suspend () does not release lock resources
    • Using the flag flag

    • Blocking with sleep emulation
What's the difference between 4.10.8 lock and synchronixed?
    • Use different synchronized you can download the method before or write a code block, and lock needs to be written in the start and end positions.
    • Performance is different, not intense case synchronized excellent, intense case lock better use.
    • Lock mechanism different lock need artificial open release, synchronixed not need.
    • Use cases
4.10.9 Daemon Process
    • The user process is finished and the daemon is finished.
    • The thread is set by Setdaemon (true) as the daemon thread.
What is the role of the 4.10.10 join () method
    • Join is a thread merge that implements synchronization and waits for the thread to end.
    • You can also add a parameter join (2000) to indicate a maximum wait of 2s.
4.11 Java Database Operations 4.11.1 How to access the database through JDBC
    • Steps
      • Load the JDBC drive, both the package
      • Load the JDBC driver, typically using reflection Class.forName (String drivename)
      • Establish database connection, get connection object, generally through drivermanager.getconnection (URL, username,passwd)
      • Establishes a statement object or PreparedStatement object.
      • Executes the SQL statement.
      • Accesses the result set ResultSet object.
      • Shut down
      • Case

4.11.2 how the JDBC handles transactions
    • End the transaction through commit () and rollback ().
    • Not autocommit can be set by Setautocommit (false)
    • Transaction ISOLATION LEVEL
      • The Transaction_none description does not support transactions.
      • Transaction_read_uncommitted indicates that a transaction can see changes in another transaction before committing. Such dirty reads, non-repeatable reads, and virtual reads are allowed.
      • Transaction_read_committed indicates that reading uncommitted data is not allowed. This level still allows non-repeatable reads and virtual reads to occur.
      • Transaction_repeatable_read indicates that the transaction guarantees the ability to read the same data again without failure, but the virtual read will still appear.
      • Transaction_serializable is the highest transaction level, which prevents dirty reads, non-repeatable reads, and virtual reads.
What is the role of 4.11.3 Class.forName ()
    • Loading classes into the JVM virtual machine
4.11.4 Statement, PreparedStatement and CallableStatement differences
    • The Statement is used to execute SQL statements without parameters.
    • PreparedStatement executes a parameter statement, precompiled, to prevent SQL injection.
    • CallableStatement provides an interface for calling stored procedures.
The difference between 4.11.5 getString () and GetObject ()
    • GetString () can occur when the data set is very large, because it is read to memory at once.
    • GetObject () is not read-once to memory.
4.11.6 JDBC Considerations
    • Connect first
    • Remember to close the connection
    • Create statement statements outside the loop
4.11.7 What is JDO
    • Java Data Data Objects
    • is a standardized API for storing objects of some kind of data warehousing.
4.11.8 the difference between JDBC and hibernate
    • Hibernate is the encapsulation of JDBC

4 Java Fundamentals

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.