hai

iam newbie in java programming.

i declared like this:

StringBuffer s1=new String Buffer("hello");

StringBuffer s2=s1;

i want to know exactly how many objects created: 2 or 3 am not certain


suppose i want to show the number of objets in


System.out.println()....


how i need to proceed....


regards

ramesh :rolleyes:

StringBuffer s1=new String Buffer("hello");

StringBuffer s2=s1;

creates a compiler error.

StringBuffer s1=new StringBuffer("hello");

StringBuffer s2=s1;

creates at most 2 objects, a StringBuffer on the heap which lasts for the scope of the method, and a String on the String constant pool (unless one already exist for the string "hello" in which case that one is referenced instead).
It also creates 2 references to the single StringBuffer.

There is no way to count objects or references that exist in Java, there is no such mechanism provided in any public API (there may be something in an internal API used by the garbage collector).

they hook into the JVM from the outside, which should give them more information.
It's probably available, but think of it: when you try to find out how many objects there are you're creating objects yourself, thereby changing the result.

jvm creates one object of StringBuffer class with the value "hello"
and creates two reference s1 and s2 both shares the same object.

This article has been dead for over six months. Start a new discussion instead.