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( );    


// 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.

import java.util.Scanner;

public class FullNameString {

 public static void main(String[] args) {

  Scanner input = new Scanner(;
  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(" ");   // For space between names
  fullName.append(" ");   // For space between names
  System.out.println("Hello, " + fullName);
C:\>java FullNameString
Enter first name :: Rahul
Enter middle name :: S.
Enter surname :: Tamkhane
Hello, Rahul S. Tamkhane


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet