Strings in Java



Although, the concept of String is usually introduced after you have learned the concept of Class, we think that it is an important concept and its usage does not require a lot of theoretical background.

The String class is essentially an array of character strings. An String is decalred as follows

String FirstName = "Michael";

Notice the capital S in the keyword String.

Strings are constants and their values cannot be changed after they are created. Let us start our very simple java code that just declares String and prints first and last name.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   Java String Processing
  4.   */
  5.  
  6. class string1 {
  7. public static void main(String[] args) {
  8.  
  9. String FirstName="Roger ";
  10. String LastName=" William";
  11. System.out.println("Hi "+ FirstName + LastName);
  12. }
  13. }


If you compile and run, it simply prints the name preceded by Hi.


Hi Roger William 




Finding Length of a String



You can use the length() method to find the length of a String.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   Find length of String in Java
  4.   */
  5.  
  6. class string1 {
  7. public static void main(String[] args) {
  8.  
  9. String text ="This is a referencedesigner.com java tutorial ";
  10. int x = text.length() ;
  11. System.out.println("length of string is "+ x);
  12. }
  13. }


If you compile and run, it simply prints the name preceded by Hi.


length of string is 46