Friday, 25 November 2016

Program to accept first name, middle name and surname in three different strings and then concatenate the three strings to make full name

StringBuffer class is like a String, but can be modified. StringBuffer class is mutable. StringBuffer is fast and consumes less memory when you concat strings. For example,
// Constructs string buffer with no characters in it 
// and an initial capacity of 16 characters.
StringBuffer  s1 = new StringBuffer( );    

OR

// Constructs a string buffer with no characters in it and the specified 
// initial capacity to 5.
StringBuffer  s2 = new StringBuffer(5);

// Constructs a string buffer that contains the three characters.  
// The initial capacity of the string buffer is 16 plus 
// the length of the "abc" string in short it is 19. 
StringBuffer s3 = new StringBuffer("abc");

Here we have used the append(String str) method of StringBuffer class which appends the specified string to this character sequence. In program we get first name, middle name and last name from user and then append them in a StringBuffer object.


PROGRAM
import java.util.Scanner;

public class FullNameString {

 public static void main(String[] args) {

  Scanner input = new Scanner(System.in);
  
  System.out.print("Enter first name :: ");
  String firstName = input.nextLine();
  
  System.out.print("Enter middle name :: ");
  String middleName = input.nextLine();
  
  System.out.print("Enter surname :: ");
  String lastName = input.nextLine();
  
  // Here StringBuffer is used to combine 3 strings into single
  StringBuffer fullName = new StringBuffer();
  fullName.append(firstName);
  fullName.append(" ");   // For space between names
  fullName.append(middleName);
  fullName.append(" ");   // For space between names
  fullName.append(lastName);
  System.out.println("Hello, " + fullName);
 }
}
OUTPUT
C:\>javac FullNameString.java
C:\>java FullNameString
Enter first name :: Rahul
Enter middle name :: S.
Enter surname :: Tamkhane
Hello, Rahul S. Tamkhane

No comments:

Post a Comment