Search code examples
javaclassvariablesscopeprimitive

Arithmetic operation on primitive class variables


Couldn't find an explicit description of what's happening so thought i'd bring this up to the community.

public class Temp {
static int i;
int j;
int sum = i+j;
}


public class Main{
public static void main(String[] args){

Temp obj = new Temp();
obj.i = 1;
obj.j = 2;
System.out.println(obj.sum); //returns '0'

}}

Is it because both integers i and j were empty during instantiation that the 'sum' variable is empty?

Thanks in advance!


Solution

  • Temp obj = new Temp(); // creates an instance of object type Temp
    

    Here, data members, i, j, and sum are initialized to 0

    obj.i = 1; // assigns value of Temp data member, i to 1
    obj.j = 2; // assigns value of Temp data member, j to 2
    

    Note that the value of data member sum of Temp Object obj is still 0.
    To make, sum = i + j, you need to initialize it to i + j when i and j are initialized.

    Simply write obj.setSum() method to set the value of sum and obj.getSum() after that to retrive the updated value of it.

    public class Temp {
        static int i;
        int j;
        int sum = i+j;
    
        public void setSum(){
            sum = i + j;
        }
        public int getSum(){
            return sum;
        }
    
    }
    
    
    public class Main{
        public static void main(String[] args){
    
        Temp obj = new Temp();
        obj.i = 1;
        obj.j = 2;
        obj.setSum();
        System.out.println(obj.sum); //OR obj.getSum()
    
        }
    }