PhysicsTeacher.in

High School Physics + more

Java program showing features of String class

Here is a Java program that helps you to understand how to use some important features of the String class. Multiple ways of creating String instances (objects) are demonstrated in this program. String concatenation and String array are also shown in this java program.

Java program showing different ways to instantiate String class | String array & concatenation

class StringTest
{
public static void main(String args[])
{
String s1=new String();
String s2=new String(“Java Class @ SAFE,NBP”);
char chars[]={‘J’,’A’,’V’,’A’,’ ‘,’C’,’L’,’A’,’S’,’S’,’E’,’S’};
String s3=new String(chars);
String s4=new String(s3);

System.out.println(“OUTPUT”);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);

String s5=new String(chars,0,4);//String(char array,start index,numbers)
System.out.println(s5);

System.out.println(“Length of s5:”+s5.length());
//String concatenation
String scon1=”four”+2+2;

System.out.println(scon1);
String scon2=”four”+(2+2);
System.out.println(scon2);
//String array

String strarr[]={“Saraswati”,”Academy”,”For”,”Excellence”};

for (int i=0;i<strarr.length;i++)//for array its length, not length()
{
System.out.println(strarr[i]);
}
}
}

See also  Write a Java program to display the first 10 numbers of the Fibonacci
Scroll to top
error: physicsTeacher.in