use of static keyword
I wrote a very simple program in java to get used with the use of static keyword.But i am getting the output as 0. I am not able to find the reason for that.I am a beginner in java .Can anyone please suggest a solution,also please do explain why such an problem was encountered ...My code is as followin开发者_StackOverflow社区g :
public class Cube{
static int length;
static int breadth;
static int height;
public static int volume(final int i, final int j, final int k){
return length * breadth * height;
}
public static void main(final String args[]){
System.out
.println("volume of the cube is : " + Cube.volume(10, 20, 30));
}
}
int
fields, static
or not, are initialized as 0
.
You should multiply your operands (i * j * k
) or assign to your static int
fields.
Changing your method to this:
public static int volume(final int i, final int j, final int k){
return i*j*k;
}
will give you value you wanted.
Also, read @eljenso's answer for more details.
What you probably wanted is this:
public static int volume(final int i, final int j, final int k){
this.length = i;
this.breadth = j;
this.height = k;
return length * breadth * height;
}
You encountered a problem since values 10, 20, 30
are passed to i, j, k
, but you didn't assign them to length, breadth, height
.
And by the way, you don't really need static
in this case. This would be a better design for your class:
class Cube{
int length;
int breadth;
int height;
public Cube(int length, int breadth, int height) {
this.length = length;
this.breadth = breadth;
this.height = height;
}
public int volume(){
return length * breadth * height;
}
}
and it can be used as follows:
public static void main(String[] args) {
Cube c = new Cube(10, 20, 30);
System.out.println(c.volume());
}
This will always return 0
because length & breadth & height are initially 0;
public static int volume(final int i, final int j, final int k){
return length * breadth * height;
}
Change it like that and it will work
public static int volume(final int i, final int j, final int k){
return i*j*k;
}
The reason being when you call:
return length * breadth * height;
These variables are enclosed within an object that has not been initialized and you do need to instantiate it by using the new keyword if you want to go object oriented route. You would want to use static if there is no need to encapsulate the data of length, breadth and height.
public class cube{
static int length=20;
static int breath=30;
static int height=10;
public static int volume( final int i, final int j, final int k){
System.out.println("i=" + i + "j= " + j + "k= " + k);
return length*breath*height;
}
public static void main(final String args[]){
int a;
a=volume(10, 20, 30);
System.out.println(" area of cube " + a);
}
}
精彩评论