Global local scope

I have declared a variable (int val=20) as global but in eclipse it is showing error that I have to declare it as (static int val =20). why it is showing error ?

main method is static in java and static functions can only access static variables

why we declare a function as static ? you have not explained in the video why we declare

sorry ,it was not written correctly

i was saying that why we declare a function as static ?

i was saying that why we declare a function as static? you have not explained in the video and i am not getting it.

Static function or variables can be accessed directly by class name(className.funcName)…static variables or functions are properties of a class…though they can be accessed with objectName but it is better to access them with className…for ex data member count(which counts the total num of students) in student class is static and you create a getterFunc for this count…if your func is static it can access only static variables but if it is non-static it can access both static and non-static members…also we define main as static because main is the first prog to get executed so no objects are created before its execution and hence it is called by jvm using className…thus it is always static.

why we declare (Scanner sc = new Scanner (System.in)

why we declare (Scanner sc= new Scanner (System.in) as static?

Hi Mansi

You have to declare Scanner sc= new Scanner (System.in) as static when you declare it globally, not when you are writing it in the main function for the same reason mentioned as above.

The concept will be more clear when you will proceed to the OOPS topic in the videos.

Hi Mansi
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.

Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.