JAVA notes: common Java class libraries

Source: Internet
Author: User

JAVA notes: common Java class libraries

In this article, we will summarize the common class libraries in Java. These classes and methods in the class library are carefully designed, with high running efficiency and quality. These classes and methods are almost included in all Java software, so they are highly portable.

Next we will learn in detail.


The StringBuffer class StringBuffer uses a buffer and is also an operation String. However, unlike the String class, the content in the String class cannot be changed once determined, but the point of its memory address is changed, the content in the StringBuffer class can be changed. For StringBuffer, It is a specific operation class, so it cannot be directly assigned as a String, and must be completed through the constructor.
Common StringBuffer Methods: append (); used for String connection. The effect is equal to + in the String; insert (): Add characters to the String at the specified position; reverse (): reverse the String; replace (); replace the character content at the specified position; substring (); intercept the specified content of the string; delete (); delete the specified string; indexOf (); find whether the specified content exists;
Instance:
Public class StringBuffer01 {public static void main (String [] args) {// TODO Auto-generated method stubStringBuffer buffer = new StringBuffer (); buffer. append ("hello"); buffer. append ("nhpop12345656"); // Concatenates the string System. out. println (buffer); buffer. insert (2, "***"); // insert System. out. println (buffer); buffer. replace (7, 9, "AAA"); // replace System. out. println (buffer); String str1 = buffer. substring (); // truncate System. out. println (str1); StringBuffer str2 = buffer. reverse (); // invert System. out. println (str2); System. out. println (buffer); buffer. delete (5, 7); // delete System. out. println (buffer); if (buffer. indexOf ("pop") =-1) {// query System. out. println ("cannot be found");} else {System. out. println ("available ");}}}

The Runtime class is a class that encapsulates JVM processes. Every Java program starts a JVM process, and every JVM process corresponds to a Runtime instance, which is instantiated by JVM. There is no constructor In the Runtime definition, and the constructor of this class is private.
Runtime instance:
Public class Runtime01 {public static void main (String [] args) {// TODO Auto-generated method stubRuntime run = Runtime. getRuntime (); System. out. println ("Maximum JVM memory:" + run. maxMemory (); System. out. println ("JVM running memory:" + run. freeMemory (); String str = "sss"; for (int I = 0; I <1000; I ++) {str + = I;} System. out. println ("JVM memory size after running:" + run. freeMemory (); System. gc (); System. out. println ("JVM memory after the garbage collector is started" + run. freeMemory ());}}


Runtime and Process can use Runtime to directly call local applications. Instance: Call the application notepad and turn it off in 5 seconds.
Public class Runtime01 {public static void main (String [] args) {// TODO Auto-generated method stubRuntime run = Runtime. getRuntime (); Process p = null; try {p = run.exe c ("notepad.exe");} catch (Exception e) {e. printStackTrace (); // TODO: handle exception} try {Thread. sleep (5000); // This thread survived for 5 seconds} catch (Exception e) {// TODO: handle exception} p. destroy ();}}

The System class is a set of System-related methods and attributes. Instance: Use the System class to print the running time:
public class System01 {public static void main(String[] args) {// TODO Auto-generated method stublong startTime = System.currentTimeMillis();int sum = 0;for (int i = 0; i < 30000000; i++) {sum += i;}long endTime = System.currentTimeMillis();System.out.println("TotalTime:"+(endTime-startTime));}}

The System class can also display all System attributes of the local machine:
public class System01 {public static void main(String[] args) {System.getProperties().list(System.out);}}

The Date (Calendar) Date class directly outputs the instantiated object.
Import java. util. date; public class DateDemo01 {public static void main (String args []) {Date date = new Date (); // instantiate the Date object System directly. out. println ("current date:" + date );}};
In the Calendar class, the time can be accurate to milliseconds.
Import java. util. *; public class DateDemo02 {public static void main (String args []) {Calendar calendar = new GregorianCalendar (); // instantiate the Calendar class Object System. out. println ("YEAR:" + calendar. get (Calendar. YEAR); System. out. println ("MONTH:" + (calendar. get (Calendar. MONTH) + 1); System. out. println ("DAY_OF_MONTH:" + calendar. get (Calendar. DAY_OF_MONTH); System. out. println ("HOUR_OF_DAY:" + calendar. get (Calendar. HOUR_OF_DAY); System. out. println ("MINUTE:" + calendar. get (Calendar. MINUTE); System. out. println ("SECOND:" + calendar. get (Calendar. SECOND); System. out. println ("MILLISECOND:" + calendar. get (Calendar. MILLISECOND ));}};

The methods in Math and Random Math classes are static methods, so you only need to directly use the class name and method. Common Math methods include max, min, sqrt (), n (pow (m, n) m, and round (digits after decimal point are omitted ). The Random class is mainly used to generate Random numbers, which can generate Random numbers within the specified size range.
Random random = new Random();for(int i = 0;i<10;i++){System.out.print(random.nextInt(50)+"\t");}


Big number operations (BigInteger and BigDecimal) Java provides two classes for large number operations, where BigInteger can operate on large integer numbers. Instance:
Import java. math. bigInteger; public class BigIntegerDemo01 {public static void main (String args []) {BigInteger bi1 = new BigInteger ("123456789 "); // declare the BigInteger object BigInteger bi2 = new BigInteger ("987654321"); // declare the BigInteger object System. out. println ("addition operation:" + bi2.add (bi1); // addition operation System. out. println ("subtraction operation:" + bi2.subtract (bi1); // subtraction operation System. out. println ("Multiplication operation:" + bi2.multiply (bi1); // Multiplication operation System. out. println ("division operation:" + bi2.divide (bi1); // division operation System. out. println ("maximum number:" + bi2.max (bi1); // obtain the maximum number System. out. println ("Min:" + bi2.min (bi1); // obtain the min number BigInteger result [] = bi2.divideAndRemainder (bi1); // obtain the division operation System of the remainder. out. println ("OPERATOR:" + result [0] + "; remainder:" + result [1]) ;}};

The BigInteger class can perform decimal operations on large numbers, so that precise rounding can be performed.

The Comparator (Comparable and Comparator) class can only be used for comparison between numbers.
Example: implement the binary tree algorithm.
Class BinaryTree {class Node {// declare a Node class private Comparable data; // Save the specific content private Node left; // Save the left subtree private Node right; // Save the public Node (Comparable data) {this. data = data;} public void addNode (Node newNode) {// determine whether to place the Node in the left subtree or right subtree if (newNode. data. compareTo (this. data) <0) {// small content, placed in the left subtree if (this. left = null) {this. left = newNode; // directly set the new node to the left subtree} else {this. left. addNode (newNode); // continue downward judgment} if (newNode. data. compa ReTo (this. data)> = 0) {// place it in the right subtree if (this. right = null) {this. right = newNode; // if there is no right subtree, set this node to the right subtree} else {this. right. addNode (newNode); // continue downward judgment }}} public void printNode () {// when outputting, traverse if (this. left! = Null) {this. left. printNode (); // output left subtree} System. out. print (this. data + "\ t"); if (this. right! = Null) {this. right. printNode () ;}}; private Node root; // The root element public void add (Comparable data) {// add the Element Node newNode = new Node (data ); // define a new node if (root = null) {// No root node root = newNode; // The first element serves as the root node} else {root. addNode (newNode); // determine whether to put it in the left subtree or right subtree} public void print () {this. root. printNode (); // output through the root node}; public class ComparableDemo03 {public static void main (String args []) {BinaryTree bt = new BinaryTree (); bt. add (8); bt. add (3); bt. add (3); bt. add (10); bt. add (9); bt. add (1); bt. add (5); bt. add (5); System. out. println ("sorted Result:"); bt. print ();}};


In addition, common class libraries include the Observable class used in The Observer mode, class libraries that support regular expressions, and Timer of the scheduled scheduling class, which will be summarized later.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.