How to call a variable in another method? - java

How to call a variable in another method in the same class?
public void example(){
String x='name';
}
public void take(){
/*how to call x variable*/
}

First declare your method to accept a parameter:
public void take(String s){
//
}
Then pass it:
public void example(){
String x = "name";
take(x);
}
Using an instance variable is not a good choice, because it would require calling some code to set up the value before take() is called, and take() have no control over that, which could lead to bugs. Also it wouldn't be threadsafe.

You make it an instance variable of the class:
public class MyClass
{
String x;
public void example(){ x = "name"; } // note the double quotes
public void take(){ System.out.println( x ); }
}

Since they are in different scopes you can't.
One way to get around this is to make x a member variable like so:
String x;
public void example(){
this.x = "name";
}
public void take(){
// Do stuff to this.x
}

public class Test
{
static String x;
public static void method1
{
x="name";
}
public static void method2
{
System.out.println(+x);
}
}

Related

How do I call a method that has a variable passed through it?

I'm trying to call a method from within another method. I'm understanding this simply enough, until one of those methods needs a variable carried through, and then nothing I try works.
I know that I could do this in one method, but my coursework needs me to lay it out in such a way. Why doesn't this work?
public class test2 {
public static void testMethod() {
int randomNumber = 1;
}
public static void anotherTestMethod(int randomNumber) {
System.out.println(randomNumber);
}
public static void main(String[] args) {
anotherTestMethod();
}
}
You are calling a method that has an int parameter in its signature. You should pass that parameter when calling the method. I think you are trying to use a global variable, in that case, you should declare it outside any method, as a part of the class.
public class test2 {
public static int testMethod() {
int randomNumber = 1;
return randomNumber;
}
public static void anotherTestMethod() {
System.out.println(testMethod());
}
public static void main(String[] args) {
anotherTestMethod();
}
}

How to call a non-void method from a void method?

Is it possible to call an int method which receives an object and returns an int value from a void method by sending a temporary object to it?
When I tried this, I got nothing; the output window appears for a millisecond and vanishes. I used this code:
class test {
int x (test ob) { return 10;}
public static void main (String args[]) { new test().x(new test()) }
}
Yes. If it just expects any object, you can pass new Object() and recieve the int value as a result.
In a word yes. The return type of the calling method has no effect on the return type of the method being called. E.g.:
public class SomeClass() {
public int increment(int i) {
return i + 1;
}
public void printFiveTheHardWay() {
System.out.println(increment(4));
}
}
Yes, you can call any method from Void method irrespective of return type of method , e.g:
Your example from comment should be like below:
class test {
int x(test ob) {
return 10;
}
public static void main(String args[]) {
System.out.println(new test().x(new test()));
}
}
More generic code for your better understanding here:
public class Foo {
private Integer value;
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
public class TestVoidMethodCall {
public void voidMethod() {
Foo f = new Foo();
f.setValue(100);
System.out.println(integerReturnMethod(f));
}
private Integer integerReturnMethod(Foo f) {
return f.getValue();
}
}
So, Calling method return type has no relation with called method return type.

Variable access in another class

I have a variable in x class .And I have another class called "Y" to access the variable. Will it change the value in X class, if the value is incremented in Y class?
Java uses pass by value but we can achieve what you are asking for by passing an object as an argument to a method like this:
public class ClassX {
public int classId;
public ClassX(int id) {
this.classId = id;
}
public void setId(int id) {
classId = id;
}
public int getId() {
return classId;
}
}
public class ClassY {
public static void main(String[] args) {
ClassX cx = new ClassX(100);
ClassY cy = new ClassY();
System.out.println("classId:"+cx.classId);
cy.modifyId(cx); // an object is passed as argument to a method
System.out.println("classId:"+cx.classId);
}
public void modifyId(ClassX classx) {
classx.setId(220);
}
}
Assuming you have it defined like
public int anInteger = 4;
Then yes, it would change.
These are the sorts of things best learned from experimentation, try various ways of structuring the classes, declaring the variable, and accessing it. See what happens.
Yes. All you need is to pass a reference to it to the other class.

Is it possible to set method level variable as class level variable?

I want to set my method level variable as class level variable. Is it possible to set method level variable as class level variable in Java?i want to get method level variable value as class level variable how to get it?
class A {
void m(String s){
String s1 = s;
}
}
I guess that you want (as a basic example)
class A {
String s1;
void m(String s) {
s1=s;
}
}
Note that this is what you do with a setter function:
public class A {
private String s1;
//Since the attribute is private, you need a function to access to the value
public String getS1() {
return this.s1;
}
public void setS1(String s) {
this.s1 = s;
}
}
And you can also pass the dynamic value in the class constructor:
public class A {
private String s1;
public A(String s1) {
this.s1 = s1;
}
//Since the attribute is private, you need a function to access to the value
public String getS1() {
return this.s1;
}
public void setS1(String s) {
this.s1 = s;
}
}
Try this code
class A {
String s;
void m(String s){
this.s=s; //this keyword is used to ambiguity between local variable and class level variable
}
}
If you asking about setting the Instance variable in that method here's how you do it.
String s;//instance var
void m(String s)//s is dynamic value
{
this.s=s;
}

Java: Anonymous inner class using a local variable

How can I get the value of userId passed to this method in my anonymous inner subclass here?
public void doStuff(String userID) {
doOtherStuff(userID, new SuccessDelegate() {
#Override
public void onSuccess() {
Log.e(TAG, "Called delegate!!!! "+ userID);
}
});
}
I get this error:
Cannot refer to a non-final variable userID inside an inner class defined in a different method
I'm pretty sure I can't assign it as final since it's a variable with an unknown value. I had heard that this syntax does preserve scope in some way, so I think there must be a syntax trick I don't quite know yet.
As everyone else here has said, local variables have to be final to be accessed by an inner class.
Here is (basically) why that is... if you write the following code (long answer, but, at the bottom, you can get the short version :-):
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
foo = new Foo()
{
public void bar()
{
System.out.println(x);
}
};
foo.bar();
}
}
the compiler translates it roughly like this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
class $1
implements Foo
{
public void bar()
{
System.out.println(x);
}
}
foo = new $1();
foo.bar();
}
}
and then this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
foo = new $1(x);
foo.bar();
}
private static class $1
implements Foo
{
private final int x;
$1(int val)
{
x = val;
}
public void bar()
{
System.out.println(x);
}
}
}
and finally to this:
class Main
{
public static void main(String[] args)
{
final int x;
Main$Foo foo;
x = 42;
foo = new Main$1(x);
foo.bar();
}
}
interface Main$Foo
{
void bar();
}
class Main$1
implements Main$Foo
{
private final int x;
Main$1(int val)
{
x = val;
}
public void bar()
{
System.out.println(x);
}
}
The important one is where it adds the constructor to $1. Imagine if you could do this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
int x;
Foo foo;
x = 42;
foo = new Foo()
{
public void bar()
{
System.out.println(x);
}
};
x = 1;
foo.bar();
}
}
You would expect that foo.bar() would print out 1 but it would actually print out 42. By requiring local variables to be final this confusing situation cannot arise.
Sure you can assign it as final - just put that keyword in the declaration of the parameter:
public void doStuff(final String userID) {
...
I'm not sure what you meant about it being a variable with an unknown value; all that final means is that once a value is assigned to the variable, it cannot be re-assigned. Since you're not changing the value of the userID within your method, there's no problem making it final in this case.
In Java 8, this has changed a little bit. You can now access variables that are effectively final. Relevant snippet and example from the Oracle documentation (emphasis mine):
However, starting in Java SE 8, a local class can access local
variables and parameters of the enclosing block that are final or
effectively final.
Effectively final: A non-final variable or parameter whose value is never changed after it is initialized is effectively final.
For example, suppose that the variable numberLength is not declared final, and you
add the highlighted assignment statement in the PhoneNumber
constructor:
PhoneNumber(String phoneNumber) {
numberLength = 7; // From Kobit: this would be the highlighted line
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
Because of this assignment statement, the variable numberLength is not
effectively final anymore. As a result, the Java compiler generates an
error message similar to "local variables referenced from an inner
class must be final or effectively final" where the inner class
PhoneNumber tries to access the numberLength variable:
if (currentNumber.length() == numberLength)
Starting in Java SE 8, if you declare the local class in a method, it
can access the method's parameters. For example, you can define the
following method in the PhoneNumber local class:
public void printOriginalNumbers() {
System.out.println("Original numbers are " + phoneNumber1 +
" and " + phoneNumber2);
}
The method printOriginalNumbers accesses the parameters
phoneNumber1 and phoneNumber2 of the method validatePhoneNumber
What's the problem with making it final as in
public void doStuff (final String userID)
declare the method
public void doStuff(final String userID)
The value needs to be final so that the compiler can be sure it doesn't change. This means the compiler can bind the value to the inner class at any time, without worrying about updates.
The value isn't changing in your code so this is a safe change.

Categories

Resources