This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 1 year ago.
could someone explain this piece of code. The output is where I am confused. It seems only one thing (i.e. p) was modified by the modifyObject function, but the other (i.e. s) is left unchanged. But I am confused. Could someone explains what's going on.
class Person{
int a = 8;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
#Override
public String toString() {
return "Person [a=" + a + "]";
}
}
public class TestMutable {
public static void main(String[] args)
{
Person p = new Person();
p.setA(34);
String s = "bar";
modifyObject(s, p); //Call to modify objects
System.out.println(s);
System.out.println(p);
}
private static void modifyObject(String str, Person p)
{
str = "foo";
p.setA(45);
}
}
why is it that the following is output? i.e. str is still bar , but person.A is now 45?
bar
Person [a=45]
You can see this thread to understand why String value doesn't change and how to make it to change it: Passing a String by Reference in Java?
Related
This question already has answers here:
How to write a Unit Test?
(5 answers)
Closed 4 years ago.
I have a problem with Mockito. I have two different class. My purpose is test “setChanges” function. this is my first class :
class M {
private String a;
private String b;
private boolean c = false;
public String getA() {
return a;
}
public void setA( String _a ) {
a = _a;
}
public String getC() {
return c;
}
public void setC( final boolean imp ) {
c = imp;
}
}
this is the main class which has “setChanges” function:
class MyMainClass {
private String getMyA() {
return "Data";
}
private static void setChanges(final M m) {
if (getMyA().equals(m.getA())){
m.setC(true);
}
}
}
How can I test "setChanges"? Which means that if getA() returns "Data", How can I check getC() that should be "true"?
Thanks, It works with this code :
#Test
public void testsetChanges(){
MyMainClass mmc = new MyMainClass ();
M m = new M();
m.setA("Data");
Method method = MyMainClass.class.getDeclaredMethod(
"setChanges",
M.class
);
method.setAccessible(true);
method.invoke(method, m );
assertTrue(m.getC());
}
Pass in an instance of M which satisfies (or doesn't satisfy) getMyA and validate that M#getC returns true (or false, depending on what you're testing). No mocks required.
This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 6 years ago.
In Java, is it possible for a calling method to get the value of a local variable inside the called method without returning it?
See below in C, where I can use pointers to change the value of the local variable of the fun function.
#include <stdio.h>
int main(void) {
int* a;
a = malloc(sizeof(int));
*a = 10;
printf("before calling, value == %d\n",*a);
fun(a);
printf("after calling, value == %d",*a);
return 0;
}
int fun(int* myInt)
{
*myInt = 100;
}
Can I do something similar in Java. I did try, but wasn't able to.
public class InMemory {
public static void main(String[] args) {
int a = 10;
System.out.println("before calling ..."+a);
fun(a);
System.out.println("after calling ..."+a);
}
static void fun(int newa)
{
newa = 100;
}
}
int and Integer are not mutable. You could pass in a reference to a collection and modify the contents of it, or use a mutable implementation of an integer such as AtomicInteger if you're that keen on it.
public class InMemory {
public static void main(String[] args) {
AtomicInteger a = new AtomicInteger(10);
System.out.println("before calling ..." + a);
fun(a);
System.out.println("after calling ..." + a);
}
static void fun(AtomicInteger newa) {
newa.set(100);
}
}
You can use method as setter for your global variable to get the local variable of that function.
public class InMemory {
static int g=10; // global in class
public static void main(String[] args) {
System.out.println("before calling ..."+g);
fun();
System.out.println("after calling ..."+g);
}
static void fun()
{
int l = 100; // local in fun
g = l; // assign value to global
}
}
This question already has answers here:
cannot make a static reference to the non-static field
(7 answers)
Closed 7 years ago.
When I am calling a method directly from main method, it is not allowed. However, when I am calling the same method from the constructor of a class, it is allowed.
The allowed version;
public class App {
Integer firstVariable;
Integer secondVariable;
public static void main(String[] args) {
App obj = new App(3, 2);
}
public App(Integer firstVariable, Integer secondVariable) {
this.firstVariable = firstVariable;
this.secondVariable = secondVariable;
this.calculate(firstVariable, secondVariable);
}
public int calculate(int a, int b) {
int result = a + b;
return result;
}
}
The disallowed version;
public class App {
Integer firstVariable;
Integer secondVariable;
public static void main(String[] args) {
App obj = new App(3, 2);
obj.calculate(firstVariable, secondVariable);
}
public App(Integer firstVariable, Integer secondVariable) {
this.firstVariable = firstVariable;
this.secondVariable = secondVariable;
}
public int calculate(int a, int b) {
int result = a + b;
return result;
}
}
I know it is "Cannot make a static reference to the non-static field firstVariable" error. My question is; In both code blocks, the same thing is done but what is the difference between them?
The issue isn't your method. The issue is that your variables (the arguments that you're trying to pass) are being referenced from a static context.
I have asked this question here. I will try to make this one more specific.
class Example {
public static void main(String[] args) {
A a = null;
load(a);
System.out.println(a.toString());
// outcome is null pointer exception
}
private static void load(A a) {
a = new A();
}
}
class A {
public void String toString() {
return "Hello, world!"
}
}
So, does it possible to update a reference in a method? For some reason I need to do this. The reasons can be seen at above linked page.
Yes, it's possible if you define the parameter as A[] i.e. load(A[] a) and then in the method you update the element at position 0 in that array i.e. a[0] = new A(). Otherwise, it's not possible as Java is pass by value. I often use this workaround.
EXAMPLE 1:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = new A("outer");
System.out.println(a[0].toString());
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
EXAMPLE 2:
class Example {
public static void main(String[] args) {
A[] a = new A[1];
a[0] = null; // not needed, it is null anyway
load(a);
System.out.println(a[0].toString());
}
private static void load(A[] a) {
a[0] = new A("inner");
}
}
class A {
private String name;
public A(String nm){
name = nm;
}
public String toString() {
return "My name is: " + name;
}
}
NOTE: In fact, instead of an A[] you can use any wrapper object (an object which contains in itself a reference to an A object). The A[] a is just one such example. In this case a[0] is that reference to an A object. I just think that using an A[] is the easiest (most straightforward) way of achieving this.
As already pointed by other java is pass-by-value.You need something like pointer in C with the object location address so that you can modify that particular address value.As an alternate to pointer you can use array.Example
class Example {
public static void main(String[] args) {
A[] aArray=new A[1];
load(aArray);
System.out.println(aArray[0].toString());
// outcome is Hello, world!
}
private static void load(A[] aArray2) {
aArray2[0] = new A();
}
}
class A {
public String toString() {
return "Hello, world!";
}
}
You could just have:
public static void main(String[] args) {
A a = load();
}
private static A load() {
return new A();
}
No you can't.
In java everything is passed as value not as reference.
I came out with this. Perfectly satisfied my need and looks nice.
class A {
private A reference;
private String name;
public A() {
reference = this;
}
public void setReference(A ref) {
reference = ref;
}
public void setName(String name) {
reference.name = name;
}
public String getName() {
return reference.name;
}
}
have two strings, String1 = hello String2 = world, I want to call a class Hello and send to the two strings. The class should return a boolean value and a string. If the boolean is true it should do the followig:
System.out.println("Hello to you too!");
Can someone help me out with this code?
First, a terminology problem: you cannot "call a class." You can call a method on a class, such as:
someObject.someMethod(string1, string2);
More to the point, you can't return two different values from a method. You could certainly store two different values in the object and return them from different methods, though. Perhaps a class like:
public class Foo {
protected boolean booleanThing;
protected String stringThing;
public void yourMethod(String string1, String string2) {
// Do processing
this.booleanThing = true;
this.stringThing = "Bar";
}
public String getString() {
return this.stringThing;
}
public boolean getBoolean() {
return this.booleanThing;
}
}
Which would be used as:
someObject.yourMethod(string1, string2);
boolean b = someObject.getBoolean();
String s = someObject.getString();
Having said all that, though, this may not at all be the best way to solve your actual problem. Perhaps you can explain better what you're trying to accomplish. Perhaps throwing an Exception is better than trying to return a boolean, or perhaps there's another solution entirely.
The more detail we have, the better.
You should review your definition of classes but for now I'll assume this is what you meant, comment if this isn't what your looking for:
public class Hello {
private final String first;
private final String second;
public static void main(String[] args) {
String s1 = "Hello";
String s2 = "World";
Hello h = new Hello(s1,s2);
if(h.isHelloWorld()) {
System.out.println("Hello to you too!");
}
}
private Hello(String first, String second) {
this.first = first;
this.second = second;
}
private boolean isHelloWorld() {
return (first.equals("Hello") && second.equals("World"));
//If that scares you then do this instead:
/**
if(first.equals("Hello") && second.equals("World") {
return true;
} else { return false; }
**/
}
}
When you run this program it will always print "Hello to you too!", if you change s1 or s2 it won't print anything.
public class Hello{
boolean val = false;
String str = "";
public Hello(String a, String b){
if(a == "hello" && b == "world"){
this.val = true;
this.str = "hello to you too";
}
}
public static void main(String args[]){
String a = "hello";
String b = "world";
Hello hello = new Hello(a,b);
if(hello.val == true)
System.out.println(hello.str);
}
}