Search code examples
javastringinitializationappletpaint

Why String variables are needed to be initialized and sometimes it doesn't required initialization while declaring them in java?


I was writing an simple applet program that takes an input from the user and displays them. `

public void init(){
    text1=new TextField(8);

    add(text1);

    text1.setText("0");

}
public void paint(Graphics g){
    int x=0;
    String s1,str = null;
    g.drawString("input in the  box",10,50);
    try{
        s1=text1.getText();
        str=String.valueOf(s1);


    }
    catch(Exception e){}
    g.drawString(str,75,75);
}
public boolean action (Event event,Object object){
    repaint();
    return true;
}

` in the paint() method why is that str variable must be declared to null while declaring the other string variable s1 without initialization is okay? IT doesn't compile without initialization the str variable.


Solution

  • Because you only use the value of s1 in a place where it's guaranteed to have a value, but you use str in a place (the catch handler) where it isn't guaranteed to have a value if you don't initialize it to something up front, since after all, an exception could be thrown in the try prior to assigning to str.

    If you moved the call to g.drawString(str,75,75); into the try, you wouldn't need the = null initializer.


    Side note: s1 is already a string, so there's no need to do str = String.valueOf(s1). Just use s1 in the g.drawString(str,75,75); line.