In Java, memory-wise does it make a difference to use private vs public?

2.4k views Asked by At

Let's say I can use both private or public and it doesn't make any difference for me to choose between.

For memory usage which one is better?Why?

3

There are 3 answers

0
discipliuned On

No, access modifiers have no effect on runtime memory utilization in either Java or PHP, nor in any other language I have heard of. Possibly the code size may increase a few bytes due to access modifiers in some bytecodes depending on how they are encoded. Your program must be extremently efficient in other respects before it is worth worrying about this.

from this answer

0
George Daramouskas On

These are access modifiers. Memory-wise (RAM) no, there is no difference. This does not happen with the static keyword. Using static keeps the object in the memory.

0
raddevus On

No, in a class the property modifier of public or private does not change the memory footprint.

The number of bytes set aside for the item is simply related to the size of the type (int, long, etc) in memory.

The modifier only limits the fact that the memory address is not accessible outside the class (in the case of private).

So if you have a class like:

class Point
{
     private int x;
     public int y;
}

Both of those variables take the same number of bytes when accessed. However to access y you can do so like the following:

Point p = new Point();
p.y = 55;

However, you cannot do that with x since it is private.

You can access x from within the code inside the class like the following though.

class Point
{
     private int x;
     public int y;
     public Point ()
     {
            // this is the contstructor but other member functions woud
            // work too
            this.x = 77;
            // or 
            x = 77;
     }
}