This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
I would like to store reference to variable in some class, and make operations on it inside this class. Operations should modify original variable.
In particular following code should print 1 instead of 0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
How to achieve this behaviour?
You can replace Long with AtomicLong which is mutable. You'll lose autoboxing features though.
The problem in your code is that Integer is an immutable class.
Every time that you change the value you are really building a new instance of Integer.
Doing the same with mutable objects will work.
For example
class Test {
private StringBuilder metric;
public Test(StringBuilder m) {
this.metric = m;
this.metric.append(" Xter");
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
StringBuilder b = new StringBuilder("Hello ");
Test test = new Test(metric);
System.out.println(b.toString());
// Will print Hello Xter
}
}
As already metioned, the primitive wrapper classes are inmutable.
Since your metric is private in Test, and you want to use its value in the calling method main, you should use the java bean guidelines and use a getter for it:
public Long getMetric(){return this.metric;}
And on main:
metric=test.getMetric();
System.out.println(metric);
Related
This question already has answers here:
Calling Non-Static Method In Static Method In Java [duplicate]
(14 answers)
Closed 2 years ago.
//I'd like to now why I can;t printout the return value in below java code
public class client08 {
public static void main(String[] args) {
String w=test();
System.out.println(w);**// I'd like to print out the return value here but it now work**
}
public String test() {
String result="";
String[] words=new String[5];
words[0]="Amy";
words[2]="Tom";
words[4]="Jane";
for(int i=0; i<words.length;i++) {
if(words[i]!=null) {
result=words[i].toUpperCase();
}else {
result="null";
}
}
return result;
}
First of all class names should start with an upper case character. Learn and follow Java conventions.
Next:
Your code doesn't compile.
You can't invoke a method from your "client08" class unless you create an instance of the class or make the method static.
So the code should be:
//String w=test();
client08 client = new client08();
String w= client.test();
Or you need to make the method static:
public static String test() {
Then you would invoke the method using:
String w = client08.test();
System.out.println(w);
This question already has answers here:
Difference between Static and final?
(11 answers)
Closed 4 years ago.
As mentioned in the below link Link
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.
A single copy to be shared
by all instances of the class.
But i am able to change the value of static variable
class Test {
static int a =10;
public static void main(String args[])
{
a=20;
System.out.println("rest of the code...");
Test1 t= new Test1();
t.m();
}
}
public class Test1 {
void m ()
{
System.out.println(Test.a);
}
}
The definition means that the variable will be initialized only once in a context of the class definition. Id est, for the class Test in your example it will be initialized only once no matter the number of objects you instantiate for this class.
Take also into account that initialization is not the same as changing the value of the variable later.
To ilustrate your question in comments:
class Test {
public static long staticAtr = System.currentTimeMillis();
public long nonStaticAtr = System.currentTimeMillis();
public static void main(String[] args) {
Test t1 = new Test();
Thread.sleep(100);
Test t2 = new Test();
System.out.println(t1.staticAtr);
System.out.println(t1.nonStaticAtr);
System.out.println(t2.staticAtr);
System.out.println(t2.nonStaticAtr);
}
t1 and t2 show the same staticAtr that was initialized only once at the start of the execution, while the nonStaticAtr of t1 and t2 where initialized once per instantiation and have therefor different values.
What is meant by the quoted rule is that when you create instance A of class Test and this initialized member a with 10. If you now change the value of a in A to .e.g 12, the next created class, as well as all previous instances, will see a having a value of 12.
This question already has answers here:
What does "void" mean as the return type of a method? [duplicate]
(5 answers)
Closed 5 years ago.
I have done a simple code to reverse a string in Java without using the inbuilt functions. But I have observed that unlike C where we can get a changed string back in the same variable using pointers, which it is not possible in Java due to the absence of pointer concept. So please show me what alternative way can I get back the string in the main function in Java.
class RevFun{
public void revFun(StringBuilder str)
{
for(int i=str.length()-1;i>=0;i--)
{
System.out.println(str.charAt(i));//Here I am able to print it!
}
return;
}
}
class Rev
{
public static void main(String args[])
{
RevFun rev = new RevFun();
StringBuilder str = new StringBuilder("Hello");
System.out.println("Before reversing : "+str);
rev.revFun(str);
System.out.println("After reversing : "+str);//Here what should I do to get the reversed string from RevFun
}
}
give the second method returntype String
public static String handleString(String input){
// modify input
input += " test";
return input;
}
and either use, or assign the (new) value in your main:
public static void main(String[] args){
String a = "hello";
String b = handleString(a);
System.out.println(a);
System.out.println(b);
}
another way is to have your variable on class level:
static String test = "hi";
public static void main(String[] args){
System.out.println(test);
handleString();
System.out.println(test);
}
public static void handleString(){
test += " and bye";
}
both methods have access to the variable, so you won't even need to pass it as a parameter.
In Java Strings are immutable. This means that you can't change them. You can read more here
So if you want to "manipulate" an String you will have to return a new object
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
I'm a beginner and I'm starting to learn programming by doing some
exercises...
Why this simple java code gives me an error?
class HelloWorldEdited {
public int a = 5;
public int b = 2;
public static int sum() {
return a + b;
}
public static void main(String[] args) {
HelloWorldEdited obj = new HelloWorldEdited();
System.out.println(obj.sum());
}
}
I think it's because you are accessing "non static" properties (a, b) from a static method (sum), this operation is forbidden.
Try to change
public static int sum()
to
public int sum()
To understand the "static" modifier I suggest you to read:
official tutorial
The method sum() is static. In this method you can't access variables "non static".
This question already has an answer here:
An object reference is required for the non-static field, method, or property
(1 answer)
Closed 9 years ago.
Here is the my class..
public class Oop {
int count = 0;
public static void main(String args[])
{
this.count(15, 30);
System.out.print(this.count);
}
public void count(int start, int end)
{
for(;start<end; start++)
{
this.count = this.count + start;
}
}
}
I can't call count function inside of main function. Reason is static and non-static functions. I'm really new for Java. How can i use count inside of main? What i need to learn?
You need to instantiate Oop and then call the method with it, like this:
Oop oop = new Oop();
oop.count(1,1);
For further information check this out: Difference between Static methods and Instance methods
You should make the count function and the count variable static too.
That's the least of your worries - once you've called the method, you won't be able to access the result.
You must create an instance of your class, and use that instance to call your method and get the result:
public static void main(String args[]) {
Oop oop = new Oop();
oop.count(15, 30);
System.out.print(oop.count);
}