Char&string In Java

  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Char&string In Java as PDF for free.

More details

  • Words: 2,057
  • Pages: 7
Characters and Strings The Java platform contains four classes that you can use when working with character data: Character: A class whose instances can hold a single character value String : A class for working with immutable (unchanging) data composed of multiple characters. StringBuffer: A class for storing and manipulating mutable data composed of multiple characters StringBuilder: A faster, drop-in replacement for StringBuffer, designed for use by a single thread only. Character : An object of Character type contains a single character value. You use a Character object instead of a primitive char variable when an object is required for example, when passing a character value into a method that changes the value or when placing a character value into a data structure, such as an ArrayList, that requ ires objects. *Example(CharacterDemo) Character a = new Character('a');

Strings and String Buffers The Java platform has always provided two classes, String, and StringBuffer, which store and manipulate strings- character data consisting of more than one character. The String class provides for strings whose value will not change. The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. You typically use string buffers for constructing character data dynamically String buffers are safe for use in a multi-threaded environment String builder in the same way as a string buffer, but only if it's going to be accessed by a single thread. Question Which class to use under what conditions • If your text is not going to change, use a string. • If your text will change, and will only be accessed from a single thread, use a string builder. • If your text will change, but will be accessed from multiple threads, use a string buffer. A string is often created from a string literal—a series of characters enclosed in double quotes. You can also create String objects as you would any other Java object: using the new keyword and a constructor. The String class provides several constructors that allow you to provide the initial value of the string, using different sources, such as an array o f characters, an array of bytes, a string buffer, or a string builder. String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data);

Constructors in the String Class

*

Constructor

Description

String()

Creates an empty string.

String(byte[]) String(byte[], int offset,int length) String(byte[], int, i nt, String) String(byte[], String )

Creates a string whose value is set from the contents of an array of bytes. The two integer arguments, when present, set th e offset and the length, respectively, of the subarray from whic h to take the initial values. The String argument, when present, specifies the character encoding to use to convert bytes to char acters.

String(char[]) String(char[], int, int)

Creates a string whose value is set from the contents of an array of characters. The two integer arguments, when present, s et the offset and the length, respectively, of the subarray from which to take the initial values.

String(String)

Creates a string whose value is set from another string. Using this constructor with a literal string argument is not recommen ded, because it creates two identical strings.

String(StringBuffer)

Creates a string whose value is set from a string buffer.

String(StringBuilder)

Creates a string whose value is set from a string builder.

Constructors in the StringBuffer Class Constructor StringBuffer()

Description Creates an empty string buffer whose initial capacity is 16 characters.

Constructs a string buffer containing the same characters as StringBuffer(CharSequence) the specified CharSequence. This constructor was introduce d in JDK 5.0. StringBuffer(int)

Creates an empty string buffer with the specified initial capacity.

StringBuffer(String)

Creates a string buffer whose value is initialized by the specified String. The capacity of the string buffer is the lengt h of the original string plus 16.

Getting the Length of a String or String Buffer Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings, string buffers, and string b uilders is the length method, which returns the number of characters contained in the object. String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); The StringBuffer and StringBuilder classes have a method called capacity,

returns the amount of space allocated rather than the amount of space used.

which

String

class doesn't have a capacity method, because a string cannot change

Getting Characters by Index from a String or String Buffer You can get the character at a particular index within a string, string buffer, or string builder by invoking the charAt accessor method. Example

String anotherPalindrome = "Niagara. O roar again!"; char aChar = anotherPalindrome.charAt(9); Indices begin at 0, so the character at index 9 is 'O' Note To compute the index of the last character of a string, you have to subtract 1 from the value returned by the length method. If you want to get more than one character from a string, string buffer, or string builder, you can use the substring method. Method

Description

Returns a new string that is a substring of this string, string String substring(int buffer, or string builder.The first integer argument specifies the index of the first character. The second integer argument is the i beginIndex) String substring(int ndex of the last character -1. The length of the substring is ther beginIndex, int endIn efore the second int minus the first int. If the second integer i dex) s not present, the substring extends to the end of the original str ing. Example What will be the output of the following? String anotherPalindrome = "Niagara. O roar again!"; String roar = anotherPalindrome.substring(11, 15);

Answer roar Searching for a Character or a Substring within a String(*Example StringsIndexof) The String class provides two accessor methods that return the position within the string of a specific character or substring: indexOf and lastIndexOf.

The indexOf and lastIndexOf Methods in the String Class Method

Description

int indexOf(int ch) int lastIndexOf(int ch)

Returns the index of the first (last) occurrence of the specified character.

int int int ch,

Returns the index of the first (last) occurrence of the specified character, searching forward (backward) from the spe cified index.

indexOf(int ch, fromIndex) lastIndexOf(int int fromIndex)

int indexOf(String str) int lastIndexOf(Strin g str)

Returns the index of the first (last) occurrence of the specified string.

int indexOf(String, int) int lastIndexOf(Strin g, int)

Returns the index of the first (last) occurrence of the specified string, searching forward (backward) from the specified index

Comparing Strings and Portions of Strings Methods in the String Class for Comparing Strings

*

Method

Description

boolean endsWith(String) boolean startsWith(String) boolean startsWith(String, int)

Returns true if this string ends with or begins with the substring specified as an argument to the method. The integer argument, when present, indicates the off set within the original string at which to begin looki ng.

Compares two strings lexicographically and returns an integer indicating whether this string is int compareTo(String) greater than (result is > 0), equal to (result is = 0), int compareTo(Object)** or less than (result is < 0) the argument. The Object int compareToIgnoreCase(String)** argument is converted to a string before the comparis on takes place. The com-pareToIgnoreCase method i gnores case; thus, “a” and “A” are considered equal. boolean equals(Object) boolean equalsIgnoreCase(String)

Returns true if this string contains the same sequence of characters as the argument. The Object argument is converted to a string before the comp arison takes place. The equalsIgnoreCase method ig nores case; thus, “a” and “A” are considered equal.

Manipulating Strings Can we manipulate Strings. The String class has several methods that appear to modify a string. Of course, strings can't be modified, so what these methods really do is create and return a seco nd string that contains the result. Methods in the String Class for Manipulating Strings Method

Description

String concat(String)

Concatenates the String argument to the end of this string. If the length of the argument is 0, the original string object is r eturned.

String replace(char, char) *Example(Replac eDemo)

Replaces all occurrences of the character specified as the first argument with the character specified as the second argumen t. If no replacements are necessary, the original string object is returned.

String trim()

Removes white space from both ends of this string.

String toLowerCase() String toUpperCase()

Converts this string to lower- or uppercase. If no conversions are necessary, these methods return the original str

ing. Modifying String Buffers String buffers and String builders can change their content after they've been created. Both classes provide various methods for modifying their data. Methods for Modifying a String Buffer

*

Method

Description

StringBuffer append(boolean) StringBuffer StringBuffer StringBuffer int, int) StringBuffer StringBuffer StringBuffer StringBuffer StringBuffer StringBuffer

append(char) append(char[]) append(char[], append(double) append(float) append(int) append(long) append(Object) append(String)

Appends the argument to this string buffer. The data is converted to a string before the append operation takes place.

StringBuffer delete(int start, int end)** StringBuffer deleteCharAt(int index)**

Deletes the specified character(s) in this string buffer.

StringBuffer insert(int offset, boolean b) . StringBuffer insert(int of fset, char c) StringBuffer insert(int offs et, char[]str) StringBuffer insert(int, dou ble) StringBuffer insert(int, flo at) StringBuffer insert(int, int ) StringBuffer insert(int, lon g) StringBuffer insert(int, Obj ect) StringBuffer insert(int, Str ing)

Inserts the second argument into the string buffer. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a str ing before the insert operation takes place.

StringBuffer replace(int start, int end, String str)

StringBuffer reverse()

Replaces the specified character(s) in this string buffer. Reverses the sequence of characters in this string buffer

Strings and the Compiler The compiler uses the String and the StringBuffer classes behind the scenes to handle literal strings and concatenation. Use String methods directly from a literal string: int len = "Goodbye Cruel World".length();

use + to concatenate strings: String cat = "cat"; System.out.println("con" + cat + "enation"); Behind the scenes, the compiler uses string buffers to implement concatenation String cat = "cat"; System.out.println(new StringBuffer().append("con"). append(cat).append("enation").toString()); Question 1: What is the initial capacity of the following string buffer? StringBuffer sb = new StringBuffer("Able was I ere I saw Elba."); Answer 1: It's the length of the initial string + 16: 26 + 16 = 42. Question 2: Consider the following string: String hannah = "Did Hannah see bees? Hannah did."; Question 2a: What is the value displayed by the expression hannah.length()? Answer 2a: 32. Question 2b: What is the value returned by the method call hannah.charAt(12)? Answer 2b: e. Question 2c: Write an expression that refers to the letter b in the string referred to by hannah. Answer 2c: hannah.charAt(15). Question 3: How long is the string returned by the following expression? What is the string? "Was it a car or a cat I saw?".substring(9, 12) Answer 3: It's 3 characters in length: car. It does not include the space after car.

The Wrapper Classes Each Java primitive data type has a corresponding wrapper class. A wrapper class is simply a class that encapsulates a single, immutable value. For example, the Integer class wraps up an int value, and the Float class wraps up a float value. The wrapper class names do not perfectly match the corresponding primitive data type names. Primitive Data Type boolean byte char short int long float double

Wrapper Class Boolean Byte Character Short Integer Long Float Double

The following code fragment shows how to construct an instance of each wrapper type: boolean primitiveBoolean = true; Boolean wrappedBoolean =new Boolean(primitiveBoolean); byte primitiveByte = 41; Byte wrappedByte = new Byte(primitiveByte);

char primitiveChar = ‘M’; Character wrappedChar = new Character(primitiveChar); There is another way to construct any of these classes, with the exception of Character: You can pass into the constructor a String that represents the value to be wrapped. Most of these constructors throw NumberFormatException, because there is always the possibility that the string will not represent a valid value. Only Boolean does not throw this exception. Boolean wrappedBoolean = new Boolean(“True”); try { Byte wrappedByte = new Byte(“41”); Short wrappedShort = new Short(“31313”); Integer wrappedInt = new Integer(“12345678”); Long wrappedLong = new Long(“12345678987654321”); Float wrappedFloat = new Float(“1.11f”); Double wrappedDouble = new Double(“1.11111111”); } catch (NumberFormatException e) { System.out.println(“Bad Number Format”); }

Related Documents

Introduce Re In Java
April 2020 14
Xml Programming In Java
December 2019 13
Data Structures In Java
November 2019 11
Using Xml In Java
December 2019 24