Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations sizbut on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Are these variables well initialized?

Status
Not open for further replies.

chals1

Technical User
Sep 3, 2003
73
ES
are c1 c2 c3 correctly employed ?
Here, 'read' is a static method that return an object of Complex class.


public static void main(String args[]) {
int n,k;
Complex c1,c2,c3;
c1=read();
c2=read();
c3 = c1.add(c2);
System.out.println(c3.toString());

}
 
Does read() always return a Complex class, i.e. it can never return NULL?

Does Complex.add() always return a Complex class, i.e. it can never return NULL?

if NULL is ever returned, a NullPointerException will be thrown.
 
There ain't exceptions.
Do i need any 'new' to create properly objects c1 c2 c3?

Another related question:
Is correct create the same object two times with different parameters, like here where there are two instances of c :

static Complejo lectura() {
double a;
double b;
Complejo c;

a = consola.leerdouble();
b = consola.leerdouble();

c = new Complejo(a,b);

if((eleccionMenu < 5) && (eleccionRead == 1)) {
a = c.getParteReal();
b = c.getParteImaginaria();
System.out.println(b);
}
if((eleccionMenu > 4) && (eleccionRead == 2)) {
a = c.getModulo();
b = c.getArgumento();
}

c = new Complejo(a,b);
return c;
}
 
Do i need any 'new' to create properly objects c1 c2 c3?

No. &quot;new&quot; is called somewhere in read(), or in a method called by read(). Function return values don't need &quot;new&quot; because they are already instantiated before they are returned to the caller.

Is correct create the same object two times with different parameters, like here where there are two instances of c :

It is correct to reuse variable names, but I try to avoid it. It can cause confusion. It is easier to debug if variable names are not reused and the lifetime of variables are kept to a minimum.

Remember, c is just a variable name.

StringBuffer sb1 = new StringBuffer();
StringBuffer sb2 = sb1;
StringBuffer sb3 = sb1;

Here we create only one StringBuffer. sb1, sb2, and sb3 all reference the same object.

If we call do this.
sb2.append(&quot;Hello&quot;);
sb1.append(&quot;World&quot;);
System.out.println(sb3);

we will print: HelloWorld

We can also create an object without assigning it to a variable name like this:

Vector v = new Vector();
v.add(new Complejo(1.1, 1.1));

Here Compejo is not assigned to a variable name, but is stored in a Vector.

Sean McEligot
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top