Aliasing in objects - java

When running the function foo1, why does the output for this code will be: 15 30 5
and not 15 15 5 ?
I underdtand that the pointer of the object v is now points to the object va1, so the output for the code line: System.out.print(v.getI() + " ");
should be 15. So why is it 30 ?
public class Value
{
private int _i;
public Value()
{
_i=15;
}
public int getI()
{
return _i;
}
public void setI (int i)
{
_i=i;
}
}
public class TestValue
{
public static void foo1()
{
int i=5;
Value v= new Value();
v.setI(10);
foo2(v,i);
System.out.print(v.getI() + " ");
System.out.print(i+ " ");
}
public static void foo2( Value v, int i)
{
v.setI(30);
i=10;
Value va1= new Value();
v=va1;
System.out.print (v.getI() + " ");
}
}

Java only supports pass-by-value. So when you pass an object "v" to the method foo2 a copy of the reference "v" is created. So when you set v = val1 in foo2 the copy of the reference is being changed in foo2 not the original reference "v" in foo1.

Related

How can i know when the passed object/variable is referring to the same or different object

There are two programs here . I am not able to understand the explanation of the problems as they have very contrasting explanations.
//Question1
What will be the output of the program?
class Test
{
static int s;
public static void main(String [] args)
{
Test p = new Test();
p.start();
System.out.println(s);
}
void start()
{
int x = 7;
twice(x);
System.out.print(x + " ");
}
void twice(int x)
{
x = x*2;
s = x;
}
}
ans: 7 14
explanation: The int x in the twice() method is not the same int x as in the start() method. Start()'s x is not affected by the twice() method. The instance variable s is updated by twice()'s x, which is 14.
//ANOTHER QUESTION
```
class Two
{
byte x;
}
class PassO
{
public static void main(String [] args)
{
PassO p = new PassO();
p.start();
}
void start()
{
Two t = new Two();
System.out.print(t.x + " ");
Two t2 = fix(t);
System.out.println(t.x + " " + t2.x);
}
Two fix(Two tt)
{
tt.x = 42;
return tt;
}
}
```
ans= 0 42 42
explanation:
In the fix() method, the reference variable tt refers to the same object (class Two) as the t reference variable. Updating tt.x in the fix() method updates t.x (they are one in the same object). Remember also that the instance variable x in the Two class is initialized to 0.

print N-Dimensional array in java

I want a generic method to print all the elements of a multidimensional array.
In the below code i am able to print all the elements of any multidimensional array which belongs to the parent Object class but not of any primitive types.
Is it possible to print all elements of a multidimensional array of primitive type.
One more doubt if int value can be hold in a Object type then why not int[] can be cast to Object[] but, String[] can be cast to Object[].
public class MultiDimension {
public static void main(String[] args) {
//final String ar[][][] = {{{"1","2"},{"3","4","5"}},{{"6","7","8"}},{{"9","10"},{"11"},{"12","13","14","15"}}};//new String[1][3][2][2];
Integer intAr[][][][][][] = {{{{{{1},{2},{3}},{{4},{5},{6}}},{{{7}},{{8}}}}}};
recPrintArray(intAr);
}
public static void recPrintArray(Object ar) {
recPrintArray((Object[])ar,getDimensions(ar));
}
public static void recPrintArray(Object[] ar,int noODDimension) {
for (Object obj:(Object[]) ar) {
if (noODDimension > 0)
recPrintArray((Object[])obj, noODDimension - 1);
else {
System.out.print("> " + obj + " ");
}
}
}
/*return the number of dimension of an array
* takes any type as argument
* using the Object class getClass() and Class class getName() methods
*/
public static int getDimensions(Object intAr) {
return intAr.getClass().getName().lastIndexOf("[");
}
}
To answer your question, we need to introduce the concept of autoboxing first. Primitive types have their class matches. int has Integer, double has Double and so on. When a primitive type needs to be handled as an Object, the compiler will automatically convert the primitive into an instance of its wrapper class. Since you have an array of Objects, your primitive values are needed as Objects, so autoboxing will happen. If you want this to happen in a generic way, then you need to just check whether you have an array and if not, print the Object by calling its toString method.
As for your second question, you cannot convert a primitive array to an array of Objects, because your array was allocated for primitive types, not for Objects, but you can upcast a String array to an Object array, because all Strings are Objects.
since in java multidimensional arrays are array of array and array is an object. so if i recursively iterate on any array references in the last i will get only one dimensional array which i can type cast explicitly in the type supplied by using getClass().getName()
package learning;
public class MultiDimension {
public static void main(String[] args) {
final String ar[][][] = {{{"1","2"},{"3","4","5"}},{{"6","7","8"}},{{"9","10"},{"11"},{"12","13","14","15"}}};//new String[1][3][2][2];
//Integer integerAr[][] = {{1},{2}};
//byte byteAr[][] = {{1},{2}};
//int[] intAr = (int[])byteAr;
recPrintArray(ar);
}
public static void recPrintArray(Object ar) {
recPrintArray(ar,getDimensions(ar));
}
public static void recPrintArray(Object ar,int noOfDimension) {
for (Object obj:(Object[]) ar) {
if (noOfDimension > 1)
recPrintArray(obj, noOfDimension - 1);
else {
String dataType = obj.getClass().getName();
switch (dataType) {
case "[B":
printAll((byte[]) obj);
break;
case "[S":
printAll((short[]) obj);
break;
case "[I":
printAll((int[]) obj);
break;
case "[J":
printAll((long[]) obj);
break;
case "[F":
printAll((float[]) obj);
break;
case "[D":
printAll((double[]) obj);
break;
case "[Z":
printAll((boolean[]) obj);
break;
case "[C":
printAll((char[]) obj);
default:
printAll((Object[]) obj);
}
//System.out.print("> " + obj + " ");
}
}
}
public static void printAll(byte[] ar) {
for (byte val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(short[] ar) {
for (short val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(int[] ar) {
for (int val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(long[] ar) {
for (long val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(float[] ar) {
for (float val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(double[] ar) {
for (double val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(char[] ar) {
for (char val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(boolean[] ar) {
for (boolean val: ar)
System.out.print(">" + val + " ");
}
public static void printAll(Object[] ar) {
for (Object val: ar)
System.out.print(">" + val + " ");
}
/*return the number of dimension of an array
* takes any reference type as argument
* using the Object class getClass() and Class getName() methods
*/
public static int getDimensions(Object intAr) {
return intAr.getClass().getName().lastIndexOf("[");
}
}

Passed parameter into void method (integer or object)

I'm trying to find out what is the output of the following code and I almost got all of them right except 2 lines. Line 3 and 7.
The expected output would be:
1 : 10
2 : 20
3 : 20
4 : 15
5 : 40
6 : 75
7 : 35
8 : 75
9 : 20
As I mentioned I got everything right except 3 and 7. Line 3 for me was 25 and Line 7 was 40. Could you guys please explain why is line 3: 20 and line 7: 35? I tried to look it up before but couldn't find a good explanation.
It's not a homework!
public class Alpha {
protected int x;
public Alpha() { this(10); }
public Alpha(int x) { this.x = x; }
public void f() { x = 20; }
public void f(int x) { x = 25; }
public void g(Object a) { x = 30; }
public void h(Object a) { x = 50; }
public void h(Integer a) { x = 55; }
}
public class Beta extends Alpha {
public Beta() { super(15); }
public void g(Object a) { x = 35; }
public void g(Integer a) { x = 40; }
public void h(Object b) { x = 70; }
public void h(Integer b) { x = 75; }
public static void main(String[] args) {
Alpha a = new Alpha();
System.out.println("1 : " + a.x);
a.f();
System.out.println("2 : " + a.x);
a.f(100);
System.out.println("3 : " + a.x);
Beta b = new Beta();
System.out.println("4 : " + b.x);
b.g(200);
System.out.println("5 : " + b.x);
b.h(300);
System.out.println("6 : " + b.x);
Alpha c = b;
c.g(400);
System.out.println("7 : " + c.x);
c.h(500);
System.out.println("8 : " + c.x);
c.f();
System.out.println("9 : " + b.x);
}
}
For problem #3, the variable a is an Alpha. Before a.f(100) is called, a.f() is called, which sets x to 20. While calling a.f(100), the local variable x gets set to 25 in the method f(int x), not the instance variable x. The instance variable remains 20.
For problem #7, the variable b, which is a Beta, gets assigned to c, an Alpha reference. When c.g(400) is called, the compiler must make a call to g(Object), because that is the only overload of g that is available in Alpha. At runtime, polymorphism dictates that because the object is a Beta, the override of g(Object) in Beta is chosen, which sets x to 35. This is because the compiler chooses the method overload while the method override is chosen at runtime with polymorphism.
The reason line 3 is 20 is because you are changing the value of 'x' passed into the method and not the class level variable 'x'. Change your code to the below. If you read up on variable scope you'll get a better understanding too.
public class Alpha {
protected int x;
public Alpha() { this(10); }
public Alpha(int x) { this.x = x; }
public void f() { x = 20; }
public void f(int x) { this.x = 25; }
public void g(Object a) { x = 30; }
public void h(Object a) { x = 50; }
public void h(Integer a) { x = 55; }
}

java constructor: this(.)

Why the output is "021"? Why there are "0" and "1"(since "i" get "2" why it changes to "1")?
public class C {
protected int i;
public C(int i){
this(i,i);
System.out.print(this.i);
this.i=i;
}
public C(int i, int j) {
System.out.print(this.i);
this.i=i+j;
}
public C(){
this(1);
System.out.print(i);
}
public static void main(String[] args) {
C c=new C();
}}
C() calls C(1) which calls C(1,1)
C(1,1) prints 0 (the default value of this.i) and assigns 2 (i+j) to this.i
then C(1) prints 2 and assigns 1 to this.i
then C() prints 1
I think this is better for understanding:
public C(int i) {
this(i, i);
System.out.println("*"+this.i);
this.i = i;
}
public C(int i, int j) {
System.out.println("#"+this.i);
this.i = i + j;
}
public C() {
this(1);
System.out.println("#"+i);
}
Now, you can get the sequence of these methods when you invoke C();
Here the code commented, you will understand your problem now,
public class C {
protected int i;
public C(int i) {
this(i, i); // got to two parameter constructer and after the result print the next line
System.out.print(" + second "+this.i); // print value of i which is come from C(int i, int j) = 2
this.i = i; // set the value of i to 1
}
public C(int i, int j) {
System.out.print("first "+this.i); // print the value of i (in this case 0 the default value)
this.i = i + j; // set i to 2
}
public C() {
this(1); // got to one parameter constructer and after the result print the next line
System.out.print(" + Third is "+i); // print value of i which is come from C(int i) = 1
}
public static void main(String[] args) {
C c = new C();
}
}
I hope that help.

Method undefined for type method?

I have a program to find pythagorean triples. in it, i have an object that needs to be used to call methods. Said object is broken. Errors are " The method Triples(int) is undefined for the type Triples" and "The method greatesCommonFactor() is undefined for the type Triples" mind you, not everything in Triples does useful stuff atm. It isn't completely finished yet.
public class TriplesRunner
{
public static void main(String args[])
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the natural number :: ");
number=keyboard.nextInt();
Triples test = new Triples();
test.Triples(number);
test.greatestCommonFactor(number);
System.out.println(test.toString());
}
}
public class Triples
{
public int number;
public Triples(int num)
{
setNum(number);
}
public void setNum(int num)
{
int a = 0;
int b = 0;
int c = 0;
}
public int greatestCommonFactor(int a, int b, int c)
{
int max = 0;
for(a=1; a<=number-2; a++)
{
for(b=a+1; b<=number-1; b++)
{
for(c=b+1; c<=number; c++)
{
if(a*a + b*b == c*c);
}
}
}
return 1;
}
public String toString()
{
String output="";
output+="a + b + c";
return output+"\n";
}
}
you are trying to call the constructor as a method,
Change this part:
Triples test = new Triples();
test.Triples(number);
to
Triples.test = new Triples(number);
Triples isn't a method - it's your constructor, meaning it's invoked with the new operator:
Triples test = new Triples(number);
greatestCommonFactor is not defined properly. It currently takes three int arguments, instead of taking none and using Triples' data members:
public int greatestCommonFactor()

Categories

Resources