this is often different from C++ where objects can be allocated memory either on Stack or on Heap. In C++, once we allocate the thing using new(), the thing is allocated on Heap, otherwise on Stack if not global or static.">

how to stored Java objects in memory in java?

 
In Javaonce we only declare a variable of a category type, only a reference is made (memory isn't allocated for the object). To allocate memory to an object, we must use new(). therefore the object is usually allocated memory on the heap (See this for more details).

For example, the following program fails within the compilation. The compiler gives the error “Error here because t isn't initialized”.
 
 
class Test {

// class contents
void show()
{
	System.out.println("Test::show() called");
}
}

public class Main {

		// Driver Code
	public static void main(String[] args)
	{
		Test t;
		
		// Error here because t
		// is not initialzed
		t.show();
	}
}

Allocating memory using new() makes the above program work.

class Test {
	
// class contents
void show()
{
	System.out.println("Test::show() called");
}
}

public class Main {
	
	// Driver Code
	public static void main(String[] args)
	{
		
		// all objects are dynamically
		// allocated
		Test t = new Test();
		t.show(); // No error
	}
}

 

Submit Your Programming Assignment Details