-3

i need help i am getting error like

Description                               Resource        Path                Location    Type  
Resource leak: 'input' is never closed    Methods.java    /piyush/src/piyush  line 7      Java Problem  

Code:

import java.util.Scanner;
public class Methods {


 public static void main(String[] args){
   Scanner input = new Scanner(System.in);
   System.out.print("what is your name ");
   String yourName = input.nextLine();
   System.out.println("hello " + yourName);
 }


 }
Salman A
  • 262,204
  • 82
  • 430
  • 521

4 Answers4

4

You should close streams after their use. In your case, add

input.close();

just after the last System.out.println() to close your Scanner and get rid of the warning.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
2

Its not a error, its a warning. Errors/Exceptions are if there is some mistake in your code (compilation errors) or if something goes wrong while execution of program (runtime exceptions).

You should always close streams that you use, in your case Scanner input:-

input.close();

This warning can be ignored and it should work fine without the close() , but it is a good practice to close resources after usage.

Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
0

You need to close the scanner to release any system resources. Use

input.close();

as the last line in your code. See Closeable.close() javadoc for some more info.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
0

You can close the Scanner and it would be fine in this case, but this will close the underlying System.in input stream and prevent you from accepting input in case you later read from the standard input stream.

M A
  • 71,713
  • 13
  • 134
  • 174