This section contains the Example for creating string in java.
Example for creating string
In general, strings are sequence of characters but in java strings are objects. Some of the strings' common process are given below :
Creating Strings :
You can create string as follows :
String greeting = "welcome to Devmanuals";
The compiler creates a string object whenever it found the string literal in
your code. Using 'new' keyword and constructor, you can create String objects as
:
public class StringDev{ public static void main(String args[]){ String devString = new String("devArray"); System.out.println( devString ); } }
After execution, it will produce following results :
C:\Program Files\Java\jdk1.6.0_18\bin>javac StringDev.java C:\Program Files\Java\jdk1.6.0_18\bin>java StringDev devmanuals |
Calculating String Length
You can calculate the length of the string by using length() method as :
public class CalString{ public static void main(String args[]){ String dev = "welcome to devmanuals"; int len = dev.length(); System.out.println( "Length of String is : " + len ); } }Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac CalString.java C:\Program Files\Java\jdk1.6.0_18\bin>java CalString 21 |
Concatenating Strings:
For concatenating two strings , we have 'concat()' method in java, it van be used as :
public class StringConcat{ public static void main(String args[]){ String str = "Manuals "; System.out.println("Dev" + str+ "website"); } }Output :
C:\Program Files\Java\jdk1.6.0_18\bin>javac StringConcat.java C:\Program Files\Java\jdk1.6.0_18\bin>java StringConcat DevManuals website |
Print output with formatted numbers
You can print output with format numbers using 'printf' and 'format' methods as :
System.out.printf("value of variable:" +"%f");Example using format method :
String dv; dv = String.format("value of variable is " +"%f"); System.out.println(dv);The format( ) method returns a String object rather than a PrintStream object. The format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement.
Download Source Code
[ 0 ] Comments