Getting Started with Java--(5) Java API

Source: Internet
Author: User
Tags dateformat natural logarithm square root truncated

Keywords: string class, StringBuffer class, System class, Math class, Random class, date class, Calendar class, DateFormat class API (Application programming Interface) refers to the application programming interface. The string class and the StringBuffer class string class and the StringBuffer class bit are in the Java.lang package. 1. String class

① strings are objects

② once initialized, it cannot be changed because it is a constant.

③ can be known by the constructor of the string class to convert a byte array or character into a string.

2. Constructing method of String class
Method declaration Function description
String () Create a string with an empty content
String (char[] value) Creates an object based on a specified array of characters
String (string value) Creates an object based on the specified string content
3, String class commonly used methods: (Package left not packet right)
int indexOf (int ch) int lastIndexOf (int ch)
char charAt (int index) Boolean endsWith (String suffix)
int Length () Boolean equals (Object anobject)
Boolean IsEmpty () Boolean startsWith (String prefix)
Boolean contains (Charsequence CS) String toUpperCase ()
String toLowerCase () String valueOf (int i)
Char[] ToCharArray () String replace (charsequence oldstr,charsequence newstr)
String[] Split (String regex) String substring (int beginindex)
String substring (int beginindex,int endIndex) String Trim ()

Example:

1 public classEXAMPLE02 {2 public static voidMain (string[] args) {3 new Thread (newOne ()). Start (); 4 New Thread (new(). Start (); 5 New Thread (newThree ()). Start (); 6 New Thread (newFour ()). Start (); 7 New Thread (newFive ()). Start (); 8} 9}10//String basic operation one class one implementsrunnable{12 public voidRun () {String s = "ABCDEDCBA"; System.out.println ("The length of the string is:" +S.length ()); System.out.println ("The first character in a string:" +s.charat (0); System.out.println ("The first occurrence in character C:" +s.indexof (' C ')); System.out.println ("The last occurrence in character C:" +s.lastindexof (' C ')); System.out.println ("_____________")); 19}20}21//String judgment operation of class implementsRunnable {% public voidRun () {String S1 = "ABCDEDCBA"; String s2 = "ABCDEDCBA"; System.out.println ("The end of the string is a:" + S1.endswith ("a"); System.out.println ("String S1 is the same as S2:" + s1.equals ("ABCDEDCBA"); System.out.println ("String S1 is empty:" +S1.isempty ()); System.out.println ("String S1 starts with ABC:" + S1.startswith ("abc")); System.out.println ("string s1 contains ABC:" + S1.contains ("abc")); System.out.println ("Convert string S1 to uppercase:" +S1.touppercase ()); System.out.println ("Convert string s2 to lowercase:" +S1.tolowercase ()); System.out.println ("_____________")); 34}35}36//String conversion operation Notoginseng class three implementsrunnable{38 public voidRun () {s3 String = "ABCD"; System.out.print ("Results after converting a string to a character array"); char[] Chararray=S3.tochararray (); (int i = 0;i<chararray.length;i++) {if (i!=chararray.length-1) {System.out.print (chararray[i]+ ",");}else46System.out.println (Chararray[i]); 47}48 System.out.println ("The result of converting an int to a String type:" +string.valueof (123); System.out.println ("_____________")); 50}51}52//string substitution and removal of whitespace operations with class four implementsrunnable{54 public voidRun () {String s = "Itcase"; System.out.print ("Replace it with cn.it results:" +s.replace ("It", "cn.it"); S4 String = "I t c a s E"; System.out.println ("The result of removing both ends of a string:" +S4.trim ()); System.out.println ("The result of removing all whitespace from the string:" +s4.replace ("", ""); System.out.println ("_____________"); }63 }64//String interception and Segmentation class Five implements  runnable{66 public void Run () {x-String str = "Badminton-basketball-ping-pong"; System.out.println ("The result from the fifth character truncated to the end:" + Str.substring (4)); System.out.println ("The result of clipping from the fifth character to the sixth character:" +str.substring (4,6)); The elements in the segmented string array are: "); string[] Strarray = Str.split ("-"); * * for(int i = 0;i<strarray.length;i++) {73 if (i!=strarray.length-1) {System.out.print (strarray[i]+ ",");}else { System.out.println ( Strarray[i]); }78 }79 System.out.println ("_____________"); }81}    

Operation Result:

The length of the string is: 9 The first character in the string: the first occurrence of a character C: the position of the last occurrence in the 2 character C: 6 _____________ Whether the end of thestring is A:false string S1 is the same as S2: false whether the string S1 is empty: False if the string S1 begins with ABC: true if the string S1 contains abc:true to capitalize the string S1: ABCDEDCBA turns the string s2 to lowercase: abcdedcba____ _________ The result of converting a string to a character array a,b,c,d converts the int value to the result of a string type: 123_____________ The result from the fifth character to the end: Basketball-  Table tennis is truncated from the fifth character to the sixth character: the elements in the string array after the basketball split are: The result of replacing it with cn.it: cn.itcase The result of removing both ends of the string: I t c a s E strips the result of all the blanks in the string: itcase______ _______ Badminton, basketball, table tennis _____________         

4. StringBuffer: A string buffer, similar to a character container, adds any data conversion string.

5, StringBuffer class commonly used methods:
StringBuffer append (char c) StringBuffer Insert (int offset, String str)
StringBuffer deletecharat (int index) StringBuffer Delete (int start, int end)
StringBuffer replace (int start, int end, String str) void Setcharat (int index,char ch)
String toString () StringBuffer reverse ()
Example:
1 public classEXAMPLE08 {2 public static voidMain (string[] args) {3Add (); 4 New Thread (newRemove ()). Start (); 5 System.exit (0); 6 New Thread (newAlter ()). Start (); 7} 8 public static voidAdd () {9 System.out.println ("1, add ——————————————————"): Ten StringBuffer sb = new StringBuffer (); Define a string buffer Sb.append ("ABCDEFG");//Add a string at the end of the System.out.println ("Append add Result:" +SB); Sb.insert (2, "123"); System.out.println ("Insert Add Result:" +SB); 15}16}17 class Remove Implements runnable{18  @Override19 public void  run () {System.out.println ("2, delete ——————————————————" ); StringBuffer sb = new StringBuffer ("ABCDEFG" ); Sb.delete (1,5);//Specify range Delete at System.out.println ("Delete specified range result:" +  SB); Sb.deletecharat (2);//Specify Location Delete System.out.println ("Delete specified location result:" +  SB); Sb.delete (0,sb.length ()); /Clear Buffers System.out.println ("Empty buffer result:" +  SB); }29 }30 class alter implements  RUNNABLE{31  @Override32 public void  run () {System.out.println ("3, modify ——————————————————" ); StringBuffer sb = New StringBuffer ("ABCDEFG" ); Sb.setcharat (1, ' P ');//Modify the specified position character by System.out.println ("modify the specified position character result:" +  SB); PNS Sb.replace (1,3, "QQ");//replace the specified position string or character System.out.println ("replace the specified position string or character result:" +  SB); String Rollover Result: "+  Sb.reverse ()); }41}          

Operation Result:

1. Add —————————————————— Append Add Result: Abcdefginsert Add Result: Ab123cdefg2, delete —————————————————— Delete the specified range result: AFG Delete The result of the specified position: AF empties the buffer result: 

6. The difference between StringBuffer and string

The string represented by the ①string class is a constant, and once created, the content and length are immutable, while StringBuffer represents the character container, whose contents and length can be changed at any time.

The ②string class overrides the Equals () method of the object class, and the StringBuffer class does not overwrite it.

③string class objects can be connected with operator +, but not between StringBuffer class objects.

Second, the system class commonly used methods
static void exit (int status) Static Long GC ()
Static Long Currenttimemills () static void Arraycopy (Object src, int srcpos,object dest,int destpos,int length)
Static Properties getProperties () static string GetProperty (String key)
The runtime class is used to represent the state of the virtual machine runtime, which is used to encapsulate the JVM VM process. Example method: Runtime run = Runtime.getruntime (); Third, the math class and the random Class 1, math class is a mathematical operation class, static method. Such as
1 public classTestt01 {2 public static voidMain (string[] args) {3 System.out.println ("Absolute Value:" +math.abs (-2)); 4 System.out.println ("Rounding Up:" +math.ceil (2.1)); 5 System.out.println ("Rounding:" +math.round (2.1)); 6 System.out.println ("Rounding Down:" +math.floor (2.1)); 7 System.out.println ("Max value:" +math.max (3.2,2.1)); 8 System.out.println ("Take min:" +math.min (3.21,2.1)); 9 System.out.println ("Inverse cosine:" +math.acos (math.pi/90 )), and System.out.println ("Inverse chord:" +math.asin (MATH.PI/45  ); System.out.println ("Anyway Cut:" +math.atan ()); System.out.println (Math.atan2 (12,12 )); 13 System.out.println ("Cosine:" +math.cos (Math.pi/3 )), System.out.println ("Sine:" +math.sin (30*math.pi/180));// The unit is in radians, 30 degrees in radians (30*math.pi/180), and System.out.println ("base E of natural logarithm:" +  MATH.E); System.out.println (" The N-square of the base e of the natural logarithm: "+math.exp ()"); System.out.println ("PI:" +  Math.PI); System.out.println ("Square root:" + MATH.SQRT (5 )); System.out.println ("generates a random value greater than or equal to 0.0 less than 1.0:" +  math.random ()); 
System.out.println ("2 of 3 times:" +math.pow (2,3 ));
System.out.println (System.currenttimemillis ());//Get the current system time, run the program to save memory
of System.out.println (New Date (). GetTime ());
System.out.println (Calendar.getinstance (). GetTime ());

}
-

Operation Result:

1 Absolute Value: 2 2 Rounding up: 3.0 3 Rounding: 2 4 Down rounding: 2.0 5 Take maximum: 3.2 6 Take the minimum: 2.1 7 Inverse cosine: 1.5358826490960904 8 inverse chord: 0.06987000497506388 9 Tangent: 1.4 87655094906455310 0.785398163397448311 Chords: 0.500000000000000112 sine: 0.4999999999999999413 Base of natural logarithm e:2.71828182845904514 N of the base e of the natural logarithm: 162754.7914190039215 pi: 3.14159265358979316 square root: 2.2360679774997917 Generates a random value greater than or equal to 0.0 less than 1.0:0.366045471773395518 2 of 3 parties: 8.019 149897643508020 149897643508521 Sun Jul 14:20:35 CST 2017
2, Rondom class, non-static method Rondom class construction method: Rondom (); Rondom (long Seed); Common methods of Rondom class
Boolean Nextboolean () Double nextdouble () Float Nextfloat ()
int Nextint () int nextint (int n) Long Nextlong ()

Example:

1 public classEXAMPLE16 {2 public static voidMain (string[] args) {3 new Thread (newOne ()). Start (); 4 New Thread (new(). Start (); 5 New Thread (newThree ()). Start (); 6} 7} 8 Class One implementsrunnable{9 public voidRun () {ten random R = new Random ()///not pass in seed 11//randomly generate 10 [0,100] integer between (int x=0;x<10;x++) {System.out.println (r.nextint); }15 System.out.println ("_____________"); }17 } Class two implements runnable{19 public void Run () {Random r = new random (13);//not pass in seed 21//randomly generate 10 [0,100) between Integer (int x=0;x<10;x++) {System.out.println (r.nextint), }25 System.out.println ("_______ (___ ") }27 }28 class three implements runnable{29 public void Run () {Random r = new  Random (); System.out.println ("Generate float Type stochastic" +r.nextfloat ()); System.out.println ("Generate 0~100 int type random number" + R.nextintSystem.out.println ("Generate double type random number" +r.nextdouble ()); System.out.println ("_________ ____ "); }36}               

Operation Result:

_____________23 produces float type random number 0.958026924 produces 0~100 int type random number 4425 produces double type random number 0.1398726690347320626 _____________ 
Four, for the date type of operation class has three, respectively is Java.util.date,java.util.calendar and Java.text.DateFormat. 1. The date class is used to represent the date and time: The ①date () is used to create a date object of the current datetime, and ②date (long Date) is used to create a date object of the specified time. Create such as: Date date1 = new Date (), Date date2 = new Date (9666546565L), 2, Calendar class is used to complete the operation of date and Time fields, is abstract class, cannot be instantiated, need to call its static in the program Method getinstance () to get a calendar object, and then call its corresponding method: Calendar calendar = calendar.getinstance (); Calendar Common methods:
int get (int field) Returns the value of the specified calendar field, such as: Calendar. (Calendar.yerr);
void Add (int field,int amount) void set (int field,int value)
void set (int year,int month,int date) void set (int year,int month,int date,int hourofday,int minute,int second)
Note: The starting value for the Calendar.month field month starts at 0 instead of 1. Example:
1 public classExample {2 public static voidMain (string[] args) {3 new Thread (newOne ()). Start (); 4 New Thread (new(). Start (); 5} 6} 7 Class One implements Runnable {8 public void  Run () {9 Date date = new  date (), and date date2 = new Date (966666666666L ) ;  System.out.println (date);  System.out.println (Date2); System.out.println ("--------------" ) }15 }16 class implements  Runnable {public void  run () {Calendar calendar = Ca Lendar.getinstance ();//Gets the Calendar19 int representing the current time year =  calendar.get (calendar.year); int month = Calendar.get ( Calendar.month) +1 , int date =  Calendar.get (calendar.date), int hour =  Calendar.get (calendar.hour ); minute int =  Calendar.get (calendar.minute); second =  calendar.get (calendar.second); 25 System.out.println ("The current time is:" +year+ "year" +month+ "month" +date+ "Day" +hour+ "when" +minute+ "cent" +second+ "seconds" ); 26 System.out.println ("--------------" ); }28}        

Operation Result:

Sun Jul 14:29:41 CSTSat 14:31:06 CST------------- Current time: July 2, 2017 2:29 41 seconds-------------- /c0>

3. The DateFormat class, which is designed to convert dates into strings or date strings displayed in a particular format, is not instantiated, but provides a static method. SimpleDateFormat, DateFormat class subclass, is a class that formats and parses dates in a locale-sensitive way by creating an instance object from new. SimpleDateFormat allows you to select any user-defined date-time format to run. such as: simpledateformat ft = new SimpleDateFormat ("E yyyy.     Mm.dd ' at ' hh:mm:ss a zzz ');     This line of code establishes the format of the conversion, where YYYY is the full ad year, MM is the month, DD is the date, HH:MM:SS is time, minutes, seconds.     Note: Some format uppercase, some format lowercase, such as MM is the month, MM is divided; HH is 24-hour, and HH is a 12-hour system. The results of the above example compilation run as follows: Current Date:sun 2014.07.18 at 14:14:09 PM PDT where the parse (String source) method, which attempts to follow the given SimpleDateFormat object The formatted store to parse the string. Example:
1 public class Example {2 public     static void Main (string[] args) throws exception{3//        Create a Simpledatefor Mat Object 4         SimpleDateFormat df1 = new SimpleDateFormat (5                 "gyyyy year mm DD day: Today is yyyy year D, E"); 6//        The date template for the SimpleDateFormat object is formatted with Date Object 7         System.out.println (Df1.format (new Date ())); 8  9         SimpleDateFormat DF2 = new SimpleDateFormat ("yyyy year mm DD Day"); String dt = "August 3, 2012" }14} /c7>  

Operation Result:

AD2017 July 02: Today is the 183th day of 2017, Sunfri 00:00:00 CST 2012

Getting Started with Java--(5) Java API

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.