0

My codes are like the following.

public class readfile {
    public static void readfile() {   
        int i = 0;  
        System.out.println("hello"); 
    }

    public static void main(String[] args) {  
        readfile(); 
        System.out.println(i); 
    }  
}

And it works well if I do not refer to the variable i. (That means it can print out hello.) So how can I refer i in the main method?

hata
  • 11,633
  • 6
  • 46
  • 69
  • 2
    `i` is local variable of `readfile ()`. so u can not directly. – Bacteria Sep 26 '15 at 16:54
  • 1
    you cannot refer i in main method since it is local variable. its scope is limited to your readfile() function. if you want to access it in main you need to declare it as static variable in class. – Murli Sep 26 '15 at 16:55

3 Answers3

0
public class readfile {
    static int i;

    public static void readfile() {   
        i = 0;
        System.out.println("hello"); 
    }

    public static void main(String[] args) {  
        readfile(); 
        System.out.println(i); 
    }  
}
  • As UUIIUI says in comment, if you declare i inside of readfile(), it is valid only inside of the method.
  • As Murli says in comment, you need a member variable in the class field. And also it must be static one.
hata
  • 11,633
  • 6
  • 46
  • 69
0

You are writing java code in a bad way :

1.First, the class name char in Java is Uppercase so your class need to be named ReadFile.

  1. You cannot use the i variable in your main method, because it's just a local variable of your readFile method, and you have compilation errors, because of the use of i in the main method, and a warning in the readFile method, because you don't use it in the local block code.

Java appear new for you? and you need to learn a litle bit more. There's a full of book or documentation on the web.

Your sample corrected, compiled well and run well :

package stackWeb;

public class ReadFile {

    static int i = 0;  
    public static void readfile() {   

        System.out.println("hello"); 
    }

    public static void main(String[] args) {  
        readfile(); 
        System.out.println(i); 
    }  
}
fabien t
  • 358
  • 1
  • 9
0

You could try this

class readfile {
    static int i =0;
    public static void readfile() {   

        System.out.println("hello"); 
    }

    public static void main(String[] args) {  
        readfile(); 
        System.out.println(i); 
    }  
}
ABHISHEK RANA
  • 333
  • 3
  • 7