I'd simply like to know if the following is possible to do somehow.
public void foo(int a) {
String a = Integer.toString(a);
}
Now obviously this code doesn't actually work; the string a shadows the parameter a. What I'd like to know is, is there a way to explicitly tell the compiler "Hey, this is actually that other a up there!" I'm looking for something similar to the this keyword, except for method parameters.
Is there anything like this or am I forced to use a different variable name?
No, this feature does not exist in java. You should just make up another variable name.
You can do-
String ab = Integer.toString(a);
Even if you could use the same variable name as the parameter variable, it would create confusion. You cannot do that in Java. Just use some other variable name.
Also, modifying method parameters are not a good idea. Rather, have them declared final like-
public void foo(final int a) {
String ab = Integer.toString(a);
}
You can't do that but you could overload the method
public void foo(int a) {
foo(Integer.toString(a));
}
public void foo(String a) {
//
}
For what you want to do, you should probably just create another variable. For example:
public void foo(int a1) {
String a = Integer.toString(a1);
}
You cannot have twice the same name of the variable in the same range. But you can override names of the variables, fields for example:
class A
{
int a;
void f(int a)
{
this.a = a;
}
}
Now field a is overridden, and using this you can refer to the overriden field.
Related
Preface
I'd like to saying two things:
I don't know how to phrase this question in a few words. So I can't find what I'm looking for when searching (on stackoverflow). Essentially, I apologize if this is a duplicate.
I've only been programming Java consistently for a month or so. So I apologize if I asked an obvious question.
Question
I would like to have a method with a parameter that holds (path to) an integer.
How is such a method implemented in Java code?
Restrictions
The parameter should be generic.
So, when there are multiple of that integer variables, the correct one can be used as argument to the method, when it is called (at runtime).
My Idea as Pseudo-Code
Here's the idea of what I want (in pseudo-code). The idea basically consist of 3 parts:
the method with parameter
the variables holding integer values
the calls of the method with concrete values
(A) Method
.
Following is the definition of my method named hey with generic parameter named pathToAnyInteger of type genericPathToInt:
class main {
method hey(genericPathToInt pathToAnyInteger) {
System.out.println(pathToAnyInteger);
}
}
(B) Multiple Integer Variables
Following are the multiple integer variables (e.g. A and B; each holding an integer):
class A {
myInt = 2;
}
class B {
myInt = 8;
}
(C) Method-calls at runtime
Following is my main-method that gets executed when the program runs. So at runtime the (1) previously defined method hey is called using (2) each of the variables that are holding the different integer values:
class declare {
main() {
hey("hey " + A.myInt);
hey("hey " + B.myInt);
}
}
Expected output
//output
hey 2
hey 8
Personal Remark
Again, sorry if this is a duplicate, and sorry if this is a stupid question. If you need further clarification, I'd be willing to help. Any help is appreciated. And hey, if you're going to be unkind (mostly insults, but implied tone too) in your answer, don't answer, even if you have the solution. Your help isn't wanted. Thanks! :)
Java (since Java 8) contains elements of functional programing which allows for something similiar to what you are looking for. Your hey method could look like this:
void hey(Supplier<Integer> integerSupplier) {
System.out.printl("Hey" + integerSupplier.get());
}
This method declares a parameter that can be "a method call that will return an Integer".
You can call this method and pass it a so called lambda expression, like this:
hey(() -> myObject.getInt());
Or, in some cases, you can use a so called method referrence like :
Hey(myObject::getInt)
In this case both would mean "call the hey method and when it needs an integer, call getInt to retrieve it". The lambda expression would also allow you to reference a field directly, but having fields exposed is considered a bad practise.
If i understood your question correctly, you need to use inheritance to achive what you are looking for.
let's start with creating a hierarchy:
class SuperInteger {
int val;
//additional attributes that you would need.
public SuperInteger(int val) {
this.val = val;
}
public void printValue() {
System.out.println("The Value is :"+this.value);
}
}
class SubIntA extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntA(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("A Value is :"+this.value);
}
}
class SubIntB extends SuperInteger {
//this inherits "val" and you can add additional unique attributes/behavior to it
public SubIntB(int val) {
super(val);
}
#override
public void printValue() {
System.out.println("B Value is :"+this.value);
}
}
Now you method Signature can be accepting and parameter of type SuperInteger and while calling the method, you can be passing SubIntA/SuperInteger/SubIntB because Java Implicitly Upcasts for you.
so:
public void testMethod(SuperInteger abc) {
a.val = 3;
a.printValue();
}
can be called from main using:
public static void main(String args[]){
testMethod(new SubIntA(0));
testMethod(new SubIntB(1));
testMethod(new SuperInteger(2));
}
getting an Output like:
A Value is :3
B Value is :3
The Value is :3
Integers in Java are primitive types, which are passed by value. So you don't really pass the "path" to the integer, you pass the actual value. Objects, on the other hand, are passed by reference.
Your pseudo-code would work in Java with a few modifications. The code assumes all classes are in the same package, otherwise you would need to make everything public (or another access modifier depending on the use case).
// First letter of a class name should be uppercase
class MainClass {
// the method takes one parameter of type integer, who we will call inputInteger
// (method-scoped only)
static void hey(int inputInteger) {
System.out.println("hey " + inputInteger);
}
}
class A {
// instance variable
int myInt = 2;
}
class B {
// instance variable
int myInt = 8;
}
class Declare {
public static void main() {
// Instantiate instances of A and B classes
A aObject = new A();
B bObject = new B();
// call the static method
MainClass.hey(aObject.myInt);
MainClass.hey(bObject.myInt);
}
}
//output
hey 2
hey 8
This code first defines the class MainClass, which contains your method hey. I made the method static in order to be able to just call it as MainClass.hey(). If it was not static, you would need to instantiate a MainClass object in the Declare class and then call the method on that object. For example:
...
MainClass mainClassObject = new MainClass();
mainClassObject.hey(aObject.myInt);
...
public class JavaApplication6 {
public static void a(int b)
{
b++;
}
I am calling the function a and passing the variable b with the intention of incrementing it like a C++ reference (&b). Will this work? If not, why?
public static void main(String[] args) {
int b=0;
a(b);
System.out.println(b);
}
}
While you can't really accomplish that with int (the primitive type for integer), you can accomplish something very similar with AtomicInteger. Simply invoke the getAndIncrement method on an instance of the class. Something like this:
public static void a(AtomicInteger b) {
b.getAndIncrement();
}
(Note that you also can't do this with java.lang.Integer, because java.lang.Integer is an immutable class.)
First of all: Java does not allow for pass-by-reference. Further, out-parameters (when a function's calculations/results are placed in one or more of the variables passed to it) are not used; instead, something is returned from a method like so:
b = a(b);
Otherwise, in Java, you pass objects as pointers (which are incorrectly called references). Unfortunately (in your case) most types corresponding to int (Integer, BigInteger, etc.) are immutable, so you cannot change the properties in the object without creating a new one. You can, however, make your own implementation:
public static class MutableInteger {
public int value;
public MutableInteger(int value) {
this.value = value;
}
}
public static void main(String[] args) {
MutableInteger b = new MutableInteger(2);
increment(b);
System.out.println(b.value);
}
public static void increment(MutableInteger mutableInteger) {
mutableInteger.value++;
}
The following will be printed to the console when this code is run:
3
At the end of the day, using the above requires a strong argument on the programmer's part.
You can't do that with primitive types like int, because Java passes primitives by value. Simply wrap b in a mutable container object :
class Holder {
int b;
}
Now you can modify the value by doing :
public static void a(Holder h) {
h.b++;
}
You should, however, consider to work with Immutable Objects, which are generally considered a good thing in Java to avoid side effects and concurrency issues.
You cannot pass a value by reference in Java. If a primitive is passed to a method, the JVM passes it by value. If it is an object that is sent to a method, the JVM creates a copy of the its reference. Since this is a "copy" the modification won't change the initial object. But still, there are workaround such as using the AtomicInteger suggested in the previous posts.
I have a class with several methods. Now I would like to define a helper method that should be only visible to method A, like good old "sub-functions" .
public class MyClass {
public methodA() {
int visibleVariable=10;
int result;
//here somehow declare the helperMethod which can access the visibleVariable and just
//adds the passed in parameter
result = helperMethod(1);
result = helperMethod(2);
}
}
The helperMethod is only used by MethodA and should access MethodA's declared variables - avoiding passing in explicitly many parameters which are already declared within methodA.
Is that possible?
EDIT:
The helper mehod is just used to avoid repeating some 20 lines of code which differ in only 1 place. And this 1 place could easily be parameterized while all the other variables in methodA remain unchanged in these 2 cases
Well you could declare a local class and put the method in there:
public class Test {
public static void main(String[] args) {
final int x = 10;
class Local {
int addToX(int value) {
return x + value;
}
}
Local local = new Local();
int result1 = local.addToX(1);
int result2 = local.addToX(2);
System.out.println(result1);
System.out.println(result2);
}
}
But that would be a very unusual code. Usually this suggests that you need to take a step back and look at your design again. Do you actually have a different type that you should be creating?
(If another type (or interface) already provided the right signature, you could use an anonymous inner class instead. That wouldn't be much better...)
Given the variables you declare at the top of your method can be marked as final (meaning they don't change after being initialized) You can define your helper method inside a helper class like below. All the variables at the top could be passed via the constructor.
public class HelperClass() {
private final int value1;
private final int value2;
public HelperClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int helperMethod(int valuex) {
int result = -1;
// do calculation
return result;
}
}
you can create an instance of HelperClass and use it inside the method
It is not possible. It is also not good design. Violating the rules of variable scope is a sure-fire way to make your code buggy, unreadable and unreliable. If you really have so many related variables, consider putting them into their own class and giving a method to that class.
If what you mean is more akin to a lambda expression, then no, this is not possible in Java at this time (but hopefully in Java 8).
No, it is not possible.
I would advise you create a private method in your class that does the work. As you are author of the code, you are in control of which other methods access the private method. Moreover, private methods will not be accessible from the outside.
In my experience, methods should not declare a load of variables. If they do, there is a good chance that your design is flawed. Think about constants and if you couldn't declare some of those as private final variables in your class. Alternatively, thinking OO, you could be missing an object to carry those variables and offer you some functionality related to the processing of those variables.
methodA() is not a method, it's missing a return type.
You can't access variables declared in a method from another method directly.
You either has to pass them as arguments or declare methodA in its own class together with the helpermethods.
This is probably the best way to do it:
public class MyClass {
public void methodA() {
int visibleVariable=10;
int result;
result = helperMethod(1, visibleVariable);
result = helperMethod(2, visibleVariable);
}
public int helperMethod(int index, int visibleVariable) {
// do something with visibleVariable
return 0;
}
}
Lets say this is the C++ code:
void change(int& x){
x++;
}
or
void change2(int* a){
*a++;
}
Both will change the global x, right?
So how can I do something like that in java?
Specifically, I want to point to a Vector object
But since Java has no pointers, I'm not sure what to do.
From searching the internet I saw people saying that Java does that in some other way, but I haven't found any real example.
Thanks for
help!
In Java, instead of pointers you have references to objects. You cannot pass a primitive type by reference, but you can wrap a primitive type inside an object and then pass a reference to that object.
Java provides the type Integer which wraps int, however this type is immutable so you cannot change its value after construction. You could however use MutableInt from Apache Commons:
void change(MutableInt x) {
x.increment();
}
The change to x will be visible to the caller.
Specifically, I want to point to a Vector object
When you write Vector v = ...; you are assigning a reference to a vector to the variable v. A reference in Java is very similar to a pointer. References are in fact implemented internally using pointers.
Java uses pass by value. When you pass a vector to a method, you are actually copying a reference to that vector. It does not clone the vector itself. So passing a reference in Java is very similar to passing a pointer in C++.
With Java you cannot pass primitive types like int by reference, they are passed only by value.
The only things you can do is to find artifices to do that, because instead Objects are passed by reference. Here two examples.
Use an array of single value, like this
int[] value = new int[1];
value[0] = 2;
// call a method
obj.setValue(value);
// and in setValue
public void setValue(int[] value) {
value[0] = 5;
}
Or second approach use an holder class:
public class Holder<T> {
public T value;
public Holder(T value) {
this.value = value;
}
}
// then use it in this way
Holder<Integer> h = new Holder<Integer>(2);
obj.setValue(h);
// and in setValue
public void setValue(Holder<Integer> h) {
h.value = 5;
}
In this case I use an holder class implements with generics but you can have a simple holder too, only for integer. For example:
public class IntHolder {
public int value;
public IntHolder(int value) {
this.value = value;
}
}
Java always passes by value and there are no global variables as in the C++ sense. So if you want to do the same as in C++ you need to return the new value.
Thusly:
public int change(int x) {
return ++x;
// or
// return x + 1;
}
To test it:
int x = 2;
change(x);
System.out.println(x); // returns 2
x = change(x);
System.out.println(x); // returns 3
So it doesn't make any sense to let the method be called change, it is more sensible along the lines of calculateThisInt.
Java does pass objects by value. But as Mark Byers mentions the Integer class is immutable and you could use MutableInt from Apache Commons library. To describe how this works you could implement it yourself for your example:
public class MyInt() {
public int i;
public void setInt(int i) {
this.i = i;
}
public int getInt() {
return this.i;
}
public int increment() {
this.i++;
}
}
You need to change your change function to have the above MyInt object as argument:
public void change(MyInt i) {
i.increment();
}
Usage:
MyInt x = new MyInt();
x.setInt(2);
change(x);
System.out.println(x.getInt); // returns 3
In your case you want to change a Vector object...
public void changeVector(Vector v) {
// anything you do with 'v' will change it even
// for the scope that called this method
}
// Usage:
Vector v = new Vector();
changeVector(v);
// v should be changed after calling change vector method
Hope this all makes sense.
Both will change the global x, right?
So how can I do something like that in java? Specifically, I want to
point to a Vector object
The question is somewhat vague, but I got the impression that you ultimately want a global Vector that you can keep stuff in?
Many ways to do that, but one of the simplest is to have a static field in a class, with public static methods for accessing it. (Or simply a public static field which is accessed directly, but that really wouldn't be idiomatic in Java.)
public class Foo {
private static List<Integer> globalVector = new Vector<Integer>();
public static void add(int number){
globalVector.add(number);
}
// ... plus whatever other accessors to the global list that you need
}
Anywhere else in code:
Foo.add(23); // modifies the global vector
(Btw, Vector is kinda obsolete, and typically we'd use ArrayList in its place now. As the Javadoc says, it's been retrofitted to implement the List interface, which I also used in the example.)
While you can't replace an object that's been passed to a function, you can change its state by altering fields directly or calling methods. If you need something like a pointer to a primitive, wrap it in an object. To follow your code, you could do this:
public class IntPointer {
public int value;
public IntPointer(int value) {
this.value = value;
}
}
Then elsewhere you could say:
public static void change(IntPointer ipoint) {
ipoint.value++;
}
public static void main(String[] args) {
IntPointer a = new IntPointer(10);
change(a);
}
This might seem a bit awkward, but it hasn't come up for me as often as you'd think. I'd be more likely to do something like this:
public class ABPair {
private int a = 0;
private int b = 0;
public static void changeA() {
a++;
}
public static void changeB() {
b++;
}
}
So that elsewhere I can say:
public static void main(String[] args) {
ABPair ab = new ABPair();
if (ACondition) {
ab.changeA();
}
}
In other words, my data tends to already be wrapped in some sort of object, and I tend to use the data object's methods to mediate any changes.
Java supports what it calls "references". References act alot like pointers in C/C++-like languages. They don't act the same way "references" work in those languages.
The major differences between a pointer in C and a reference in Java are:
You can't do pointer arithmetic in Java (i.e. you can't "add" or "subtract" from a Java reference, you can only dereference it or compare it with another one).
You can't cast it to an incompatible type: Java is strongly type-safe, you can't "re-interpret" the bytes in memory as some other object.
For some uses of pointers this has no real effect (for example linked lists work pretty much the same in both languages), for others the difference is quite major (arrays in C are just fancy pointer arithmetic, in Java they work quite differently).
So in a way Java references could be called "restricted pointers".
New to Java here, please help. How arguments are passed in java? Why am I unable to change argument value in the calling method from within called method?
Code
public class PassTest {
public static void changeInt(int value)
{
value=55;
}
int val;
val=11;
changeInt(val);
System.out.println("Int value is:" + val);// calling modifier changeInt
}
Output
Int value is: 11
why it is not 55..?
Java passes by value, not by reference. In your method value contains a copy of the value from val. Modifying the copy does not change the original variable.
You could pass an int wrapped inside an object if you want your changes to be visible to the caller. You can for example use the class org.apache.commons.lang.mutable.MutableInt.
Java : Best way to pass int by reference
Java passes ByValue, meaning the value of the object you put as a parameter is passed, but not the object itself, therefore
val=11;
changeInt(val);
does the exact same thing as
int val=11;
int val2=val
changeInt(val2);
int is a primitive, primitives don't "wrap" a value, you could try to use an Integer class, or make your own class that stores an integer, and then change that classes integer value. Instances of an object are sometimes passed ByReference if setup right. here is an example
MyStringClass.java
public class MyStringClass{
private String string = null;
public MyStringClass(String s){
string = s;
}
public String getValue(){
return string;
}
public void setValue(String s){
string = s;
}
}
and then the workings
public static void addTo(String s){
s += " world";
}
public static void addTo(MyStringClass s){
s.setValue(s.getValue() + " world");
}
public static void main(String[] args){
String s = "hello";
MyStringClass s1 = new MyStringClass("hello");
addTo(s);
addTo(s1);
System.out.println(s);//hello
System.out.println(s1);//hello world
}
I would wonder why you need to change the value instead of just returning it? isn't it easier?
Java passes by Value, it makes a copy which is completely dis-associated with the original variable reference, which means it doesn't have access to change the original int. This is true for primitives as well as object references as well.
You can use AtomicInteger or something like it, to achieve what you are desiring to do.
Primitive variables are passed by value not reference as you are suggesting.
As others said, Java passes byValue by default which means that you are just getting a copy in the function. You can pass byReference, which will pass a pointer to the object and allow you to directly edit but this is not seen as best practice. I would suggest doing it like this:
public class PassTest {
public int changeInt(int value)
{
value = 55;
return value;
}
int val;
val=11;
val = changeInt(val);
System.out.println("Int value is:" + val);// calling modifier changeInt
Here is a Example to pass argument:
class Test {
int a,b;
public Test(int j, int k) {
a=j;
b=k;
}
void change(Test ko){
ko.a=ko.b+ko.a;
ko.a=ko.b-12;
}
}
class sdf {
public static void main(String[] args){
Test op=new Test(12,32);
System.out.println(op.a+" "+op.b);
op.change(op);
System.out.println(op.a+" "+op.b);
}
}
Take a look at this piece of code::
you can see , in this case the action inside change() have affected the object passed to the method
When an object reference is passed to the method ,the reference itself is passed to the method call-by-value . therefore , the parameter receives a copy of the reference used in this argument .As a result A change to the parameter (such as making it refers to the different object ) will not affect the reference used as the argument . however , since the parameter and the argument both refer to the same object , a change through the parameter will affect the object reffered by the argument.