Important String Methods and Operations
09:52:00
How to convert
string to int in Java
Sometimes
there is a need to convert a
String
into an Integer
value. Even though a String is made up of digits like 1,2,3 etc
any arithmetic operation cannot be performed on it until unless it gets
converted into an Integer value. In this tutorial we will see two ways for
String to int conversion.
Method 1: Using Integer.parseInt
String str3="1234";
int num3 = Integer.parseInt(str3);
The value of
num3 would be 1234.
Note: All
characters in the String must be digits however the first character can be a
minus ‘-‘ sign. For e.g.
String str="-1234";
int num = Integer.parseInt(str);
The value of num
would be -1234
Integer.parseInt
throws NumberFormatException
If the String is not valid for
conversion for e.g.String str="1122ab";
int num = Integer.valueOf(str);
This set of
statement would throw
NumberFormatException
. you would see a compilation error like this:Exception in thread "main" java.lang.NumberFormatException: For input string: "1122ab"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
Complete example:
public class Example1{
public static void main(String args[]){
String str="123";
int num1 = 100;
int num2 = Integer.parseInt(str);
int sum=num1+num2;
System.out.println("Result is: "+sum);
}
}
Output:
Result is: 223
Method 2: Using Integer.valueOf
Integer.valueOf
works same as Integer.parseInt
. It also converts a String into an
integer value. This is how it can be used:String str="1122";
int num = Integer.valueOf(str);
The value of num
would be 1122.
It also allows
first character of String to be a minus ‘-‘ sign.
String str="-1122";
int num = Integer.valueOf(str);
Value of num
would be -1122.
Like parseInt
method it also throws
NumberFormatException
when the all the characters in the
String are not digits. For e.g. a String with value “11aa22” would cause such
exception during conversion.
Complete example:
public class Example2{
public static void main(String args[]){
String str="-234";
int num1 = 110;
//num2 would be having a negative value
int num2 = Integer.valueOf(str);
int sum=num1+num2;
System.out.println("Result is: "+sum);
}
}
Output:
Result is: -124
Java – int to
String conversion
There are
two ways to convert an integer value to a String.
1) Method 1: Using String.valueOf(int i): This method takes integer value as an argument and returns a string representing the int augment.
Method declaration:
public static String valueOf(int i)
parameters:
i – integer that needs to be converted to a string
returns:
A string representing the integer argument
1) Method 1: Using String.valueOf(int i): This method takes integer value as an argument and returns a string representing the int augment.
Method declaration:
public static String valueOf(int i)
parameters:
i – integer that needs to be converted to a string
returns:
A string representing the integer argument
int ivar = 111;
String str = String.valueOf(ivar);
2) Method 2:
Using Integer.toString(int i): This method works same as String.valueOf(int i) method. It
belongs to the Integer class and converts the specified integer value to
String. for e.g. if passed value is 101 then the returned string value would be
“101”.
Method declaration:
public static String toString(int i)
parameters:
i – integer that requires conversion
returns:
String representing the integer i.
Method declaration:
public static String toString(int i)
parameters:
i – integer that requires conversion
returns:
String representing the integer i.
int ivar2 = 200;
String str2 = Integer.toString(ivar2);
Example: Converting int to String
This program
demonstrates the use of both the above mentioned methods(valueOf and toString).
Here we have two integer variables and we are converting one of them using
String.valueOf(int i) method and other one using Integer.toString(int i)
method.
package com.beginnersbook.string;
public class IntToString {
public static void main(String[] args) {
/* Method 1: using valueOf() method
* of String class.
*/
int ivar = 111;
String str = String.valueOf(ivar);
System.out.println("String is: "+str);
/* Method 2: using toString() method
* of Integer class
*/
int ivar2 = 200;
String str2 = Integer.toString(ivar2);
System.out.println("String2 is: "+str2);
}
}
Output:
String is: 111
String2 is: 200
Java – String
to ArrayList conversion
In this
program we are converting a String to ArrayList. The steps involved are as
follows:
1) First we are splitting the string using String split() method and storing the substrings into a String array.
2) Creating an ArrayList while passing the substring reference to it using Arrays.asList() method.
1) First we are splitting the string using String split() method and storing the substrings into a String array.
2) Creating an ArrayList while passing the substring reference to it using Arrays.asList() method.
package com.beginnersbook.string;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class StringtoArrayList {
public static void main(String args[]){
String num = "22,33,44,55,66,77";
String str[] = num.split(",");
List<String> al = new ArrayList<String>();
al = Arrays.asList(str);
for(String s: al){
System.out.println(s);
}
}
}
Output:
22
33
44
55
66
77
Java –
StackTrace to String conversion
There are
times when we want to convert the occurred exception to String. In the following program we are
converting the stacktrace to String by using
Throwable.printStackTrace(PrintWriter pw).
Example: Converting Exception StackTrace
to String
package com.beginnersbook.string;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StacktraceToString {
public static void main(String args[]){
try{
int i =5/0;
System.out.println(i);
}catch(ArithmeticException e){
/* This block of code would convert the
* stacktrace to string by using
* Throwable.printStackTrace(PrintWriter pw)
* which sends the stacktrace to the writer
* that we can convert to string using tostring()
*/
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
String stacktraceString = sw.toString();
System.out.println("String is: "+stacktraceString);
}
}
}
Output:
String is: java.lang.ArithmeticException: / by zero
at com.beginnersbook.string.StacktraceToString.main(StacktraceToString.java:8)
Convert String
to date in Java
In this
tutorial we will see how to convert a
String
to Date
in Java.
Convert String to Date: Function
After this
section I have shared a complete example to demonstrate String to Date
conversion in various date formats.
For those who just want a function for this conversion, here is the function
code:
public Date convertStringToDate(String dateString)
{
Date date = null;
Date formatteddate = null;
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
try{
date = df.parse(dateString);
formatteddate = df.format(date);
}
catch ( Exception ex ){
System.out.println(ex);
}
return formatteddate;
}
Example program for string to date
conversion
package beginnersbook.com;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDateDemo{
public static void main(String args[])
{
String testDateString = "02/04/2014";
String testDateString2 = "02-04-2014 23:37:50";
String testDateString3 = "02-Apr-2014";
String testDateString4 = "04 02, 2014";
String testDateString5 = "Thu, Apr 02 2014";
String testDateString6 = "Thu, Apr 02 2014 23:37:50";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
DateFormat df2 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
DateFormat df3 = new SimpleDateFormat("dd-MMM-yyyy");
DateFormat df4 = new SimpleDateFormat("MM dd, yyyy");
DateFormat df5 = new SimpleDateFormat("E, MMM dd yyyy");
DateFormat df6 = new SimpleDateFormat("E, MMM dd yyyy HH:mm:ss");
try
{
//format() method Formats a Date into a date/time string.
Date d1 = df.parse(testDateString);
System.out.println("Date: " + d1);
System.out.println("Date in dd/MM/yyyy format is: "+df.format(d1));
Date d2 = df2.parse(testDateString2);
System.out.println("Date: " + d2);
System.out.println("Date in dd-MM-yyyy HH:mm:ss format is: "+df2.format(d2));
Date d3 = df3.parse(testDateString3);
System.out.println("Date: " + d3);
System.out.println("Date in dd-MMM-yyyy format is: "+df3.format(d3));
Date d4 = df4.parse(testDateString4);
System.out.println("Date: " + d4);
System.out.println("Date in MM dd, yyyy format is: "+df4.format(d4));
Date d5 = df5.parse(testDateString5);
System.out.println("Date: " + d5);
System.out.println("Date in E, MMM dd yyyy format is: "+df5.format(d5));
Date d6 = df6.parse(testDateString6);
System.out.println("Date: " + d6);
System.out.println("Date in E, E, MMM dd yyyy HH:mm:ss format is: "+df6.format(d6));
}
catch (Exception ex ){
System.out.println(ex);
}
}
}
Output:
Date: Wed Apr 02 00:00:00 IST 2014
Date in dd/MM/yyyy format is: 02/04/2014
Date: Wed Apr 02 23:37:50 IST 2014
Date in dd-MM-yyyy HH:mm:ss format is: 02-04-2014 23:37:50
Date: Wed Apr 02 00:00:00 IST 2014
Date in dd-MMM-yyyy format is: 02-Apr-2014
Date: Wed Apr 02 00:00:00 IST 2014
Date in MM dd, yyyy format is: 04 02, 2014
Date: Wed Apr 02 00:00:00 IST 2014
Date in E, MMM dd yyyy format is: Wed, Apr 02 2014
Date: Wed Apr 02 23:37:50 IST 2014
Date in E, E, MMM dd yyyy HH:mm:ss format is: Wed, Apr 02 2014 23:37:50
Java – ASCII
to String conversion
In this
tutorial we will learn how to convert ASCII values to a String.
Example: Converting ASCII to String
Here is the
complete code wherein we have an array of ASCII values and we are converting
them into corresponding char values then transforming those chars to string
using toString() method of Character class.
package com.beginnersbook.string;
public class ASCIIToString {
public static void main(String args[]){
int num[] = {65, 120, 98, 75, 115};
String str =null;
for(int i: num){
str = Character.toString((char)i);
System.out.println(str);
}
}
}
Output:
A
x
b
K
s
How To Convert
Char To String and a String to char in Java
In this
tutorial, we will see programs for char to String and String to char
conversion.
Program to convert char to String
We have
following two ways for char to String conversion.
Method 1: Using toString() method
Method 2: Usng valueOf() method
Method 1: Using toString() method
Method 2: Usng valueOf() method
class CharToStringDemo
{
public static void main(String args[])
{
// Method 1: Using toString() method
char ch = 'a';
String str = Character.toString(ch);
System.out.println("String is: "+str);
// Method 2: Using valueOf() method
String str2 = String.valueOf(ch);
System.out.println("String is: "+str2);
}
}
Output:
String is: a
String is: a
Converting String to Char
We can convert a
String to char using charAt() method of String class.
class StringToCharDemo
{
public static void main(String args[])
{
// Using charAt() method
String str = "Hello";
for(int i=0; i<str.length();i++){
char ch = str.charAt(i);
System.out.println("Character at "+i+" Position: "+ch);
}
}
}
Output:
Character at 0 Position: H
Character at 1 Position: e
Character at 2 Position: l
Character at 3 Position: l
Character at 4 Position: o
Java Program
to find duplicate Characters in a String
This program
would find out the duplicate characters in a String and would display the count
of them.
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Details {
public void countDupChars(String str){
//Create a HashMap
Map<Character, Integer> map = new HashMap<Character, Integer>();
//Convert the String to char array
char[] chars = str.toCharArray();
/* logic: char are inserted as keys and their count
* as values. If map contains the char already then
* increase the value by 1
*/
for(Character ch:chars){
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
} else {
map.put(ch, 1);
}
}
//Obtaining set of keys
Set<Character> keys = map.keySet();
/* Display count of chars if it is
* greater than 1. All duplicate chars would be
* having value greater than 1.
*/
for(Character ch:keys){
if(map.get(ch) > 1){
System.out.println("Char "+ch+" "+map.get(ch));
}
}
}
public static void main(String a[]){
Details obj = new Details();
System.out.println("String: BeginnersBook.com");
System.out.println("-------------------------");
obj.countDupChars("BeginnersBook.com");
System.out.println("\nString: ChaitanyaSingh");
System.out.println("-------------------------");
obj.countDupChars("ChaitanyaSingh");
System.out.println("\nString: #@$@!#$%!!%@");
System.out.println("-------------------------");
obj.countDupChars("#@$@!#$%!!%@");
}
}
Output:
String: BeginnersBook.com
-------------------------
Char e 2
Char B 2
Char n 2
Char o 3
String: ChaitanyaSingh
-------------------------
Char a 3
Char n 2
Char h 2
Char i 2
String: #@$@!#$%!!%@
-------------------------
Char # 2
Char ! 3
Char @ 3
Char $ 2
Char % 2
Difference
between String and StringBuffer
In the last
post we discussed the difference between StringBuffer and StringBuilder.
Here we are gonna discuss the differences between
String
and StringBuffer
class.
String vs StringBuffer
1) Mutability: String is immutable (Once created, cannot be
modified) while StringBuffer is mutable (can be modified).
Example –
String is immutable:
String is immutable:
String str = "Hello World";
str = "Hi World!";
By seeing this
code you would say that the value of str has changed so how can it be
immutable? Let me explain this:
In first statement an object is created using string literal “Hello World”, in second statement when we assigned the new string literal “Hi World!” to
In first statement an object is created using string literal “Hello World”, in second statement when we assigned the new string literal “Hi World!” to
str
, the object itself didn’t change instead a new object got
created in memory using string literal “Hi World!” and the reference to it is
assigned to str
.
So basically both the objects “Hello World” and “Hi World!” exists in memory
having different references(locations).
StringBuffer is mutable:
Lets see
StringBuffer mutability
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
In the first
statement StringBuffer object got created using string literal “Hello” and in
second statement the value of the object got changed to “Hello World” from
“Hello”. Unlike Strings here the object got modified instead of creating the
new object.
2) Performance: While performing concatenations you
should prefer
StringBuffer
over String
because it is faster. The reason is:
When you concatenate strings using String, you are actually creating new object
every time since String is immutable.
What java documentation
says about StringBuffer:
From StringBuffer javadoc:
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.
0 comments
Thanks for intrest.. We will touch withbyou soon..