Movatterモバイル変換


[0]ホーム

URL:


Open In App

In Java,variables are containers that store data values, such as numbers, text, or Boolean values. Java variables are categorized into different types based on their scope, lifetime, and usage, helping programmers manage data efficiently and write organized, maintainable code

Types of Variables in Java
Type of Variable

Let us discuss the traits of every type of variable listed here in detail.

Local Variables 

A variable defined within a block, method, or constructor is referred to as a local variable. 

Key Features

  • The Local variable is created at the time of declaration and destroyed when the function completes its execution.
  • The scope of local variables exists only within the block in which they are declared.
  • We first need to initialize a local variable before using it within its scope.

Example: Java Program to show the use of local variables

Java
importjava.io.*;classGeeks{publicstaticvoidmain(String[]args){// Declared a Local Variableintvar= 10;System.out.println("Local Variable: "+var);}}

Output
Local Variable: 10

Example:This example demonstrates that local variables are only accessible within the block in which they are declared

Java
// Java Program to show the use of Local Variablesimportjava.io.*;publicclassGeeks{publicstaticvoidmain(String[]args){// x is a local variableintx=10;// message is also a local// variableStringmessage="Hello, world!";System.out.println("x = "+x);System.out.println("message = "+message);if(x>5){// result is a// local variableStringresult="x is greater than 5";System.out.println(result);}// Uncommenting the line below will result in a// compile-time error System.out.println(result);for(inti=0;i<3;i++){StringloopMessage="Iteration "+i;// loopMessage is a local variableSystem.out.println(loopMessage);}// Uncommenting the line below will result in a// compile-time error// System.out.println(loopMessage);}}

Output
x = 10message = Hello, world!x is greater than 5Iteration 0Iteration 1Iteration 2

Instance Variables

Instance variables are known as non-static variables and are declared in a class outside of any method, constructor, or block. 

Key Features

  • Instance variables are created when an object is instantiated and destroyed when the object is destroyed.
  • Can have access specifiers; default access is used if none is specified.
  • Instance Variables are not mandatory to initialize; take default values based on data type (0 for int,null for String, etc.).
  • Scope is throughout the class, except in static contexts.
  • Accessed only through objects of the class.
  • Instance Variables can be initialized usingconstructors orinstance blocks.

Example:This example demonstrates the use of instance variables, which are declared within a class and initialized via a constructor, with default values for uninitialized primitive types.

Java
importjava.io.*;classGeeks{// Declared Instance VariablepublicStringgeek;publicinti;publicIntegerI;publicGeeks(){// Default Constructor// initializing Instance Variablethis.geek="Sweta Dash";}// Main Methodpublicstaticvoidmain(String[]args){// Object CreationGeeksname=newGeeks();// Displaying O/PSystem.out.println("Geek name is: "+name.geek);System.out.println("Default value for int is "+name.i);// toString() called internallySystem.out.println("Default value for Integer is: "+name.I);}}

Output
Geek name is: Sweta DashDefault value for int is 0Default value for Integer is: null

Static Variables

Key Features

Static variables in Java are variables declared with the static keyword inside a class but outside any method. They are shared among all objects of the class and exist for the entire lifetime of the program. 

  • There is only one copy of a static variable for the entire class, and all objects share it
  • Static variable are created at program start and destroyed when the program ends.
  • Not mandatory to initialize; default values depend on the data type (0 for int, null for String, etc.).
  • Can be accessed via the class name; accessing through objects shows a compiler warning.
  • Cannot be declared locally inside instance methods.
  • Can be initialized usingstatic blocks.

Example:This example demonstrates the use of static variables, which belong to the class and can be accessed without creating an object of the class.

Java
importjava.io.*;classGeeks{// Static variablestaticStringgeek="Sweta Dash";publicstaticvoidmain(String[]args){// Access static variable without creating an objectSystem.out.println("Geek Name is: "+Geeks.geek);// static int c = 0;// Error: static variables cannot be declared inside a method}}

Output
Geek Name is: Sweta Dash

Difference Between Local, Instance, and Static Variables

FeatureLocal VariableInstance VariableStatic Variable
DeclaredInside method/blockInside class, outside methodsInside class with static keyword
ScopeOnly within the block/methodAcross class methods (non-static)Shared across all objects of class
LifetimeExists only during method/blockExists as long as object existsExists throughout program execution
Number of CopiesEach method call creates newEach object has its own copyOnly one copy for the class
Default ValueNo default; must initializeDefault based on type (0, null)Default based on type (0, null)
AccessOnly within method/blockThrough objectsThrough class name (or object)
InitializationRequired before useOptional; can use constructorsOptional; can use static blocks


Improve
Improve
Article Tags :

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp