+ 1

The below code giving required output. If I remove static keyword in the 3rd line of the code ,it ll give error. why static is used there?? what's the use??and how it is helpful to "Scanner" class???

import java.util.Scanner; public class MyClass { static Scanner lal=new Scanner(System.in); public static void main(String[ ] args) { int[] arr={1,2,3,4,5}; mod(arr); for(int x:arr) System.out.println(x); } static void mod(int[] brr){ for(int i=0;i<5;i++) System.out.println(brr[i]=lal.nextInt()); } } // if I enter 6 7 8 9 10, then output: 6 7 8 9 10 6 7 8 9 10

11th Jul 2016, 9:00 AM
Anup Shetty
3 ответов
+ 2
your scanner is static and you are accessing it in static method mod() its perfect. but when you remove static from scanner it will become non static variable and in java you can't access non static variable in static method
11th Jul 2016, 10:26 AM
Girish Yadawad
Girish Yadawad - avatar
0
thank u
11th Jul 2016, 10:29 AM
Anup Shetty
0
you can run this code by removing both static keyword from scanner and from method create obj of myclass and class mod()
11th Jul 2016, 10:30 AM
Girish Yadawad
Girish Yadawad - avatar