Showing posts with label String. Show all posts
Showing posts with label String. Show all posts

String Vs String Buffer . Difference between String & StringBuffer class example

Java String object is immutable that means the content of the String Object contents cannot be modified after they are created . There are no methods available to manipulate the contents of the string once it is created. Methods that operate on a string returns a new string rather than manipulating the original copy of the string. String concatenation is done using "+" operator which creates many temporary objects and increases garbage collection . So String concatenation using "+" may be avoided.
The StringBuffer class represents a mutable string of characters that means their values can be changed after they are created. There are methods like append , insert are available which allows to manipulate the contents of the string once it is created . String concatenation is done using append method which avoids creating many temporary strings. So it is better to use the Java StringBuffer object to concatenate strings because it is more efficient.
Note : Both String and String buffers are safe for use by multiple threads because the operations on string will create a new string and String buffer methods are synchronized . Every string buffer has a initial capacity. If the internal buffer used by the string buffer overflows, it is automatically made larger.
String buffer / StringBuilder are used by the compiler to implement the binary string concatenation operator +. StringBuilder is similar to StringBuffer except String bulider is not synchronised. For example, the code:
input = "StringConcatenation is done using " + "StringBuffer.append " +4 + " u" is compiled to the equivalent to the following line.
input = new StringBuffer().append("StringConcatenation is done using ").append("StringBuffer.append ").append(4).append(" u").toString()
   
class StringCat
{
public static void main(String...args)
{
String input = "StringConcatenation is done using " + "StringBuffer.append " +4 + " u"
System.out.println("Output= "+ input);
}
}

Compile the above program using javac StringCat.java and Run the using javap -c StringCat which will display the bytecode of the StringCat.class as follows.
   
Compiled from "StringBuffer.java"
class StringBuffer extends java.lang.Object{
StringBuffer();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: ldc #2; //String StringConcatenation is done using StringBuffer.append 4 u
2: astore_1
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: new #4; //class java/lang/StringBuilder
9: dup
10: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
13: ldc #6; //String Output=
15: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
18: aload_1
19: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
22: invokevirtual #8; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
25: invokevirtual #9; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
28: return

}


Read more...

Write own code for Java String indexOf() to find position of a given string in a source string

Let us first see what java String indexOf() does . It returns position of the given character / substring in a given String from the first occurance or starting from the specified position. IndexOf() is overloaded into four methods.
1. indexOf(int ch) - Returns the position / index of the given charater with in this string .
2. indexOf(int ch, int fromIndex) - Same as the above method but search starts from the the specified index.
3. indexOf(String str) - Returns the position / index of the given String with in this string
4. int indexOf(String str, int fromIndex) - Same as the 3rd method but search starts from the the specified index.
Now let us write code for indexOf(String source, String substr, int startPos, int occurrence, char caseSensitive) which does the same work with more options using Regexp, where source is the original string to search in , substr is the substring to be searched in the original string , startPos is the starting position to search , occurrence is used to tell which match to get. There may be more than one substring in the given string . If we give occurrence is 2 , then it will return the position of the second match. Matching can be done using CaseSensitive or Case In Sensitive . We have to pass 'N' for CaseInSensitive .
    
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
class customIndexOf
{
public static void main(String args[])
{
String source="Using Db2 UDB , Udfs can be created. DB2 UDFs is DB2 User Defined Functions";
String sub="db2";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,2,'N' ));
sub="UDFs";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,1,'Y' ));
sub="c";
System.out.println("Position of " + sub + " = "+ indexOf(source,sub,0,1,'N' ));
sub="DB2";
System.out.println("Using Java Index of () Position of " + sub + " = "+ (source.indexOf(sub, 0)+1));
}

public static int indexOf(String source, String substr, int startPos, int occurrence, char caseSensitive)
{
int position = 0;
int flag=2;
int occurrenceCount = 0;
if(caseSensitive=='Y') flag=0;
if ( source == null || source.length()==0) return -1;
Pattern pattern=null;
try
{
pattern = Pattern.compile(substr, flag);
}
catch (PatternSyntaxException e)
{
return 0;
}
Matcher matcher = pattern.matcher(source);
if (matcher.find(startPos))
{
position = matcher.start()+ 1;
occurrenceCount++;
while ((occurrenceCount < occurrence) && (matcher.find()))
{
position = matcher.start() + 1;
occurrenceCount++;
}
}

if (occurrenceCount!=occurrence) position =0 ;
return (position);
}
}



Output:

Read more...

Convert Charater Arrays to String in Java | Example code using String.copyValueOf()

You can convert character arrays to string in two ways .
1. String Class has a method copyValueOf() can be used to create a String object from charater arrays. (i.e. array of type char[])
a) String str=String.copyValueOf(charArray) -> All the characters of array is converted to String
b) String str = String.copyValueOf(charArray, 5, 4) - > Only 4 charactes starting from 5th position , are converted to string.

2. String class supports several constructors . One of the constructor accepts array of characters and string object is created by the initialised array of charaters. String str=new String ('a','e','i','o','u');

The following example code explains how the character arrays are converted to string object using the above two methods.

  

public class CharArrayToString {

public static void main(String[] arg) {
char[] charArray = { 'V', 'o', 'w', 'e', 'l', 's', ':', 'a', 'e', 'i', 'o', 'u' };

System.out.println("Given CharArray\n");
for (char c:charArray) System.out.println(c);

String str = new String(charArray);
System.out.println("After converting to String using Constructor : " + str);

String str1 = String.copyValueOf (charArray);

System.out.println("After converting to String using copyValueOf method : " + str1);

// converting subset of charater arrays to string
System.out.println("\n");
System.out.println("Converting subset of charater arrays to string\n ") ;
String str2 = new String(charArray,0,5);
System.out.println("Using Constructor : " + str2);

String str3 = String.copyValueOf (charArray,7,5);

System.out.println("Using copyValueOf method : " + str3);

}

}

After Running the above program Output :

java CharArrayToString
Given CharArray

V
o
w
e
l
s
:
a
e
i
o
u
After converting to String using Constructor : Vowels:aeiou
After converting to String using copyValueOf method : Vowels:aeiou


Converting subset of charater arrays to string

Using Constructor : Vowel
Using copyValueOf method : aeiou


Read more...

Java String to Character Array Example Code | How to copy chars from string to char Array

In several ways, we can copy the charaters of a string object into an character array. (ie. converting the string to an array of characters.) Using the following String methods we can convert the string to an array of characters
charAt(i);
toCharArray();
getChars(int srcBegin, int srcEnd, char[] dest, int destBegin) .

The following code illustrates how to convert String to array of charaters using above 3 methods.*/


public class StringToChrArray {
public static void main(String[] args) {

String inputString = "Techlabs4u.com";
int len = inputString.length();
char[] charArray1 = new char[len];
char[] charArray3 = new char[len];
// Converting using String to array of chars using charAt(i);
for (int i = 0; i < len; i++) {
charArray1[i] = inputString.charAt(i);
}

// Converting String to array of chars using toCharArray();

char[] charArray2=inputString.toCharArray();

// Converting String to array of chars using getChars();

inputString.getChars( 0, len, charArray3, 0) ;

System.out.println("From charArray1\n");
for (char c:charArray1) System.out.println(c);

System.out.println("From charArray2\n");
for (char c:charArray2) System.out.println(c);

System.out.println("From charArray3\n");
for (char c:charArray3) System.out.println(c);

}
}



Running the above program will output the following

java StringToChrArray
From charArray1

T
e
c
h
l
a
b
s
4
u
.
c
o
m
From charArray2

T
e
c
h
l
a
b
s
4
u
.
c
o
m
From charArray3

T
e
c
h
l
a
b
s
4
u
.
c
o
m
Read more...

String Split in Java using Pattern.split() Example Code using Regular Expression (util.regex)

The following program splits the given string using the split method of Pattern Calss of the package java.util.regex available with JDK 1.4 onwards. An instance of the Pattern class represents a regular expression which is specified in string . Pattern Class has various methods . Some of the methods are as follows.

1. compile(String regex) -> Compiles the given regular expression into a pattern.
2. split(CharSequence input) -> Splits the given string using the pattern.
3. matches(String regex, CharSequence input) -> Compiles the given regular expression (regex) and Matches the given input string against it.

The following Program splits the given input string by the delimiter # , white space and commas

   

import java.util.regex.*;
import java.util.Scanner;
public class SplitByRegex {
public static void main(String[] args) throws Exception {

Pattern pattern = Pattern.compile("[#,\\s]+"); // created pattern using # comma whitespace

Scanner sc=new Scanner(System.in).useDelimiter("\n"); //Accepts Line of String
System.out.println("Enter Line to Split "); //
String inputStr=sc.next();
System.out.println("Enterd Line : " + inputStr + "\n");
String[] resultStr = pattern.split(inputStr);
System.out.println("\nResult Strings after Split\n");
for (int i=0; i<resultStr.length; i++)
System.out.println((i+1) +"." + resultStr[i]);
}
}

Running the Program :

D:\as2\JF1>java SplitByRegex
Enter Line to Split
Mumbai # Calcutta # Chennai # Delhi , US, Washinton , Canada Singapore Malasia
India
Enterd Line : Mumbai # Calcutta # Chennai # Delhi , US, Washinton , Canada Sing
apore Malasia India


Result Strings after Split

1.Mumbai
2.Calcutta
3.Chennai
4.Delhi
5.US
6.Washinton
7.Canada
8.Singapore
9.Malasia
10.India


Read more...

Java Number to String Example , Integer to String in Java


/*Converting a number to string can be done very eaisly in java .We can do in many ways .

1. We can use toString() method of Integer , Byte , Long class . The Integer and Long classes also provide the methods like toBinaryString(), toHexString(), toOctalString();
2. String.valueOf can be used to convert number to string.
3. java.text.DecimalFormat is used to parse and format numbers in any locale
4. Simple Concatenation (+) : Any integer concatenated with string is converted to string . */




import java.text.DecimalFormat;
import java.io.*;
public class NumberToStr {
public static void main(String[] args) {

Example1();
Example2();
}

// Example 1:

private static void Example1()
{

System.out.println("Example 1 ");

int number = 1932;

System.out.println ("Given Number is : " + number); // using concatenation

System.out.println(" Number to String by toString(): " + Integer.toString(number)); // using toString of Integer

System.out.println(" Number to String by valueOf(): " + String.valueOf(number)); // using valueOf of String

System.out.println(" Number to Binary : " + Integer.toBinaryString(number));

System.out.println(" Number to Hexadecimal : " + Integer.toHexString(number));

System.out.println(" Number to Octal : " + Integer.toOctalString(number));

}

// Example 2:

private static void Example2()
{

System.out.println("Example 1 ");
DecimalFormat df= new DecimalFormat("##,###.##");

int number = 400;

String str1="" + number ; //using concatenation

String str2 = "Number is "+number; //using concatenation

double decimal = 65132.39 ;

String numInFormat = df.format(decimal);

System.out.println("String1 = " +str1);
System.out.println("String2 = " +str2);
System.out.println("Number in Format = " +numInFormat);
}

}



Output :
-----------
D:\as2\JF1>java NumberToStr
Example 1
Given Number is : 1932
Number to String by toString(): 1932
Number to String by valueOf(): 1932
Number to Binary : 11110001100
Number to Hexadecimal : 78c
Number to Octal : 3614
Example 1
String1 = 400
String2 = Number is 400
Number in Format = 65,132.39
Read more...

Java String to Integer Example . Use of Integer.ValueOf(), parseInt()

/* Many times , We may come accross a situation where a string needs to be changed to an Integer . For example when we accept a input through keyboard , it will be read as String . For doing any calculation , we have to convert the string to an integer . Integer Object has methos like valueOf & parseInt for converting sting to integer.
We can convert String to Integer using the following ways

Integer.valueOf - converts String to Integer Object
Integer.parseInt - converts String to int primitive type
If we pass a string to the constructor of the Integer object , it returns Integer Object. */



import java.io.*;
public class StringToInt {
public static void main(String[] args) {

Example1();
Example2();
}

// Example 1:

private static void Example1()
{

System.out.println("Example 1 ");
String numStr ="110";
Integer number = new Integer(numStr);

String numStr1="0005";
int number1 = Integer.valueOf(numStr1);

String numStr2="0007";
int number2=Integer.parseInt(numStr2); //converts to integer primitive type.

System.out.println( "Number String is ( string concatenation)" + numStr+numStr2+numStr2);

int result=number+number1+number2;
Integer result1=number+number1+number2;

System.out.println("Input Numer" + number);
System.out.println("Input Numer1" + number1);
System.out.println("Input Numer2" + number2);

System.out.println( "After Converting Integer ( string concatenation) " + number+number1+number2);
System.out.println( "result " + result);
System.out.println( "result1 " + result1);

}

// Example 2:

private static void Example2()
{

BufferedReader br=new BufferedReader (new InputStreamReader(System.in) );

String numStr="";
int number=0;
int sum=0;

System.out.println("Example 2 ");
System.out.println("Enter Numbers to add & type quit to exit ");

do
{

try
{
numStr=br.readLine();
number = Integer.parseInt(numStr);
}
catch (Exception e)
{
if (numStr.equalsIgnoreCase("quit") )
{
System.out.println("Quiting....");
number=0;
}
else
{
System.out.println("Invalid Input");
number=0;
}
}
sum = sum + number;
} while (numStr.compareTo("quit") !=0);

System.out.println("Sum is =" +sum);
}

}



Output :
--------

D:\as2\JF1>java StringToInt
Example 1
Number String is ( string concatenation)11000070007
Input Numer110
Input Numer15
Input Numer27
After Converting Integer ( string concatenation) 11057
result 122
result1 122
Example 2
Enter Numbers to add & type quit to exit
7
5
3
7
2
quit
Quiting....
Sum is =24
Read more...

Java String to Date , Date to String Example code using SimpleDateFormat , parse , format

SimpleDateFormat Class is used for Parsing ( String to Date ) and Formatting (Date to String ) . It has many methods . For converting String to Date and vice-versa , the following methods are used .

1) parse(String text, ParsePosition pos) - Parses text from a string to convert to a Date
2) format(Date date, StringBuffer toAppendTo, FieldPosition pos) - Formats the given Date into a date/time string(which may be dd/MM/yyyy,dd/MMM/yyyy, yyyyy.MMMMM.dd GGG hh:mm aaa etc ) and appends the result to the given StringBuffer.

The following code converts spring to date and date to string ......
    
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatParse {

public static void main(String[] args) {

SimpleDateFormat out = new SimpleDateFormat("dd/MM/yyyy");

SimpleDateFormat out1 = new SimpleDateFormat("dd-MMM-yyyy");

System.out.println("String to Date : " + StringToDate(15, 06, 2011) );// which returns a date

System.out.println("String to Date : " + StringToDate("15/06/2011") );// which returns a date

// Now Date is converted into String for printing in a format (dd/mm/yyy or dd/MMM/yyyy)

System.out.println("Date to String : " + out.format (StringToDate(15, 06, 2011) ));// which returns a string

System.out.println("Date to String : " + out1.format (StringToDate("15/06/2011") )); // which returns a string

}



// The following two functions are used to convert string to date (One accepts (dd/mm/yyyy) , another method accepts day, month & year)




public static Date StringToDate(String dateString) // Accepts a Date String and Converts to Date
{
SimpleDateFormat in= new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {

date = in.parse(dateString);

} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}


public static Date StringToDate(int day, int month, int year) // Accepts a Day , Month and Year and Converts to Date
{
SimpleDateFormat in = new SimpleDateFormat("dd/MM/yyyy");
String dateString = day + "/" + month + "/" + year;
Date date=new Date();
try {

date = in.parse(dateString);

} catch (ParseException e)
{
e.printStackTrace();
}
return date;
}
}


Output of the above program :

String to Date : Wed Jun 15 00:00:00 IST 2011
String to Date : Wed Jun 15 00:00:00 IST 2011
Date to String : 15/06/2011
Date to String : 15-Jun-2011


Read more...

 
Copyright 2011 Java Online