Common classes of Java basics

Source: Internet
Author: User
Tags dateformat square root string format stringbuffer

A, String

1. A string of data consisting of multiple characters that can be converted to and from a character array

2. Construction Method:
Public String () empty construct
public string (byte[] bytes) turns the byte array into a string
public string (byte[] bytes,int offset,int length) turns part of a byte array into a string
public string (char[] value) turns the character array into a string
public string (char[] value,int offset,int count) turns a part of a character array into a string
public string (string original) turns the string constant value into a string

3. Method:
     Judging function
Boolean equals (Object obj) compares the contents of a string for the same, case-sensitive
Example S1.equals (s2) S1 and S2 compare
Boolean equalsignorecase (String str) comparing string contents, ignoring case
Example s1.equals (S2) s    1 and S2 comparison, note the case-sensitive
Boolean contains (String str) to determine if a large string contains a small string
example S1.contains ("Hello") determines if there is no hello in S1 in the string
Boolean startsWith (String str) determines whether a string begins with a specified string
example S1.startwith ("H")   determines whether the S1 starts with H
Boolean Endswit      H (String str) determines whether the string ends with a specified string
example S1.endwith ("s")   determines whether S1 ends with S
Boolean isEmpty () to determine if the string is empty
Example S1.isempty () determines whether S1 is an empty string

Get features
int length () Gets the length of the string
Example S.length ()
char charAt (int index) Gets the character of the specified position index
Example S.charat (7) Gets the character of the seventh position (starting from 0)
int indexOf (int ch) returns the index of the first occurrence of the specified character in this string
Example S.indexof ("C") gets the position of the first occurrence of C
int indexOf (String str) returns the index of the first occurrence of the specified string in this string
Example S.indexof ("Cake") gets the position of the first occurrence of the cake
int indexOf (int ch,int fromIndex) returns the index at the first occurrence of the specified character from the specified position in this string
Example S.indexof ("C", 4) gets the index of C from the 4th index
int indexOf (string str,int fromIndex) returns the index at the first occurrence of the specified string from the specified position in this string
Example S.indexof ("Cake", 4) gets the index of cake from the 4th index
string substring (int start) intercepts the string from the specified position, by default to the end
Example s.substring (5) intercepts a string from the 5th position
string substring (int start,int end) intercepts a string from the specified position to the end
Example S.substring (5,8) intercepts a string from the 5th position to the end of 8th, excluding the 8th character. (Package left without packet right)

Conversion function
Byte[] GetBytes () converts the string to a byte array.
Example byte[] bys = S.getbytes ();
Char[] ToCharArray () converts a string to a character array
Example char[] cha = S.tochararray ();
The static string ValueOf (char[] CHS) turns the character array into a string.
Example String ss = string.valueof (CHA);
static string valueOf (int i) to convert data of type int to string
example int y=100;
String s2= string.valueof (y);
String toLowerCase () turns the string into lowercase
Example String s1=s.tolowercase
String toUpperCase () turns the string into uppercase
Example String s1=s.touppercase
String concat (String str) concatenation of strings
Example S1.concat (S2) splicing S1 and S2


Other features
String replace (char old, char new) replaces one of the characters in a string
Example S1.replace ("P", "U") replaces all P characters in the S1 with the U character
String Replace (string old, string new) replaces strings in a string
Example S1.replace ("Hello", "Feiji") replaces the Hello in S1 with the Feiji
String trim () to remove whitespace at both ends of a string
Example S1.trim ();
int CompareTo (String str) compares two strings in a dictionary order
Example S1.compareto (S2);
Compare S1 and S2 to return 0.
int compatetoignorecase (String str) compares two strings in a dictionary order, case-sensitive
Example Ibid.

Second, StringBuffer(is synchronous, data security, low efficiency)/stringbuilder (single thread use, unsynchronized, high efficiency)

1. Thread-safe variable strings.


2. Construction method
Public StringBuffer () no parameter construction method.
public stringbuffer (int capacity) Specifies the capacity of the string buffer object.
Public StringBuffer (String str) specifies the string content of the string buffer object.


3. Methods
A: Add Features
Public StringBuffer Append (string str) add any type to the string in the Cup
Public stringbuffer Insert (int offset,string str) inserts any type of data into the cup at the specified location

B: Delete Feature
Public stringbuffer deletecharat (int index) deletes a character at the specified position
Public StringBuffer Delete (int start,int end) Removes all characters from the specified interval (package left without packet right)

C: Replace function
Public stringbuffer replace (int start,int end,string str) replaces the specified interval string (packet left without packet right)

D: Invert function
Public StringBuffer reverse () reverses the string, example ABC--CBA

E: Interception function (note that the return value is of type string)
public string substring (int start) truncates the string (all strings before the input parameter are truncated)
public string substring (int start,int end) truncates the range of strings (packet left without packet right)
public int Capacity () returns the current capacity.
public int Length () returns the length (number of characters).

third, contrast Stringand theStringBufferthe efficiency of stitching strings
 Packagetext; Public classText { Public Static voidMain (string[] args) {String s= ""; Longstart_s =System.currenttimemillis ();  for(inti = 0;i < 10000;i++) {s+ = "AAAA"; }        Longend_s =System.currenttimemillis (); System.out.println ("String concatenation n times" + (end_s-start_s) + "MS" ); StringBuffer SS=NewStringBuffer (); LongSTART_SS =System.currenttimemillis ();  for(inti = 0;i < 10000;i++) {ss.append ("AAAA"); }        LongEND_SS =System.currenttimemillis (); System.out.println ("StringBuffer splicing n Times" + (END_SS-START_SS) + "MS" ); }}

iv. Math

The 1.Math class contains methods for performing basic mathematical operations, such as elementary exponents, logarithms, square roots, and trigonometric functions.

2. Member Methods
public static int abs (int a) returns the absolute value of an int.
public static double Ceil (double A) rounding up
public static double floor (double a) rounding down
public static int max (int a,int b) compares the maximum values of two numbers
public static Double pow (double a,double b) a power of B
public static double random () number
public static int round (float a) rounding
public static double sqrt (double a) positive square root

Example: Because all are static, so direct math. Method can be used

 Package text;  Public class Text {    publicstaticvoid  main (string[] args) {        System.out.println ( MATH.E);   // the output value is: 2.718281828459045        // the output value is: 3.141592653589793        System.out.println (Math.Abs (-123)); // output values are: 123, absolute value     }}
v. Random

1. This class is used to generate random numbers

2. Construction method

Public Random () does not give the seed, using the default seed, is the millisecond value of the current time.
Example Random r = new Random ();
The public random (long Seed) gives the specified seed, and the random number obtained after the seed is given is the same
Example Random r = new Random (1201);

3. Member Methods

public int Nextint () returns a random number in the range of int
Example R.nextint () returns a random number in the range of int
public int Nextint (int n) returns the random number in the "0,n" range
Example R.nextint (10) returns a random number within 0 to 10

Example 1:

 Package text; Import Java.util.Random;  Public class Text {    publicstaticvoid  main (string[] args) {        new  Random ();         int a = R.nextint (ten);        System.out.println (a); // The return value is a random number within 0~10     }}

Example 2:

 package   text;  import   Java.util.Random;  public  class   Text { public  static  void   main (string[] args) { for  (int  i=0;i<10;i++) {//  For loop, loop 10 times, output a random number of 0~10 at a time  random r = new   Random ();             int  a = R.nextint (10

VI. Date

1.Date represents a specific moment, accurate to milliseconds

2. Construction method

Public date () creates a Date object based on the current millisecond value
Public date (long date) creates a Date object based on the given millisecond value

3. Member Methods
Public long GetTime () gets the current time
public void SetTime (long time) setting

Seven, DateFormat

1.DateFormat is an abstract class of date/time formatting subclasses that formats and resolves dates or times in a language-independent manner.
is an abstract class, so use its subclasses SimpleDateFormat

2.SimpleDateFormat (can convert date to string type)

3. Construction method
Public SimpleDateFormat () default mode
Public SimpleDateFormat (String pattern)
SimpleDateFormat SDF = new SimpleDateFormat ("yyyy mm month DD Day HH:MM:SS")
4. Member Methods
Public final string format (date date) converts a datetime to a string type
Public Date Parse (string source) parses the given string into a date format

Example:

 Packagetext;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date; Public classDateformatutil { Public StaticString datetostring (date date) {//See the name, date, turn the stringSimpleDateFormat SDF =NewSimpleDateFormat ("yyyy mm month DD Day HH:MM:SS"); returnSdf.format (date); }         Public StaticDate stringtodate (String str) {//See name, string to dateDate d =NULL; SimpleDateFormat SDF=NewSimpleDateFormat ("Yyyy-mm-dd"); Try{d=sdf.parse (str); } Catch(ParseException e) {e.printstacktrace (); }        returnD; }}
 Packagetext;Importjava.util.Date; Public classText { Public Static voidMain (string[] args) {Date d=NewDate (); System.out.println (dateformatutil.datetostring (d)); //the output value is: July 23, 2017 14:55:23String SS= "2015-07-23"; System.out.println (Dateformatutil.stringtodate (ss)); //the output value is: Thu Jul 00:00:00 CST    }}
viii. Calendar

The 1.Calendar class is an abstract class that provides methods for converting between specific moments and a set of calendar fields such as year, MONTH, Day_of_month, HOUR, and provides methods for manipulating calendar fields, such as getting the date of the next week.

2. Member Methods
public static Calendar getinstance () gets the current time
Calendar C = calendar.getinstance;

public int get (int field) returns the value of the given Calendar field.
public void Add (int field,int amount) operates on the current calendar based on the given calendar field and the corresponding time
Public final void Set (int year,int month,int date) Sets the current calendar time

Common classes of Java basics

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.