Instance variable in java

Instance Variables in Java: The Complete Guide

Instance variables are an important topic in Java programming. They are responsible for defining the characteristics of an object and preserving its state for its whole life cycle. In this blog, we will discuss instance variables in great detail, their different characteristics, usage, and best practices.

What Are Instance Variables?

An instance variable is a variable defined in a class (as opposed to a static variable). Since each object of a class has its own copy of instance variables, changes made to such variables in one object do not have any impact on another object of the same class.

Instance Variables:

  • Defined within a class but out of any method, block, or constructor.
  • Every instance has its own copy of instance variables.
  • Gets a default value until you assign it.
  • Can take any access modifier (private, protected, public, or default).
  • They are not shared between entities, unlike static variables.

Syntax of Instance Variables

class Car { String brand; int speed; // Instance variables }

Here, brand and speed are instance variables. Each instance of the Car class will have its own brand and speed values.

Default values of instance variables:

If an instance variable is not initialized, Java assigns default values as shown below:

Data Type Default Value
int 0
double 0.0
boolean false
char '\u0000' (null character)
String (or Other objects) null

Example:

  1. class Example {
  2.     int number; // default value is 0
  3.     String text; // default value is null
  4.     
  5.     void display() {
  6.         System.out.println("Number: " + number);
  7.         System.out.println("Text: " + text);
  8.     }
  9.     
  10.     public static void main(String[] args) {
  11.         Example obj = new Example();
  12.         obj.display();
  13.     }
  14. }

    Instance Variables and Access Modifiers

    Instance variables can have different access modifiers, which control their visibility and accessibility.

    Private Instance Variables

    • Accessibility: same class only.
    • Use getters and setters to provide access.
    1. class Person {
    2.     private String name;
    3.     
    4.     public String getName() {
    5.         return name;
    6.     }
    7.     
    8.     public void setName(String name) {
    9.         this.name = name;
    10.     }
    11. }

      Public Instance Variables

      • Accessible from anywhere in the program.
      • Not recommended, as it violates encapsulation.
      class Animal { public String species; }

      Protected Instance Variables

      • Available within the same package and to subclasses.
      class Vehicle { protected int speed; }

      Default (Package-Private) Instance Variables

      • Only accessible within the same package.
      class Employee { String designation; // Default access modifier }

      Using Instance Variables

      Instance variables are used to store object-specific data.

      Example java program :

      1. class Student {
      2.     String name;
      3.     int age;
      4.     
      5.     // Constructor to initialize instance variables
      6.     public Student(String name, int age) {
      7.         this.name = name;
      8.         this.age = age;
      9.     }
      10.     
      11.     void display() {
      12.         System.out.println("Name: " + name + ", Age: " + age);
      13.     }
      14.     
      15.     public static void main(String[] args) {
      16.         Student s1 = new Student("Alice", 20);
      17.         Student s2 = new Student("Bob", 22);
      18.         
      19.         s1.display();
      20.         s2.display();
      21.     }
      22. }

          Output:

          Name: Alice, Age: 20 Name: Bob, Age: 22

          Each Student object holds its own copy of name and age.


          Instance Variable vs Static Variable

          Feature Instance Variables Static Variables
          Ownership Object specific Class specific
          Memory Allocation At object creation At class loading
          Access Requires an object Accessed via class name

          Example

          1. class Company {
          2. static String companyName = "Tech Corp"; // Static variable
          3. String employeeName; // Instance variable
          4. }

            Best Practices for Instance Variables

            1. Encapsulation: Use the private access modifier and access it through getters and setters.
            2. Meaningful Names: Assign well-defined names to variables.
            3. Initialize in Constructor: Ensure instance variables are initialized in constructors.
            4. Limit Visibility: Use private or protected unless absolutely necessary.
            5. Lower Memory Usage: Use only the necessary instance variables in memory-sensitive applications.

            Instance variables are critical components of Java's object-oriented programming paradigm. They enable objects to store their own independent state and data. Understanding how they work and following best practices allows you to write clean, efficient, and maintainable Java code.

            Want to learn more about Java concepts? Let us know in the comments!

            How to read values from properties file in java example

            • To store configurable parameters, .properties file will be used in java.
            • We can Store data in key value pair (key=value).
            • Re compilation not required if we change any keys or values in properties file.
            • Used for internationalization  and to store frequently changeable values. 
            • java.util.Properties class is sub class of Hashtable. 
            • We can read / load the propertied file using InputStream.
            • InputStream inputStream = getClass().getClassLoader().getResourceAsStream(properties_FileName);
            • Create a maven project, under resources create one .properties file and load this file in main class using getClass().getClassLoader().getResourceAsStream(properties_FileName).
            • Lets see an example java program on java read properties file from resource folder or how to read values from properties file in java example or how to get values from properties file in java.

             #1: Create a maven project:

            java read properties file from classpath


            Create properties file:

            reading properties file in java

            #1: Java example program  to get values from properties file in java

            1. package com.instanceofjava.propertiesfile;
            2. import java.io.FileNotFoundException;
            3. import java.io.IOException;
            4. import java.io.InputStream;
            5. import java.util.Date;
            6. import java.util.Properties;
            7. /**
            8.  *  
            9. * @author www.instanceofjava.com
            10.  * @category: java example programs
            11.  *  
            12. * Write a java example program to read/ load properties file
            13.  *
            14.  */
            15. public class ReadPropertiesFile {
            16.  
            17.     public Properties getProperties() throws IOException {
            18.         
            19.         InputStream inputStream=null;
            20.         Properties properties = new Properties();
            21.         try {
            22.             
            23.             String propFileName = "config.properties";
            24.  
            25.             inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
            26.  
            27.             if (inputStream != null) {
            28.                 properties.load(inputStream);
            29.             } else {
            30.                 throw new FileNotFoundException("property file '" + propFileName + "' not found
            31. in the classpath");
            32.             }
            33.  
            34.  
            35.         } catch (Exception e) {
            36.             System.out.println("Exception: " + e);
            37.        } finally {
            38.             inputStream.close();
            39.         }
            40.          return properties;
            41.     }
            42.     
            43.     
            44.     public static void main(String[] args) throws IOException {
            45.         
            46.         ReadPropertiesFile obj= new ReadPropertiesFile();
            47.         Properties properties=obj.getProperties();
            48.         // get the each property value using getProperty() method 
            49.         System.out.println("username: "+properties.getProperty("username"));
            50.         System.out.println("password: "+properties.getProperty("password"));
            51.         System.out.println("url: "+properties.getProperty("url"));
            52.         
            53.                 
            54.     }
            55.  
            56. }

            Output:

            1. username: user1
            2. password: abc123
            3. url: www.instanceofjava.com

            Super keyword java programs for interview for freshers and experienced

            • Lets see some interesting java programs on super keyword.
            • Basically super keyword used to refer super class methods and variables. So now let us see how super will work in some scenarios. lets practice.
            • Try to answer below java programming interview questions for beginners. 
            • Java programs asked in technical interview for freshers and experienced.




            Program #1: What will be the output of below java program

            1. package com.superkeywordinjava;
            2.  public Class SuperDemo{ 
            3.  
            4. int a,b;
            5.  
            6. }

            1. package com.superkeywordinjava;
            2. public Class Subdemo extends SuperDemo{ 
            3. int a,b;
            4. void disply(){

            5. super.a=10;
            6. super.b=20;
            7.  
            8. System.out.println(a);
            9. System.out.println(b);
            10. System.out.println(super.a);
            11. System.out.println(super.b);
            12.  
            13. }
            14.  
            15. public static void main (String args[]) {
            16.  Subdemo obj= new Subdemo();
            17.  
            18. obj.a=1;
            19. obj.b=2;
            20.  
            21. obj.disply();
            22.  

            23.  
            24. }
            25. }






            Program #2: What will be the output of below java program


            super keyword java interview programs for freshers





            Program #3: Basic java programs for interview on super keyword

            1. package com.superinterviewprograms;
            2. public Class SuperDemo{ 
            3.  
            4. int a,b;
            5.  
            6. SuperDemo(int x, int y){
            7.  a=x;
            8. b=y
            9. System.out.println("Super class constructor called ");
            10.  
            11.  
            12. }

            1. package com.superinterviewprograms;
            2.  
            3. public Class Subdemo extends SuperDemo{ 
            4.  
            5. int a,b;
            6.  
            7. SubDemo(int x, int y){
            8. super(10,20);
            9.  a=x;
            10. b=y
            11. System.out.println("Sub class constructor called ");
            12. }
            13.  
            14. public static void main (String args[]) {
            15.  Subdemo obj= new Subdemo(1,2);

            16.  
            17. }
            18. }





            Program #4: Java interview Program on super keyword

            • What will happen if our class constructor having super() call but our class not extending any class.

            1. package com.superinterviewprograms;
            2.  
            3. public Class Sample{ 
            4.  
            5. Sample(){
            6. super();
            7. System.out.println("Sample class constructor called "); 
            8.  
            9. }
            10.  
            11. public static void main (String args[]) {
            12.  
            13.  Sample obj= new Sample();
            14.  
            15. }
            16. }





            Java Program to find shortest palindrome in string

            • We have a Letter or a word then we need add some letters to it and need to find out shortest palindrome 
            • For example we take "S":  S will be the shortest palindrome string.
            • If we take "xyz"zyxyz will be the shortest palindrome string
            • So we need to add some characters to the given string or character and find out what will be the shortest palindrome string by using simple java program.


            Java example Program to find out shortest palindrome of given string


            1. package shortestpalindromeexample.java;
            2. import java.util.Scanner;
            3.  
            4. public class ShortestPalindromeDemo {
            5.  
            6. public static String shortestPalindrome(String str) {
            7.      
            8. int x=0;  
            9. int y=str.length()-1;
            10.      
            11.   while(y>=0){
            12.      if(str.charAt(x)==str.charAt(y)){
            13.           x++;
            14.          }
            15.             y--;
            16.   }
            17.  
            18. if(x==str.length())
            19. return str;
            20.  
            21. String suffix = str.substring(x);
            22. String prefix = new StringBuilder(suffix).reverse().toString();
            23. String mid = shortestPalindrome(str.substring(0, x));
            24.  
            25. return prefix+mid+suffix;
            26. }
            27.  
            28. public static void main(String[] args) {
            29.  
            30. Scanner in = new Scanner(System.in);
            31.  
            32. System.out.println("Enter a String to find out shortest palindrome");
            33.  
            34. String str=in.nextLine();
            35.  
            36. System.out.println("Shortest palindrome of "+str+" is "+shortestPalindrome(str));
            37.  
            38. }
            39.  
            40. }
            Output:

            1. Enter a String to find out shortest palindrome
            2. java
            3. Shortest palindrome of java is avajava

            find shortest palindrome in java program

            Java Program to find missing numbers in an array

            • To find missing numbers in an array first we need to make sure that array is sorted.
            • After sorting we need to check that array each element with next element then we can find the difference.
            • if Array is not sorted :To sort array use Arrays.sort(array);
            • If difference is 1 then no need to do any thing because numbers are in order.
            • If difference is not equal to 1 then we need to print all those numbers or pick those numbers and place it in one array.
            • this would be the logic to find missing numbers in an array
            • Here there may be a chance of array not starts with 1 then we need to check first itself whether array starts with 1 or not if not we need to print 1 to starting element of array.
            • for example int a[]={4,5,6,8}; then we need to print 1 2 3  7.



             Lets see a java example program to find missing numbers in an array.

            1. package arraysInterviewQuestions;
            2. public class PrintMissingNumbers {
            3.  
            4. private static void findMissingNumber(int[] number){
            5.  
            6.         // take max length as last number in array
            7.     int k[] = new int[number[number.length-1]];
            8.         
            9.   int m=0;
            10.  
            11.   if(number[0]!=1){
            12.    for (int x = 1; x < number[0]; x++) {
            13.        k[m] =  x;
            14.        m++;
            15.        }
            16.   }
            17.         
            18.  for (int i = 0; i < number.length -1; i++) {
            19.     
            20.     int j = i+1;
            21.     int difference = number[j] - number[i] ;
            22.             
            23.             
            24.    if(difference != 1 ){
            25.         
            26.   for (int x = 1; x < difference; x++) {
            27.  
            28.           k[m] = number[i] + x;
            29.            m++;
            30.     
            31. }
            32.             
            33.  }
            34.  }
            35.         
            36. System.out.println("missing numbers in array ::");
            37.         
            38. for (int l = 0; l < m ; l++) {
            39.     System.out.println( k[l]+" ");
            40. }
            41. }
            42.  public static void main(String[] args) {
            43.         
            44.    int a[]= {2,4,6,9,10,20};
            45.  
            46.    //if Array is not sorted :To sort array use Arrays.sort(a); 
            47.  
            48.   findMissingNumber(a);
            49.  
            50.    
            51. }
            52. }
             
            program to find missing number in an array in java


            • Change the array in main method and practice try to find missing elements in an array that contains 1 to 100 numbers.

            Basic Java Example Program to check even or add

            1.Basic Java program to check even or add

            1. package com.BasicJavaProgramsExamples;
            2. import java.util.Scanner;
            3. public Class EvenOrOdd{ 
            4.  
            5. public static void main(String args[]) {
            6.  
            7. Scanner in= new Scanner(System.in);
            8. System.out.println("Please enter number to check even or odd");
            9.  
            10.     int n=in.nextInt();
            11.    
            12.          
            13. if(n%2==0){
            14.   System.out.println(+n" is even number");
            15. } else{
            16.  
            17. System.out.println(+n" is even number");
            18.  
            19. }
            20. }
            21. }

            Output:


            1. Please enter number to check even or odd
            2. 4
            3. 4 is even number




            2.Basic Java program to check even or add from 1 to 10

            1. package com.BasicJavaProgramsExamples;
            2. public Class EvenOrOdd{ 
            3.  
            4. public static void main(String args[]) {
            5.  
            6. for (int a=1; a<=10; a=a++){
            7.  if (a%2==0)
            8.     System.out.println(a+" is even");
            9. else
            10.     System.out.println(a+" is odd");
            11.  
            12. }   
            13. }
            14. }

            Output:

            1. 1 is odd
            2. 2 is even
            3. 3 is odd
            4. 4 is even
            5. 5 is odd
            6. 6 is even
            7. 7 is odd
            8. 8 is even
            9. 9 is odd
            10. 10 is even

            3.Basic Java program to check even or add from an array

            1. package com.BasicJavaProgramsExamples;
            2. import java.util.Scanner;
            3. public Class EvenOrOdd{ 
            4.  
            5. public static void main(String args[]) {
            6.  
            7. int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
            8.  
            9. for (int a=0; a<=numbers .length; a=a++){
            10.  
            11.  if (numbers[i]%2==0)
            12.     System.out.println(numbers[i]+" is even number");
            13. else
            14.     System.out.println(numbers[i]+" is odd number");
            15.  
            16. }    

            17. }
            18. }

            Output:


            1. 1 is odd number
            2. 2 is even number
            3. 3 is odd number
            4. 4 is even number
            5. 5 is odd number
            6. 6 is even number
            7. 7 is odd number
            8. 8 is even number
            9. 9 is odd number
            10. 10 is even number
             

            Java Example program to calculate area of reactangle

            In this tutorial we will see how to calculate Area of Rectangle.

            1.Write a Basic java example  program to find area of Rectangle

            •  To calculate the area of rectangle we need to ask user to enter length and width of the rectangle so that we can calculate area of rectangle using formula area of rectangle=length*width



            1. package com.BasicJavaProgramsExamples;
            2. import java.util.Scanner;
            3. public Class AreaOfRectangle{ 
            4.  
            5. public static void main(String args[]) {
            6.  
            7. Scanner in= new Scanner(System.in);
            8. System.out.println("Please enter length of a rectangle");
            9.  
            10.     double length=in.nextDouble();
            11.      
            12. System.out.println("Please enter width of a rectangle");
            13.  
            14.     double width=in.nextDouble();
            15.  
            16. /*
            17.  *Area of a rectangle is
            18.  *Area= length*width;
            19.  *
            20.  */
            21.          
            22.     double area=length*width;
            23.       
            24.     System.out.println("Area of the Rectangle="+area);
            25.  
            26. }
            27. }

            Output:

            1. Please enter length of a rectangle
            2. 4
            3. Please enter width of a rectangle
            4. 8
            5. Area of the circle =32.0




            2.Write a Basic java example program to find Area of rectangle without user interaction
             

            1. package com.BasicJavaProgramsExamples;
            2. public Class AreaOfRectangle{ 
            3.  
            4. public static void main(String args[]) {
            5.  
            6.  
            7.   double length=4;
            8.      
            9.   double width=8;
            10.  
            11. /*
            12.  *Area of a rectangle is
            13.  *Area= length*width;
            14.  *
            15.  */
            16.          
            17.     double area=length*width;
            18.       
            19.     System.out.println("Area of the Rectangle="+area);
            20.  
            21. }
            22. }

            Output:

            1. Area of the circle =32.0
            1.Write a Basic java example  program to find perimeter of Rectangle

            •  To calculate the perimeter of rectangle we need to ask user to enter length and width of the rectangle so that we can calculate perimeter of rectangle using formula perimeter of rectangle=2*length*width



            1. package com.BasicJavaProgramsExamples;
            2. import java.util.Scanner;
            3. public Class PerimeterOfRectangle{ 
            4.  
            5. public static void main(String args[]) {
            6.  
            7. Scanner in= new Scanner(System.in);
            8. System.out.println("Please enter length of a rectangle");
            9.  
            10.     double length=in.nextDouble();
            11.      
            12. System.out.println("Please enter width of a rectangle");
            13.  
            14.     double width=in.nextDouble();
            15.  
            16. /*
            17.  *perimeter of a rectangle is
            18.  *perimeter= length*width;
            19.  *
            20.  */
            21.          
            22.     double perimeter=length*width;
            23.       
            24.     System.out.println("Perimeter of the Rectangle="+perimeter);
            25.  
            26. }
            27. }

            Output:

            1. Please enter length of a rectangle
            2. 4
            3. Please enter width of a rectangle
            4. 8
            5. Perimeter of the circle =64.0

            Select Menu