Hi guys, I seem to be struggling with the understanding of Java variables. The Visibility of Variables lesson was extremely complicated for me. I have read the lesson numerous times and get completely lost without some sort of context concerning the reasons behind where, how, and why to use a variable. Can someone please help!
Java Variable Questions
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Soham1087
20 January 2023, 12:46
Understanding variables in Java can be tricky, especially when it comes to visibility. Variables in Java have different levels of visibility, which determines where and how they can be accessed in a program. The most common levels of visibility are:
Local variables: These variables are defined within a method or block of code, and can only be accessed within that method or block. They are not accessible from outside the method or block.
Instance variables: These variables are defined within a class, but outside of any method. They are associated with an instance of the class, and can be accessed by any method of that class.
Class variables: These variables are also defined within a class, but are marked with the "static" keyword. They are associated with the class itself, rather than an instance, and can be accessed by any method of that class, regardless of whether an instance of the class exists.
Public variables: These variables are defined with the "public" keyword, which makes them accessible from any class or package.
Private variables: These variables are defined with the "private" keyword, which makes them accessible only within the class they are defined in.
It's important to note that good programming practice is to keep the visibility of variables as restrictive as possible, in order to minimize the chances of errors and unexpected behavior.
As for why we use variables, it's because they are the basic building block of any programming language, they are used to store values, perform operations and make decisions. They also help us to organize our code and make it more readable.
Also, don't hesitate to ask questions and seek help if you are struggling to understand something, it's a normal part of the learning process.
+1
Tony Marloe
27 December 2022, 10:29
In java variables can be declared and defined inside a class, method, or block. Variables that are declared inside a method, constructor, or block cannot be accessed outside in which it is defined. Variables declared inside a pair of curly braces {} have block-level scope.Variable declared inside main() function cannot be accessed outside the main() function.
0