I am trying to assign value to a class variable via a method. However, after the execution comes out of the scope of the method, the variable is still initialized to the default value. How do we accomplish this in Java?
I want to initialize x to 5 by calling the method hello(). I don't want to initialize by using a constructor, or using this. Is it possible?
public class Test {
int x;
public void hello(){
hello(5,x);
}
private void hello(int i, int x2) {
x2 = i;
}
public static void main(String args[]){
Test test = new Test();
test.hello();
System.out.println(test.x);
}
}
When you do
hello(5,x);
and then
private void hello(int i, int x2) {
x2 = i;
}
it seems like you might be trying to pass the field itself as parameter to the hello method, and when doing x2 = i you meant x2 to refer to the field. This is not possible, since Java only supports pass-by-value. I.e. whenever you give a variable as argument to a method, the value it contains will be passed, not the variable itself.
(Thanks #Tom for pointing out this interpretation of the question in the comments.)
The class property x is only visible by using this.x in hello() because you have declared another variable called x in the method's arguments.
Either remove that argument:
private void hello(int i) {
x = 5;
}
Rename the argument:
private void hello(int i, int y) {
x = 5;
}
Or use this.x to set the class property:
private void hello(int i, int x) {
this.x = 5;
}
You can create two methods.
public void setX(int a)//sets the value of x
{
x=a;
}
public int getX()//return the value of x
{
return x;
}
call setX to set the value of x and getx to return the value x.
Essentially these are called getter and setter and we use them to access private members from outside the class.
Related
import comp102x.IO;
public class testing {
private int x;
public testing(int x) {
x = x;
}
public static void main(String[] args) {
testing q1 = new testing(10);
IO.outputln(q1.x);
}
}
Why is the output 0 instead of 10? This is a JAVA script. The concept of instance and local variables is very confusing to me, can someone help to explain?
public testing(int x) {
x = x;
}
here you only reassign the value of the local variable x to itself, it doesn't change the instance variable.
Either change the name of the local variable, like this:
public testing(int input) {
x = input;
}
or make sure you assign the value to the instance variable, like this:
public testing(int x) {
this.x = x;
}
#include<stdio.h>
void decrease(int *i);
int main(){
int i = 10;
decrease(&i);
printf("%d",i);
}
void decrease(int *i){
*i = *i - 1;
}
What would be the Java program for the same?
As you pointed out (no pun intended), Java does not support pointers. So, there is no way to directly manipulate the value of a primitive passed to a method, because only a copy of the primitive would be used in the method. One way to get around this would be to just return the updated value, and then overwrite the integer in the calling scope:
public static int decrease(int i) {
return i - 1;
}
public static void main(String[] args) {
int i = 10;
i = decrease(i);
System.out.println(i); // prints 9
}
You have two options, either (return) the value, and modify it in the main class, or pass an Object, not a primitive.
An object with your values:
public class Holder {
public int x;
}
And a method to modify it
public void modify(Holder h){
h.x = 2;
}
Called like:
Holder h = new Holder();
h.x = 1;
modify(h);
System.out.println(h.x);
Results in:
2
Here when I run this below code I get called as the output and I was wondering why not called new. Since 1 comes under both short and int range.
public class MyClass {
private int x;
public MyClass(){
this(1);
}
public MyClass(int x){
System.out.println("called");
this.x = x;
}
public MyClass(short y){
System.out.println("called new");
this.x = y;
}
public static void main(String args[]) {
MyClass m = new MyClass();
System.out.println("hello");
}
}
1 is an int literal, so MyClass(int x) is chosen.
Even if you remove the MyClass(int x) constructor, MyClass(short y) won't be chosen. You'll get a compilation error instead, since 1 is not short.
You'll have to cast 1 to short - this((short)1); - in order for the MyClass(short y) to be chosen.
As an addition to others answer I can suggest you to check which constructors are being called when you initialize variables of other types using the same literal:
short s = 1;
int i = 1;
And then check which constructor of MyClass is being called as you call them with above arguments.
I'm trying to compile this code
public class Foo {
static final int x = 18;
public void go(final int y){
System.out.println(x);
}
}
public class Mixed2 {
public static void main(String[] args){
Foo f = new Foo();
f.go(11);
}
}
And it is compiled. And even gives the result (18)
But this does not have to be. Why is this happening?
I use the idea
Thanks
The fact is, You cannot change the value of a final... However, you are not changing any final numbers, and if you were, you would get compiler errors, not exceptions.
It is important to know the differences between static and final:
Static makes a variable the same between all classes- Changing go() to static will still allow you to access it, but making go() static and removing static from x will prevent you from referencing x, because the go() function does not know which Foo class to find x in.
Final Makes a variable unchangeable- I do not know of any performance reasons for this, but mostly for constants.
For example, you do not want to be able to set the value of Boolean.TRUE to false
public class Foo {
static final int x = 18;
public void go(final int y) {
// This is not possible because 'x' is final,
// however the state of 'y' does not matter,
// because its value is not being changed
x = y;
System.out.println(x);
}
}
public class Mixed2 {
public static void main(String[] args){
Foo f = new Foo();
f.go(11);
}
}
From what I understand, you wonder why the code is valid in the following cases, when you expect it to throw an error.
In this case, you are not changing the field x, but simply adding a new variable with the same name, that override (shadows) the field x:
public class Foo {
static final int x = 18; // field x
// This creates a new variable x which hides the field x above
public void go(final int x /* variable x */) {
System.out.println(x);
}
}
In these next two cases, you are trying to change x, which will result in an error:
public class Foo {
static final int x = 18; // field x
// The field x is final and cannot be changed.
public void go() {
x += 1;
}
}
public class Foo {
static final int x = 18; // field x
// The variable x is final and cannot be changed.
public void go(final int x /* variable x */) {
x += 1;
}
}
Old Answer: If you're trying to have it print 11, you should call System.out.println(y) instead of using x.
Try following some Java tutorials and look closely at the code and at variable names.
I have 2 classes, A and B. A contains properties that I want to use in B.
I want to put all objects I initialize in B into an array every time a new object is initialized. With this code, the first object should go to array-position 1, the second object to array-position 2 and so on. The variable n basically determines to which position the object should go.
I know that with "this." I can access individual variables from this object (as you can see with x and y), but I don't know how I can access the object as a whole. You see that I have a comment in my code, which shows what I try to do. It doesn't work, because it's not the proper syntax.
What do I have to put there so it will work?
class A{
private int x, y;
private static int n;
A(int x, int y){
this.x = x;
this.y = y;
n++;
//B.object[n] = this.object;
//I tried this but it doesn't work
};
}
class B{
public static A[] object = new A[10];
public static void main(){
A object1 = new A(1,2);
A object2 = new A(3,4);
A object3 = new A(5,6);
};
}
Your object reference inside B class holds an array of A types, so you need to simply set B.object[n] = this; as shown below (Here, this itself represents the current A object, so no need to say this.object):
class A{
private int x, y;
private static int n;
A(int x, int y){
this.x = x;
this.y = y;
n++;
B.object[n] = this;
};
}
class B{
public static A[] object = new A[10];
public static void main(String[] args){
A object1 = new A(1,2);
A object2 = new A(3,4);
A object3 = new A(5,6);
};
}
Also, in Java, main method takes String[] as input arguments (shown above) which will be the method executed by the JVM at the start (though with main(), the code compiles, but JVM does not invoke it at the start).
But as a side note, remember that what you are trying do creates circular dependencies (class A depends on class B and then class B depends on class A), so avoid that.
Although javaguy's solution solves your problem, it will probably cause the compiler to give a warning about a "leaking this" in the constructor.
This could be potentially dangerous in a multithreaded environment because it allows you to get hold of a reference to A (via B.object) before A has fully run through its constructor.
A better pattern in this case would probably be to have a static helper method in A that constructs those objects for you, adds them to the list and then returns a reference to them.
class A{
private static int n;
private int x, y;
public static A createA(int x, int y){
A result = new A(x, y);
n++;
B.object[n] = result;
return result;
}
private A(int x, int y){
this.x = x;
this.y = y;
}
}
class B{
public static A[] object = new A[10];
public static void main(String[] args){
A object1 = createA(1,2);
A object2 = createA(3,4);
A object3 = createA(5,6);
}
}
By making the constructor of A private, you ensure that new A(1,2) won't work from another class, so you have to use the helper method to get an instance.