1

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?

2
  • 1
    Why is it "BG" and not "BB" ? Commented Mar 4, 2014 at 23:09
  • My bad, you're right. Edited it. Commented Mar 4, 2014 at 23:13

1 Answer 1

4

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(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I totally missed that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.