-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrimitiveAndReference.java
More file actions
88 lines (75 loc) · 2.21 KB
/
Copy pathPrimitiveAndReference.java
File metadata and controls
88 lines (75 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
class Dog{
String name;
int age;
void bark(){
System.out.println("Woof");
}
int umber(int n){
return n+1;
}
void naam(){
this.name="Pascal";
}
}
class Test{
static void renameDog(Dog d){
d.name="Buddy";
}
static void replacing(Dog d){
d=new Dog();
d.name="Charlie";
}
}
public class PrimitiveAndReference {
public static void main(String[] args){
// Answer 1:-
// Dog d;
// d.bark();//Compile time error
// Answer 2:-
Dog d1=new Dog();
Dog d2=d1;
d1.name="Alpha";
System.out.println(d2.name);//Alpha its like 2 remote controlls are controlling a single TV
// Answer 3:-
d1.name="Rex";
d1=new Dog();
d1.name="Buddy";
System.out.println(d2.name);//Rex because d2 object is unaware of d1's transformation
// Answer 4:-
Dog d3=new Dog();
d3.name="Pluto";
Test t1=new Test();
t1.replacing(d3);//Reassigning
System.out.println(d3.name);//Pluto
t1.renameDog(d3);//Modifing the parameter
System.out.println(d3.name);//Buddy
// Answer 5:-
System.out.println(d1==d2);//false
// Because their memory addresses are different.
// Answer 6:-
Dog d4=null;
Dog d5=null;
System.out.println(d4==d5);//true
// Because their memory addresses are same.
// Answer 7:-
// There are 2 scenarios to question 7
// Scenario 1:-
Dog d6=new Dog();
Dog d7=d6;
d6.name="Bruno";
d7.name="Mar";
System.out.println(d6.name);//Mar
System.out.println(d7.name);//Mar 2 remotes 1 TV logic. or same memory address.
d6=null;
System.out.println(d7.name);//Mar still pointing to the memory address
// System.out.println(d6.name);//RunTime Error
// But d7 still pointing to the memory address so no garbage collection for now.
// Scenario 2:-
Dog d8=new Dog();
Dog d9=new Dog();
d8.name="Jolly";
d9.name="Rancher";
System.out.println(d8.name);
System.out.println(d9.name);
}
}