Home » Java programming language

Java variables types with examples

Variables in Java: Here, we are going to learn about the variables, various types of variables in Java.
Submitted by Karan Ghai, on May 26, 2019

Java variables

Variables are the user-defined names of the memory blocks, and their values can be changed at any time during program execution. They play an important role in a class/program as they help in to store, retrieve a data value.

Types of the variables in Java

There are three types of Java variables,

  1. Instance Variables
  2. Local Variables
  3. Class/Static Variables

1) Instance Variables

  • Instance variables are declared in a class but outside a Method, Block or Constructor.
  • Instance variables have a default value 0.
  • These variables can be created only when the object of a class is created.

Example:

public class Bike {
    public String color;

    Bike(String c) {
        color = c;
    }

    public void display() {
        System.out.println("color of the bike is " + color);
    }

    public static void main(String args[]) {
        Bike obj = new Bike("Red");
        obj.display();
    }
}

Output

Color of the bike is Red

2) Local Variables

  • Local variables are the variables which are declared in a class method.
  • We can use these variables within a block only.

Example:

public class TeacherDetails {
    public void TeacherAge() {
        int age = 0;
        age = age + 10;
        System.out.println("Teacher age is : " + age);
    }

    public static void main(String args[]) {
        TeacherDetails obj = new TeacherDetails();
        obj.TeacherAge();
    }
}

Output

Teacher age is : 10

3) Class Variables/Static Variables

  • This can be called Both Class and Static Variable.
  • These variables have only one copy that is shared by all the different objects in a class.
  • It is created during the start of program execution and destroyed when the program ends.
  • Its Default value is 0.

Example:

public class Bike {
    public static int tyres;
    public static void main(String args[]) {
        tyres = 6;
        System.out.println("Number of tyres are " + tyres);
    }
}

Output

Number of tyres are 6





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.