Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      Variable Scopes

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      Variable Scopes

      The variable's scope refers to the region where they are created and accessed in a given program or function. The variable scope also refers to its lifetime.
      In this tutorial, we will learn about the scopes of the different types of Java variables.

      Scope of Java Instance Variables

      A variable which is declared inside a class and outside all the methods and blocks is an instance variable. The general scope of an instance variable is throughout the class except in static methods. The lifetime of an instance variable is until the object stays in memory.

      Example: Scope of Java Instance Variables

      In the example below, we define an instance variable puppyAge in Puppy class and using its setAge(), we're modifying it and using getAge() method, we're getting it. This variable is available till the lifetime of myPuppy object instance.
      package com.tutorialspoint;
      
      public class Puppy {
      private int puppyAge;
      public void setAge( int age ) {
      // access the instance variable and modify it
      puppyAge = age;
      }
      
      public int getAge( ) {
      // access the instance variable
      return puppyAge;
      }
      
      public static void main(String []args) {
      Puppy myPuppy = new Puppy();
      myPuppy.setAge( 2 );
      System.out.println("Puppy Age :" + myPuppy.getAge() );
      }
      }
      Compile and run the program. This will produce the following result
      Output
      Puppy Age :2

      Scope of Java Local Variables

      A variable which is declared inside a class, outside all the blocks and is marked static is known as a class variable. The general scope of a class variable is throughout the class and the lifetime of a class variable is until the end of the program or as long as the class is loaded in memory.

      Example: Scope of Java Local Variables

      In the example below, we define a class variable BREED in Puppy class. This variable is available till the lifetime of program. Being static in nature, we can access it using class name directly as shown below:
      package com.tutorialspoint;
      
      public class Puppy {
      private int puppyAge;
      public static String BREED="Bulldog";
      public void setAge( int age ) {
      // access the instance variable and modify it
      puppyAge = age;
      }
      
      public int getAge( ) {
      // access the instance variable
      return puppyAge;
      }
      
      public static void main(String []args) {
      Puppy myPuppy = new Puppy();
      myPuppy.setAge( 2 );
      System.out.println("Puppy Age :" + myPuppy.getAge() );
      // access the class variable
      System.out.println("Breed :" + Puppy.BREED );
      }
      }
      Compile and run the program. This will produce the following result
      Output
      Puppy Age :2
      Breed :Bulldog

      Scope of Java Class (Static) Variables

      All other variables which are not instance and class variables are treated as local variables including the parameters in a method. Scope of a local variable is within the block in which it is declared and the lifetime of a local variable is until the control leaves the block in which it is declared.

      Example: Scope of Java Class (Static) Variables

      In the example below, we define two local varables in main() method of Puppy class. These variables are availble till the lifetime of method/block in which these are declared and can be accessed as shown below:
      package com.tutorialspoint;
      
      public class Puppy {
      private int puppyAge;
      public static String BREED="Bulldog";
      public void setAge( int age ) {
      // access the instance variable and modify it
      puppyAge = age;
      }
      
      public int getAge( ) {
      // access the instance variable
      return puppyAge;
      }
      
      public static void main(String []args) {
      Puppy myPuppy = new Puppy();
      myPuppy.setAge( 2 );
      System.out.println("Puppy Age :" + myPuppy.getAge() );
      // access the class variable
      System.out.println("Breed :" + Puppy.BREED );
      // local variables
      int a = 10;
      int b = 20;
      int c = a + b;
      System.out.println("c: " + c);
      }
      }
      Compile and run the program. This will produce the following result
      Output
      Puppy Age :2
      Breed :Bulldog
      c: 30

      Important Points About Variables Scope

      • By default, a variable has default access. Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
      • A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.
      • Java provides a number of access modifiers to set access levels for classes, variables, methods, and constructors. The four access levels are
      • default − Visible to the package. No modifiers are needed.
      • private − Visible to the class only.
      • public − Visible to the world.
      • protected − Visible to the package and all subclasses.