1

Whenever I use Scanner class for input it shows a warning regarding memory leak, ".in" not closed. While using Buffered Reader it does not show any warning. Why So?

    class Demo    
    {    
        public static void main(String[] arg){    
        System.out.println("Enter a String");    
        Scanner sc = new Scanner(System.in);    
        String[] str = new String[1];    
        str[0] = sc.next();    
        System.out.println(str[0]);    
    }

1 Answers1

2

In either case, you should close the Scanner or BufferedReader to avoid resource leaks. The compiler apparently doesn't recognize the problem with BufferedReader and doesn't issue the warning.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • Can you please explain how memory leaks? What if we define a string type array with only 1 value str[0] and taking only one input? – user3436422 Sep 07 '14 at 08:17
  • @user3436422, Add some code to your question so we can understand clearly. – Chaitanya Sep 07 '14 at 08:19
  • @user3436422 The memory leak has nothing to do with the variables where you store the input. It is the `Scanner` or `BufferedReader` object itself that causes the leak. When you close the `Scanner` or `BufferedReader`, you release the operating system resources which are used by these classes. – Code-Apprentice Sep 07 '14 at 08:22