Lecture_3.3-Java variables,Modifiers
Lecture_3.3-Java variables,Modifiers
• Java Modifiers
2
Variables in java
3
Variables in java
Variables
Instance Class/Static
Local Variables
Variables Variables
4
1. Local variables
• Local variables are visible only within the declared method, constructor or block.
5
2. Instance variables
• Instance variables are declared in a class, but outside a method, constructor or any block.
• Instance variables are created when an object is created with the use of the keyword 'new'
and destroyed when the object is destroyed.
• The instance variables are visible for all methods, constructors and block in the class.
6
3. Class/static variables
• Class variables also known as static variables are declared with the static keyword in a class,
but outside a method, constructor or a block.
• Static variables are rarely used other than being declared as constants.
• However, most static variables are declared public since they must be available for users of the
class.
7
Key points
❑ Local Variable
A variable that is declared inside the method
❑ Instance Variable
A variable that is declared inside the class but outside the method.
It is not declared as static.
❑ Static variable
Similar to instance variable but it is declared as static.
8
Example to understand the types of variables
Example - 1:
class A
{
int data=50; // instance variable
static int m=100; // static variable
void method()
{
int n=90; // local variable
}
}
9
Example - 2:
public class MyClass
{ public static void main(String[] args)
int a = 50; {
static int b = 100; MyClass ob = new MyClass ();
ob.method1 ();
public void method1() ob. method2 ();
{ }
int n = 90;
System.out.println(n); }
System.out.println(a);
System.out.println(b);
}
10
Example - 3:
12
Modifiers
Modifiers are keywords that you add to those definitions to change their meanings.
1. Access modifiers
2. Non-access modifiers
13
1. Access Modifiers
14
1. Access Modifiers in java
1. private
2. default
3. protected
4. public
15
1) private access modifier
• The private access modifier is accessible only within the class.
17
2) default access modifier
18
Example of default access modifier
19
default access
modifier
20
3) protected access modifier
• The protected access modifier is accessible within package and outside
the package but through inheritance only.
• The protected access modifier can be applied on the data member, method
and constructor. It can't be applied on the class.
21
• Example of protected access
modifier
22
protected
access
modifier
23
4) public access modifier
24
public
access modifier
25
26
2. Non-Access Modifiers
27
2. Non-Access Modifiers
• static modifier
▪ for creating class methods and variables
• final modifier
▪ for finalizing the implementations of classes, methods, and variables.
• abstract modifiers
▪ for creating abstract classes and methods.
29