💻 Step 7:Variables – 4th hour +code

Learn with our youtube video – 


It’s a name of memory block which can hold any value.


Comparison of these three types of variables:

Variable TypeScopeAccessibility
InstanceWithin the objectAccessible by all methods of the object
LocalWithin the methodAccessible only within the method
Class/StaticWithin the classAccessible by all objects of the class

💡Types of variable in java-

1- Instance variable
2- Local variable
 3- Static variable or class variable

💡1- Instance variable

-declared in class, not in any local field such as method, constructor etc)
-used on instance/objects.

💡2- Local variable

-declared in any local field such as method, constructor etc.
-used within local fields.

💡3-Static/class variable

-declared in class with static keyword
-used on class name.

code samples are here

1- Program to create 2 instance variable, ‘String s’ with value “asd” and ‘int i’ with value 10 and print them using object

package var5;

public class ExVar1 {
String s="asd"; //instance variable
int i=10; //instace variable
public static void main(String[] args) {
ExVar1 v = new ExVar1();

Run This Program ▶️

2- Program to create 2 Local variable, ‘int a’ with value 10 inside method show and ‘String n’ with value asdfg inside constructor and use both method and constructor to print them.

package var5;

public class ExVar2 {
void show(){
int a=10;
String n="asdfg";
public static void main(String[] args) {
ExVar2 v1 = new ExVar2();

Run This Program ▶️

3- Program to create static variable, ‘int a’ with value 20  and print it using class name.

package var5;
public class ExVar3 {
static int a=20;
public static void main(String[] args) {

Run This Program ▶️

Interview Questions —

  • What is difference between instance variable and static variable?
  • What is difference between local variable and static variable?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.