Website For Developers

Strings in Java



Simplest way to create a string in Java

String str = "I Love Java Programming!";


Example of Strings in Java

public class StringClass {

   public static void main(String args[]) {
     String learnJava = "Onlineprogramminghub Java Tutorials" ;
     System.out.println( learnJava );
   }
}

Output

Onlineprogramminghub Java Tutorials

An array of characters works same as java string.

Example of Strings in Java

public class StringClass {

   public static void main(String args[]) {
     char[] learnJava ={'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g', 'H', 'u', 'b'};
     System.out.println( learnJava );
   }
}

Output

ProgrammingHub


String Methods in Java

Example

public class StringMethod {
   public static void main (String [] args) {
     String a = "If you are a developer, ";
     //concate method combine the two strings into one.
     String b = a.concat( "You are a genius person." );
     System.out.println(b);

     // length() is a string class method, used to count the total number of elements in a string.
     int c = b.length();
     System.out.println(c);
   }
}

Output

If you are a developer, You are a genius person.
48