Quick way to check if all the characters of a string are same | Java program for above approach ; Function to check is all the characters in string are or not ; Insert characters in the set ; If all characters are same Size of set will always be 1 ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static void allCharactersSame ( String s ) { Set < Character > s1 = new HashSet < Character > ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) s1 . add ( s . charAt ( i ) ) ; if ( s1 . size ( ) == 1 ) System . out . println ( " YES " ) ; else System . out . println ( " NO " ) ; } public static void main ( String [ ] args ) { String str = " nnnn " ; allCharactersSame ( str ) ; } }