簡體   English   中英

為什么在Java中聲明字符串變量時需要對其進行初始化,而有時卻不需要初始化?

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

我正在編寫一個簡單的applet程序,該程序接受用戶的輸入並顯示它們。 `

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;
}

`在paint()方法中,為什么在聲明其他字符串變量s1而不進行初始化的同時,必須將str變量聲明為null呢? 沒有初始化str變量,IT不會編譯。

因為您只在保證有值的地方使用s1的值,但是在沒有保證將其初始化為某個值的地方( catch處理程序)中使用str因為畢竟,在分配給str之前, try可能會引發異常。

如果將調用移至g.drawString(str,75,75); try ,你就不需要= null初始化。


旁注: s1已經是一個字符串,因此無需執行str = String.valueOf(s1) 只需在g.drawString(str,75,75);使用s1 線。

Java編譯器允許未初始化的變量,只要可以保證它們在用於某些事物時就具有值。

String s1,str = null; // s1 is not set
g.drawString("input in the  box",10,50);
try{
    s1=text1.getText(); // s1 is set
    str=String.valueOf(s1); // s1 is used
}
catch(Exception e){}
g.drawString(str,75,75);

由於上一行已初始化s1 ,因此可以安全地將其傳遞給String.valueOf

str的問題在於,它在try-catch塊之后使用,這可能會跳過設置它的行。

String s1,str; // str is not set
g.drawString("input in the  box",10,50);
try{
    s1=text1.getText(); // if this throws an exception...
    str=String.valueOf(s1); // ...this is never reached
}
catch(Exception e){} // the exception is caught and ignored, so we continue
g.drawString(str,75,75); // str is still not set - error!

只要在初始化之前就有可能使用變量,編譯器就會拒絕它。 在這種情況下,您可以在catch塊中將str設置為默認值,或者從catch塊returnthrow異常,以便僅在try塊無例外完成的情況下才到達g.drawString行。

實例變量不需要初始化,只需要初始化局部變量(位於函數或構造函數內部)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM