Facebook

Strings in Java

String is a non primitive data type in Java. Non primitive refers to an object i.e it refers to a memory location where data is stored and are created by programmers. String is a type of object that can hold text.

Syntax to write String

String myName = "Hi! Jack.";
String is a class and myName is a variable that stores "Hi! Jack.".

Program to  print String

public class PrintString
{
 public static void main(String [] args)
{
String myName = "Hi! Jack.";
System.out.println(myName);
}
}

Run

Concatenate Strings

We can join two or more strings by using '+' operator or concat method. Program to join/concatenate two or more strings by using '+' operator is given below:

public class StringConcatenate
 {
 public static void main(String[] args)
   {
   String myFirstName = "Jack";
   String blank = " ";
   String myLastName = "Vanderbilt";
   int myAge = 35;
   String myHobby = "I like to play Badminton and Volleyball";
   String myCombinedString = "My name is " + myFirstName + blank + myLastName + " " +"and my age is " + myAge  + "." + "" + myHobby + ".";
   System.out.println(myCombinedString);
   }

}

Run

Using concat() method

concat() method is an another way to join two or more strings.Program to illustrate this is given below:

public class StringConcatenate
{
public static void main(String[] args)
 {
 String myFirstName = "Jack";
 String blank = " ";
 String myLastName = "Vanderbilt";
 String myAge = "Thirty-Five";
 String myHobby = "I like to play Badminton and Volleyball.";
 String myCombinedString = "My name is ".concat(myFirstName).concat(blank).concat(myLastName).concat(" and my age is ").concat(myAge).concat(". ").concat(myHobby);
 System.out.println(myCombinedString);
 }
}

Run

Rate this post

Comments

So empty here ... leave a comment!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sidebar