Hen Sapir
Hen Sapir

Reputation: 1263

Unable to use StringBuilder to concatenate chars to String

BThis is my code:

public static void main(String[] args)
{
    String teacherName = "Benjamin Brown";
    int teacherSecondInitialIndex = (teacherName.indexOf(" ") + 1);
    String teacherInitials = new StringBuilder(teacherName.charAt(0)).append(teacherName.charAt(teacherSecondInitialIndex)).toString();
    System.out.println(teacherInitials);
}

I want to print out the initials of teacherName, which would be "BB". But only "B" is being printed out. What is the issue?

Upvotes: 1

Views: 123

Answers (1)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

This constructor

new StringBuilder(teacherName.charAt(0))

accepts an int. So the char value you are passing is being widened and used as the StringBuilder capacity, not as the first char in the underlying String.

Create an empty StringBuilder and append two chars.

String teacherInitials = new StringBuilder()
        .append(teacherName.charAt(0))
        .append(teacherName.charAt(teacherSecondInitialIndex))
        .toString();

Upvotes: 4

Related Questions