I have a below code. The variable c and d are class variables and initially they were pointing to value 0, but when I did c=a* a; and d =b* b*b they printed value as 25 and 64 which is correct. so what I think now is that the c and d are now pointing to value 25 and 64 and they are class variables, so if I do j=c+d; it should give me 89 as j value, but it is giving me 0... why? I know if I use static with c and d variable it will give me 89 value... but why I should use static as c and d are global variables and there values are now updated to 25 and 64. Please let me know. Thanks.
public class BaiscSum {
int a=5;
int b=4;
int c;
int d;
int j;
public void square() {
c=a*a;
System.out.println(c);
}
public void cube() {
d=b*b*b;
System.out.println(d);
}
public void sum() {
j=c+d;
System.out.println(j);
}
public static void main(String[] args) {
BaiscSum squ= new BaiscSum();
squ.square();
BaiscSum cub = new BaiscSum();
cub.cube();
BaiscSum su = new BaiscSum();
su.sum();
}
}
You are using three separate instances of your class. This means that squ, cub, and su each have their own version of the class. Instead, use the same one instance, so that all changes will happen to the same instance.
public static void main(String[] args) {
BaiscSum sum= new BaiscSum();
sum.square();
sum.cube();
sum.sum();
}
If I do j=c+d; it should give me 89 as j value, but it is giving me
0. why?
Because you are referencing sum() with su object but you have not called cube() and square() on su instead you called it with cub and squ respectively.
Change to
BaiscSum su = new BaiscSum();
su.square();
su.cube();
su.sum();
It will give you the expected output.
Since all the variables you are using are instace so every object will have its own set of variable on their respective memory spaces and if you changed any one objects variable it will not effects other objects value.
This could clear more
As an explanation every object is assigned a seperate memory and so changes to the variable of one objects doesn't effect changes to other objects variable unless they are static. So in the third object c and d is not initialized for su object so jvm uses default value if int ie 0 giving you a sum of zero.
Related
I want to build a method that when it is called in main, automatically increment the value of variable.If first value is 0 when its called increment it to 1 , when I call for second time from 1 to be incremented at 2 and so on.
Notes: The method is part of a class and it called via object in main.
you can use the static variables. Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
Create a static variable whose value can be updated in a function.
let this be your class
class Student {
static int b; //initialized to zero only when class is loaded not for each object created.
public void update(){
//incrementing static variable b
b++;
}
public void showData(){
System.out.println("Value of b = "+b);
}
}
and this be your main class
public class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.update();
s1.showData();
Student s2 = new Student();
s2.update();
s1.showData();
}
}
output:
Value of b = 1
Value of b = 2
Well, you kinda left a lot up for interpretation here, assuming the "value of variable" is part of the object the code would be something like this:
public class MyClass {
public int myVariable = 0;
public MyClass() {}
public void incrementMyVariable() {
myVariable++;
}
}
How you would handle this depends on where the variable your referring to is located ie. main method, object variable, etc... Additionally, if the variable needs to be kept constant across all the objects created for the class you would need it to be static.
I am getting a bit confused regarding few points regarding Java memory management.
Understood what is the difference between Stacks and Heap and I went to see a proper example on what is those memories when we execute some code.
I took for example this few lines
public static void main(String[] args)
{
int a = 5;
calculate(a);
System.out.println(a); //will print 5 not 50
}
private static void calculatee(int a)
{
a = a * 10;
}
I understood what is happening in the stack and in the heap. The variable is not getting returned and there is no reference to the Heap in this case.
while in this example:
public static void maina(String[] args)
{
Customer customer = new Customer("John");
setAName(customer);
System.out.println(customer.getName()); // this will return Philip
}
private static void setAName(Customer c)
{
c.setName("Philip");
}
I can see the state of the object changed this time!
Stacks are not shared thought threads, but heap is shared! Which make sense to me that the object customer has changed its value from Jhon to Philip when I am printing it!
Great! all make sense!
However, I was expecting that if I will do this
public static void main(String[] args)
{
Integer i = new Integer(5);
calculate(i);
System.out.println(i); // printing 5 and not 50
}
private static void calculate(Integer i)
{
i = i * 10;
}
I would get 50 and not 5!
In this case Integer is an object and I am assuming it is created in the heap!
Funny thing is that if I will wrap the Integer inside Customer I will get 50 instead of 5.
Why is this happening? Isn't the Integer type getting created in the Heap?
This is a problem of references and not of heaps and stacks.
When calling the method calculate, you pass a reference (in your case, i from main).
The trick is, that Java will create a new reference inside of calculate. So i inside of calculate and i inside of main might initially "point" to the same object, but they are not the "same".
So, if you change i inside of calculate to the object resulting from your multiplication, you don't automatically change the reference of the i inside of main.
With Customer, it's different. You never change where c in setAName points to. You change one reference inside of the object, but both customer inside of main and c in setAName still point to that one object!
Here two shitty Paint drawings to explain what I mean (numbers prefixed with 0x are references):
For the Integer example:
For the Customer example:
Don't hesitate to come back with any questions.
I hope this helps.
So I'm having a problem with passing values to another class in java.
I have an application which accepts an equation from the user, after the button gets clicked, it finds out the number of variables the equation has and I'm putting the variables in two lists. Now, I need to pass these variables to another class.
here's the snippet of code where I need to use the variables:
beeColony.java
public class beeColony {
int D;
double Foods[][]=new double[FoodNumber][D];
public void getDimension(int D)
{
this.D = D;
}
}
based from here, I need to initialize the variable Foods into having a size depending on the FoodNumber and D. There's no problem w/ regards to the FoodNumber since it is a static one.
in my main application there is an event handler
private void getvalueMouseClicked(java.awt.event.MouseEvent evt) {
bee.getDimension(dim);
}
when I output the variable D in one of my methods, it is equal to the value that I assigned it to. My problem is that the size of array Foods. I get an IndexOutOfBounds Exception. I think that when I initialize the array Foods, it is unable to get the value of D.
Any thoughts on how to fix this?
Why are you using getDimension() to set a value?
The reason this is happening is because you must have created a new class of beeColony and while doing that you used the default value of D (set to zero). It would then use this value of D to create the Foods array. This would create a Foods array of size FoodNumber x 0
I would change it as follows:
public class beeColony {
int D;
double Foods[][]=null;
public void getDimension(int D)
{
this.D = D;
this.Foods = new double[FoodNumber][D];
}
}
}
I don't know what's wrong with my code. I want to display the value of b (10) in my info() method, but when I run this code, the value of b is 0. Why does this happen?
class Alpha {
public int a = 5;
public void info() {
System.out.println("a = " + a);
Beta3 betaku;
betaku = new Beta3();
System.out.println("b = " + betaku.perolehB());
System.out.println("Dipanggil pada " + this.getClass().getName());
System.out.println("----------");
}
}
Here's the main class:
class Beta3 extends Alpha {
private int b;
public void isiB(int b){
this.b=b;
}
public int perolehB(){
return b;
}
public static void main(String[] args) {
Beta3 varobjBeta;
varobjBeta = new Beta3();
varobjBeta.isiB(10);
varobjBeta.info();
Alpha varobjAlpha;
varobjAlpha = new Alpha();
varobjAlpha.info();
}
}
That will never work, in the info method you wrote this:
Beta3 betaku;
betaku = new Beta3();
System.out.println("b = " + betaku.perolehB());
And ever will display 0(Because b is not initialized in the betaku instance, so the default is 0), you should delete that line, and pass the b value in some way, or override the info method in Beta3 class.
class Beta3 extends Alpha
{
//Another code
public void info()
{
// super.info(); if you wanna show the a value too
System.out.println("b=" + this.b);
}
//Some other code
}
Or if you need to access that value from Alpha class:
class Alpha
{
public void info(Beta3 aux)
{
this.info();
aux.info();
}
}
Then in main you can do something like this:
public static void main(String[] args)
{
Beta3 varobjBeta;
varobjBeta = new Beta3();
varobjBeta.isiB(10);
Alpha varobjAlpha;
varobjAlpha = new Alpha();
varobjAlpha.info(varobjBeta);
}
Make line 4 of your main() method, beta_ku.info();. Your other calls to .info aren't working because you haven't called isiB and they're defaulting to 0.
Every time you write new Beta3, a new object of type Beta3 is created, with a new pair of attributes. If you want the value of an attribute you set in a previous object, just pass the reference of that object to the method and fetch the value from it.
That's because you are asking for the value of an instance of Beta3, which never initializes its value anyways and Java automatically initializes ints to 0 (for some reason).
beta_ku should print out 10 correctly, but varobjBeta does not set its b value.
The instance of Beta3 in your info call to Alpha does not have its b value set. Therefore, it is initialized at instantiation to 0.
The real reason this happens is due to the way initial values are established, per the JLS:
Each class variable, instance variable, or array component is initialized with a default value when it is created. ...
...which in general, means that all primitives are initialized to some form of zero, and all objects are initialized to null.
How would you get around this? Either create an instance by hand of Beta3 and pass that to the instance of Alpha, or just use Beta3 to print its own info.
Observe that beta_ku would work fine, if you were calling info - for that instance, b is defined to 10.
betake = new Beta3();
When you instantiate the betake it just assign the default values to the attributes of the class Beta3. Here the attribute of the class Beta3 is b.
Below is a table of default values of class variables by type:
Type default
--------------------------------------------------------
boolean false
int 0
float 0.0
char /u0000
reference type null
So in you class Beta3 b is int so the it gets the default value of 0. You need to call isiB(int b) to set the intended value to b or you have to write a parameterized con structure to set the value of b i.e.
public Beta3(int bb){
this.b= bb;
}
EDIT
Beta3 betaku;
betake = new Beta3();
betake.isiB(10);
System.out.println("b = " + betaku.perolehB());
Hope it helps.
I know that static blocks are run before anything. But here, what happens when B.test() is called? Order of execution and setting of values? Later, when b1 is set to null, still how b1.i evaluates to 20?
class B
{
static int i;
static {
i = 20;
System.out.println("SIB");
}
static int test() {
int i = 24;
System.out.println(i);
return i;
}
}
public class Manager {
public static void main(String[] arg) {
B.test();
B b1 = null;
System.out.println(b1.i);
}
}
The output is:
SIB
24
20
The value of i here
static int i;
static {
i = 20;
System.out.println("SIB");
}
is set to 20 and never modified, so when you access b1.i, it's still 20.
In your test() method you are using another i variable that is not related to the static one.
i is static, so b1.i is equivalent to B.i. Just setting b1 to null doesn't change any static variables.
When B.test() is called, first the B class is loaded, and the static blocks are run. Next, B.test() creates a new method-local variable called i, which is completely different from B.i. This new, local i is printed and returned. No changes are made to B.i, and certainly not just because you created a new B object reference that was null -- that would never have any effect on anything.
But here, what happens when B.test() is called? Order of execution and setting of values?
There is no change.
Later, when b1 is set to null, still how b1.i evaluates to 20?
Because b1 isn't used, the field is static so you are actually using B.i
What happens is:
B.test() is called for the first time, before actually running it:
Class B is loaded,
Static initializer executed (B.i = 20 now)
Contents of B.test() method are executed
(creates a method-local int i = 24 (which shadows the static variable B.i) and prints it)
b1.i is interpreted as B.i (which is still 20) and it's printed.
What you did: What really happened:
B.test() - static block of class B is run, static i set to 20, SIB is displayed
- test method is called, local property i set to 24, 24 is displayed
b1 = null - set reference for b1 to null. Note that this doesn't change the value of class B's static properties
System.out.println(b1.i) - b1 is still Class B. It doesn't matter what its current reference is. Static i for class B is still 20, 20 is displayed