Java Strings & Substrings

Can anyone pls help me to understand this code, for making the first letter of a word to uppercase.

code:
Scanner sc=new Scanner(System.in);
String A=sc.next();
String B=sc.next();
System.out.print(A.substring(0,1).toUpperCase()+ A.substring(1) + " "+B.substring(0,1).toUpperCase() + B.substring(1));

why they are using substring here?
A[0].toUpperCase() why this wont work?

Hi.

Basically you ask the user for 2 strings.
Then when you display those, for each of them
you take the first character (with substring(0,1)) and display it uppercase and then you display the remaining characters skipping the 1st one (with substring(1)).

Substring returns a portion of your string.
If there is 1 parameter it is the starting index (until the end of that string).
If there is two the second one is the length of the string.

I did not try that last part yet with Java recently, but to me a string is a table of characters so it should work. Alternatively charAt could have been used to retrieve the 1st character. The question though is do we have something that would display it uppercase.

Hope it helped you understand.

Regards.

1 Like

Because that syntax is invalid (Java does not allow you to index a String like that). There is a charAt method you can use to get the character at a given index, but then you would have to append the char returned back into a String. You could also try putting both Strings into a StringBuilder and then you would have access to methods like setCharAt which could replace a single character. You could combine that with the charAt method and Character.toUpperCase to change the casing of those particular characters. That would look something like this:

var result = new StringBuilder()
  .append(A)
  .append(" ")
  .append(B);
result.setCharAt(0, Character.toUpperCase(A.charAt(0)));
result.setCharAt(A.length() + 1, Character.toUpperCase(B.charAt(0)));
System.out.print(result);

On the whole, both versions work just fine and take a similar amount of space.


Technically, the code never “asks” for anything. It just expects the user to type in two strings (separated by any whitespace). The purpose of the code is to print the two words with the first letter of each word capitalized (and separating the two words by a single space).

2 Likes

okay, thank you jason