Access a method's variable in Java - java

I am new to Java so I need help.
How can I access the variables of the method method1 and compare them with the variable int c? What should I return?
public static void main (String [] args){
int c = 30;
// I want to compare c with a, for example:
if (c > a)
{
System.out.println(c + " is greater than " + a);
}
}
I want to do the above comparison without touching method1()
public double method1(){
int a = 10; int b = 20;
if (a > b)
{
System.out.println(a + " is greater than " + b);
}
else if (a < b)
{
System.out.println(b + " is greater than " + a);
}
//What should I return?
return ????;
}

if you are writing "int c = 30;" directly below main then it becomes global variable.
Global Variable means: "c" can be accessed inside methods(anywhere in same class).
if you are writing "int c = 30;" inside particular method than you cannot access outside that particular method.
Following is example of global variable.
public static void main (String [] args){
int c = 30;
public double method1(){
int a = 10;
if (a > c)
{
System.out.println(a + " is greater than " + c);
return a;
}
else if (a < c)
{
System.out.println(c + " is greater than " + a);
return b;
}
}
I hope it works for you.

How can I access the variables of the method "method1" [...] without touching the method1()?
You can't.
Local variables in a method are only accessible inside that method. And if that method doesn't give you a way to see them, then without modifying the method, you can't see them.
Since a is always 10, you could do if (c > 10) instead.

Related

Error Storing static function from another class in BiFunction

I have two classes and, in one of them, I want to create a variable that will hold a function from the other class. I want to do this so I can change behaviour dinamically conditionally.
I tried the following prototype which results in a compilation error:
class A {
public String myFn(int a, int b) {
return "<" + a + " " + b + ">";
}
public String myFn2(int a, int b) {
return "(" + a + " " + b + ")";
}
}
class B {
static int mode = 1;
public void fn() {
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = ClassA.myFn(); // This results in an error "Cannot resolve method fn()".
}
else {
//fn = ClassA.myFn2();
}
// next I will use fn ...
}
}
This results in an error "Cannot resolve method fn()".
How can I store the function?
Thanks.
Calling ClassA.myFn() would require the method to be static and this is a method call, you wan't to store the method, not calling it.
Lambda
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = (a, b) -> ClassA.myFn(a, b);
}
Method reference
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = ClassA::myFn;
}
⚠️ Also
both myFn and myFn2 should be static
public static String myFn(int a, int b) {
return "<" + a + " " + b + ">";
}
chosse ClassA or A but they should be matching
class ClassA {
Your method myFn is not static, so you can't access it in a static context like you are trying to do. Your class is also called A, but you reference it as ClassA. Also, when assigning the BiFunction, you assign it to the return value, when you want a lambda expression. Here's an edited copy of your example:
class A {
public static String myFn(int a, int b) { //notice the static keyword
return "<" + a + " " + b + ">";
}
public static String myFn2(int a, int b) { //notice the static keyword
return "(" + a + " " + b + ")";
}
}
class B {
static int mode = 1;
public void fn() {
BiFunction<Integer, Integer, String> fn = null;
if(mode == 1) {
fn = A::myFn; // use a lambda expression, and class is named A
}
else {
//fn = A::myFn2;
}
// next I will use fn ...
}
}

Quick sort not sorting array [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
I have the following code:
public class Main {
static void swap (Integer x, Integer y) {
Integer t = x;
x = y;
y = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
swap(a, b);
System.out.println("a=" + a + " b=" + b);
}
}
I expect it to print a=2 b=1, but it prints the opposite. So obviously the swap method doesn't swap a and b values. Why?
This doesn't have anything to do with immutability of integers; it has to do with the fact that Java is Pass-by-Value, Dammit! (Not annoyed, just the title of the article :p )
To sum up: You can't really make a swap method in Java. You just have to do the swap yourself, wherever you need it; which is just three lines of code anyways, so shouldn't be that much of a problem :)
Thing tmp = a;
a = b;
b = tmp;
Everything in Java is passed by value and the values of variables are always primitives or references to object.
If you want to implement a swap method for Integer objects, you have to wrap the values into an array (or ArrayList) and swap inside the array. Here's an adaptation of your code:
public class Main {
static void swap (Integer[] values) {
if ((values == null) || (values.length != 2)) {
throw new IllegalArgumentException("Requires an array with exact two values");
}
Integer t = values[0];
values[0] = values[1];
values[1] = t;
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] integers= new Integer[]{a,b};
swap(integers);
System.out.println("a=" + integers[0] + " b=" + integers[1]);
}
}
(Just added this answer because Svish mentioned, that "You can't really make a swap method in Java" fg)
As Svish and others pointed out it it's call by value, not by reference in Java. Since you have no pointers in Java you need some kind of holder object to really swap values this way. For example:
static void swap(AtomicReference<Integer> a, AtomicReference<Integer> b) {
Integer c = a.get();
a.set(b.get());
b.set(c);
}
public static void main(String[] args) {
AtomicReference<Integer> a = new AtomicReference<Integer>(1);
AtomicReference<Integer> b = new AtomicReference<Integer>(2);
System.out.println("a = " + a);
System.out.println("b = " + b);
swap(a, b);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
You would need to pass the parameters by reference, which it's not possible in java. Also Integers are inmutables, so you cannot exchange the values as you don't have a setValue method.
Integer are immutable - you can't change their values. The swapping that occurs inside the swap function is to the references, not the values.
You would need to return both references in an array to achieve what you want
static Integer[] swap(Integer a, Integer b) {
return new Integer[]{b, a};
}
public static void main(String[] args) {
Integer a = 1;
Integer b = 2;
Integer[] intArray = swap(a, b);
a = intArray[0];
b = intArray[1];
System.out.println("a=" + a + " b=" + b);
}
If Integer had a setValue method, you could do something like this.
static void swap(Integer a, Integer b) {
int temp = a.intValue();
a.setValue(b.intValue());
b.setValue(temp);
}
But it doesn't - so to achieve what you want, return an array.
Using the XOR operator is a very bad idea:
First, it is far less readable. Second, there were times when this was faster but nowadays the opposite is the case. See
Wikipedia
for reference.
As all the guys mentioned its a Pass-By-Value thing.
Just liked to add: you can use this method of swapping GLOBAL integers.
private void swap (){
a ^= b;
b ^= a;
a ^= b;
}
It eliminates the use of another variable, and its just cooler :)
Java code:
class swap {
int n1;
int n2;
int n3;
void valueSwap() {
n3 = n1;
n1 = n2;
n2 = n3;
}
public static void main(String[] arguments) {
Swap trial = new Swap();
trial.n1 = 2;
trial.n2 = 3;
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
trial.valueSwap();
System.out.println("trial.n1 = " + trial.n1);
System.out.println("trial.n2 = " + trial.n2);
}
}
Output:
trial.n1 = 2
trial.n2 = 3
trial.n1 = 3
trial.n2 = 2
Using Scanner:
import java.util.*;
public class Swap {
public static void main(String[] args){
int i,temp,Num1,Num2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Number1 and Number2");
Num1=sc.nextInt();
Num2=sc.nextInt();
System.out.println("Before Swapping Num1="+Num1+" Num2="+Num2);
temp=Num1;
Num1=Num2;
Num2=temp;
System.out.println("After Swapping Num1="+Num1+" Num2="+Num2);
}
}

Java: non-static variable value cannot be referenced from a static context error [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 10 months ago.
I am writing a code in 2 separate classes that takes a temp as 2 separate variables and prints it out and then runs conversion methods to get temps in other scales. I keep getting the error non-static variable value cannot be referenced from a static context in the Temperature.java part of my code because of the variables being in the constructor which is not static. The whole concept is a bit confusing to me and I'd love any input on hope static and non-static works and how you can switch between them without issue.
code as follows:
public class Temperature
{
int value = 50;
String scale = "F";
public Temperature(int value, String scale){
value = value;
scale = scale;
}
public static void value(int value){
int number;
}
public static boolean scale(String scale){
if (scale == "C"){
return true;
}
else if (scale == "F"){
return true;
}
else if (scale == "K"){
return true;
}
else{
return false;
}
}
public static void convertToCelsius(int value, String scale){
if (scale == "F"){
int newValue = (5/9) * (value - 32);
System.out.println("The equivalent tempurature is " + newValue + "C");
}
else if (scale == "K"){
double newValue = value - 273.15;
System.out.println("The equivalent tempurature is " + newValue + "C");
}
else{
}
}
public static void convertToFarenheit(int Value, String scale){
if (scale == "C"){
int newValue = ((9/5) * (value + 32));
System.out.println("The equivalent tempurature is " + newValue + "F");
}
else if (scale == "K"){
int newValue = ((9/5) * (value - 273) + 32);
System.out.println("The equivalent tempurature is " + newValue + "F");
}
else{
}
}
public static void convertToKelvin(int value, String scale){
if (scale == "F"){
int newValue = ((5/9) * (value - 32) + 273);
System.out.println("The equivalent tempurature is " + newValue + "C");
}
if (scale == "C"){
double newValue = (value + 273.15);
System.out.println("The equivalent tempurature is " + newValue + "C");
}
else{
}
}
}
for the main method the code is in the separate class as follows:
public class UsingTemperature
{
public static void main(String[] args)
{
Temperature t = new Temperature(50, "F");//declaring an object
System.out.println(t);
// Test out conversions:
System.out.println("Test out conversions:");
// F to C
t.convertToCelsius();
System.out.println(t);
// C to F
t.convertToFahrenheit();
System.out.println(t);
// F to K
t.convertToKelvin();
System.out.println(t);
// K to F
t.convertToFahrenheit();
System.out.println(t);
// F to K:
t.convertToKelvin();
System.out.println(t);
// K to C
t.convertToCelsius();
System.out.println(t);
// C to K
t.convertToKelvin();
System.out.println(t);
}
}
When you use the Static Modifier in your methods, these methods will exist independently of any instances created for the class.
So in your class Temperature your static methods:
Exist before you make a new instance of Temperature
There is just one copy of your static methods, regardless of the number of instances of Temperature you have.
Besides, I think that you only want Temperature as a utility, so the constructor makes no sense because a constructor is used only to create instances
When you need to use methods from Temperature: Temperature.name_method(params)
t is an object, but all of your convertToScale methods are static. Use Temperature.convertToScale(t.value, t.scale)
Also,
t.convertToCelsius();
System.out.println(t);
probably does not do what you expect it to do. None of your convertToScale methods are mutators (they just print stuff), so calling t.convertToCelsius() only prints out what the conversion does, then System.out.println(t) would print the default object.toString() (which gives you #0012378 or something)
Also, I just noticed all of the (5/9) and (9/5) you have, which will almost certainly break the math as given, due to how integer division works. Explicitly declare one of them as a double with 5.0 or 5d

Accessing the int value outside of the method

I have a method A in class Test, which generates a number a and b, heres the code for it:
public class Test
{
int a,b;
public void A()
{
a = currentMenu.getCurrentFocusedItem().getItemID();
b = currentMenu.getMenuID();
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B()
{
System.out.println("Inside B ()" + a + " &&" + b);
}
}
Now, I want to acces the a and b int values, into another method B(), in the same
class file.
Need some pointer
If you are working with the same instance of the class Test, the value of a and b as set in method A() should still be visible in method B().
So, the below would work:
Test test = new Test();
test.A();
test.B();
However, the below wouldn't
new Test().A();
new Test().B();
On a side note, methods in Java should always begin with a lowercase letter and use camelcase.
If what you are trying to do is to get the current(and latest) value of a and b,
you could write 2 methods like
public int getA() {
return currentMenu.getCurrentFocusedItem().getItemID();
}
public int getB() {
return currentMenu.getMenuID();
}
and use these methods instead of calling A() to update the values of a,b and then accessing them again in method B.
you can get the a and b values in instance initialization block
public class TestClass {
int a,b;
{
a= 10;
b =45;
}
public void A() {
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B() {
System.out.println("Inside B ()" + a + " &&" + b);
}
}
Using this method, you don't have to call your A() method for populating the values to be used in B()
You can try this too
public void A()
{
a = currentMenu.getCurrentFocusedItem().getItemID();
b = currentMenu.getMenuID();
System.out.println("Inside A ()" + a + " &&" + b);
}
public void B()
{
Test test=new Test();
test.A(); // assign values for a and b
System.out.println("Inside B ()" + a + " &&" + b);
}

Have I invoked correctly?

I have been given a piece of code (the class QuestionTwo).
I am asked to state the values of a, b, and c after method mQ2 is invoked on a newly created object of class Q2.
My main.java file
package openuniversity;
public class Main
{
public static void main(String[] args)
{
QuestionTwo qt = new QuestionTwo();
qt.mQ2();
}
}
My QuestionTwo.java class file:
package openuniversity;
public class QuestionTwo
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
}
a++;
}
}
I arrived at:
a: 1
b: 1
c: 3
Note I can also select 'undefined' as an answer?
So would it be 1, 1, undefined as c does not exist outside of the codeblock?
The question:
Study the following code and then select the options from the drop-down lists below that are correct about the values of a, b and c after the method mQ2 is invoked once on a newly created object of class Q2. Note that the answers you choose for a, b and c may or may not be different from each other.
public class Q2
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
System.out.println("c: " + c); //correct place?
}
a++;
}
System.out.println("a: " + a + "b: " + b); // correct place?
}
Since this is homework, I'll restrict my answer to a couple of pointers.
You can verify your solution by printing out the variables after calling mQ2() (hint: you could use System.println() for that).
This is either a trick question or is partially ill-defined (hint: think about which a, b and especially c you're being asked about).
I'd suggest you first print out all the values using System.out.println() after calling mQ2, then step through the code in your mind to try to work out why the values are what they are. Remember that any variable declared is only visible within the scope ({...}s for simplicity), but these variables can have the same name as other variables so they might look like the same even if they're not.
I'd like to particularly point out that c does not exist outside that method.

Categories

Resources