preface

This article is from an article of Baidu network, because there is no answer, now I have sorted out some better answers and good blog, you can expand your thinking, if you have a better answer to the questions below, welcome to leave a message in the comment area. All from the Internet! In addition, my wechat public account will share the following interview questions related knowledge points summary every day, welcome to pay attention to wechat public account: learn Java well!

The article recommended

  • Select a full set of learning resources such as Java
  • Selected Java e-book resources
  • Select big data learning resources
  • Java project exercises selected

The basic concept

The difference between heap and stack in the operating system

Heap: Heap space is usually allocated by programmers and can be reclaimed by garbage collection mechanisms. Usually used to store objects and arrays created by new. Stack: A stack is a “last in, first out” storage space, generally used to store basic types of data and object references.

2. What is annotation-based aspect implementation

AOP, implemented in an annotated manner, allows you to insert code (such as logging code) before or after the execution of a method.

3. What is the object/relational mapping integration module

Object/Relational mapping (ORM) : The automatic persistence of objects in a program to a relational database

4. What is Reflection in Java

Reflection: The ability of a program to access or modify its own state and methods at run time.

5. What is ACID

A: Atom C: consistency I: Isolation D: Durability

6. The connection and difference between BS and CS

Client/Server (C/S) : indicates the Client application to be installed. B/S (Brower/Server) : an application that can be accessed directly by a browser.

7. The difference between cookies and sessions

Cookie: Data is stored locally in the browser and sent to the server with each request. Session: Saves user data on the server.

8. What is the difference between fail-fast and Fail-safe

Fail fail – fast (quick) : fast failure mechanism in traverse a collection, if the collection content has been changed, and will throw ConcurrentModificationException. Fail-safe: Any changes made to the collection by the security failure mechanism will be made on a replicated collection, so no exceptions will be thrown.

9. Differences between GET and POST requests

Get: 1. Request parameters are appended to the URL. Multiple parameters are concatenated with &. 2. Due to the length limitation of URL, the size of data transmitted in GET mode is limited. 3. Low security because the transferred data is displayed in the requested URL. Post: 1. Place the request parameters in the HTTP packet and send it to the server. 2. Large amount of data to be transmitted 3. High security

10, The difference between Interface and abstract class

1. Interfaces need to be implemented and abstract classes need to be inherited. 2. A class can implement multiple interfaces, but a class can inherit only one abstract class. 3, interface methods are all abstract, abstract class can have non-abstract methods.

11. What are the advantages of IoC

The advantage of IoC (inversion of control) is that when we need to use an object, we don’t need to create it ourselves. We can just grab an object from the IoC container and use it.

The difference between IO and NIO, NIO’s advantages

IO is stream-oriented, NIO is buffer-oriented. IO is blocking, NIO is non-blocking. NIO has a selector mechanism that allows a single thread to monitor multiple IO channels. NIO’s advantages: 1. You can process file content without using read() or write(). 2. NIO’s processing efficiency is fast.

13. What new features does Java 8 / Java 7 offer us

New features in Java7:

List\ tempList = new ArrayList<>(); Java8 allows us to add a non-abstract method implementation to an interface using the default keyword. Lambda expressions

14. What are race conditions? Let me give you an example.

When two threads compete for the same resource, a race condition is said to exist if the order in which the resources are accessed is sensitive.

What are the differences between JRE, JDK, JVM and JIT

JVM (Java Virtual Machine) : The JVM processes bytecode files, making the Java language cross-platform. JRE (Java Runtime Environment) : THE JRE is a superset of the JVM. JDK (Java Development Toolkit) : The JDK contains the JRE and Java development environment. JIT (Just-in-time Compiler) : A just-in-time compiler is a special compiler that improves the efficiency of the JVM by turning bytecode into machine code.

16. What technologies are used to implement various parts of MVC? How to do that?

Model layer: This can be implemented using plain Javabeans. View layer: can be implemented with JSP or JS. Controller layer: Can be implemented using Struts2 or Spring MVC.

17. Difference between RPC communication and RMI

Remote Procedure Call (RPC). Remote Method Invocation (RMI). The essence of both is to invoke remote services, but RPC is implemented in a procedural language such as C, while RMI is implemented in an object-oriented language such as Java.

What is a Web Service?

A Web Service is a resource that calls another Web site over the network.

19. Introduction of JSWDL development package. JAXP, JAXM interpretation. SOAP, UDDI, WSDL interpretation.

JAXP :(Java API for XML Parsing) defines a generic interface to use DOM, SAX, and XSLT in Java. This way you can just use these generic interfaces in your programs, and you don’t have to change the code when you need to change the implementation. JAXM (Java API for XML Messaging) is an API that provides access methods and transport mechanisms for SOAP communication. SOAP: Simple Object Access Protocol, a lightweight Protocol for exchanging XML-encoded information. UDDI: THE purpose of UDDI is to establish standards for e-business; UDDI is a set of web-based, distributed, information registry standards for Web services, and also contains a set of access protocol standards that enable enterprises to register their own Web services so that other enterprises can discover them. WSDL: Is an XML format for describing a network service as a set of endpoints that operate on messages containing either document-oriented or process-oriented information. This format first abstracts operations and messages, then binds them to concrete network protocols and message formats to define endpoints. The associated concrete endpoints are then combined into abstract endpoints (services).

What are the main functions of the WEB container? List some common WEB container names.

WEB container features: communication support, managing the life cycle of servlets, multithreading support, JSP support (translation of JSP to Java) Common WEB containers: Tomcat, WebLogic, WebSphere

21. Can a.java source file contain multiple classes (not inner classes)? What are the restrictions

Yes, a “. Java “source file can contain multiple classes, but only one public class is allowed, and the class name must match the file name.

22. Tell me briefly what you know about classloaders. Whether a class loader has ever been implemented

The class loader is responsible for loading the bytecode of Java classes into the Java Virtual machine. Implementing your own ClassLoader typically requires inheriting java.lang.ClassLoader and overwriting the findClass(String Name) method.

Explain what AOP is (aspect oriented programming)

AOP (Aspect Oriented Programming) uses a technique called “crosscutting” to rip open the interior of an enveloped object and encapsulate the common behavior that affects multiple classes into a reusable module named “Aspect”, or Aspect. The so-called “section” is simply to encapsulate the logic that has nothing to do with business, but is called by business modules together, which is convenient to reduce the repeated code of the system, reduce the coupling degree between modules, and is conducive to future operability and maintainability.

24. Briefly describe the life cycle of servlets and related methods

(1) Instantiation stage: the server instantiates the Servlet and calls the constructor of the Servlet. (2) Initialization stage: the server calls the init method of the Servlet to initialize it (only on the first request). ③ Request processing stage: the server invokes the service method of the Servlet, and then invokes the corresponding doXXX method according to the request mode. ④ Service termination phase: The server calls the destroy method of the Servlet to destroy the Servlet instance

25. Briefly explain how Ajax works and how to implement it

Ajax, also known as Asynchronous Javascript And XML, allows web pages to be updated asynchronously by exchanging small amounts of data in the background with the server. This means that part of a web page can be updated without reloading the entire page. Principle: HTTP protocol asynchronous communication steps: 1, create an XMLHttpRequest object 2, call the object’s open method 3, set the callback function

26. Briefly describe the main functions of Struts

1, retrieve content, forms and organize generated parameters object 2, according to the request of forwarding the request to the appropriate controller 3, business interface in the controller calls 4, will return to the results of the business interface packing up and sent to the specified view, and by the view to complete the processing results show 5, the internationalization of calibration or do some simple job

27. What is n-tier architecture

N-layer architecture is a hierarchical structure of software abstraction, which is a vertical segmentation of complex software. Each layer completes the same type of operation, so that various codes can be divided according to their mission to reduce the complexity of software and improve its maintainability. Generally speaking, there is downward dependence between layers. The upper layer code cannot be developed until the interface of the lower layer code is determined. The change of the interface of the lower layer code will make the upper layer code change together.

28. What is CORBA? What is it for?

CORBA (Common Object Request Broker Architecture) is a standard Object oriented application system specification developed by OMG. Purpose: 1. Access distributed information and resources from existing desktop applications; 2. Make existing business data and systems available network resources; 3. Enhance existing desktop tools and applications with customized features and capabilities for a particular business; 4. Change and develop web-based systems to reflect new topologies or new resources;

29. What is a Java virtual machine? Why Java is called a “platform Independent Programming language”

The Java virtual machine is a virtual machine process that executes bytecode files (.class). Because different platforms have different Java virtual machines, they can interpret the same.class files into machine code for different platforms. So Java is known as a platform-independent programming language.

What is a regular expression? What is it for? Which package uses regular expressions for pattern matching

Regular expression: a logical formula used to manipulate strings. It uses predefined characters and their combinations to form a “regular string”, and uses the “regular string” to express the filtering logic of strings. Uses include: 1, string matching 2, specify string substitution 3, specify string lookup 4, string splitting regular expression package: java.util.regex package

What is Lazy Loading?

Lazy loading: Lazy loading, as the name implies, is loaded when needed. This method is inefficient but occupies a low memory footprint.

32. What is tail recursion and why is it needed

A recursive function is said to be tail-recursive if all recursive calls to it occur at the end of the function. Why tail recursion is needed: The difference between tail recursion and regular recursion is the memory footprint. Regular recursion creates a stack with less memory, while tail recursion consumes a constant amount of memory.

Inversion of Control and Dependency Injection

Inversion of control: Transferring the ability to create objects to the Spring container. When we need to use objects, we don’t need to create them ourselves. We can get them directly from the container. Dependency injection: Dynamically supplying an object with other objects on which it depends.

Keywords to finalize

1. What is finalize() method

Java can use the Finalize () method to do some necessary cleanup before the garbage collector purifies objects from memory.

When will finalize() method be called

This method is called by the garbage collector on an object when it determines that the object is not referenced.

What is the purpose of finalization

The purpose of a destructor is to do some cleanup, such as freeing memory, before purging an object.

4. The difference between final and Finalize

The final keyword can be used before a class, method, or variable to indicate that the class, method, or variable is immutable.

Finalize methods are used to recycle resources, and you can add Finalize methods to any class. This method is called before the garbage collector cleans up the object.

Note:

The request header is too long to publish! On the following Java foundation, IO, collection, multithreading, virtual machine, design pattern, etc. Article and source code analysis, you can go to my wechat public number to obtain, daily share!

final

1. What are the uses of the final keyword

Where can the final and static keywords be used? What do they do

3. Differences between final, finally, Finalize

4. What are the differences between Final, Finalize and finally?

Can static final types be assigned at run time

6. When you use the final keyword to modify a variable, whether the reference or the referenced object cannot be changed

7. What does it mean when a class is declared final

Throws, throw, try, catch, finally represent what meanings

9. How many modifiers do Java have? What are they used to modify

volatile

1. What is the practice with volatile modifiers

2. What are volatile variables? What is the difference between volatile variables and atomic variables

3. What guarantees do volatile variables provide? Can a non-atomic operation be turned into an atomic operation

Can volatile arrays be created?

5. What are the characteristics of transient variables

6. When is super used

7, How about public static void

Public static void main(String args[])

9. Name the difference between the public, private, protected, and non-write scopes

Is sizeof a Java keyword

static

1, Static class and non-static class

2. What does the static keyword mean? Can override a private or static method in Java

3. What are the features of static typing

4. Why must the main() method be static? Can you declare the main() method non-static

Whether calls to non-static methods can be made from inside a static method

6. When are static variables loaded? Compile time or run time? When static blocks load

Can member methods access static variables? Why can’t static methods access member variables

switch

1. What types of data can expressions in switch statements be

2, whether the switch can work on byte, whether it can work on long, whether it can work on String

3. What’s the difference between a while loop and a do loop

The operator

1. What is the difference between the & and & operators?

A + b = a + b

3, logical operators (&, |, ^) and conditional operators, &&, | |)

4, 3*0.1 == 0.3 will return what? True or false?

5, loat f = 3.4; Is that correct?

6, short s1 = 1; s1 = s1 + 1; What’s wrong with that?

The data structure

Primitives

1. How is Primitives different from Wrappers

2. Briefly describe the size of the nine basic data types and their encapsulation classes

3. Which takes up more memory, int or Integer? What’s the difference between int and Integer? When is the parseInt() function used

What are the default values for float and double

5, how to round the decimal place to keep two decimal places

6. Can a char variable store a Chinese character? Why

Type conversion

1. How to convert bytes to long

2. How to convert byte to String

3. How to convert numeric characters to numbers

4. Can we cast int to byte? What happens if the value is greater than the byte range

5. Can a double be assigned to a long without casting

6. What are type downcasts

An array of

1. How to weigh whether to use an unordered array or an ordered array

2, how to determine whether the array is null or empty

3. How to print an array? How do I print duplicate elements in an array

4. What’s the difference between Array and ArrayList? When should you use Array instead of ArrayList

5, array and linked list data structure description, their time complexity

Does array have a length() method? String does not have a length() method

The queue

What are queues and stacks? List the differences between them

2. What is BlockingQueue

ConcurrentLinkedQueue LinkedBlockingQueue (ConcurrentLinkedQueue)

4, ArrayList, Vector, LinkedList storage performance and features?

5. What is the difference between String and StringBuffer?

6. What is the difference between ByteBuffer and StringBuffer?

HashMap

1. How does HashMap work

2. What is the internal data structure

3, How to determine the capacity of HashMap table? What is loadFactor? How does this capacity change? What problems will this change bring?

4. What is the data structure implemented by HashMap? How to implement

5. Differences between HashMap and HashTable and ConcurrentHashMap

6. Traversal method and efficiency of HashMap

7. Differences between HashMap, LinkedMap and TreeMap

8. How to decide whether to use HashMap or TreeMap

9. What if the size of the HashMap exceeds the capacity defined by the Load factor

10. Is HashMap thread safe? What maps are used concurrently, and what are their internal principles, such as storage, Hashcode, capacity expansion, default capacity, etc.

HashSet

1. What is the difference between HashSet and TreeSet

2. How does a HashSet work internally

3. How does WeakHashMap work?

Set

1. Elements in a Set cannot be repeated. Equals == or equals()? What’s the difference?

2. TreeMap: What tree is used to implement TreeMap? TreeMap, HashMap, LindedHashMap. How do TreeMap and TreeSet compare elements when sorting? How does the sort() method in the Collections utility class compare elements?

3. TreeSet: How to reverse sort a TreeSet that has been built.

4. What is EnumSet

The Hash algorithm

1. What Hashcode does

2. Describe the consistent Hash algorithm

3. Is it possible that two objects that are not equal have the same Hashcode? What happens when two objects have the same Hashcode? How do I get a value object

4. Why do I need to override hashCode when overriding equals? What is the difference between Equals and hashCode

5. What does a.hashcode () do? What does it have to do with A. als(b)

6. Where are the hashCode() and equals() methods important

7, Object: What are the common methods of Object? Object class HashCode equals design principle? Why does Sun design this way? An overview of the Object class

8. How do I automatically complete all hashcode and equals implementations for subclasses in a parent class? What are the pros and cons of this.

9. Can I use random numbers in hashCode ()?

LinkedHashMap

1. What is the difference between LinkedHashMap and PriorityQueue

1. What are the characteristics of List, Set and Map interfaces when accessing elements

2. Check whether List, Set, Map inherit from Collection interface

3, What are the different ways to traverse a List

LinkedList

1. LinkedList is a one-way list or a two-way list

What’s the difference between LinkedList and ArrayList

3. Describe the concepts of Collections, Interfaces, Implementations in Java. What is the difference between LinkedList and ArrayList?

4. Which is faster when inserting data: ArrayList, LinkedList, or Vector?

ArrayList

1. The default size of ArrayList and HashMap is majority

2, ArrayList and LinkedList differences, when ArrayList?

What is the difference between an ArrayList and a Set?

4. ArrayList, LinkedList, Vector

5, How to implement ArrayList, ArrayList and LinkedList difference

6. How to expand ArrayList

7. What’s the difference between Array and ArrayList? When is it better to use Array

8, Name the storage performance and features of ArraList,Vector, LinkedList

Map

1. Map, Set, List, Queue, Stack

2. What are the different collection views provided by the Map interface

3. Why does Map interface not inherit from Collection interface

Collections

1. Introduce the Collection FrameWork in Java. What are the basic interfaces of the collection class framework

2. What is the Collections class? What’s the difference between Collections and Collections? Collection, Map implementation

3. What are the best practices of the collection class framework

4. Why does Collection not inherit from Cloneable and Serializable interfaces

Name some best practices for using Collections in Java.

6. Differences between legacy classes (HashTable, Vector) and existing classes in Collections

7, what is B+ tree, B- tree, list the actual usage scenarios

interface

What are the Comparator and Comparable interfaces? List the differences

Object Copy (Clone)

1, how to implement object cloning

2. Difference between deep copy and shallow copy

3. How do deep and shallow copies implement activation mechanisms

4. When writing the clone() method, there is usually one line of code

To compare

How is the “==” operator different from equals when comparing objects

2. What do I need to consider if I want to override equals on an object

3. Two objects with the same value (x.equals(y) == true) can have different hash codes

The constructor

What is a constructor chain

2. The order in which the constructor is called when the object is created

Immutable object

1. What is an immutable object

2. Why Java strings are Immutable

3. How to build immutable class structures? What are the key points

4. Can I create an immutable object that contains a mutable object

5. How to sort a group of objects

methods

1. Whether the constructor can be overridden

2. Can methods be static and synchronized

3. Abstract method can be static, native, and synchronized

4. Which parameter passing types are supported in Java

5. An object is passed as a parameter to a method, whether by value or by reference

6. When an object is passed as a parameter to a method that changes the object’s properties and returns the changed result, is this value passed or reference passed

Can we override main()

What happens if the main method is declared private

concept

1. What is GC? Why GC

2. When will it lead to garbage collection

How does GC work

4. What is new, old and permanent

5. How many ways does GC work? How to configure

6. When is an object GC? How do you tell if an object is alive

7, System.gc() runtime.gc () does something? Is GC execution guaranteed

Can the garbage collector reclaim memory right away? Is there any way to proactively notify the virtual machine for garbage collection?

9. When will Minor, Major, Young, and Full GC occur

10. Realization principle of garbage collection algorithm

11. If an object reference is set to NULL, does the garbage collector immediately free the memory occupied by the object?

12. What are the best practices for recycling

What are the GC collectors

1. What is the basic principle of garbage collector?

What is the difference between a serial collector and a throughput collector

3. Differences between Serial and Parallel GC

4. Characteristics and differences between CMS collector and G1 collector

5. The working process of CMS garbage collector

What is a complete GC flow in the JVM? How does the target get promoted to the old age

Throughput – and response-first garbage collector selection

GC policy

For a practical scenario, choose a GC strategy

2. Does garbage collection occur in JVM permanent generations

Collection methods

1. The principle and characteristics of mark clearing, mark sorting and copy algorithms? What are they used for

2. What ideas do you have if you are asked to optimize the collection method

The JVM parameter

1. Name the main JVM parameters you know

2. -xx :+UseCompressedOops

ClassLoader

What are the Java class loaders

How does the JVM load bytecode files

Memory management

1. What are the partitions of JVM memory, and what are the functions of each partition

2. How does an object survive and migrate in these parts from creation to destruction

3, Explain the usage of stack, heap and method area in memory

4. Which parameter in the JVM is used to control the thread stack size

5. Describe the memory allocation and reclamation policies

Resort, memory barriers, happen-before, main memory, working memory

Is there a memory leak in Java? Please give an example

8. Brief introduction of soft reference, WeakReference and virtual reference in Java

9. What is the memory mapped cache

Jstack, jstat, jmap, jConsole

What is the maximum heap memory for 32-bit and 64-bit JVMS? For 32-bit and 64-bit JVMS, is the length of a variable of type int the majority?

12. How do I determine whether the JVM is 32-bit or 64-bit using a Java program

Does the JVM itself maintain the cache? Whether objects are allocated in the heap, the operating system’s heap, or the JVM manages the heap itself

14. When can stack memory overflow occur

15. What is the parental delegation model

Basic concepts of multithreading

1. What is a thread

2, the advantages of multi-threading

3, several ways to achieve multithreading

4. Thread or Runnable

5. What is thread safety

Vector, SimpleDateFormat is thread-safe

7. What Java prototype is not thread-safe

Which collection classes are thread-safe

What is a busy loop in multithreading

How to create a thread

11. There are several ways to write multithreaded programs

What are thread-local variables

What is the difference between a thread and a process? How do processes communicate with each other? How do threads communicate with each other

What is false sharing in multi-threaded environment?

What are the similarities and differences between synchronous and asynchronous, and when are they used respectively? For example

Current

ConcurrentHashMap and Hashtable

ArrayBlockingQueue CountDownLatch

3. What is the concurrency of ConcurrentHashMap

4. What’s the difference between CyclicBarrier and CountDownLatch? What are the internal principles and usage of each

5. Semaphore

Thread

Do I call the run() or start() method to start a thread? What is the difference between the start() and run() methods

2. The run() method is called when the start() method is called. Why not call the run() method directly

3. What is the difference between the sleep() and wait() methods that suspend execution

4. What does yield do? What’s the difference between the sleep() method and yield() method

How do you stop a thread in Java

6. Why are stop() and suspend() methods not recommended

7. How to share data between two threads

How do I force a thread to start

9. How do I suspend a running thread for a while

What are thread groups and why are they not recommended in Java

How do you invoke wait? If block or loop? why

The life cycle

What are the different thread life cycles

What is the difference between BLOCKED and WAITING

3. Draw a thread lifecycle state diagram

4, What is the purpose of ThreadLocal? What is the principle of ThreadLocal

ThreadPool

What is a thread pool? Why use it

2. How to create a Java thread pool

ThreadPool usage and advantages

4. What happens when the thread pool queue is full when a task is submitted

5. What is the difference between newCache and newFixed? Explain the principle. What are the meanings of the various arguments to the constructor, such as coreSize, maxsize, etc.

6. Thread pool implementation strategy

7. There are several ways to close a thread pool. What are the differences

What is the difference between submit() and execute() methods in the thread pool?

Thread scheduling

1. What is the thread scheduling algorithm used in Java

2. What is context switching in multithreading

3. What do you understand about thread priorities

What is Thread Scheduler and Time Slicing?

Thread synchronization

1. Name a thread synchronization method that you know of

2. What is the principle of synchronized

3. What’s the difference between synchronized and ReentrantLock

4. When can volatile replace synchronized

5, there are three threads T1, T2, T3, how to ensure that they are executed in order? How to ensure that T2 is executed after T1 and T3 after T2

6. What happens when a thread in a synchronized block throws an exception

7. After A thread enters the synchronized method A of an object, whether other threads can enter the synchronized method B of the object

8. What is the difference between using synchronized and non-static methods

9. How to create a synchronized collection from a given collection

The lock

1. What is the Java Concurrency API Lock interface? What are the advantages over synchronization

2. The difference between Lock and Synchronized? What are the advantages of the Lock interface over synchronized blocks

3. What is ReadWriteLock?

4. What is the use of locking mechanism

5. What is Optimistic Locking? How to implement optimistic locking? How to avoid ABA problems

6. Explain the terms: reorder, spin lock, bias lock, lightweight lock, reentrant lock, fair lock, unfair lock, optimistic lock, pessimistic lock

7. When should reentrant locks be used

8, briefly describe the lock level method lock, object lock, class lock

What is the difference between live locks and deadlocks in Java?

10. What is a Deadlock? What causes thread deadlocks? How do I ensure that N threads can access N resources without causing deadlocks

The difference between deadlocks and live locks, the difference between deadlocks and hunger

How do I check if a thread has a lock

13. How to implement distributed lock

14. What are the unlocked data structures and how do they work

What application scenarios can read/write locks be used in

Executors? The difference between Executor and Executors

What is a Java Thread Dump and how do I get it

How do I get a thread stack in Java

Name three best practices for using threads in Java

20. How do you handle uncatchable exceptions in threads

Examples of using multithreading in real projects. What are some common problems you encounter in multi-threaded environments? How did you solve it

22. Describe methods related to thread synchronization and thread scheduling

There are 3 sockets in the program, how many threads are needed to process

24. If you have a third-party interface that is called by many threads to retrieve data, it is now specified that at most 10 threads are called at the same time every second. How to do this

How do I find which thread is using the most CPU time on Windows and Linux

26. How do I ensure that main() is the last thread to terminate a Java program

27, many threads (possibly different machines) need to wait for coordination between each other to complete some work, ask how to design this coordination scheme

28. You need to implement an efficient cache that allows multiple users to read, but only one user to write, in order to maintain its integrity. How would you implement it

abnormal

The basic concept

1. What is the difference between Error and Exception

2, UnsupportedOperationException is what

What is the same between 3, NullPointerException and ArrayIndexOutOfBoundException

4. What are checked exceptions and runtime exceptions

5. What are the similarities and differences between runtime exceptions and general exceptions

6, Describe a Runtime exception that you see most often.

finally

How is the finally keyword used in exception handling

2. If the method returns a result before executing a finally block, or if the JVM exits, does the code in the finally block still execute

3. Return in try, finally? Will the code in finally {} immediately after the try be executed, and when, before or after the return

4. When do finally statements not execute

Throws throws throws throws throws

What situations have you met in OOM? How did you pull it off?

7. What situations have you encountered?

8. Why do you think there are checking exceptions in Java when we can handle errors with RuntimeExceptions

9. What should I pay attention to when creating my own exception class

10. The cause of the null pointer exception

11. How to understand the handle or declare principle

12, How to use JUnit to test a method exception

13. What’s wrong with not writing code in catch blocks

Have you ever custom implemented an exception? How to write the

15. What is an exception chain

Can an exception be thrown in a try block

JDBC

1. What are the ways to connect to the database through JDBC

2. Describe the basic steps of JDBC database operation

3. How do transactions work in JDBC

What is a JdbcTemplate

5. What is a DAO module

6. How to improve the performance of reading data when using JDBC database? How to improve the performance of updated data

List five JDBC best practices that should be followed

IO

File

What methods are defined in the File type to create a level 1 directory

2. What method is defined in the File type to determine whether a File exists

flow

1. What flows can be used to improve read and write performance

2. There are several types of flows in Java

The JDK provides some abstract classes for each type of stream to inherit from

4. What I/O stream is used for text file operations

5. What stream is used for reading and writing various basic data types and strings

What is the type of I/O stream that can specify a character encoding

serialization

What is serialization? How to implement Java serialization and considerations

2, Serializable vs. Externalizable

Socket

1, what is the socket option TCP NO DELAY

2. Which layer of the TCP/IP stack does the Socket work on

3, TCP, UDP differences and Java implementation

4, say some IO best practices

What is the difference between a direct buffer and an indirect buffer?

6. How to read and write ByteBuffer? What is the byte order in ByteBuffer

7, The number of bytes stored in the buffer after typing n characters from the keyboard with system.in.read (buffer)

How to use Scanner Class tokenization

Object-oriented programming (OOP)

1. Polymorphism, encapsulation, cohesion and coupling are explained

2. Realization principle of polymorphism

What are encapsulation, inheritance, and polymorphism

4. What are the principles of object encapsulation?

class

1, how to get the class object of a class

2. The difference between Overload and Override. Can overloaded methods be differentiated by return type?

Name a few best practices for method overloading in Java

An abstract class

1. Distinction between abstract classes and interfaces

2. Can abstract classes have static main methods

3, Whether abstract classes can implement (implements) interfaces

4. Can an abstract class inherit a concrete class?

Anonymous Inner Class

1. Can anonymous inner classes inherit from other classes? Whether the interface can be implemented

The inner class

1. There are several internal classes

2. Can an inner class reference a member of its containing class

3. Why are inner classes introduced in Java? There are also anonymous inner classes

inheritance

1. What is the difference between Inheritance and Aggregation

What is the difference between inheritance and composition

3. Why can a class only inherit from a single interface

4, There are two classes, B inherits A, C inherits B, can convert B to C? So C = (C) B

5, If class A inherits from class B and implements interface C, but class B and interface C define a variable with the same name, what is the problem

interface

1. What is interface

2. Whether the interface is inheritable

3. Why use interfaces instead of concrete classes? What are the advantages of interfaces

The generic

1. What problems do generics exist to solve

2. Common features of generics

3, List can be converted to List

Utility class

The calendar

1. The purpose of Calendar Class

How do I get an instance of the calendar class in Java

Explain some important methods in the calendar class

What is the GregorianCalendar class

5. What is the SimpleTimeZone class

6. What is the Locale class

7. How to format date objects

How to add hour to a Date object

How to convert string YYYYMMDD to date

Math

Math.round() Math.round(11.5) equals what? What is math.round (-11.5)?

XML

How many forms does an XML document definition take? What are the essential differences between them? What are some ways to parse AN XML document? What’s the difference between DOM and SAX parsers?

2. How Java parses XML

3. How to solve the Chinese problem when parsing XML files with JDOM? How to parse

4. What aspects of XML technology have you used in your project? How to implement

A dynamic proxy

1. Describe several implementation methods of dynamic proxy, and tell the corresponding advantages and disadvantages respectively

Design patterns

1. What are Design Patterns? What design patterns have you used? For what occasion

2. What business level design patterns do you know?

3. Which design patterns can increase the scalability of the system

The singleton pattern

1. Besides singletons, what other design patterns have you used in production?

2. Write Singleton Singleton

What is the double check of singleton mode

4, How to create thread-safe Singleton

What is the singleton pattern of a class

6. Write three singleton pattern implementations

Adapter mode

1. What is the adapter pattern? When to use

2. What was the difference between the adapter pattern and the proxy pattern

What is the difference between adapter mode and decorator mode

4. When to use the free mode

5. When to use composite mode

6. When to use visitor mode

What is the template method pattern

Please give an example of a design pattern that conforms to the open and close principle

Note:

The request header is too long to publish!On the above Java foundation, IO, collection, multithreading, virtual machine, design pattern and other articles and source code analysis, you can go to my wechat public number to obtain, daily share!

Open questions (It’s up to you)

1. Summarize the features of Web programming in one sentence

2. How does Google return search results to users in less than a second

Which dependency injection method do you recommend, constructor injection or Setter injection

4. Trees (binary or otherwise) form the basis of many common data structures. Describe some of these data structures and when they can be used

5. How to design a particular function

6. How do you find problems when online systems suddenly become extremely slow

7. What kind of project doesn’t fit the framework

8. How does Sina Weibo push its microblog to subscribers

What happens in a Java Web application from the time the browser enters the URL to the time the request is retrieved

10. Talk about SSH integration

11, under high concurrency, how to safely modify the same row of data

12. How to realize the booking system of 12306.cn and how to ensure that the tickets will not be oversold

How to optimize the site performance

14. Talked about the server architecture I had participated in designing

15. Consider a solution to implement countDownLatch in a distributed environment

16. Consider a solution to design an adaptive local cache that controls the overall size of the cache

17. What has been the most difficult technical challenge in your career

18, How to write a design document, what is the catalog

19. What is the capital O? Just a couple of examples

How do I consider some design principles in programming, such as open and close principle, and the application in work

21. Explain the patterns and characteristics of network applications

22, Design an online document system, documents can be edited, how to prevent multiple people to edit the same document at the same time update

What is the working mechanism of datapool

How do I get the highest frequency of words in a file

Describe the programming style you use most often

If you had the chance to redesign your product, what would you do

27. How to build a high availability system

28. How to boot without input user name and password

29, How to implement file upload and download in Java-based Web projects

How to achieve a second kill system, to ensure that only a few users can buy a product.

31. How to achieve load balancing and what algorithms can be implemented

32, How to design a shopping cart? Think about taobao shopping cart how to achieve

33, How to design a set of high concurrent payment scheme, how to design the architecture

34, how to design and maintain 100W long connection

How to avoid browser caching.

36. How to prevent cache avalanche

If AB two systems are interdependent, how to remove the dependence

What can I do if someone creates an illegal connection maliciously

If there are billions of whitelists, every day need high concurrency query, need to update once at night, how to design this function

40, If the system uses large integers (beyond the long range), design a data structure to store such large numbers and an algorithm to add large integers.

41, if you want to design a graphics system, please design basic graphic element (Point, Line, Rectangle, Triangle) of simple implementation

If you were asked to implement a concurrency safe linked list, what would you do

What is the difference between an application server and a WEB server? How does the application server monitor performance? What application server optimization techniques have you used

What problems should be considered in the architecture of large websites

Have you ever dealt with online problems? How to handle memory leaks, high CPU usage, and unresponsive applications

What books have you read recently? What is the most impressive one

Describe common refactoring techniques

What version management tool do you use? What’s the difference between a Branch and a Tag

49. Have you ever seen what anti-patterns exist

What technology do you use to optimize the front end of the website

51, How to analyze Thread dump

52. How do you understand the concepts of Joinpoint, Pointcut, Advice, Introduction, Weaving and Aspect in AOP

How do you deal with memory leaks or stack spills

54, What are the JVM parameters you are using online

How to improve system QPS and throughput

knowledge

1. Explain MESI protocol (Cache consistency)

Reference: http://blog.csdn.net/zxp_cpinfo/article/details/53523697

Talk about the REACTOR model

Reference: https://www.jianshu.com/p/2461535c38f3

3. What new features does Java 9 bring

Reference: http://blog.csdn.net/u013322876/article/details/76610029

4, Java and C++ contrast, C++ or Java exception handling mechanism in the simple principle and application

Reference: http://blog.sina.com.cn/s/blog_c065adec0101eu98.html

5. A brief introduction to the Tomcat structure and its classloader process

Reference: http://blog.csdn.net/lai1365266/article/details/45271985

6. What is virtual memory

Reference: http://blog.csdn.net/guoweimelon/article/details/50849710

7. Explain the SOLID principle

Reference: https://www.cnblogs.com/OceanEyes/p/overview-of-solid-principles.html

8. Briefly explain what you know about test Driven Development (TDD)

Reference: https://www.cnblogs.com/OlderBird/p/4322925.html

9. Realization principle of CDN

Reference: https://www.cnblogs.com/losbyday/p/5843960.html

What’s the difference between Maven and ANT

Reference: http://blog.csdn.net/yangkai_hudong/article/details/12554983

What diagrams are commonly used in UML

Reference: http://blog.csdn.net/suxinpingtao51/article/details/8011335

Linux

1. There are several IO models under Linux, what are their meanings?

Reference: http://www.jb51.net/article/94783.htm

What kernel parameters do you care about in Linux

Reference: http://www.jb51.net/LINUXjishu/335549.html

3. In Linux, view the last five lines of the file with one command

cat filename | tail -n +3000 | head -n 1000Copy the code

4. Which Linux commands do you use

Reference: https://www.cnblogs.com/bugutian/p/4528650.html

5. Output the running Java process with a single command

Reference: https://www.cnblogs.com/bugutian/p/4528650.html

What command is used to determine if there is a Tomcat instance running on the machine

7. What is the N+1 problem

Reference: https://www.cnblogs.com/yzlpersonal/p/5077392.html

What is the PaxOS algorithm

Reference: http://blog.csdn.net/21aspnet/article/details/50700123

9. What is restful? Tell me what you understand restful

Reference: http://www.ruanyifeng.com/blog/2011/09/restful.html

10. What is zAB protocol

Reference: https://www.cnblogs.com/jian-xiao/p/5821675.html

11. What is domain Model? What is the difference between the anaemic Domain model and the rich Domain model

Reference: https://www.cnblogs.com/feng9exe/p/5611992.html

12. What is Domain Driven Development?

Reference: http://blog.csdn.net/johnstrive/article/details/16805121

13. Introduce the Web Service framework in the Java domain

Reference: http://blog.csdn.net/apicescn/article/details/42965785/

What is the difference between Web Server, Web Container and Application Server

Reference: https://www.cnblogs.com/vipyoumay/p/5853694.html

15. What is the difference between MicroServices and Monolithic Applications

16. Describe the functions, differences and application scope of Cookie and Session, and the working principle of Session

Reference: http://blog.csdn.net/yanghaitao_1990/article/details/51723066

17. What Continuous Integration and Static Code Analysis tools do you often use

18, Briefly describe database Normalizations

19. What are the meanings of KISS,DRY,YAGNI and other principles

Reference: http://blog.csdn.net/zj_show/article/details/8078447

20, the principle of distributed transaction, advantages and disadvantages, how to use distributed transaction?

Reference: http://blog.csdn.net/a291382932/article/details/52567094

21. How to achieve unique serial number in cloth cluster

Reference: https://www.cnblogs.com/yelongsan/p/6306418.html

network

1. What is the encryption method of HTTPS? Talk about the whole encryption and decryption process

Reference: http://blog.csdn.net/shw372029857/article/details/52687906

The difference between HTTPS and HTTP

Reference: https://www.cnblogs.com/wqhwe/p/5407468.html

3. Implementation principle of HTTP connection pool

Reference: https://www.cnblogs.com/likaitai/p/5431246.html

4. HTTP clustering scheme

Reference: http://aokunsang.iteye.com/blog/2053719

5, Nginx, Lighttpd, Apache three mainstream Web server differences

Reference: http://blog.csdn.net/u013404872/article/details/70799420

Have you seen some of the framework code

7. What are the problems to be considered in the design of persistence layer? What persistence layer frameworks have you used

“Persistence” means saving data to fail-safe storage devices for future use. In simple terms, it means saving in-memory data to relational databases, file systems, message queues, and other devices that provide persistence support. The persistence layer is the relatively independent layer of the system that focuses on data persistence.

The objectives of persistence layer design include:

  • Separation of data storage logic to provide an abstract data access interface.
  • The separation of the underlying implementation of data access allows switching of the underlying implementation without changing the code.
  • Separation of resource management and scheduling to achieve unified resource scheduling (such as caching mechanism) at the data access layer.
  • Data abstraction, providing more object-oriented data manipulation.

The persistence layer framework has:

  • Hibernate
  • MyBatis
  • TopLink
  • Guzz
  • jOOQ
  • Spring Data
  • ActiveJDBC

8. What is numerical enhancement

Reference: http://blog.csdn.net/yangcheng33/article/details/76408580

9. Can you explain Richter’s substitution principle

Reference: http://blog.csdn.net/xingyunlost/article/details/53169283

10. How do you test an app? Know which test frameworks

Reference: https://www.cnblogs.com/fnng/p/3653793.html

11. What are the common programming protocols at the transport layer? And describe their characteristics

The transport layer is located at the fourth layer in the OSI seven-layer network model. The protocol is TCP · UDP · TLS · DCCP · SCTP ·RSVP · PPTP. The OSI (Open System Interconnection) seven-layer network model is a logical definition, a specification, that divides networks logically into seven layers. Each layer has related and corresponding physical devices, such as routers and switches. The main purpose of the seven-layer model is to solve the compatibility problems encountered in heterogeneous network interconnection. Its main function is to help different types of hosts to achieve data transmission. Its biggest advantage is that the three concepts of service, interface and protocol are clearly separated, and the reliable communication between different systems and different networks is realized through seven hierarchical structure models.

Programming problem

Calculate overtime pay

Overtime less than 10 hours will be paid 1.5 times the hourly rate. Overtime of 10 hours or more will be charged 4 yuan per hour. Tips :(work 26 days a month, 8 hours a day)

1. Calculate the overtime pay of 9 hours of overtime at 1000 monthly salary

2. Calculate the monthly salary of 2500 and overtime pay for 11 hours of overtime

3. Calculate the overtime pay of 15 hours of overtime at 1000 monthly salary

Sell things

A shopping mall sells red apples and green apples. (Red apples 5 yuan /, green apples 4 yuan /).

1, simulate a purchase. 200 red apples and 200 green apples each.

2. Simulate a sale. Buy ten red apples and ten green apples. Every apple sold needs to be counted.

Tip: An apple is a separate entity.

Date extract

Write a regular expression that matches the time string 2008-8-8 20:08:08, and write Java code to extract the hours and seconds following the date: 20:08:08 thread

1. Design 4 threads, in which two threads increase j by 1 each time, and the other two threads decrease J by 1 each time. Write the program.

2, use Java to write a multithreaded program, such as write four threads, two plus 1, two on a variable minus one, output

3, Wait-notify Write a piece of code to solve the producer-consumer problem

digital

1, determine how many primes there are between 101 and 200, and print all primes

package C; public class Sushu { public static void main(String[] args) { int sum=0;for (int i = 101; i < 201; i++)         {            for (int j = 2; j <=i; j++)            {                if(j==i)                {                    System.out.println(j);                }                else if(i%j==0)                {                    sum++;                    break;                }            }        }        System.out.println(There's a total of+(100-sum)+"Primes");    }}Copy the code

Figure out what 2 times 17 is the most efficient way

17 > > 1Copy the code

3, there are 100 million numbers, two of which are repeated, quickly find it, time and space to optimal

400, 200 million randomly generated unordered integers, find the value of the middle size

public class Test2{public static void main(String [] srgs){int i=(int)(Math.random()*900)+100; //int i= new java.util.Random().nextInt(900)+100; Can also be System. Out. Println (I); }}Copy the code

Find the 10 smallest numbers in a 500 million

package com.yuzhiyun; import java.util.Arrays; /** * First create a maximum heap of 10 nodes, then consider each new value, compare it with the top of the heap, discard the element larger than the top, and replace the top with the number smaller than the top, then adjust the heap. */public class MaxTenNumber {public static void main(String[] args) { Array [k]>array[2k] && array[k]>array[2k+1] Here temporarily substitute number 20, 100 million * / int [] array =,1,2,3,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,6,5 {0}; // create a maximum heap with 10 nodesfor(int i=10/2; i>=1; i--){ adjustHeap(array, i, 10); } //System.out.println(Arrays.toString(array));for(int i=11; i<array.length; I++){// if the element is smaller than the top of the heap, swap it with the top and resize the heapif(array[i]<array[1]){                swap(array, i, 1);                adjustHeap(array, 1, 10);            }        }        System.out.println(Arrays.toString(array));        System.out.println("The ten smallest numbers are:");        for(int i=1; i<=10; i++){ System.out.print(array[i]+""); }} /** * swap * @param array * @param I * @param j */ private static void swap(int[] array, int I, int j) { int tem=array[i]; array[i]=array[j]; array[j]=tem; @param array * @param head * @param tail */ static void */ static void */ static void */ static void */ static void */ static void adjustHeap(int[] array,int head,int tail){ int root=array[head]; int i=2*head;while(i<=tail){            int max=array[i];            if(i+1<=tail)                if(array[i+1]>array[i]){                    max=array[i+1];                    i++;                }            if(root> Max) //return;                break;            else{                array[i/2]=array[i];                    }            i*=2;        }        array[i/2]=root;    }}Copy the code

6, 1 to 100 million natural numbers, find the sum of all numbers, such as 286 divided into 2, 8, 6, such as 1 to 11 divided into the sum of the numbers => 1 +… Plus 9 plus 1 plus 0 plus 1 plus 1

7. A number is called perfect if it is equal to the sum of its factors. For example, 6=1+2+3. Program to find all completions up to 1000

package a; public class Wanshu { public static void main(String[] args) {for (int i = 1; i <= 1000; i++)        {            int sum=0;            for (int j = 1; j < i; j++)            {            if(i%j==0) { sum+=j; }}if(i==sum) { System.out.println(i); }}}}Copy the code

8. All elements in an array appear three times and only one element appears once

    int singleNumber(int A[], int n) {          int result=0;          for(int i=0; i<32; i++){ int bit=0;for(int j=0; j<n; j++){ bit+=(A[j]>>i)&1; } result |= (bit%3)<<i; }return result;      }  Copy the code

9, a ball from the height of 100 meters free fall, each time after the landing bounce back to the original height of half; And when it lands again, how many meters does it travel on the 10th landing? How high is the 10th bounce?

package lianxi; Public class Qiu {public static void main(String[] args) {double sum1 = 0, sum2 = 0, hight = 100.0;for(int i = 0; i < 10; i++) { sum1 = sum1 + hight; // system.out. print(hight); hight = hight / 2; // System.out.print(""+hight);            //System.out.println();            if (i < 9)            {                sum2 = sum2 + hight;            }        }        System.out.println("On the tenth landing, we passed together." + (sum1 + sum2) + "米");        System.out.println("The height of the tenth rally is + hight + "米");    }}Copy the code

Find the sum of primes between 100 and 1000

Public class TestZhiShu {public static void main(String[] args) {/** * count=0;for(int i = 102; i <= 1000; I++) {// primefor(int k = 2; k <= i; K ++) {// Divisor // exclude all numbers divisible by k (remainder 0) until I =kif(i % k == 0 && i ! = k) {break; } // Print all numbers where I =k and I %k=0if(i % k == 0 && i == k) { //System.out.println(i); count++; } } } System.out.println(count); }}Copy the code

Take the average of the sum from 1 to 100

12, s = a + a + aaa + aaaa + aa… The value of a, where a is a number. For example, 2+22+222+2222+22222(a total of 5 numbers added), the addition of several numbers is controlled by the keyboard. Take the sum from 1 to 100

package com.liron.p1; import java.io.IOException; import java.util.Scanner; / * * * o s = a + aa + aaa + aaaa + aa... The value of a, where a is a number. * For example, 2+22+222+2222+22222(a total of 5 numbers added), several numbers * plus keyboard control. */public class Topic18 { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); System.out.println("Which number cycle? :");        int _temp = sc.nextInt();          System.out.println("How many times do the cycles add up? :"); int temp = sc.nextInt(); int newNumber = 0; Int total = 0; // Calculate the resultfor (int i = 0; i < temp; i++)          {              newNumber = newNumber * 10 + _temp;              System.out.println(newNumber);              total = total + newNumber;          }          System.out.println("Calculation result :" + total);      }}Copy the code

13. Count prime numbers from 1 to 40 and put them in an array

① Display the number in the group

② Find the number [5]

③ Delete the number [9] and display the deleted number [9]

There are 3n+1 numbers, among which 3n are repeated, only 1 is not repeated, how to find out.

15. There is a group of numbers 1.1.2.3.5.8.13.21.34. Write a program that inputs any number and gives you the first five numbers that follow the same pattern as the previous set

Calculate the factorial of the specified number

public class CalculatingFactorial {    public static void main(String args[]) {        for (int counter = 0; counter <= 10; counter++) {            System.out.printf("%d! = %d\n", counter, factorial(counter));        }    }    public static long factorial(long number) {        if (number <= 1)            return 1;        else            return number * factorial(number - 1);    }}Copy the code

17. Develop Fizz Buzz

Reference: https://www.cnblogs.com/webary/p/6507413.html

18. Given an array of N integers, find the missing integers

    import java.util.*;      public class Finder {          public int findMissing(int[][] numbers, int n) {              // write code here              int i = 0;              for(i=0; i<n; ++i){                  if(i%2! =numbers[i][0]){break; }}returni; }}Copy the code

An sorted array, find all combinations where the sum of two numbers is m

public static void main(String[] args) throws UnsupportedEncodingException { int[] ints = { 1, 3, 10, 12 , 13, 18, 22, 58}; int find = 23; int start = 0; int end = ints.length - 1;while (ints[start] >= find) {                  System.out.println("Are bigger than him -------------------------------!");                  return;              }              while (end > start) {                  if (ints[start] + ints[end] == find) {                      System.out.println(ints[start] + "+" + ints[end] + "="                              + find);                      end--;                      start++;                  } else if (ints[start] + ints[end] < find) {                      start++;                  } else if (ints[start] + ints[end] > find) {                      end--;                  }                  System.out.println(start +""+end); }}Copy the code

Decompose a positive integer into its prime factors. For example, enter 90 and print 90=233*5.

//【 program 4】FenJie. Java title: A positive integer factorization of prime factors. For example, if you enter 90, 90=2*3*3*5 is printed. (1) If the prime number is exactly equal to n, then the process of prime factorization is over. Print it out. //(2) If n<>k, but n is divisible by k, then print out the value of k and repeat the first step as the new positive integer n divided by the quotient of k. If n is not divisible by k, repeat step 1 with k+1. // Any positive integer can be decomposed by multiplying multiple prime numbers. import java.io.*; import java.util.*; public class FenJieApp { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Please enter a number:");                Scanner scanner = new Scanner(System.in);                int parm=scanner.nextInt();                System.out.print(parm+"=");                for(int i=2; i<=parm; i++) {while(parm! =i) {if(parm%i==0)                      {                           System.out.print(i+"*");                          parm=parm/i;                      }                       else                          break; } } System.out.print(parm); }}Copy the code

21, print out all the “daffodil number”, the so-called “daffodil number” is a three-digit number, its cube sum is equal to the number itself. For example, 153 is a “daffodil number” because 153=1 to the third power +5 to the third power +3 to the third power

package com.hanqi; public class Text4 { public static void main(String[] args) {for(int num=100; num<1000; num++) { int gw=num%10; int sw=num/10%10; int bw=num/100%10;if(gw*gw*gw+sw*sw*sw+bw*bw*bw==num) { System.out.println(num); }}}}Copy the code

22. Exchange the values of two variables in place

Reference: https://www.cnblogs.com/Brad-Lee/p/5808299.html

Find the median of a 4-byte integer

Reference: http://blog.csdn.net/randyjiawenjie/article/details/6968591

Find the square root of an integer

Reference: https://www.cnblogs.com/Matrix_Yao/archive/2009/07/28/1532883.html

25. Fibonacci

Reference: http://blog.csdn.net/duhacker/article/details/48295807

network

1, using Java Socket programming, read server several characters, and then write local display

reflection

1. What function does reflection provide?

Class ownerClass = owner.getClass() constructs an object of Class at runtime: Class newoneClass = class.forname (className) : The first step is to get the Class of the instance to be constructed. Constructor cons = newoneClass. GetConstructor (argsClass) : get structure. Cons. newInstance(args) : creates a newInstance. Class ownerClass = owner.getClass() : Gets the Class of the object.

Field Field = ownerClass.getField(fieldName) : Gets the property declared by the Class.

Object Property = field.get(owner) : Get an instance of the property from the Object. If the property is not public, IllegalAccessException is reported. Call a Method of an object at runtime: Method Method = ownerClass.getMethod(methodName, argsClass) : Get the Method to execute from the Method name and the Class array of parameters.

Method.invoke (owner, args) : Invoke the method. The invoke method takes the object to execute the method and an array of parameters. The return value is Object, which is also the return value of this method.

2. How is reflection implemented

Reflection is a mechanism for retrieving and calling properties and methods of a class in a run-time state. The purpose of this mechanism is to get a Class and its fields and methods that are not known at runtime, to call the methods, and to set the values of the properties. The most important step in implementing reflection in Java, and the first step, is to get a Class object. Once you get a Class object, you can use that object to call corresponding methods to get properties, methods, and methods in that Class. In Java, reflection can be implemented in several ways: 1. Use the class.forname () method to load a string and get the Class object represented by the string. For example: Class clazz = class.forname (” java.lang.string “) to get a String Class object. Note that the string must be the full name of the class, that is, the package name + the class name. The following code configures an action in the Struts configuration file struts.xml.

/registeResult.jsp /registe2.jsp

Here the class attribute gives a string with the full name of a class. How does the server get the class object from this string? RegisteAction object by reflection. The default execute() method in this class is then called. 2. Call the class attribute from the class name to get the class object for that class. For example, Class clazz = string. Class can also get a String Class object. 3. Call the instance’s getClass() method. For example: Date Date = new Date(); Class clazz = date.getClass(); You can get the Class object of the date instance with the above two lines of code. 4. If it is a wrapper Class of a primitive Type, the wrapper Class object can be obtained by calling the Type attribute of the wrapper Class. For example, Class clazz = integer.type;

3. Where is reflection used

Java’s reflection mechanism is to increase the flexibility of the program, so as to avoid writing the program dead in the code, the typical application is Spring for example: instantiate a Person () object, do not use reflection, new Person (); If you want to instantiate another class, you must modify the source code and recompile it. Use reflection: class.forname (“person”).newinstance (); And this class description can be written to a configuration file, such as **.xml, so that if you want to instantiate another class, you can simply change the “class description” of the configuration file without having to modify the code and compile it again.

4. The difference between class. forName and ClassLoader in reflection

Reference: http://blog.csdn.net/qq_27093465/article/details/52262340

What are the three ways reflection can create class instances

Reference: http://blog.csdn.net/u012110719/article/details/45226937

6. How to call object methods through reflection

Reference: blog.csdn.net/handsome_fan/article/details/54862873

7, How to get and set the value of the object private field by reflection

Reference: http://blog.csdn.net/u012726702/article/details/72027028

8. Pros and cons of reflection

Reference: http://blog.csdn.net/u010154380/article/details/78150251

The database

1, write a JDBC connection to Oracle program, and achieve data query

package svn; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; {public static void Main (String[] args) throws Exception {// 1."com.mysql.jdbc.Driver"); Conn = null; conn = DriverManager .getConnection("jdbc:mysql://localhost:3306/db? useUnicode=true&characterEncoding=UTF-8"."root"."123456"); PreparedStatement psPreparedStatement = conn. prepareStatement("select * from t_user"); // Statement stmtStatement=conn.createStatement(); / / 4, perform database command the ResultSet rSet. = psPreparedStatement executeQuery (); //ResultSet rs=stmtStatement.executeQuery("select * from t_user"); //5. Process the execution resultwhile(rSet.next()){                  int id=rSet.getInt("id");                  String usernameString=rSet.getString("username");                  String passwordString=rSet.getString("password");              }              if(rSet! =null) rSet.close();if(psPreparedStatement! =null) psPreparedStatement.close();if(conn!=null)                  conn.close();          }      }  Copy the code

algorithm

1, 50 people sit in a circle, count to three or a multiple of three, ask who the rest of the people are, what was their original position

/* Exit algorithm is a typical algorithmic interview question, which can be a good test of a candidate's programming background. Because it is a kind of circular logic, it is a little more difficult than the general basic algorithm. This example answers this question and explains the realization idea of loop - out algorithm in detail. For the loopout problem, it has a relatively big difficulty point, is that it always repeats, its head is its tail, so the loopout problem is more difficult to write. The number of elements in the circle is 50. Each time you reach 3 or a multiple of 3, take the current element out of the circle and continue counting until you reach another multiple of 3. Here, if the index starts at zero and goes all the way to the end of the circle, it gets to the end of the circle, what do I do with that? In fact, the best way to do it is to use the mod method, and you can always get 3 multiples, no matter what its multiples are, no matter how many elements it has. Because each time you remove an element, there is one less element, so the next multiple of 3 actually takes only two steps. When assigning its subscript, you need to subtract one to keep the element removed each time as a multiple of 3. Note: If you use a subscript starting from 0, you should initialize with -1 to simulate that the element has been reduced by one. For storing elements, you can use arrays or linked lists. When an array element is removed, its next element does not automatically move forward. It is not easy to use, but it can be used. Here, it's best to use the java.util.List List, which has both subscripts and a handy way to get the current number of elements, although it's a little less efficient than an array, but it's enough. */ import java.util.LinkedList; import java.util.List; Public class Cycle {public static int Cycle (int total, List<Integer> dataList = new LinkedList<Integer>(); // Create a linked list objectfor(int i = 0; i < total; // Add dataList. Add (new Integer(I + 1)); int index = -1; // Define the subscript, the simulation has already removed one element, so start at -1while(dataList. Size () > 1) {// Keep iterating until only one element is left. Index = (index + k) % dataList. // Get the index dataList. Remove (index--); // Remove elements}return((Integer) dataList.get(0)).intValue(); Public static void main(String[] args) {system.out.println () {system.out.println ();"The original position of the number was:"+cycle(50, 3)); }}Copy the code

2, to achieve an elevator simulator

Basic idea: Simulate elevator operation (for a single elevator, not considering the load limit, the shortest waiting time and other issues) basic conditions: 1, the elevator has three states: static, up, down. 2, each floor of the indicator light has three states: up, down, arrive (open only). 3, open the door for 1 second, each upper or lower layer with 0.1 seconds. /* Implementation: use a queue (think of it as time first) to queue all button events in sequence. When the elevator is stationary, first respond to the button event of the team head, and determine the moving direction according to the position of the button floor and the current floor; When moving up, it will move to the top floor of all the buttons on the light, when the direction of the button is consistent with the direction of the elevator or the internal of the floor to open the door when the button lights up; Moving down is similar. When there are no button events in the queue, the elevator stands still. It is similar to LOOK arithmetic, but does not scan back and forth without button events. Using the main thread to control the elevator up and down, you need to pay attention to the synchronization of "setting and obtaining the method of the highest or lowest level of the elevator button". * /while(true) {if(! ele.getPushedFloor().isEmpty()){ int nextFloor = ele.getPushedFloor().peek();if(nextFloor > 0){// Up buttonif(ele.getCurFloor() - nextFloor <= 0){                        ele.liftUp();                    }else if(ele.getCurFloor() - nextFloor > 0){ ele.liftDown(); }}else{// Down buttonif(ele.getCurFloor() + nextFloor < 0){                        ele.liftUp();                    }else if(ele.getCurFloor() + nextFloor >= 0){ ele.liftDown(); }}}else{                ele.setStat(RunningStat.INIT);            }            Thread.sleep(100);        }Copy the code

3. Write a bubble sort

package sort; Public void Bubble1(int[]a,int n){int I,j; Bubble1(int[]a,int n){int I,j;for(i=0; i<n-1; i++){for(j=1; j<n-i; j++){if(a[j-1]>a[j]){ swap(a,j-1,j); //int k; //k=a[j-1]; //a[j-1]=a[j]; //a[j]=k; }}}} // The second method of code optimization to write a flag bit, if a switch occurs down the flag istrue, if no exchange occurs, isfalsePublic void Bubble2(int[]a,int n){int u,v; boolean flag; flag=true;        while(flag){            flag=false;            for(u=0; u<n-1; u++){for(v=1; v<n-u; v++){if(a[v-1]>a[v])                        swap(a,v-1,v);                }                flag=false; }}} / / the third method, if there are a number of 50 array, just in front of the number 10 is unordered, 40 number is orderly, behind and in front of more than 10 Numbers, so / / sorted for the first time, the exchange position shall be less than 10, and after the position of data must be ordered, record the position, Public void Bubble3(int[]a,int n){int p,q; int flag1=n;while(flag1>0){            q=flag1;            flag1=0;            for(p=1; p<q; p++){if(a[p-1]>a[p]) swap(a,p-1,p); flag1=p; } } } public void swap(int a[],int p,int q ){ int k; k=a[p]; a[p]=a[q]; a[q]=k; }}Copy the code

4. Write a split lookup

    import java.util.Comparator;      public class MyUtil {         public static <T extends Comparable<T>> int binarySearch(T[] x, T key) {            returnbinarySearch(x, 0, x.length- 1, key); } public static <T> int binarySearch(T[] x, T key, Comparator<T> comp) {int low = 0; int high = x.length - 1;while (low <= high) {                int mid = (low + high) >>> 1;                int cmp = comp.compare(x[mid], key);                if (cmp < 0) {                  low= mid + 1;                }                else if (cmp > 0) {                  high= mid - 1;                }                else {                  returnmid; }}return- 1; } private static<T extends Comparable<T>> int binarySearch(T[] x, int low, int high, T key) {if(low <= high) {              int mid = low + ((high -low) >> 1);              if(key.compareTo(x[mid])== 0) {                 return mid;              }              else if(key.compareTo(x[mid])< 0) {                 return binarySearch(x,low, mid - 1, key);              }              else {                 returnbinarySearch(x,mid + 1, high, key); }}return -1;         }      }  Copy the code

5. Randomly generate 20 characters that cannot be repeated and sort them

import java.util.HashSet; import java.util.Random; import java.util.Set; import java.util.TreeSet; public class bb { public static void main(String[] args) { Set noreapeat =new TreeSet(); Random rdm = new Random();while (noreapeat.size()<20){            int  bb =Math.abs(rdm.nextInt())%26+97;             char cc =(char)bb;            noreapeat.add(cc);        }        System.out.println(noreapeat);    }}Copy the code

Write a function that passes in two ordered arrays of integers and returns an ordered array of integers

Write code to remove an element while iterating through an ArrayList

8, classical problem: there is a pair of rabbits, from the birth of the third month from every month a pair of rabbits, rabbit children grow to the fourth month after every month and a pair of rabbits, if rabbits are not dead, ask the total number of rabbits every month

Josephine ring game

import java.util.ArrayList; import java.util.List; import java.util.Scanner; Public class No10 {// There are n people standing in a circle, marked 1-n: The first one counts to m, then drags out and kills. The next one counts to m, then kills the last one. // There are two methods // method 2 is correct. Ask god to help me change, see my printed information to know my train of thought. Public static void main(String[] args) {// TODO auto-generated method stub Scanner Scanner = new Scanner(system.in); Scanner Scanner = new Scanner(system.in); Scanner Scanner = new Scanner(system.in); Scanner Scanner = new Scanner(system.in); Scanner Scanner = new Scanner(system.in); Scanner Scanner = new Scanner(system.in); System.out.print("Please enter total number of people:"); int totalNum = scanner.nextInt(); System.out.print("Please enter the size of the count:"); int cycleNum = scanner.nextInt(); yuesefu1(totalNum, cycleNum); System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); yuesefu2(totalNum, cycleNum); }public static void yuesefu1(int t,int p){List l = new ArrayList();for(int i=1; i<=t; i++) { l.add(i); } System.out.println(l.size()); int wei =p;while(l.size()>1)    {        if(l.size()==p)        {            System.out.println("Is equal to p");            System.out.println("Delete"+l.get(p-1));            l.remove(p-1);        }if(l.size()<p)        {            System.out.println("Less than p");            System.out.println("Delete"+l.get(p-l.size()-1));            l.remove(l.get(p-l.size()-1));            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");            for(int k = 0; k<l.size(); k++) { System.out.print(l.get(k)+".");            }            System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        }        else{// delete l.emove (p-1); //--------------------------------- System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        for(int k = 0; k<l.size(); k++) { System.out.print(l.get(k)+".");        }        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        //---------------------------------        for(int j=0; j<p-1; j++) { l.add(l.get(j)); } //--------------------------------- System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        for(int k = 0; k<l.size(); k++) { System.out.print(l.get(k)+".");        }        System.out.println();        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        //---------------------------------        for(int j=0; j<p-1; j++) { l.remove(0); } //--------------------------------- System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        for(int k = 0; k<l.size(); k++) { System.out.print(l.get(k)+".");        }System.out.println();        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");        }    }    System.out.println("Last:"+l.get(0)); }public static void yuesefu2(int t,int p){ List list = new ArrayList();for(int i=1; i<=t; i++) { list.add(i); } int k=0;while(list.size()>0)    {        k = k+p;         k= k%(list.size())-1;         System.out.print("k="+k+"Value:");        if(k<0)        {            System.out.println(list.get(list.size()-1));            list.remove(list.size()-1);            k=0;        }else{ System.out.println(list.get(k)); list.remove(k); }}}}Copy the code

regular

1. Write a regular expression that matches the IP address

Before has not been able to write regular expression, many use regular expression are direct baidu, like the last time to use regular expression verification is legitimate IP address, and then the Internet search, the result is not found a right, today for everyone to contribute, write a right, and do the analysis. (suggest that we still go to read a book to learn the standard, do not directly Baidu, or are pits). The iPv4 IP addresses are in the format of (1 to 255). (0 to 255). (0 to 255). (0 to 255)."^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."+"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."+"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$"The above is not a correct verification IP regular expressions, simple explain \ \ d 0 ~ 9 any number of {2} said appears twice [0 to 4] just any Numbers | 0 ~ 4 mean or cannot little brackets () above, is to extract string matching, 1\\d{2} means any number between 100 and 199. 2[0-4]\\d means any number between 200 and 249. 25[0-5] means any number between 250 and 255 [1-9]\\d means 1 Any number between 0 and 99 [1-9]) means any number between 1 and 9 \\. By this point, it should be clear what the regular expression above means.Copy the code

Write a regular expression to determine if a string is a number

public boolean isNumeric(String str){      Pattern pattern = Pattern.compile("[0-9] *");      Matcher isNum = pattern.matcher(str);     if( !isNum.matches() ){         return false;      }      return true;   }  Copy the code

string

1. Write a method that takes a filename and a string and counts the number of times the string appears in the file.

/** * Writes a method, entering a filename and a string, counting the number of occurrences of the string in the file. * @param fileName fileName * @param STR search string * @return* @throws Exception */ / public static int funCount1(String fileName,String STR) throws Exception {int count = 0; BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); String line ; StringBuilder sb = new StringBuilder();while((line = bf.readLine() )! = null) { sb = sb.append(line); } int a = 0;while((a = sb.indexOf(str)) ! = -1) { sb = sb.delete(a, a + str.length()); count++; }returncount; } public static int funCount2(String fileName,String STR) throws Exception {int count =0; BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream(fileName))); String line ; StringBuilder sb = new StringBuilder();while((line = bf.readLine() )! = null) { sb = sb.append(line); } String pattern =". *" + str + ". *";        while(Pattern.matches(pattern, sb.toString())) {            count ++;            int a = sb.indexOf(str);            sb.delete(a, a + str.length());        }        return count;    }Copy the code

2. Write a program to find all combinations of strings and check if they are palindromic strings

public static void main(String[] args) {  String text = "abccb";  System.out.println(isHuiwen(text)); } public static boolean isHuiwen(String text){  int length = text.length();  for(int i=0; i<length/2; i++){if(text.charAt(i)! =text.charAt(length-i-1)){return false; }}return true; }Copy the code

3, write a string reversal function, enter abcde to convert to edCBA code

import java.util.Scanner; Public class Test6 {/** * Abcde --> edCBA * Analysis: * String String has index has maximum length * passfor*/ public static void main(String[] args) {Scanner sc = new Scanner(system.in); // Scanner sc = new Scanner(system.in); System.out.println("Please enter a string:"); String line = sc.nextLine(); // Print the string in reverse order system.out.println ("String reversed:"); Int I = line.length()-1; i >= 0; i--for(int i = line.length()-1; i >= 0; I --){system.out.print (line.charat (I)); }}}Copy the code

4, small games, invert the words in the sentence

public static void reverseWord( char[ ] s,int start,int end  ){      char temp;      while(start < end){           temp = s[start];          s[start] = s[end];           s[end] = temp;     }    } public static void reverseSentense(char[] s){              int len = s.length;               int start = 0,end = 0;              reverseWord(s,0,len-1);           while(start < len){                    if(s[start] == ' ' ){                                  start++;                                  end++;                                 continue;                      }else if(s[end] == ' ' || end == len ]){                                       reverseWord(s,start,end-1);                                       strat = end;                       }else{                                end++;}                    }}Copy the code

5. Convert GB2312 encoded string to ISO-8859-1 encoded string

String s2 = new String(s1.getBytes("GB2312"), "ISO-8859-1");  Copy the code

6. Write code to count the number of characters “A” in A given text. Using iterative and recursive methods respectively

public class RecursiveCall {    public int countA(String input) {        // exitCondition -- recursive calls must have anexit condition        if (input == null || input.length( ) == 0) {            return 0;        }        int count = 0;        //check first character of the input        if (input.substring(0, 1).equals("A")) {            count = 1;        }        //recursive call to evaluate rest of the input        //(i.e.  2nd character onwards)        return count + countA(input.substring(1));    }    public static void main(String[ ] args) {        System.out.println(new RecursiveCall( ).countA("AAA rating"));  // Ans. 3    }}Copy the code

7, write a string truncation function, input as a string and the number of bytes, output as a string truncated by byte. But to ensure that Chinese characters are not cut in half, such as “I ABC”, should be cut into “I AB”, input “I ABC han DEF”, should be output as “I ABC”, rather than “I ABC+ han half”

The input is a string and the number of bytes, and the output is a string truncated by bytes -------------- To convert a String into byte type 2, Chinese characters can not be cut half -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 2. Technical difficulties 1. Know that the ASC code corresponding to the byte of a Chinese character cut in half is a value less than 0. Whether the string is valid null, string length 0,1 this boundary handling code implements package com.itheima; /** * 10, write a string truncation function, the input is a string and the number of bytes, output is a string truncation by byte. * But to ensure that Chinese characters are not cut in half, such as "I ABC" 4, should be cut into "I AB", input "I ABC han DEF", 6, should be output as "I ABC" rather than "I ABC+ han half". * * @author [email protected] */public class Test10 { public static void main(String[] args) { String srcStr1 ="I am ABC";        String srcStr2 = "I am ABC han DEF";        splitString(srcStr1, 4);        splitString(srcStr2, 6);    }    public static void splitString(String src, int len) {        int byteNum = 0;        if (null == src) {            System.out.println("The source String is null!");            return; } byteNum = src.length(); byte bt[] = src.getBytes(); // Convert String to byte arrayif(len > byteNum) { len = byteNum; } // Determine if a truncation occurs, in which case the bytes are less than 0 for the ASC codeif (bt[len] < 0) {            String subStrx = new String(bt, 0, --len);            System.out.println("subStrx==" + subStrx);        } else {            String subStrx = new String(bt, 0, len);            System.out.println("subStrx=="+ subStrx); }}}Copy the code

Given two files containing word lists (one per line), programmatically list the intersections

9. Print all permutations of a string

import java.util.Scanner; public class Demo001 { public static void main(String[] args) { String str ="";        Scanner scan = new Scanner(System.in);        str = scan.nextLine();        permutation(str.toCharArray(), 0);    }    public static void permutation(char[] str, int i) {        if (i >= str.length)            return;        if (i == str.length - 1) {            System.out.println(String.valueOf(str));        } else {            for(int j = i; j < str.length; j++) { char temp = str[j]; str[j] = str[i]; str[i] = temp; permutation(str, i + 1); temp = str[j]; str[j] = str[i]; str[i] = temp; }}}}Copy the code

10. Convert a keyboard input number into Chinese output (for example: input 1234567, output: one hundred twenty-thirty-four thousand five hundred and sixty-seven)

 public class Reader {    private String strNum;    private String strNumChFormat;    private String strNumTemp;    private int intNumLen;    private String strBegin;    public Reader(String strNum) {        this.strNum = strNum;    }    public boolean check(String strNum) {        boolean valid = false;        if(strNum. Substring (0, 1). The equals ("0")){            this.strNum = strNum.substring(1);        }        try {            new Double(strNum);            valid = true;        }        catch (NumberFormatException ex) {            System.out.println("Bad number format!");        }        return valid;    }    public void init() {        strNumChFormat = "";        intNumLen = strNum.length();        strNumTemp = strNum;        strNumTemp = strNumTemp.replace('1'.'一');        strNumTemp = strNumTemp.replace('2'.'二');        strNumTemp = strNumTemp.replace('3'.'三');        strNumTemp = strNumTemp.replace('4'.'four');        strNumTemp = strNumTemp.replace('5'.'five');        strNumTemp = strNumTemp.replace('6'.'六');        strNumTemp = strNumTemp.replace('7'.'seven');        strNumTemp = strNumTemp.replace('8'.'eight');        strNumTemp = strNumTemp.replace('9'.'九');        strNumTemp = strNumTemp.replace('0'.'zero');        strNumTemp = strNumTemp.replace('. '.'point');        strBegin = strNumTemp.substring(0, 1);    }    public String readNum() {        if (check(strNum)) {            init();            try {                for (int i = 1, j = 1, k = 1; i < intNumLen; i++) {                    if (strNumTemp.charAt(intNumLen - 1) == 'zero' && i == 1) {                        strNumChFormat = "位";                    }                    else if (strNumTemp.charAt(intNumLen - i) == 'zero' && j == 1) {                        strNumChFormat = "位" + strNumChFormat;                    }                    else if (strNumTemp.charAt(intNumLen - i) == 'point') {                        j = 1;                        k = 1;                        strNumChFormat = strNumTemp.charAt(intNumLen - i) + strNumChFormat;                        continue;                   }                   else {                       strNumChFormat = strNumTemp.charAt(intNumLen - i) + strNumChFormat;                    }          if(strNumTemp.charAt(intNumLen - i - 1) ! ='位'&& strNumTemp.charAt(intNumLen - i - 1) ! ='zero') {            if (j == 1 && i < intNumLen) {              strNumChFormat = 'pick up' + strNumChFormat;            }            else if (j == 2 && i < intNumLen) {              strNumChFormat = 'best' + strNumChFormat;            }            else if (j == 3 && i < intNumLen) {              strNumChFormat = '千'+ strNumChFormat; }}if (j == 4 && i < intNumLen) {            j = 0;          }          if (k == 4 && i < intNumLen) {            strNumChFormat = '万' + strNumChFormat;          }          else if (k == 8 && i < intNumLen) {            k = 0;            strNumChFormat = '亿' + strNumChFormat;          }          j++;          k++;        }        while (strNumChFormat.indexOf("位") != -1) {          strNumChFormat = strNumChFormat.replaceAll("位"."");        }        if (strNumChFormat.substring(0, 2) == "Pick up") {          strNumChFormat = strNumChFormat.substring(1, strNumChFormat.length());        }        if (strNumChFormat.indexOf("Point") >= 0) {          String rebegin = strNumChFormat.substring(0,              strNumChFormat.indexOf("Point"));          String relast = strNumChFormat.substring(strNumChFormat.indexOf("Point"),              strNumChFormat.length());          for (int i = 1; i <= relast.length(); i++) {            relast = relast.replaceAll("Pick up"."");            relast = relast.replaceAll("Best"."");            relast = relast.replaceAll("Thousand"."");            relast = relast.replaceAll("万"."");            relast = relast.replaceAll("亿"."");          }          strNumChFormat = rebegin + relast;        }      }      catch (ArrayIndexOutOfBoundsException ex) {        ex.printStackTrace();      }      catch (Exception ex) {        ex.printStackTrace();      }      int off = strNumChFormat.indexOf("Point");      strNumChFormat = strBegin + strNumChFormat.substring(0);    }    else {      strNumChFormat = "";    }    return strNumChFormat;  }  public static void main(String args[]) {    try {      String number = args[0].toString();      System.out.println("The number is: " + number);      Reader reader = new Reader(number);      System.out.println("Output String: " + reader.readNum());    }    catch (Exception ex) {      System.out.println("Please input like that: javac Reader <number>"); }}}Copy the code

11, In the process of Web application development, we often encounter the output of a certain code character, such as from GBK to ISO8859-1, how to output a certain code string

public String translate (String str) {        String tempStr = "";        try {            tempStr = new String(str.getBytes("ISO-8859-1"), "GBK");            tempStr = tempStr.trim();        }catch (Exception e) {            System.err.println(e.getMessage());        }        return tempStr;        }Copy the code

The date of

1. Calculate the difference between the two dates

import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * DateDistance * @author Ben * @version 1.0 * @date 2009-10-21 16:38:51 */ public class DateDistance {/** * public class DateDistance * @param one Time parameter 1: * @param two Time parameter 2: * @return*/ public static long getDistanceDays(String str1, String str2) throws Exception{ DateFormat df = new SimpleDateFormat("yyyy-MM-dd");              Date one;              Date two;              long days=0;              try {                  one = df.parse(str1);                  two = df.parse(str2);                  long time1 = one.getTime();                  long time2 = two.getTime();                  long diff ;                  if(time1<time2) {                      diff = time2 - time1;                  } else {                      diff = time1 - time2;                  }                  days = diff / (1000 * 60 * 60 * 24);              } catch (ParseException e) {                  e.printStackTrace();              }              returndays; } /** * how many days, how many hours, how many minutes, how many seconds * @param str1 time parameter 1 format: 1990-01-01 12:00:00 * @param str2 time parameter 2 format: The 2009-01-01 12:00:00 * @returnLong [] returns: Public static long[] getDistanceTimes(String str1, String str2) {DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");              Date one;              Date two;              long day = 0;              long hour = 0;              long min = 0;              long sec = 0;              try {                  one = df.parse(str1);                  two = df.parse(str2);                  long time1 = one.getTime();                  long time2 = two.getTime();                  long diff ;                  if(time1<time2) {                      diff = time2 - time1;                  } else {                      diff = time1 - time2;                  }                  day = diff / (24 * 60 * 60 * 1000);                  hour = (diff / (60 * 60 * 1000) - day * 24);                  min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);                  sec = (diff/1000-day*24*60*60-hour*60*60-min*60);              } catch (ParseException e) {                  e.printStackTrace();              }              long[] times = {day, hour, min, sec};              return times; } /** * how many days, how many hours, how many minutes, how many seconds * @param str1 time parameter 1 format: 1990-01-01 12:00:00 * @param str2 time parameter 2 format: The 2009-01-01 12:00:00 * @returnString Returns the following value: Xx days xx hours xx minutes xx seconds */ public static String getDistanceTime(String str1, String str2) {DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");              Date one;              Date two;              long day = 0;              long hour = 0;              long min = 0;              long sec = 0;              try {                  one = df.parse(str1);                  two = df.parse(str2);                  long time1 = one.getTime();                  long time2 = two.getTime();                  long diff ;                  if(time1<time2) {                      diff = time2 - time1;                  } else {                      diff = time1 - time2;                  }                  day = diff / (24 * 60 * 60 * 1000);                  hour = (diff / (60 * 60 * 1000) - day * 24);                  min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);                  sec = (diff/1000-day*24*60*60-hour*60*60-min*60);              } catch (ParseException e) {                  e.printStackTrace();              }              return day + "Day" + hour + "Hour" + min + "Points" + sec + "Seconds"; }}Copy the code

If the article has any improper place, welcome to correct, but also welcome to give you the beautiful answer in the comment area, you can also follow my wechat public number: learn Java well, daily update knowledge points summary of dry goods.