javacharat

how do i use charAt() without main method


i have to use with a method (beginntMitA). somehow it doesn't work without main method. does anyone know how do i fix it?

public class StringTest{
    public static void beginntMitA(String args[]){
        String s = "java";
       char ch1 = s.charAt(0);
       char ch2 = s.charAt(1);
       char ch3 = s.charAt(2);
       char ch4 = s.charAt(3);
       char ch5 = s.charAt(4);
       
       System.out.println( ch1 );
       System.out.println( ch2 );
       System.out.println( ch3 );
       System.out.println( ch4 );
       System.out.println( ch5 );
    }

}

Solution

  • You have to use main method. As Java main method is the entry point of any java program. you can't run normal java program without it.

    you can check this link Java main method

    You can define your "beginntMitA" method and call it in the main method with the class name as it's static method like this

     public class StringTest{
        
        public static void main(String args[]){
              StringTest.beginntMitA();
        }
    
        public static void beginntMitA(){
            String s = "java";
           char ch1 = s.charAt(0);
           char ch2 = s.charAt(1);
           char ch3 = s.charAt(2);
           char ch4 = s.charAt(3);
           char ch5 = s.charAt(4);
           
           System.out.println( ch1 );
           System.out.println( ch2 );
           System.out.println( ch3 );
           System.out.println( ch4 );
           System.out.println( ch5 );
        }
    }
    

    And You can use loops to iterate on your string characters instead of using 0, 1, 2, 3, ..