• No results found

The String Class

In document Java 8 Programming Black Book (Page 90-94)

double circumference_circle() { return 2*PI*radius; } }

All the static members can also be imported by using the * notation. This import applies only to the classes defined in a named package for the static members of a class. If you require importing the name of static member of a class that you define, the definition of the class should be included in a named package. Names of static members with no names in the default package cannot be imported. The class name in the static import statement must always be qualified with its package name.

The String Class

“I have been looking through the list of simple data types in Java”, the Novice Programmer says, “And I can’t find text strings there. Shouldn’t they be there?” “Some people say so”, you reply. “Strings are handled as objects in Java. One advantage of this is that a String object has a great variety of methods you can use with it”.

In many languages, text strings are fundamental data types inherent to the specific language; but in Java, strings are handled with the String and StringBuffer classes. Let’s take a look at the String class first.

String objects hold text strings that you can’t change; if you want to change the actual text in the string, you should use the StringBuffer class instead. Here’s an example in which we create a string and print it out (notice how much this code makes the String class look like any other simple data type):

public class App {

public static void main(String[] args) { String s1 = "Hello from Java!";

System.out.println(s1); } }

Here’s the result of this code:

C:\>java App Hello from Java!

The String class is enormously powerful, with methods that enable you to convert the string into a character array, convert numbers into strings, search strings, create substrings, change the case of the string, get a string length, compare strings, and much more. The String class is obviously a class, not an intrinsic data type, which means you create objects of that class with constructors, which you’ll learn all about in Chapter 4. A constructor is just like a normal method of a class, except you use it to create an object of that class. You’ll get a sneak peek at the String class constructors here. The String class also has a data member you use when comparing strings (which we’ll take a look at in the next chapter). This data member is shown in Table 2.2. The String class constructors, which you can use to create String objects (see the topic “Creating Strings”, coming up in this chapter), appear in Table 2.3, and the methods of the String class appear in Table 2.4.

We’ll put the material you see in the tables below to use in the next few topics, in which we’ll create and use String objects.

Table 2.2: String class field summary

Field Does this

static Comparator<String>

CASE_INSENSITIVE_ORDER

It yields a comparator (which you’ll see more about later) that orders String objects, as in compareToIgnoreCase

Immediate Solutions

Table 2.3: String class constructor summary

Constructor Does this

String() It initializes a new String object so that it holds an empty character sequence

String(byte[] bytes) It constructs a new String object by converting the array of bytes by using the platform’s default character encoding

String(byte[] bytes, Charset charset)

It constructs a new String by decoding the specified array of bytes using the specified charset

String(byte[] ascii, int hibyte) It is deprecated because it did not properly convert bytes into characters String(byte[] bytes, int offset,

int length)

It constructs a new String object by converting the subarray of bytes using the default character encoding

String(byte[] bytes, int offset,

It is deprecated because it did not properly convert bytes into characters

String(byte[] bytes, int offset,

It constructs a new String object by converting the array of bytes using the specified charset

String(char[] value) It allocates a new String object so that it represents the sequence of characters contained in the character array argument

String(char[] value, int offset, int count)

It allocates a new String object that contains characters from a subarray of the character array argument

String(int[] codePoints, int offset, int count)

It allocates a new String object that contains characters from a subarray of the Unicode code point array argument

String(String original) It initializes a new String object so that it represents the same sequence of characters as the argument string

String(StringBuffer buffer) It allocates a new String object that contains the sequence of characters contained in the string buffer argument

String(StringBuilder builder) It allocates a new String object that contains the sequence of characters contained in the string builder argument

Table 2.4: String class methods

Method Does this

char charAt(int index) It yields the character at the given index int codePointAt

(int index)

It yields the character (Unicode code point) at the specified index

int codePointBefore(int index) It yields the character (Unicode code point) before the specified index int codePointCount(int

beginIndex, int endIndex)

It yields the number of Unicode code point in the specified range of this string

int compareTo

(String anotherString)

It compares two strings lexicographically

int compareToIgnoreCase (String str)

It compares two strings lexicographically, ignoring case

String concat(String str) It concatenates the given string to the end of this string

boolean contains(CharSequence s) It returns True if this string contains the specified sequence of char values

Table 2.4: String class methods

Method Does this

boolean

contentEquals(CharSequence cs)

It compares this string to the specified CharSequence

boolean

contentEquals(StringBuffer sb)

It compares this string to the specified StringBuffer

static String copyValueOf (char[] data)

It yields a String object that’s equivalent to the given character array

static String copyValueOf (char[] data, int offset, int count)

It yields a String object that’s equivalent to the given character array by using offsets

boolean endsWith (String suffix)

It returns True if the string ends with the given suffix

boolean equals (Object anObject)

It compares this string to an object

boolean equalsIgnoreCase (String anotherString)

It compares this String object to another String object, ignoring case

static String format(Locale l, String format, Object...args)

It returns a formatted string using the given locale, format string, and arguments

static String format(String format, Object...args)

It returns a formatted string using the given format string and arguments

byte[] getBytes() It converts this String object into bytes with the default charset, storing the result in a new byte array

byte[] getBytes(Charset charset) It encodes this String into a byte sequence using the given charset, storing the result in a new byte array

void getBytes

(int srcBegin,int srcEnd, byte[] dst, int dstBegin)

It is deprecated because it did not properly convert characters into bytes

byte[] getBytes (String charsetName)

It converts this String object into bytes with the given charset, storing the result in a new byte array

void getChars

(int srcBegin, int srcEnd, char[]

dst, int dstBegin)

It copies characters from this string into the destination array

int hashCode() It yields a hash code for this string

int indexOf(int ch) It yields the index within this string of the first occurrence of the given character

int indexOf(int ch, int fromIndex)

It yields the index within this string of the first occurrence of the given character, starting the search at the given index

int indexOf(String str) It yields the index within this string of the first occurrence of the given substring

int indexOf(String str, int fromIndex)

It yields the index within this string of the first occurrence of the given substring, starting at the given index

String intern() It yields a representation for the String object boolean isEmpty() It yields True if length of string is 0

int lastIndexOf(int ch) It yields the index within this string of the last occurrence of the given character

int lastIndexOf(int ch, int fromIndex)

It yields the index within this string of the last occurrence of the given character, searching backward from the given index

int lastIndexOf(String str) It yields the index within this string of the rightmost occurrence of the given substring

Immediate Solutions

Table 2.4: String class methods

Method Does this

int lastIndexOf

(String str,int fromIndex)

It yields the index within this string of the last occurrence of the given substring, searching backward from the given index

int length() It yields the length of this string

boolean matches(String regex) It returns True if this string matches the given regular expression int offsetByCodePoints(int index,

int codePointOffset)

It returns the index within this string which is offset from the given index by codePointOffset code points

boolean regionMatches

(boolean ignoreCase, int toffset, String other, int ooffset, int len)

It tests whether two string regions are equal, allowing you to ignore case

boolean regionMatches(int toffset, String other, int ooffset, int len)

It tests whether two string regions are equal

String replace(char oldChar, char matches the literal target sequence with the given literal replacement sequence

String replaceAll(String regex, String replacement)

It yields a new string by replacing each substring of this string that matches the given regular expression with the given replacement String replaceFirst(String regex,

String replacement)

It yields a new string by replacing the first substring of this string that matches the given regular expression with the given replacement String[] split(String regex) It splits this string around matches of the given regular expression String[] split(String regex, int

limit)

It splits this string around matches of the given regular expression and the limit given as parameter

boolean startsWith(String prefix) It tests whether this string starts with the given prefix boolean startsWith(String prefix,

It yields a new string, which is a substring of this string

String substring(int beginIndex, int endIndex)

It yields a new string, which is a substring of this string, allowing you to specify the end index

char[] toCharArray() It converts this string to a new character array

String toLowerCase() It converts all the characters in this String object to lowercase by using the rules of the default locale, which is returned by Locale.getDefault() method

String toLowerCase (Locale locale)

It converts all the characters in this String object to lowercase using the rules of the given Locale

String toString() It returns the string object

String toUpperCase() It converts all the characters in this String object to uppercase using the rules of the default locale, which is returned by Locale.getDefault() method

String toUpperCase (Locale locale)

It converts all the characters in this String object to uppercase using the rules of the given locale

String trim() It removes white space from both ends of this string

Table 2.4: String class methods

Method Does this

static String valueOf (boolean b)

It yields the string representation of the boolean argument

static String valueOf (char c)

It yields the string representation of the char argument

static String valueOf (char[] data)

It yields the string representation of the char array argument

static String valueOf

(char[ ] data, int offset, int count)

It yields the string representation of a specific subarray of the char array argument

static String valueOf(double d) It yields the string representation of a double type argument static String valueOf(float f) It yields the string representation of a float type argument static String valueOf

(int i)

It yields the string representation of an int type argument

static String valueOf(long l) It yields the string representation of a long type argument

static String valueOf(Object obj) It yields the string representation of an Object type argument

In document Java 8 Programming Black Book (Page 90-94)

Related documents