Object,string,stringbuffer,stringbuilder,system,runtime,date,math Introduction and Usage (API)

Source: Internet
Author: User
Tags time and seconds

1 Object objects

The core idea of object-oriented: "Find the right object and do the right thing".

The right object:

    1. Describe the class yourself and create the object yourself.
    2. Sun has described a lot of commonly used classes that can be used to create objects.

API (Application program Interface)

The ultimate parent of the many classes sun defines is object. Object describes the common properties and methods of all classes.

1.1 ToString Method

ToString () Returns the description information for the object [email protected] class name @ hash code value 16 binary form.

When you enter an object directly, the ToString method of the object is called.

Exercise: Customizing a person class to print descriptive information about the object, requiring a description: name-age

Issue: When calling the ToString method of P, the printed information is the class name + memory address value. Not meet the requirements. According to the inheritance we learned before, if the specified function of the parent class does not satisfy the requirement, then the subclass can replicate the function function of the parent class. When the object calls the ToString () method again, the ToString method of the subclass replication is called.

programming Habits: developers want to rewrite the custom class ToString (), to do a detailed description of the object

1.2 Equals method

equals () Returns the result of the comparison if equality returns TRUE, otherwise false, the memory address value of the object is compared.

Question: Compare whether two people are the same person, judging by the names of two people.

question: If according to the name to determine whether two people are the same, obviously P and P1 is the same person, but the program input is not the same person. Does not meet the requirements of our real life.

Solution: According to our inherited function, if the function of the parent does not meet our current requirements, then we can make this function in subclasses to compound our requirements.

programming Habits: developers want to override Equals () on a custom class so that when comparing two objects, the object's properties are equal, not the memory address.

1.3 Hashcode Method

hashcode () Returns the hash code value of the object: a hashing algorithm using the operating system's underlying implementation. The hash code value for the same object is unique.

java specifies that if the two object equals returns True, the Hashcode code of the two objects must be identical.

2 String class

The string class describes a sequence of text strings. Message QQ Write log.

Create a string two ways to object the class:

    1. "" Direct Assignment method
    2. New Keyword method
2.1 Comparison of String objects

String Str = "Jack" This statement first checks whether the string constant pool holds the string object "Jack1", and if it does not exist, the string object is created in the string constant pool if there is a memory address value that returns the string directly.

String str3 = new String ("Jack") the statement creates two objects, first checking that the string constant in the pool does not exist in the string object, and if it does not exist, it is created and returns the memory address value if it exists. Once created, the new string will open a string object in the heap memory. A total of two objects.

2.2 Getting methods
int Length ()  Gets the character of the string char charAt (int  index) Gets the characters at a particular position (corner label out of bounds)int  IndexOf (String str) Gets the position of a specific character (overload)int lastIndexOf (int ch) Gets the position of the last character

2.3 Judging method
Boolean whether EndsWith (String str) ends with the specified character Boolean NULL V1.6Boolean contains (charsequences) contains the specified sequence applied: Searches for Boolean equals (Object anobject) Equality Boolean equalsignorecase ( String anotherstring) ignores case equality

2.4 Conversion method
String (char[] value) converts a character array to a string (charintint  count) Static String ValueOf (char[] data)static string valueOf (charint  int  count)char[] ToCharArray ()  converts a string to a character array

2.5 Other methods
String replace (charchar  Newchar) replaces string[] Split (string regex) cuts string substring (int  beginindex) string substring (intint  endIndex) Intercept string string toUpperCase () to uppercase string toLowerCase () to lowercase string trim () to remove spaces

2.6 Practice
    1. A function that removes spaces on both sides of a string.
 Public classDemo1 {//defines a function that removes spaces around a string Public Staticstring Trim (String str) {//0. Define the starting index variable required by the string   intStart = 0; intEnd = Str.length ()-1; //1. For loop traversal of each character of a string object    for(inti = 0; I<str.length (); i++ )   {        if(Str.charat (i) = = ") {Start++; }Else{                   Break;   }} System.out.println (start);  for(; End<str.length () && end >= 0; )   {        if(Str.charat (end) = = ") {End--; }Else{             Break;   }} System.out.println (end); //2. Finding substrings   if(Start <end) {         returnStr.substring (Start, (end+1) ); }Else{         return"_"; }

2. Get the Upload file name "D:\\20120512\\day12\\demo1.java".

Public Static string getFileName2 ( string path ) {

return path. substring (path.lastindexof ("\ \") + 1 )

3. Reverse-order the characters stored in the string object.

//reverse-order characters stored in a string object     Public Staticstring reaversestring (string src) {//1. Converting a string to a character array       CharChs[] =Src.tochararray (); //2. Circular switching        for(intStart = 0, end = chs.length-1; Start < end; start++,end-- )       {           //3. Data exchange           Chartemp =Chs[end]; Chs[end]=Chs[start]; Chs[start]=temp; }      //4. Converting a character array to a string       return NewString (CHS); }

4. Find the number of occurrences of a substring in the entire string

 Public Static intGetCount (string src, string tag) {//0. Variables that define the index variables and the number of statistics      intindex = 0; intCount = 0; //1. Write Loop judgment       while(index = src.indexof (tag))! =-1)//Jackjava      {       //2. Ask for a stringSystem.out.println (SRC); SRC= src.substring (index + tag.length ());//Index 4 + 4 = 8System.out.print (Src.length () + ":" + Index + ":" +tag.length ()); //3. Accumulationcount++; }           returncount; }

3 StringBuffer

StringBuffer : Because the string is immutable, it causes the string object to flood, and in applications that frequently change the string object, you need to use a mutable string buffer class.

Characteristics:

    1. The capacity of the default buffer is 16.
    2. StringBuffer: All buffer operation methods for thread safety are synchronous. Efficiency is low.
3.1 Adding methods

StringBuffer ("Jack") assigns a value when creating an object

Append () Adds a new text object at the tail of the buffer

Insert () Adds a new text object at the specified subscript position

StringBuffer sb = new stringbuffer ("Jack");

Sb.append (true);

Sb.append (' a ');

Sb.append. Append (34.0). Append (new char[]{' O ', ' o '}); Chained programming

System.          out. println (Sb.tostring ()); Chinese text data for output buffers

SB = New stringbuffer ("Jack");

Sb.insert (2, "Java"); Jajavack

System. out. println (Sb.tostring ());

3.2 views

ToString () returns the string for this container

IndexOf (String str) returns the index of the specified substring that appears for the first time in the string.

SUBSTRING (int start) intercepts a string starting at its starting position

3.3 Modification (U)

replace (int start int endstring str) replaces the String characters in the substring of this sequence with the characters given in. The substring starts at the specified start point and continues to end - 1 the character at the index

Setcharat (int index char CH) specifies the index position to replace one character

3.4 Delete (D)

3.5 reverse order

Reverse () outputs the string in reverse order.

4 StringBuilder

StringBuilder is JDK1.5 after the thread is unsafe, but the efficiency is high. Usage is similar to StringBuffer.

5 System

System can get the properties of the systems.

6 Runtime

The runtime class primarily describes the environment in which the application is running.

7 Date

The date class encapsulates the current time of the system: But date is obsolete, and Sun recommends using the Calendar class.

Calendar: This class is a calendar class that encapsulates the time-zone of the month-day time and seconds.

Date Formatting class: SimpleDateFormat

8 Math

Math: Classes encapsulate a lot of math functionality.

Exercise: Generate a random code

Object,string,stringbuffer,stringbuilder,system,runtime,date,math Introduction and Usage (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.