How to get the first 4 characters of a string in Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        String s = "python java c c++ c#";
        String first4chars;
        
        if (s.length() > 4) {
            first4chars = s.substring(0, 4);
        } 
        else {
            first4chars = s;
        }
        System.out.println(first4chars);
    }
}




/*
run:

pyth

*/

 



answered Feb 8, 2022 by avibootz
...