Will there any issues in initializing non-static member variables this way? - java

I have initialized the variables as follows in the code below. Is it okay to initialize like this ?
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
public static int getInt() {
int ret = 10;
System.out.println("ret- " + ret);
return ret;
}
public static int processInt(int toProcess) {
int toRet = toProcess / 2;
System.out.println("toRet- " + toRet);
return toRet;
}
public static void main(String[] args) {
StaticInit sit = new StaticInit();
}
}

You can initialise with the variable declaration or in the constructor. Some will argue that one or the other is better but either works. I believe the argument for initialise in the constructor is so that all variable initialisations are in the same place, since not everything can be initialised outside of the constructor in some cases.
public class StaticInit {
int x = getInt();
String z = "Lucky Number " + processInt(x);
}
or
public class StaticInit {
int x;
String z;
public StaticInit() {
x = 10;
z = x / 2;
}
}
For this case in particular though, I would definitely recommend using the constructor since z relies on x. Plus the constructor is much nicer than using static methods.

Personally, instead of having the getInt(), I would just initialise it in the constructor.
Unless you're going to use the getInt() function externally, I don't see the point in having it, especially since it returns a hardcoded value.

Related

Alternative to pointers in Java

#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

Passing two variables to one method to get two results

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

Setting variable values to be based on other variables

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.

Cannot make a static reference to the non-static method fxn(int) from the type Two [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the reason behind “non-static method cannot be referenced from a static context”?
Cannot make a static reference to the non-static method
cannot make a static reference to the non-static field
I am not able to understand what is wrong with my code.
class Two {
public static void main(String[] args) {
int x = 0;
System.out.println("x = " + x);
x = fxn(x);
System.out.println("x = " + x);
}
int fxn(int y) {
y = 5;
return y;
}
}
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot make a static reference to the non-static method fxn(int) from the type Two
Since the main method is static and the fxn() method is not, you can't call the method without first creating a Two object. So either you change the method to:
public static int fxn(int y) {
y = 5;
return y;
}
or change the code in main to:
Two two = new Two();
x = two.fxn(x);
Read more on static here in the Java Tutorials.
You can't access the method fxn since it's not static. Static methods can only access other static methods directly. If you want to use fxn in your main method you need to:
...
Two two = new Two();
x = two.fxn(x)
...
That is, make a Two-Object and call the method on that object.
...or make the fxn method static.
You cannot refer non-static members from a static method.
Non-Static members (like your fxn(int y)) can be called only from an instance of your class.
Example:
You can do this:
public class A
{
public int fxn(int y) {
y = 5;
return y;
}
}
class Two {
public static void main(String[] args) {
int x = 0;
A a = new A();
System.out.println("x = " + x);
x = a.fxn(x);
System.out.println("x = " + x);
}
or you can declare you method as static.
A static method can NOT access a Non-static method or variable.
public static void main(String[] args) is a static method, so can NOT access the Non-static public static int fxn(int y) method.
Try it this way...
static int fxn(int y)
public class Two {
public static void main(String[] args) {
int x = 0;
System.out.println("x = " + x);
x = fxn(x);
System.out.println("x = " + x);
}
static int fxn(int y) {
y = 5;
return y;
}
}

swap two numbers using call by reference

Can we swap two numbers in Java using pass by reference or call by reference?
Recently when I came across swapping two numbers in Java I wrote
class Swap{
int a,b;
void getNos(){
System.out.println("input nos");
a = scan.nextInt();
b = scan.nextInt(); // where scan is object of scanner class
}
void swap(){
int temp;
temp = this.a;
this.a = thisb;
this.b = this.a;
}
}
In the main method I call the above mentioned methods and take two integers a,b and then using the second method I swap the two numbers, but relative to the object itself....
Does this program or logic come under pass by reference?
And is this correct solution?
Yes and no. Java never passes by reference, and your way is one workaround. But yet you create a class just to swap two integers. Instead, you can create an int wrapper and use pass it, this way the integer may be separated when not needed:
public class IntWrapper {
public int value;
}
// Somewhere else
public void swap(IntWrapper a, IntWrapper b) {
int temp = a.value;
a.value = b.value;
b.value = temp;
}
As the comments show, I might not have been clear enough, so let me elaborate a little bit.
What does passing by reference mean? It means that when you pass an argument to the method, you can change the original argument itself inside this method.
For example, if Java was pass-by-reference, the following code will print out x = 1:
public class Example {
private static void bar(int y) {
y = 10;
}
public static void main(String[] args) {
int x = 1;
bar(x);
System.out.println("x = " + x);
}
}
But as we know, it prints 0, since the argument passed to the bar method is a copy of the original x, and any assignment to it will not affect x.
The same goes with the following C program:
static void bar(int y) {
y = 1;
}
int main(int argc, char * argc[]) {
int x = 0;
bar(x);
printf("x = %d\n", x);
}
If we want to change the value of x, we will have to pass its reference (address), as in the following example, but even in this case, we will not pass the actual reference, but a copy of the reference, and by dereferencing it we will be able to modify the actual value of x. Yet, direct assignment to the reference will no change the reference itself, as it is passed by value:
static void bar(int &y) {
*y = 1;
y = NULL;
}
int main(int argc, char * argc[]) {
int x = 0;
int * px = &x;
bar(px);
printf("x = %d\n", x); // now it will print 1
printf("px = %p\n", px); // this will still print the original address of x, not 0
}
So passing the address of the variable instead of the variable itself solves the problem in C. But in Java, since we don't have addresses, we need to wrap the variable when we want to assign to it. In case of only modifying the object, we don't have that problem, but again, if we want to assign to it, we have to wrap it, as in the first example. This apply not only for primitive, but also for objects, including those wrapper objects I've just mentioned. I will show it in one (longer) example:
public class Wrapper {
int value;
private static changeValue(Wrapper w) {
w.value = 1;
}
private static assignWrapper(Wrapper w) {
w = new Wrapper();
w.value = 2;
}
public static void main(String[] args) {
Wrapper wrapper = new Wrapper();
wrapper.value = 0;
changeValue(wrapper);
System.out.println("wrapper.value = " + wrapper.value);
// will print wrapper.value = 1
assignWrapper(w);
System.out.println("wrapper.value = " + wrapper.value);
// will still print wrapper.value = 1
}
}
Well, that's it, I hope I made it clear (and didn't make too much mistakes)
import java.util.*;
public class Main
{
int a,b;
void swap(Main ob)
{
int tmp=ob.a;
ob.a=ob.b;
ob.b=tmp;
}
void get()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a and b: ");
a=sc.nextInt();
b=sc.nextInt();
}
public static void main(String[] args) {
Main ob=new Main();
ob.get();
ob.swap(ob);
System.out.println(ob.a+" "+ob.b);
}}

Categories