Objects references get deleted when not in use? [duplicate] - java

This question already has answers here:
Deleting an object in java?
(7 answers)
Closed 1 year ago.
class Point{
int x;
int y;
Point (int x,int y)
{
this.x=x;
this.y=y;
}
}
public static void main(String args[])
{
Point p =new Point (2,3);
Point p1 = new Point(2,4);
}
If I create two objects of this Point class and then again create another object of the Point class then will the last Point object that is p will get delete or will remain ??

In Java, as in many other languages, there is something called "object scope", which actually represents the lifecycle of an object.
In particular, if you instantiate an object inside a specific block of code, that represents the scope of your object, and your reference will be valid as long as the block is executed.
After reaching the first line outside that block, your reference is taken in charge by the "Gargage collector", which basically is the mechanism in Java responsible for cleaning up the memory from all those objects which don't have any reference inside your program and, thus, you don't need it anymore.
In your particular case, as there are the only two stetements of program, both references will be valid for the entire program.
However, there is a scenario in your simple program which can make you loose one reference see this piece of code:
public class Point{
int x;
int y;
Point (int x,int y)
{
this.x=x;
this.y=y;
}
}
public static void main(String args[])
{
Point p =new Point (2,3);
p = new Point(2,4);
}
As you see, because I have assigned the second object Point to the same reference p, the first one will be lost and, thus, automatically handed over to the garbage collector to be freed from the memory.
However, the above code was just one of the example of the technique you can use to make an object get taken in charge by the Garbage collector. I suggest that you have a look at the answer Deleting object in Java? where you will find more examples and different techniques.

Java do remove object whenever they are not need anymore.
In this case as long as your program runs inside the main method, the Point objects will not be removed.

Related

Helper Methods within static method are overidding multiple variables? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 5 years ago.
public class SeamCarving {
public static Seam carve_seam(int[][] disruption_matrix) {
int[][] original = disruption_matrix;
int[][] weighted_matrix = disruption_matrix;
SeamCarving s1 = new SeamCarving();
weighted_matrix = s1.buildMatrix(disruption_matrix);
....
}
In the above code I have a static method carve_seam. The method takes a matrix. That input is saved in a matrix variable called original. A calculation is performed on the matrix and that is also saved as a variable called weighted_matrix. Both are needed.
Since its in a static method, a new object of the class is made and it is called from that "s1.buildMatrix"
However, that line is doing something that is over my head. This is because afterwards, not only is weight_matrix changed (correctly from the buildMatrix method) but original is also changed to the same exact thing! How does this happen???
First thing you need to understand here is that all the three reference matrix, are referring to the same object you have passed as the input (disruption_matrix object). This is the reason why also the original and weighted_matrix are being changed.
In the first line,
int[][] original=disruption_matrix;
refers to the same object in disruption_matrix.
Then on the next line,
int[][] weighted_matrix=disruption_matrix;
refers to the same old object as well. So, you do not need to reach the line,
weighted_matrix = s1.buildMatrix(disruption_matrix);
to see that both original and weighted matrix have been changed. Actually the they have been changed when you have done the calculation to the disruption_matrix itself.
This situation is quite similar to a something like, where,
int a=10;
int b=a;
int c=a;
So, not only 'a' but also 'b' and 'c' will have their value assigned to 10.
In a OOP manner, where such same object is being assigned to different references, once a change has been made to the object through a single reference no matter that you're accessing the object through a different reference, the object has been changed.
For an example let's take this simple class,
Class A{
int val=10;
}
now, in some method we create an object and assign it to references,
A a=new A();
a.val=20;
A b=a;
b.val=30;
A c=a;
c.val=40;
As for the above code, an object is created under the reference called 'a'. In the next line, the value 'val' is accessed through that reference and has been changed from 10 to 20.
Then, the reference 'b' has been declared and it is initialized and pointed to the same object which 'a' is holding. Then in the next line, the value of that object (val) is changed again 20 to 30, but this time through 'b' instead of the reference 'a'.
Same goes to the next three lines where the value of the object is being changed from 30 to 40 through the reference 'c'.
So finally what will be the output?
System.out.println(a.val);
System.out.println(b.val);
System.out.println(c.val);
It is obviously going to give you the output,
40
40
40
This is the concept you are missing here (Pass by value and pass by reference).
In Java, Arrays are technically objects and not primitives, even for arrays of primitive types. Whenever you pass an argument to a method as an object, Java passes it as a reference; the values of the original argument change because all variables you have created are "referring" to the same object. This, however, is not the case with primitives, which are passed by value.
I suggest that whenever you need to make a matrix off of another you use the following utility method:
public static int[][] copyMatrix(int[][] original) {
int[][] copy = new int[original.length][];
for(int x = 0; x < copy.length; x++) {
copy[x] = new int[original[x].length];
for(int y = 0; y < copy[x].length; y++) {
copy[x][y] = original[x][y];
}
}
return copy;
}
At the end, your code would look like this:
public class SeamCarving {
public static Seam carve_seam(int[][] disruption_matrix) {
// no need to make an "original" variable anymore,
// since disruption_matrix already stands for it
int[][] weighted_matrix = copyMatrix(disruption_matrix);
SeamCarving s1 = new SeamCarving();
weighted_matrix = s1.buildMatrix(disruption_matrix);
....
}
}
Keep in mind that this implementation copies the arrays but not the objects. This will solve your problem when working with primitives like int but not with mutable objects.

Where does my variables and references gets stored in heap or stack? [duplicate]

This question already has answers here:
Where is allocated variable reference, in stack or in the heap?
(4 answers)
Closed 5 years ago.
please let me know where does my static reference, static primitive, object reference , object itself and method itself along with class information is stored.
*please let me know who does this memory management?
*please let me know what gets stored in permgen place?
*please specify the storage space(heap or stack) which will be allocated for all the object references,object, primitive data (for both static and non-static types) for the following program.
package training;
public class Memory {
static int var =1;
static String s="hi";
static Threadtutorial th;// this is another class in the same project,consider this an object.
static Threadtutorial tt = new Threadtutorial();
int are =2;
int d;
static float value;
public static void main(String[] args) {
// TODO Auto-generated method stub
int a;
int b=1;
Threadtutorial th;// this is another class in the nsame project,consider this an object.
Threadtutorial tt = new Threadtutorial();
final int var =1;
value=8;
}
void somemethod(){
int ne=3;
String something;
Object ref;
Object dereee= new Object();
}
static void another(int b){
int c=b;
Object ref2;
Object der= new Object();
}
}
Where things are conceptually per the JLS is one thing and deterministic, where they are physically in the JVM is another and varies with circumstances.
The easy part is where things are conceptually. Type definitions including method areas, space for static fields, and other type-level information are in the class area of heap. Method arguments and other method control information live on the stack as methods are invoked. Instances live on the heap.
Physically those things can live in various places at different times or even disappear altogether. Member variable values might live for a while on the stack or in registers while the rest of the object is not even in memory. Method calls might vanish altogether. The runtime interpreter/compiler combination has wide leeway in how it handles program logic.
Have you actually tried researching your question? What have you come up with?

Java pass by value clarified [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
I have a list of Cell object that represent a board game inside the board class.
Cell boardGame[][] = new Cell[8][8];
I needed a temporary cell to try the player move on him and compare it to the other cells, so I though that I could use a java pass-by-value to do it.
test(board.boardGame);
board.printBoard();
private static void test(Cell[][] boardGame) {
Cell c = new Cell((new Soldier(ChessPiece.QUEEN, Color.WHITE)), 7, 4);
boardGame[7][7] = c;
}
I read some post about java here, but apparently I still didn't catch it 100%.
I expected to see only one white queen on the board, but I saw two.
I know that if you pass a reference you can change its values, but I though that if I would pass the array itself its members won't be modified unless I would execute a return.
Please help me to understand this subject better.
Thanks
Edit:
I think I don't understand when it called attributes and where it doesn't.
I though the different it if you are call "new" or not.
When its part of another object it called attribute right? but every object can be created as part of another object. I can create a new string in dog class and then create the dog class in the animal class and then create it in another class. So only the top class is in the stack?
For exemple:
public class Board { //fake class
int num= 0;
public void test(int i){
i = 1;
}
}
and on another class:
public class Main {
static void outsideTest(Board board){
board.num = 1;
}
public static void main(String[] args) {
Board board = new Board();
System.out.println(board.num);
board.test(board.num);
System.out.println(board.num);
outsideTest(board);
System.out.println(board.num);
}
}
Now I didn't understand why on test() method the num didn't change and on outsideTest() the num change, num as been created in the heap because its part of the board object, so its need to be changed on both cases no?
The best and least confusing way to remember it is as follows: Java passes everything by value, that includes the references. :)
When you have a variable:
Object a = new Object();
you don't actually have an object stored in a. What you have is a reference to an object somewhere in memory.
Likewise when you call a method on an object:
String b = a.toString();
you don't do that. What you call is a method that uses the data of the referenced object as its context.
So when you pass an object as an argument
System.out.println(b);
You don't pass the whole object. You pass the reference and that reference is passed by value.
edit:
If the reference were not passed by value, but by reference, you could do something like this, which fortunately you can't.
public void swap(Object a, Object b){
Object swap = a; a = b ; b = swap;
}
String a = "a";
String b = "b";
swap(a,b);
// would print "b a" if references were
// passed by reference but instead prints
// "a b" as they're passed by value.
System.out.println(a + " " b);
The reference to the object is passed by value, which means that
boardGame = new Cell[8][8];
does not do any harm, but changing anything you get from boardGame does.
Java is essentially always "pass-by-value".
Caveat: It passes the value stored in the memory for the variable.
For primitive data types, the memory is allocated in stack space, whereas for objects reference memory is allocated in stack space but the object itself is created in heap. Similar can be stated for arrays too though they are not exactly objects in a strong sense.
Diagrams below would make it clearer.
Your Cell object 2D array should seem something like anObjectArrayVar (not exactly as the ref in the diagram pointing to the objects should now be pointing to the rows and we would need another level of allocation in heap in between ref and objects for each row (a set of cells refering to the objects).
So, when you pass boardGame, the value stored in the stack is passed that stores the reference to the array of objects (just like the value stored in the anObjectArrayVar). If say the list of refs is stored in location numbered 50 then anObjectArrayVar would have stored that and it passes that value to the test method when we call it. In such a scenario the test method wont be able to goto memory location anObjectArrayVar and change its value (to say 100) as it has only a copy of the value but it could easily change what it refers to(directly or indirectly) like the values in ref or the next level (and add new objects as in your case adding a new cell with queen) or the objects pointed to by them and those changes would reflect through out the program!
I would also like to draw your attention to the fact that the code
boardGame[7][7] = c;
would replace the current cell (as well as the soldier currently in it) which would create major issues if there was originally a soldier in that place at that point in the game. The game state would actually change.
As a suggestion (given the limited knowledge about your design) I would say at least save the cell in some other value in test method before replacing it.
Cell old = boardGame[7][7];
//now do all your operations
boardGame[7][7] = old;//just before returning from the function

Confused about Arguments Passing

I'm a bit confused about information passing to methods in Java. I'm currently studying Java basics on Oracle website and while most things I understand with no problem, some things aren't clear enough to me.
https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html
Here is where I'm having doubt. When they write the following code...
public void moveCircle(Circle circle, int deltaX, int deltaY) {
// code to move origin of circle to x+deltaX, y+deltaY
circle.setX(circle.getX() + deltaX);
circle.setY(circle.getY() + deltaY);
// code to assign a new reference to circle
circle = new Circle(0, 0);
}
What do they mean by circle = new Circle(0, 0);? Is it creating a new Cicle object or what? I think what confuses me is how the object parameter is used inside the method declaration.
Can someone explain to me clearly what Passing reference data types is about?
Start with a simpler example:
public class Main {
public static void main(String... args) {
int x = 7;
add(x);
System.out.println(x);
}
public static void add(int y){
y = 10;
}
}
What do you expect this code to print out?
It prints out 7 because even though we're reassigning the parameter received by the add() function, that doesn't affect the original value passed into the function. The x variable in the main() method is still 7.
The example code is just showing you a more complicated example of that with Objects instead of primitives. The lesson you're supposed to learn is that reassigning parameters in a function does not affect their original values.
These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change.
Read the last paragraph carefully.
You are able to modify the attributes of the referenced circle, but if you assign the variable a new reference, no changes were made to the original object. It only tells myCircleto refer to a newly created object. And this object gets immediately garbage collected after the method goes out of scope.
Explanation for the two questions you asked:-
circle = new Circle(0, 0) means that we are assigning values to the constructor of Circle object .
Yes this is creating new circle object by passing values to the reference variable circle.
Hope it helps!

Are all immutable objects re-usable?

From the effective Java book it states that "An object can always be reused if it is immutable".
String s = "shane";
String p = "shane";
This version uses a single String instance, rather than creating a new one
each time it is executed. Furthermore, it is guaranteed that the object will be
reused by any other code running in the same virtual machine that happens to contain
the same string literal.
What about the below final class which is also immutable?. Can the Point Object be re-used?.
public final class Point {
private final int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y;
}
Can anyone provide me an example of the above immutable class where its object/instance can be re-used?. I am just confused on how the re-usability would occur?.
I am able to relate with String and Integer Classes, but not with user defined classes.
It "can" be reused, in that you could use the same object in multiple places and it would be fine. But it won't be, automatically. The JVM itself manges reuse Integer objects for the range -128 - 127
Integers caching in Java
"intern"ed strings (including literals) similarly are managed by the JVM. The closest to automatic reuse you could have here would be to make the constructor private, and create a factory method:
Point.create(int x, int y)
And have the implementation maintain a cache of objects that you'd like to reuse (like Integers effectively cache -128 to 127) But you'll have to do the work yourself.
Edit:
You'd basically have:
private static final Map<Pair<Integer, Integer>, Point> cache = new HashMap<>();
public Point create(int x, int y) {
Pair<Integer, Integer> key = Pair.of(x, y);
if (cache.containsKey(key)) {
return cache.get(key);
}
Point p = new Point(x, y);
cache.put(key, p);
return p;
}
Edit:
Alternatively, add hashCode() and equals() to the Point class, and just use a HashSet. Would be simpler.
Re usable simply means to change the "reference" variable value.
e.g. an int is can be reused and its value changed
a data type is a little different the reference variable is re-initiated for example using the "new" instane e.g. myframe=new JFrame()
variables declared "final" are a "constant" and are mutable.
The class above itself requires its reference variable at initiation to be declared "final" to be mutable although its contents is effectively mutable, the difficulty is the definition of context of which (variable or class definition) part is the mutable.
Immutability means when an object is created its state at the creation time is going to stay through out its life. And yes, the class you showed and object of that class is immutable, as you are initialing states in constructor and there are no setters.
About the re-use: yes you can reuse the same object over and over where an object of type Point is required, but for that purpose you have to hold on to an object once it's created for that. As #James
suggested, you can use a factory for object creation and that factory can decide if it needs to create a new object or use an existing one when you ask for a Point object.

Categories

Resources