Stringbuilder to int java

The StringBuilder Class

StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be changed through method invocations.

Strings should always be used unless string builders offer an advantage in terms of simpler code (see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large number of strings, appending to a StringBuilder object is more efficient.

Length and Capacity

The StringBuilder class, like the String class, has a length() method that returns the length of the character sequence in the builder.

Unlike strings, every string builder also has a capacity, the number of character spaces that have been allocated. The capacity, which is returned by the capacity() method, is always greater than or equal to the length (usually greater than) and will automatically expand as necessary to accommodate additions to the string builder.

StringBuilder Constructors

Constructor Description
StringBuilder() Creates an empty string builder with a capacity of 16 (16 empty elements).
StringBuilder(CharSequence cs) Constructs a string builder containing the same characters as the specified CharSequence , plus an extra 16 empty elements trailing the CharSequence .
StringBuilder(int initCapacity) Creates an empty string builder with the specified initial capacity.
StringBuilder(String s) Creates a string builder whose value is initialized by the specified string, plus an extra 16 empty elements trailing the string.
Читайте также:  Java add hashset to hashset

For example, the following code

// creates empty builder, capacity 16 StringBuilder sb = new StringBuilder(); // adds 9 character string at beginning sb.append("Greetings");

will produce a string builder with a length of 9 and a capacity of 16:

The StringBuilder class has some methods related to length and capacity that the String class does not have:

Length and Capacity Methods

Method Description
void setLength(int newLength) Sets the length of the character sequence. If newLength is less than length() , the last characters in the character sequence are truncated. If newLength is greater than length() , null characters are added at the end of the character sequence.
void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum.

A number of operations (for example, append() , insert() , or setLength() ) can increase the length of the character sequence in the string builder so that the resultant length() would be greater than the current capacity() . When this happens, the capacity is automatically increased.

StringBuilder Operations

The principal operations on a StringBuilder that are not available in String are the append() and insert() methods, which are overloaded so as to accept data of any type. Each converts its argument to a string and then appends or inserts the characters of that string to the character sequence in the string builder. The append method always adds these characters at the end of the existing character sequence, while the insert method adds the characters at a specified point.

Here are a number of the methods of the StringBuilder class.

Various StringBuilder Methods

Method Description
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String s)
Appends the argument to this string builder. The data is converted to a string before the append operation takes place.
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
The first method deletes the subsequence from start to end-1 (inclusive) in the StringBuilder ‘s char sequence. The second method deletes the character located at index .
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)
Inserts the second argument into the string builder. The first integer argument indicates the index before which the data is to be inserted. The data is converted to a string before the insert operation takes place.
StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)
Replaces the specified character(s) in this string builder.
StringBuilder reverse() Reverses the sequence of characters in this string builder.
String toString() Returns a string that contains the character sequence in the builder.

Note: You can use any String method on a StringBuilder object by first converting the string builder to a string with the toString() method of the StringBuilder class. Then convert the string back into a string builder using the StringBuilder(String str) constructor.

An Example

The StringDemo program that was listed in the section titled «Strings» is an example of a program that would be more efficient if a StringBuilder were used instead of a String .

StringDemo reversed a palindrome. Here, once again, is its listing:

public class StringDemo < public static void main(String[] args) < String palindrome = "Dot saw I was Tod"; int len = palindrome.length(); char[] tempCharArray = new char[len]; char[] charArray = new char[len]; // put original string in an // array of chars for (int i = 0; i < len; i++) < tempCharArray[i] = palindrome.charAt(i); >// reverse array of chars for (int j = 0; j < len; j++) < charArray[j] = tempCharArray[len - 1 - j]; >String reversePalindrome = new String(charArray); System.out.println(reversePalindrome); > >

Running the program produces this output:

To accomplish the string reversal, the program converts the string to an array of characters (first for loop), reverses the array into a second array (second for loop), and then converts back to a string.

If you convert the palindrome string to a string builder, you can use the reverse() method in the StringBuilder class. It makes the code simpler and easier to read:

public class StringBuilderDemo < public static void main(String[] args) < String palindrome = "Dot saw I was Tod"; StringBuilder sb = new StringBuilder(palindrome); sb.reverse(); // reverse it System.out.println(sb); >>

Running this program produces the same output:

Note that println() prints a string builder, as in:

because sb.toString() is called implicitly, as it is with any other object in a println() invocation.

Note: There is also a StringBuffer class that is exactly the same as the StringBuilder class, except that it is thread-safe by virtue of having its methods synchronized. Threads will be discussed in the lesson on concurrency.

Previous page: Comparing Strings and Portions of Strings
Next page: Summary of Characters and Strings

Источник

String to int, String to Integer

A common conversion is taking a string from a web request parameter or parse a CSV from storage and converting it to a primitive data type or a Integer object in java. Below we will show various ways to convert string type objects to primitive data type. On the flip side we also show how to convert an int back to a string because there could be an instance you wish to operate on the value as a string. Remember that a NumberFormatException will be thrown in the even that you attempt to convert a string to a numeric type but it doesn’t have an appropriate format.

String to int

@Test public void string_to_int()  String myString = "2"; int variable = Integer.parseInt(myString); assertEquals(2, variable); >

Int back to string

@Test public void int_to_string()  int number = 2; assertEquals("2", String.valueOf(number)); >

Stringbuffer to int

@Test public void stringbuffer_to_int()  StringBuffer buffer = new StringBuffer("2"); assertEquals(2, Integer.parseInt(buffer.toString())); >

StringBuilder to int

@Test public void stringbuider_to_int()  StringBuilder builder = new StringBuilder("2"); assertEquals(2, Integer.parseInt(builder.toString())); >

String to Integer

@Test public void string_to_integer()  Integer converted = Integer.valueOf("2"); assertEquals(new Integer(2), converted); >

Integer back to String

@Test public void integer_to_string()  Integer integerToString = Integer.valueOf("2"); assertEquals("2", integerToString.toString()); >

String to int, String to Integer posted by Justin Musgrove on 22 July 2015

Tagged: java and java-number

Источник

Transform String To Int Java & Vice-Versa

Transform String To Int Java & Vice-Versa | Here we will discuss how to convert the string value to int, and how to convert int to string. The string is immutable which means cannot be changed once declared.

How To Transform String to Int Java

To convert string to int we can use the below two methods:-
1. Integer.valueOf()
2. Integer.parseInt()

The below Java program transforms a string into an int by using the Integer.parseInt() method. The Integer.parseInt() method throws NumberFormatException if the given string is not a number.

public class Main < public static void main(String[] args) < String string = "2356"; int value = 0; try < value = Integer.parseInt(string); System.out.println("Integer value = " + value); >catch (NumberFormatException e) < System.out.println("Invalid String"); >string = "4569h"; try < value = Integer.parseInt(string); System.out.println("Integer value = " + value); >catch (NumberFormatException e) < System.out.println("Invalid String"); >> >

Integer value = 2356
Invalid String

To transform string to int we can also use the valueOf() method of Integer class. The valueOf() method internally calls Integer.parseInt() method and therefore it also throws NumberFormatException if the given string is not a number.

public class Main < public static void main(String[] args) < String string = "2356"; int value = 0; try < value = Integer.valueOf(string); System.out.println("Integer value = " + value); >catch (NumberFormatException e) < System.out.println("Invalid String"); >string = "4569h"; try < value = Integer.valueOf(string); System.out.println("Integer value = " + value); >catch (NumberFormatException e) < System.out.println("Invalid String"); >> >

Integer value = 2356
Invalid String

How To Transform Int To String Java

Now let us see how to transfer int to string. There are many ways to do so as listed below:-

1. By using the toString() method of Integer class
2. By using the valueOf() method of String class
3. By using the DecimalFormat class
4. By Using the StringBuilder class
5. By using the StringBuffer class

Transform int to String in Java by using the toString() method of the Integer class

String str1 = 89456
String str2 = -12365

Transform int to String in Java by using the valueOf() method of the String class

Источник

Оцените статью