Say we have variables int a = 0; and int c;.
Is it possible to make it so that c is always equal to something like a + 1 without having to redundantly retype c = a + 1 over and over again
Thanks!
No, it is not possible to make one variable track another variable. Usually, this is not desirable either: when a value of one variable is tied to the value of another variable, you should store only one of them, and make the other one a computed property:
int getC() { return a+1; }
A less abstract example is a connected pair of age and date of birth. Rather than storing both of them, one should store date of birth alone, and make a getter method for computing the current age dynamically.
Since you have 2 variables tied in a specific way, consider using custom object to wrap a and c values. Then you can control the object state inside the class logic. You can do something like this:
public class ValuePair {
private final int a;
private final int c;
public ValuePair(int a) {
this.a = a;
this.c = a + 1;
}
public int getA() {
return a;
}
public int getC() {
return c;
}
}
Firstly, The answer is no, you can't do it directly in Java, but you can redesign your int class, There is an example:
public class Test {
public static void main(String[] args) throws IOException {
MyInt myInt1 = new MyInt(1);
KeepIncrementOneInt myInt2 = new KeepIncrementOneInt(myInt1);
System.out.println(myInt2.getI());
myInt1.setI(2);
System.out.println(myInt1.getI());
System.out.println(myInt2.getI());
}
}
class MyInt { //your own int class for keep track of the newest value
private int i = 0;
MyInt(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
public void setI(int i) {
this.i = i;
}
}
class KeepIncrementOneInt { //with MyInt Class to get the newest value
private final MyInt myInt;
KeepIncrementOneInt(MyInt myInt) {
this.myInt = myInt;
}
public int getI() {
return this.myInt.getI() + 1; //get the newest value and increment one.
}
}
Create your own Int class, because we need a reference type to keep track of the newest the value a. like the MutableInt in apache commons.
Create a always increment 1 class with your own Int class as a member.
In getI method, it's always from the reference Int class get the newest value a.
Related
I'm working on a calculator and I search how I can optimize my code.
The thing is that I have much code duplication due to if I'm working on the first number of the calculation or the second. So I'm searching if it is possible to modify the value of an attribute sent in argument of a function ? (I think not because I saw nowhere the answer).
Maybe I'm expressing myself badly so here is a code below to explain what I'm talking about:
public class MyClass
{
private static int number1 = 1;
private static int number2 = 2;
public MyClass()
{
changeValueOf(number1, 3);
}
private static void changeValueOf(int number, int value)
{
//Change here the value of the correct field
}
}
First of all, you can modify static variables inside the method:
private static void changeValueOf(int value)
{
number1 = value;
}
But I guess that is not what you a looking for :)
In Java (and in most other languages) primitive data type (int, short, long, etc) passed by value, e.g. the copy of value passes to the method (function).
And reference types (objects, e.g. created with new operator) passed by reference. So, when you modigy the value of reference type (object) you can see the changes in the outer scopes (for example, in method caller).
So, the answer is no - you cannot change the value of int so that the outer scope would see the updated value.
Howewer, you could wrap your int values with some object - and it change the value inside of it:
public class Example {
public static void main(String[] args) {
Example app = new Example();
// Could be static as well
Holder val1 = new Holder(1);
Holder val2 = new Holder(2);
app.changeValue(val1, 7);
System.out.println(val1.value); // 7
}
public void changeValue(Holder holder, int newValue) {
holder.value = newValue;
}
static class Holder {
int value;
Holder(int value) {
this.value = value;
}
}
}
Also, you could create an array with 2 values and update them inside the method, but it's not very good approach IMO
And finally, you could just return updated value and assign it to your variables:
public class Example {
private static int number1 = 2;
private static int number2 = 3;
public static void main(String[] args) {
Example app = new Example();
number1 = app.mul(number1, 7);
number2 = app.mul(number2, 7);
System.out.println(number1); // 14
System.out.println(number2); // 21
}
public int mul(int a, int b) {
return a * b;
}
}
One possibility is to use an array to store your variables, instead of separate variables with numbers affixed. Then you would write number[1] instead of number1 for example. You can pass the array index number around to indicate which variable you are referring to.
public class MyClass
{
private static int[] variables = {1, 2};
public MyClass()
{
// change value of first variable
changeValueOf(0, 3);
// now variable[0] = 3
}
private static void changeValueOf(int number, int value)
{
variables[number] = value;
}
}
#include<stdio.h>
void decrease(int *i);
int main(){
int i = 10;
decrease(&i);
printf("%d",i);
}
void decrease(int *i){
*i = *i - 1;
}
What would be the Java program for the same?
As you pointed out (no pun intended), Java does not support pointers. So, there is no way to directly manipulate the value of a primitive passed to a method, because only a copy of the primitive would be used in the method. One way to get around this would be to just return the updated value, and then overwrite the integer in the calling scope:
public static int decrease(int i) {
return i - 1;
}
public static void main(String[] args) {
int i = 10;
i = decrease(i);
System.out.println(i); // prints 9
}
You have two options, either (return) the value, and modify it in the main class, or pass an Object, not a primitive.
An object with your values:
public class Holder {
public int x;
}
And a method to modify it
public void modify(Holder h){
h.x = 2;
}
Called like:
Holder h = new Holder();
h.x = 1;
modify(h);
System.out.println(h.x);
Results in:
2
I am trying to pass two variables along to a method and have the method give me back two independent results.
int numX = 5;
int numY = 3;
System.out.println(displayTwiceTheNumber(numX, numY));
}
public static int displayTwiceTheNumber(int numX, int numY) {
int numW, numZ;
numW, numZ = 2 * (numX, numY);
return numW numZ;
}
Java takes it that at numW, numZ = 2 * (numX, numY); that I am trying to redefine numX and numY. How do I phrase the last block to take two variables and give two results?
A single int function can only return 1 int at a time.
If you want to return 2 values, consider calling the function twice or creating a custom object to be used.
You need to change the return type of the function. Currently, the return type is int, so you have to return one integer.
To return two integer, you should consider returning an array or a list or something similar.
public static int[] displayTwiceTheNumber(int numX, int numY){
//your code that do something
int[] ret = {numW, numZ};
return ret;
}
Or knowing that this function would change the value of numW and numZ, you could declare those as global variable. Now, when you call this function, those variable will be changed. Then, you can use numW and numZ subsequently.
public int numW;
public int numZ;
public static void displayTwiceTheNumber(int numX, int numY){
//your code that do something and modifies numW and numZ
}
public static void anotherfunction(){
//after calling displayTwiceTheNumber, numW and numZ would have the appropriate value
//you can now just use numW and numZ directly
}
Overview: Use a tuple. In this example I use an tuple to return more than one result. Tuple means to return more than one result type. In this example I return a tuple of two integer types. My class TupleCustom contains one method function1 which receives two parameters of type integer: x and y. I create a tuple of type integer and return the tuple as a variable. Internally, the precomiler converts the tuple json than back to a tuple with variable Item1, Item2...ItemN in the unit test method.
public class TupleCustom
{
public async Task<Tuple<int, int>> Function1(int x, int y)
{
Tuple<int, int> retTuple = new Tuple<int, int>(x, y);
await Task.Yield();
return retTuple;
}
}
public class TestSuite
{
private readonly ITestOutputHelper output;
public TestSuite(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public async Task TestTuple()
{
TupleCustom custom = new TupleCustom();
Tuple<int, int> mytuple = await custom.Function1(1,2);
output.WriteLine($" Item1={mytuple.Item1} Item2={mytuple.Item2} ");
}
When I have this problem I create a private utility class for handling the return values. By doing it this way, you can pass various types in the argument list. Aspects of the class can be tailored to your requirements.
public static void main(String [] args) {
int numX = 5;
double numY = 3.0;
Nums n = displayTwiceTheNumber(numX, numY);
System.out.println(n.numX);
System.out.println(n.numY);
}
public static Nums displayTwiceTheNumber(int numX, double numY) {
int numW;
double numZ;
// do something with arguments.
// in this case just double them and return.
return new Nums(2*numX, 2*numY);
}
private static class Nums {
int numX;
double numY;
public Nums(int nx, double ny) {
this.numX = nx;
this.numY = ny;
}
public String toString() {
return "(" + numX + ", " + numY +")";
}
}
Prints
10
6.0
Apologies for the terribly worded question, but I'm a bit new to Java and still a bit unsure how to word my problems/ not really sure if it's possible to do what I want to.
I have a class called ClassA which has a trivial method returnInt that looks something like this:
public class ClassA {
private int numberino;
public ClassA(Int int) {
this.numberino = int;
public boolean isPositive(){
if (this.numberino > 0){
return true;
return false;
public int returnInt() {
final int addVal = 2;
int sum = 1
sum = addVal*numberino + sum;
return sum;
}
Now when I call this method in another main loop, like:
ClassA temp = new ClassA(7);
temp.returnInt();
My question is, is there anyway I can pass the object temp into the returnInt() method, so I could perhaps use the isPositive(int) method on it without changing the structure (by passing in an argument) of the returnInt() method?
Something like this is how I would imagine it being (but I know it's wrong);
public int returnInt() {
final int addVal = 2;
int sum = 1
if (temp.isPositive()){
sum = addVal*numberino + sum;
}
return sum;
Where that temp is Object being created and the method returnInt() is the method being used from it.
I hope that makes sense.
Thanks!
returnInt is an instance method of ClassA, so it can call any method of ClassA. There's no need to pass anything.
public int returnInt() {
final int addVal = 2;
int sum = 1
if (isPositive()) { // or this.isPositive() if you want to be explicit
sum = addVal*numberino + sum;
}
return sum;
}
How can I swap the contents of two Integer wrappers?
void swap(Integer a,Integer b){
/*We can't use this as it will not reflect in calling program,and i know why
Integer c = a;
a= b;
b = c;
*/
//how can i swap them ? Does Integer has some setValue kind of method?
//if yes
int c = a;
a.setValue(b);
b.setValue(c);
}
You can't, precisely because Integer is immutable (along with the other primitive wrapper types). If you had a mutable wrapper class, it would be fine:
public final class MutableInteger {
{
private int value;
public MutableInteger(int value) {
this.value = value;
}
public void setValue(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
void swap(MutableInteger a, MutableInteger b) {
int c = a.getValue();
a.setValue(b.getValue());
b.setValue(c);
}
However, due to the lack of the equivalent of setValue in Integer, there's basically no way of doing what you're asking. That's a good thing. It means that for most cases, where we may want to pass an Integer value to another method, we don't need to worry about whether the method will mutate it. Immutability makes it much easier to reason about your code, without having to carefully trace what every method does, just in case it changes your data under your feet.
Wrapper types in Java are immutable hence provide no setter methods. Plus Java works by passing references by value. Can you tell us why you want to swap stuff?
The type java.lang.Integer represents an immutable number that will never change its value. If you want a mutable number, try MutableInt from Apache Commons.
In Java, as opposed to C++, you cannot pass references to arbitrary memory locations, so swapping is impossible in most cases. The closest thing you can get is this:
public static void swap(Integer[] ints, int index1, int index2) {
Integer tmp = ints[index1];
ints[index1] = ints[index2];
ints[index2] = tmp;
}
You can write similar code using a List<T>, but you always need a container (or two) in which you can swap things.
Refer this article to get a clear idea Article
You will get a clear idea about pass by value pass by reference and and its concepts
you can try something like this :
class MyClass{
int a = 10 , b = 20;
public void swap(MyClass obj){
int c;
c = obj.a;
obj.a = obj.b;
obj.b = c;
}
public static void main(String a[]){
MyClass obj = new MyClass();
System.out.println("a : "+obj.a);
System.out.println("b : "+obj.b);
obj.swap(obj);
System.out.println("new a : "+obj.a);
System.out.println("new b : "+obj.b);
}
}
public class NewInteger {
private int a;
private int b;
public int getA() {
return a;
}
public int getB() {
return b;
}
public NewInteger(int a, int b) {
this.a = a;
this.b = b;
}
public void swap(){
int c = this.a;
this.a = this.b;
this.b = c;
}
}
NewInteger obj = new NewInteger(1, 2);
System.out.println(obj.getA());
System.out.println(obj.getB());
obj.swap();
System.out.println(obj.getA());
System.out.println(obj.getB());
output :
1
2
2
1