Search code examples
javajava-8stringbuilderjava-17

Unable to use Java StringBuilder. append () as a global variable


A StringBuilder declaration as a global variable

public class Test {

    public static StringBuilder sb1=new StringBuilder("Hello");
    public static void main(String args[]){}
}

I'm using Intellij IDE. After declaration if I try to use

public class Test {

    public static StringBuilder sb1=new StringBuilder("Hello");
    sb1.append(" world!");
    public static void main(String args[]){}
}

IDE suggests. append() is not available. Appending inside a method or at declaration level it works. Whereas appending after declaration is not working

public class Test {

    public static StringBuilder sb1=new StringBuilder("Hello").append(" World!");
    public static void main(String args[]){}
}

Just wanted to know why it is not working after declaration at global level. Can anyone help me with this


Solution

  • Basically you should have a public classes with inherited methods and variables. You can use the StringBuilder constructor in your main method, in which the code execution occurs and print the result.

    public class Test {
    
        public static void main(String args[]){
            
            StringBuilder sb1=new StringBuilder("Hello").append(" World!");
            System.out.println(sb1);
        }
    }
    

    Or you can implement your StringBuilder in a separate method (in this case: build()) and execute this method in your main method and print the returned value inside the System.out.println() function. The function build() (you can insert any name you want), returns a StringBuilder Object to your main method.

    public class Test {
    
        public static void main(String args[]){
            
            System.out.println(build());
        }
        
        public static StringBuilder build(){
            
            StringBuilder sb1=new StringBuilder("Hello").append(" World!");
            return sb1;
        } }
    

    Third option: You use the StringBuilder constructor in a static block:

    public class Test {
        
        static {
            StringBuilder sb1=new StringBuilder("Hello").append(" World!");
            System.out.println(sb1);
        }
    
        public static void main(String args[]){
        }
    }
    

    https://www.javatpoint.com/java-main-method