Changing the value being passed through the parameter - java

I was testing whether you can change the value of the static variable x by passing it through a parameter, but I found out that you can't do it like that.
public class Test {
static int x;
static void changeX(int x_) {
x_ = 50;
}
public static void main(String args[]) {
changeX(x);
System.out.println(x);//it prints out zero because the static variable did not get changed
}
}
If we do it like this, we can change it:
public class Test {
static int x;
static void changeX(int x_) {
x = 50;
}
public static void main(String args[]) {
changeX(x);
System.out.println(x);
}
}
Which means you have to directly reference to the static variable in order to change it. Okay. Now. My question is, is there a way to change a class variable by just passing it through the parameter, without referencing it in the implementation? Basically, is there a way to use the first way somehow? Thanks.

You can achieve what you are asking, but you need to be aware of the subtle limitations. You can modify an object reference passed into a method, but you cannot reassign the reference in the method and have the original object be changed.
Java is always pass by value. Period.
Object references, are passed by value, but it is through those references (which point to the same memory location), that you can modify objects inside of methods, through the parameter.
You cannot modify primitives (int, float, boolean, etc) in this manner, they are always passed by value. You also cannot modify immutable objects (such as String), as they cannot be changed using a public interface.
Consider this simple example, which tests creating an object with some modifiable fields, by-value, and by-reference (it's modifying by object reference, that itself is passed by value):
public class ParameterPassingTest {
static SomeObject someStaticObject;
public static void main(String[] args) {
// initialize a static object reference
someStaticObject = new SomeObject("I am a static Object", 10);
System.out.println("My static object before: " + someStaticObject);
// try modifying the reference by value
modifySomeObjectByValue(someStaticObject);
// try printing the value, it will be the same
System.out.println("My static object after mod-by-value: " + someStaticObject);
// now, try modifying by object reference
modifySomeObjectByReference(someStaticObject);
// print again. new values should be observed
System.out.println("My static object after mod-by-reference: " + someStaticObject);
}
// this method tries to modify the original object by assigning directly to the method parameter. It won't work.
public static void modifySomeObjectByValue(SomeObject someObject) {
SomeObject newObject = new SomeObject("I am another object, from a local method", 20);
someObject = newObject; // try to modify the original object by assigning to the parameter directly
}
// this method tries to modify the original object by using the object's public interface. It works.
public static void modifySomeObjectByReference(SomeObject someObject) {
// try to modify the original object by using the reference passed in
someObject.setaString("I have been modified by a method");
someObject.setAnInt(50);
}
}
// simple, generic class object with some fields.
class SomeObject {
String aString;
int anInt;
public SomeObject(String aString, int anInt) {
this.aString = aString;
this.anInt = anInt;
}
public String getaString() {
return aString;
}
public void setaString(String aString) {
this.aString = aString;
}
public int getAnInt() {
return anInt;
}
public void setAnInt(int anInt) {
this.anInt = anInt;
}
#Override
public String toString() {
return "aString = " + getaString() + " | anInt = " + getAnInt();
}
}
This produces output:
My static object before: aString = I am a static Object | anInt = 10
My static object after mod-by-value: aString = I am a static Object | anInt = 10
My static object after mod-by-reference: aString = I have been modified by a method | anInt = 50

Java passes primitives always as value. Objects on the other hand are always passed as reference. In your second example, you access the static attribute x and not the parameter x_.
Furthermore, static does not protect an attribute from being rewritten. It binds an attribute to the class (without static attributes are bound to objects). Maybe you meant final?
EDIT: corrected a typo.

Related

List of non-static method references in Java

I am trying to use a list of function references as a lookup table (avoiding the need for a long switch statement). The code worked for a list of static methods, but when I tried to use non-static (i.e. instance) methods in the list, Java gives several errors regarding the types not matching.
Here is a minimal example:
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
public class MethodReferences {
// My original list of static references
private final static List<Function<Integer, Integer>> lookupTable = Arrays.asList(MethodReferences::f1, MethodReferences::f2);
// This doesn't work
// private final List<Function<Integer, Integer>> lookupTable = Arrays.asList(MethodReferences::f3, MethodReferences::f4);
private static int f1(int x) { return x * 2; }
private static int f2(int x) { return x * 3; }
private int f3(int x) { return x * 2; }
private int f4(int x) { return x * 3; }
public void run() {
System.out.println(lookupTable.get(1).apply(3));
}
public static void main(String[] args) {
MethodReferences testClass = new MethodReferences();
testClass.run();
}
}
The errors I received were all for the line containing the non-static definition:
Type mismatch: cannot convert from List<Object> to List<Function<Integer,Integer>>
and:
The target type of this expression must be a functional interface
I tried using this:: instead of MethodReferences:: before the function names. The code then compiled, but when it runs, nothing happens, probably because this has to be used within non-static functions.
I then moved the initialisation of the array (still using this:: to within the class constructor, but it continued to produce no output when run.
I've checked through the documentation and tutorials on method references in Java, but I cannot find an examples of creating references to instance methods within the class it is defined in (and I cannot find any examples of lists of function references either).
I'm aware that in the main method, you can do testClass::f1, but for my specific situation (not the example code) I do not even have a main class (the class is instantiated by another library), so this approach isn't possible. The methods have to be non-static because I need to be able to modify instance variables within them.
Edit:
It turns out that using this:: does work for the example code, although I am still unsure as to why it is valid (surely you can only use this within a non-static function?)
You need to use BiFunction instead of Function. The first argument is the implicit this argument.
public class MethodReferences {
private final static List<BiFunction<MethodReferences, Integer, Integer>> lookupTable
= Arrays.asList(MethodReferences::f3, MethodReferences::f4);
private int f3(int x) { return x * 2; }
private int f4(int x) { return x * 3; }
public void run() {
System.out.println(lookupTable.get(1).apply(this, 3));
}
public static void main(String[] args) {
MethodReferences testClass = new MethodReferences();
testClass.run();
}
}
output:
9
For instance method references which use the ClassName::functionName format, instead of instanceName::functionName, you also need to pass the specific instance of the class to the function when calling .apply().
This means that your method references are actually need to be a BiFunction<MethodReferences, Integer, Integer>, even though there is only one explicit parameter to the function.
When calling the method, you also need to pass this into apply:
import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;
public class MethodReferences {
// To refer to non-static methods by class name,
// you must pass in the instance explicitly:
private final List<BiFunction<MethodReferences, Integer, Integer>> lookupTable = Arrays.asList(MethodReferences::f3, MethodReferences::f4);
private int f3(int x) {
return x * 2;
}
private int f4(int x) {
return x * 3;
}
public void run() {
// We need to pass this in, because it isn't implicit
// for ClassName::functionName references:
System.out.println(lookupTable.get(1).apply(3));
}
public static void main(String[] args) {
MethodReferences testClass = new MethodReferences();
testClass.run();
}
}

Difference between Calling Static function from Object and Class itself

I was learning singleton design pattern and I did understand the concept. However, I have a doubt in the following code : -
class Token
{
private static int i = 5;
private static Token obj = new Token();
//Private Constructor
private Token()
{
}
//Returning the singleton object
public static Token getObject()
{
return obj;
}
public static int getValue()
{
return i;
}
}
public class TestMain
{
public static void main(String args[])
{
Token obj = Token.getObject();
System.out.println("Without object " + Token.getValue());
System.out.println("With object " + obj.getValue());
}
}
The instance variable i gets printed in both the cases -
Without object 5
With object 5
What is the difference between the two ways of getting instance variable and which one is recommended?
i is a static variable that belongs to class Token so it'll have the same value for all objects that are of type Token.
For all practical purposes, obj.getValue() is the same as Token.getValue() and you could use either, but for better readability, use Token.getValue() as it reinforces the idea that the static variable i and static method getValue() belong to the class as a whole and not to certain objects of that class.
In fact in obj you have reference to your singleton. So calling Token.getValue() reference to same obj as obj.getValue()
There is little difference, for instance access you need the actual instance, which you don't always have.
As for preference it depends on who you ask. For me static fields and methods should be accessed using the class not instance - this clearly shows that it is static.

How can I refer the objcet that calls a method in the method in Java? [duplicate]

This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word

Need to print function's actual parameter name used while calling

I want to print function actual parameter name in function.
For reference please refer below code.Here i am trying reflection.
class Refrction
{
public static int a=12;
public static int b=12;
public static int c=13;
public void click(int x)
{
Class cls=Refrction.class;
Field[] fields = cls.getFields();
//here i want to print "a" if function actual parameter is "a" while calling the click function
//here i want to print "b" if function actual parameter is "b" while calling the click function
//here i want to print "c" if function actual parameter is "c" while calling the click function
}
}
public class Reflections extends Refrction
{
public static void main(String[] args)
{
Refrction ab=new Refrction();
ab.click(a);
ab.click(b);
ab.click(c);
}
}
Unless the values of a, b and c never changes (and you can deduce which variable was used as argument by looking at the value) this is not possible. You need to pass more information to the method.
One way would be to do
public void click(int x, String identifier) {
...
}
and call it with
ab.click(a, "a");
Or, you could wrap the values in a (possibly mutable) object, as follows:
class IntWrapper {
int value;
public IntWrapper(int value) {
this.value = value;
}
}
and then do
public static IntWrapper a = new IntWrapper(11);
and
public void click(IntWrapper wrapper) {
if (wrapper == a) {
...
}
...
}

Implementing 2 linked lists in java without pointers

I am facing problems while trying to implement 2 linked lists in my Java code.
If I declare my "head" variables in main and pass them to any function, they could not be modified by that function as the referencing variable would be local to that function.
But if I make them class variables, the called function could not know which of the 2 "head" variables I am referring to.
This problem could be easily solved in C language by passing double pointers in functions so that the local variable can modify the passed variable but how to solve this problem in Java? Thanks.
Pointers aren’t used in Java
Defines the attribute at the class level and don't use it in the signature of your methods, or return the value of your function to the original variable.
public class MyClass{
private string value;
public myFunction(){
value = toto; // this will change the value of the attribute directly
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
myClass.myFunction(); // The new value is saved at the class level
}
}
or
public class MyClass{
public String myFunction(String value){
value = "toto";
return value; // The value modified is return back to the caller
}
public static void main(String[] args) {
MyClass myClass = new MyClass();
String myValue = myClass.myFunction(myvalue); // The new value is saved
}
}

Categories