-5

In the below program, does it mean that 3 instance variables and 3 instance methods are created and memory is allocated to them ?

class Foo{

    String name = "";

   public void greet(String name){

        this.name = name;
    }
}

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

    Foo ob = new Foo();
    Foo ob1 = new Foo();
    Foo ob2 = new Foo();

    ob.greet("hello friends");
    ob1.greet("welcome to java");
    ob2.greet("let us learn");
    System.out.println(ob.name);
    System.out.println(ob1.name);
    System.out.println(ob2.name);
    }
} 
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • 5
    Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – namokarm Jun 08 '18 at 20:03
  • Have a look: https://stackoverflow.com/questions/20796046/flow-of-class-loading-for-a-simple-program – PM 77-1 Jun 08 '18 at 20:05

2 Answers2

1

The Java Language Specification does not say anything about how memory is organized, or how objects, methods, and classes are represented.

So, the answer is: you can't and shouldn't know.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
0

All the 3 objects are stored in a heap memory. The size of the heap increases decreases as the application runs. The new operator here allocates memory to the object in the heap. Which means each time you say new in the statement a separate memory space is allocated to that object in the heap The methods are stored in JVM internal heap.

you can find a simple example of how memory is managed for objects in java here

  • 3
    There is nothing in the Java Language Specification that says anything about where objects are stored, how memory is managed, or even that there is a heap at all. In fact, most modern mainstream high-performance Java implementations, will perform Escape Analysis and/or Escape Detection and can prove that no reference escapes the local scope and will allocate everything on the stack in this example. A sophisticated implementation may even be able to prove that there are no side-effects and inline and optimize everything into just three static calls to `println` with constant strings. – Jörg W Mittag Jun 08 '18 at 20:37