DEV Community

Ritika Sharma
Ritika Sharma

Posted on

Extracting first character...

Yesterday, I was solving some basic problems in Java. Specifically related to case-check and finding vowels, and I came to know about two different extracting methods !!

  1. in.next().trim().charAt();
  2. ch.charAt();

Someone who is a beginner might often get confused by these methods,
So here is the explanation of what these do...

If you are lazy and don't want to write much code, then in.next().trim().charAt(); comes to the rescue xD ! Yes, it shortens the code and is much*_ cleaner_*. It extracts the first character from the input entered by the user.

Image description

Whereas in ch.charAt(); you need to define string. If you want clarity or to reuse the string, then this method is preferable.

Image description

Conclusion:- Both does the same work i.e, both are used for extracting the first character.

Bonus Tip - ch.charAt(0) is often used to extract the first character, but in problems like 'finding vowels' we use .charAt(i) inside the loop in order to get our desired answer.

THANKYOU FOR READING <3

Top comments (0)