Sign in to follow this  
vbuser1338

[java] Initializing variables

Recommended Posts

I am just beginning java programming because I want to see what it like compared to c++ and also so I can use it for other programs. I am reading the third edition of thinking in java and when it creates a variable when it initializes it, it will use variable = new...(..). Why this way instead of variable = ... Little example:
class Dog
{
   public String name;
   void Bark() { .... ;}
   Dog() { 
      weight = new String("yes");  // why this instead of below
      weight = "yes";
   }
}

Wouldn't this have to create a new variable and then copy the it to the original variable instead of just assigning it. Sorry if there are any mistakes because I am just learning. Cya, vbuser

Share this post


Link to post
Share on other sites
I'm not very experienced with java but I believe the reason is because of garbage collecting. new will create a new instance of that type which is than tracked by the built in garbage collector. Just like in C++ where you use new to create a class than delete it later. The java garbage collector takes care of the deletion of the object/variable/class when it goes out of scope.

Share this post


Link to post
Share on other sites
Firstly, String objects are a bad choice for such an example, as Strings are immutable and behave slightly differently than normal objects.

If you know C++, Java basically works without any kind of stack, and everything done on the heap via new. All 'references' really behave like pointers. Eg:


public class Foo
{
Bar b1;

public Foo()
{
// we don't initialise b1, it becomes assigned 'null'
}

public void baz()
{
Bar b2 = null;
Bar b3 = new Bar(3); // b3 points at Bar(3)
Bar bRef = b3; // Both b3 and bRef point at Bar(3);

In short, there is no implicit contruction and copy contrustion in Java, which is a Good Thing. If you want one, see Object.clone().

Share this post


Link to post
Share on other sites
So basically you should use a new statement for user-defined classes unless you are changing a certain portion like a value of an int. But with regular types like int,float,double,string etc you do not half use new with them because they are 'special types'( can't rememeber the name of them that I read). But with other types you should use a new statement to change the value.

class A() {
int i;
A(int a) {
i = a; // Ok
}
}

class B() {
A a1;
B(int a) {
a1 = new A(1); // Assign it one
a1 = new A(a); // Assign the value the user wants
}
}

Is this the correct way of doing this? Thanks for the help.
vbuser



Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this