Java-Common classes

Source: Internet
Author: User
Tags natural logarithm pow square root

  Main content: * String related Class (String, StringBuffer) * Basic data Type wrapper class (Byte, Character, short, Integer, Long, Float, Double, Boolean) * Math Class * File class * Enum class     java.lang.string class  * Java.lang.String class represents an immutable sequence of characters. * "XXXXX" is an object of this class. * Common construction method of String class:  * * String (string original): Creates a copy of string object original.   * * String (char[] value): Creates a string object with a character array.   * * String (char[] value, int offset, int count): Creates a string object from the count character sequence starting with the offset entry with a character array. Common methods of    string class (1): * Public char charAt (int index): Returns the index character of the string. * public int Length (): Returns the length of the string. * Public int indexOf (string str): Returns the initial address of the first STR string in a string, and cannot find 1. * Public int indexOf (string str, int fromIndex): Returns the initial address of the first STR string from FromIndex in the string, and cannot find the return-1. * Public Boolean Equalsignorecase (string another): Compare strings with another (ignoring case) * public string replace (char OldChar, Char Newchar): Replaces OldChar characters with Newchar characters in strings. * Example Program: public class Test { public static void main (string[] args) {   StRing S1 = "Sun java", s2 = "Sun java";  System.out.println (S1.charat (1));//u  System.out.println (S2.length ( ));//8  System.out.println (S1.indexof ("Java"));//4  System.out.println (S1.indexof ("Java"));//-1  S Ystem.out.println (s1.equals (S2));//false  System.out.println (s1.equalsignorecase (S2));//true   string s = "I am a programmer, I am learning Java";  String sr = s.replace (' i ', ' you ');  System.out.println (SR);//You are a programmer, you are learning java & nbsp;}} Common methods for    string class (2):  * public boolean stratswith (string prefix): Determines whether a string begins with a prefix string. * Public Bolean endsWith (string suffix): Determines whether the string ends with a suffix string. * public String toUpperCase (): Returns the uppercase form of the string. * public String toLowerCase (): Returns the lowercase form of the string. * public string substring (int beginindex): Returns the substring from the beginning of Beginindex to the end of the string. * public string substring (int beginindex, int endIndex): Returns the substring from beginindex start to the end of EndIndex (not included). * public string trim (): Returns the string that is removed from the beginning and the end of the string. * Example Program: public class Test { pubLic static void Main (string[] args) {   String s = "Welcome to Java world!";   String S1 = "Sun java";  System.out.println (S.startswith ("Welcome"));//true  System.out.println (S. EndsWith ("World"));//false  string SL = S.tolowercase ();  string sU = S.touppercase ();  System.out.print ln (sL);//welcome to Java world!  System.out.println (SU),//welcome to Java world!  String SubS = s.substring ( One);  System.out.println (SubS);//java world!  String sp = S1.trim ();  System.out.println (sp);//sun ja Common methods of Va  } }   string class (3):  * static Overloaded Method:  * * public static String valueOf (...) : You can convert data of the underlying data type to a string, for example:     *** public static string valueOf (double D)   * * public static string Val ueof (int i)   * * * public string[] Split (string regex): Returns an array of strings separated by a regex string in a string, and the trailing (i.e., last) empty string omitted. * Public string[] Split (string regex, int limit): Returns the Regex in the string String to split the string array, if limit is greater than 0, then split before limit-1 times (note: If the limit is 1 o'clock, it is also said to split 0 times), if more than the number of divisible, divided by the number of divisible, drag the empty string to retain, if not enough to split the number of times, according to Li Mit-1 Sub-points, all remaining reserved; if limit is less than 0, the empty string is divided by the divisible number, and if limit equals 0, the empty string that is dragged is ignored by the divisible number. * Example Program: public class Test { public static void main (string[] args) {   int j = 1234567;  String Snumb ER = string.valueof (j);  System.out.println ("J is" + snumber.length () + "bit number.) ");  String s =" Mary, F, 1976 ";  string[] sPlit = S.split (", ");  for (int i=0; i<split.length; i++) {   system.out.println (split[i]); }  }}output Result:j is a 7-digit number. Marryf1976    java.lang.stringbuffer class:  * java.lang.StringBuffer represents a variable sequence of characters. * StringBuffer is similar to string, but StringBuffer can change its string. * Common construction methods of the StringBuffer class:  * * StringBuffer (): Creates a "null" StringBuffer object that does not contain a sequence of characters.   * * StringBuffer (String str): Creates a StringBuffer object that contains the same sequence of characters as the String object str.    stringbuffer Common Methods (1):  * overloaded methods Public StringBuffer Append (...) : You can add a sequence of characters for the StringBuffer object, returning the StringBuffer object reference after it was added, such as:  * * Public stringbuffer append (String str)   * * Public StringBuffer Append (stringbuffer strbuf)   * * Public stringbuffer append (char[] str)   * * Public stringbuffer Append (char[] cha, int offset, int len)   * * Public stringbuffer append (Double d)   * * Public StringBuffer AP Pend (Object obj)   * * ...    stringbuffer common method (2):  * overloaded method public StringBuffer insert (.. . ): You can insert a sequence of characters at the specified location for the StringBuffer object, returning a reference to the modified StringBuffer object, such as:  * * public stringbuffer Insert (int offset, String St R)   * * Public stringbuffer Insert (int offset, double d)   * * Method public StringBuffer Delete (int s Tart, int end): You can delete a sequence of characters from start subscript to end (not including), returning a reference to the modified StringBuffer object.    stringbuffer Common Methods (3):  * and String classes contain similar methods:  * * public int indexOf (String str)   * * Publi c int indexOf (String str, inT fromIndex)   * * public string substring (int. start)   * * public string substring (int start, int end)   * * public int Length () * Method public StringBuffer reverse () is used to reverse the character sequence and return a reference to the modified StringBuffer object.    stringbuffer Example Program:  public class Test { public static void main (string[] args) {   String s = "Microsoft";  char[] A = {' A ', ' B ', ' C '};  stringbuffer sb1 = new StringBuffer (s);  Sb1.app End ('/'). Append (' IBM '). Append ('/'). Append ("Sun");  System.out.println (SB1);  stringbuffer sb2 = new St Ringbuffer ("number");  for (int i=0; i<=9; i++) {   sb2.append (i); }  System.out.println (SB 2);  Sb2.delete (8, Sb2.length ()). Insert (0, a);  System.out.println (SB2);  System.out.println (sb2.re Verse ());   }}output Result:microsoft/ibm/sun Digital 0123456789ABC digital 012345543210 words cba    Basic data Type wrapper class:  * wrapper class (e.g. Integer, double, etc.) these classes encapsulate a corresponding numeric value of the underlying data type and provide it with a series ofColumn operations. * Take the Java.lang.Integer class as an example; Construction method:  * * Integer (int value)   * * * integer (String str) * Take the Java.lang.Integer class as an example; common methods :  * * public static final int max_value: Maximum int type (2 of 31 square-1)   * * public static final int min_value: Smallest int Type Number (-2 of 31)   * * Public long Longvalue (): Returns the Long value of encapsulated data   * * public double Doublevalue (): Returns the double value of the encapsulated data &nbs P * * int intvalue (): Returns the int value of encapsulated data   * * public static int parseint (string s) throws NumberFormatException: returns s string parsed into Data after int   * * public static integer valueOf (string s) throws NumberFormatException: Returns the Integer pair of the data after parsing the S string into type int Like * Wrapper class Example program: public class Test { public static void main (string[] args) {   integer i = new integer (100);   Double d = new double ("123.456");  int j = i.intvalue () + d.intvalue ();  float f = i.floatvalue () + D.F Loatvalue ();  System.out.println (j);  System.out.println (f);  double pi = double.parsedouble ("3.14159 ");  DoublE r = double.valueof ("2.0"). Doublevalue ();  Double s = pi * R * r;  System.out.println (s);  try {   int k = integer.parseint ("1.25"); } catch (NumberFormatException nfe) {   system.out.println ("Data The format is wrong! "); }  System.out.println (integer.tobinarystring (123) +" B ");  System.out.println (Integer.tohexstri NG (123) + "H");  System.out.println (integer.tooctalstring (123) + "O");   }}output result:223223.45612 .5663704 data format is wrong! 1111011b7bh173o    java.lang.math class:  * Java.lang.Math provides a series of static methods for scientific calculations, with the parameters and return value types of the methods typically Double type.   * * ABS Absolute value   * * ACOs inverse cosine, asin, atan tangent, cos cosine, sin sine, tan tangent   * * sqrt open square root   * * POW (double A, Double b) a power b   * * Log natural logarithm (base e)   * * Exp with e exponent   * * MAX (double A, double b)   * * min (Doub Le A, double b)   * * Random () returns a number from 0.0 to 1.0   * * * long round (double a) double type data A is converted to long (rounded)   * * ToDEgrees (double angrad) radian-angle   * * Toradians (double angdeg) angle-to-Radian * Example program: public class Test { publi c static void Main (string[] args) {   Double A = math.random ();  double b = math.random ();  SYSTEM.O Ut.prinltn (Math.sqrt (A * a + b * b));  System.out.println (Math.pow (A, 8));  System.out.println (Math.rou nd (b));  System.out.println (Math.log (Math.pow (MATH.E)));  Double d = 60.0, r = math.pi/4;  S Ystem.out.println (Math.toradians (d));  System.out.println (Math.todegrees (R));   }}output result:0. 227248547678212043.0369119934905976e-10015.01.047197551196597645.0    java.io.file class  * The Java.io.File class represents the System file name (path and file name) * Common construction method for file class:  * * Public file (String pathname): Creates a file object with pathname as the path, if pathname is a relative path, the default current path is stored in the System Properties user.dir   * * Public file (string parent, String child): Parent is the path, and children create a File object for the subpath * The static property of File, String separator, stores the current system'sPath delimiter    java.io.file class common method  * the file object can access the properties of files   * * Public boolean canRead ()   * * Public bo Olean CanWrite ()   * * Public boolean exists ()   * * Public boolean isdirectory ()   * * Public boolean isfile () &n Bsp * * Public boolean Ishidden ()   * * Public long lastmodified ()   * * Public long length ()   * * Public String GETN Ame ()   * * public string GetPath ()   * * public string GetAbsolutePath () * Creates an empty file or directory from the file object (in the case where the object refers to a document or directory that does not exist) & nbsp * * Public boolean createnewfile () throws ioexception  * * Public boolean Delete ()   * * Public boolean mkdir ()//Create a Path   * * Public boolean mkdirs ()//Create a series of paths * Example program: Import java.io.*;p ublic class Test { public static void main (STR Ing[] args) {   String separator = file.separator;  string filename = "MyFile.txt";  string directory = "Mydir1" + separator + "Mydir2";  file F = new File (directory, filename);  if (f.exists ()) {   s Ystem.out.println ("FileName:" + f.getabsolutepath ());   system.out.println ("File size:" + f.length ()); } else {  &NBSP;F.G Etparentfile (). mkdirs ();//Description: This will be created in the parent directory of the class (that is, the directory where the. class file is located), but note that if the class has a package directory, it is first to find the top-level parent package of the class, and then find its parent directory. and start creating (also say the full package name plus the class name is considered the name of the class)    try {    f.createnewfile ();   } catch (IOException e) {& nbsp   E.printstacktrace ();   } }  }}    java.lang.enum enum type  * Enum type   * * Only be able to take one of the specific values   * * Using the enum keyword   * * is the java.lang.Enum type * Example program: public class Testenum { public enum MyColor {red, green, blue};  public static void Main (string[] args) {   mycolor m = mycolor.red;& nbsp Switch (m) {   case red:    System.out.println ("Red");    break;   case green:& nbsp   SYSTEM.OUT.PRINTLN ("green");    break;   default:    SYSTEM.OUT.PRINTLN (" Default "); }  System.out.println (M ;  }}    Summary:  * String Correlation   * * Regular expression * Basic data type wrapper class * java.lang.math* java.io.file  * * Recursive * Enumeration type

Java-Common classes

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.