This question already has answers here:
How do I pass a primitive data type by reference?
(8 answers)
Closed 7 years ago.
here is my code
public class Scale {
public static void main(String[] args) {
int x = 4;
int y = 3;
int faktor = 2;
skaliere(x,y,faktor);
System.out.println(x + " " + y);
}
public static void skaliere(int x, int y, int faktor){
// ?
}
}
I want to change the scale the x and y by faktor, not using a return value. Just by the skaliere method.
I want to change the scale the x and y by faktor, not using a return value. Just by the skaliere method.
Note that Java is not pass by reference, it's always pass by value.
Without any hack, simply you can't because they are primitives. If they are mutable objects, yes you can change their state.
That hack would be making them static and assigning values inside that method.
You can always make your own MutableInteger class
class MutableInteger{
private int value;
public MutableInteger(int v){
this.value = v;
}
public int get(){
return value;
}
public void set(int newValue){
this.value = newValue;
}
#Override
public String toString() {
return Integer.toString(value);
}
}
Then use it in your code:
public static void main(String[] args) {
MutableInteger x = new MutableInteger(4);
MutableInteger y = new MutableInteger(3);
int faktor = 2;
skaliere(x,y,faktor);
System.out.println(x + " " + y);
}
public static void skaliere(MutableInteger x, MutableInteger y, int faktor){
x.set(x.get() *faktor);
y.set(x.get() *faktor);
}
Since you are making your own class, you can even move the skaliere method into your MutableInteger
class MutableInteger{
...
public void skaliere(int faktor){
this.value *=faktor;
}
}
which makes your code look like this:
public static void skaliere(MutableInteger x, MutableInteger y, int faktor){
x.skaliere(faktor);
y.skaliere(faktor);
}
You don't even need the static method anymore
You could do this with an object that wraps the two values. This is because the object reference is passed to the method. If you pass a primitive which are immutable, they will never be changed on the return, it would only change a copy in the method. Using an object, you can pass the containing values and it would be the ones referenced by the main method when retrieved.
public static void main(String[] args) {
// org.eclipse.swt.graphics.Point
Point p = new Point(0, 0);
p.x = 4;
p.y = 3;
int faktor = 2;
skaliere(p,faktor);
System.out.println(p.x + " " + p.y);
}
public static void skaliere(Point p, int factor){
p.x *= factor;
p.y *= factor;
}
Related
I'm trying to add a method an an array like this.
Position[] positions = new Position[10];
Position pos = positions.getPosAt(x, y);
I know this can be accomplished like:
Position pos = getPosAt(positions, x, y)
But I would like to know if there is a way to accomplish the first method.
you can make a class handler for this, like this PositionArray class (name it as you would like):
public class Test {
public static void main(String... args) {
Position[] positions = new Position[10];
positions[0] = new Position(5, 10);
positions[1] = new Position(11, 18);
positions[2] = new Position(20, 7);
PositionArray pa = new PositionArray(positions);
System.out.println(pa.getPosAt(5, 10)); // Position{x=5, y=10}
}
}
class PositionArray {
private Position[] positions;
public PositionArray(Position[] positions) {
this.positions = positions;
}
public Position getPosAt(int x, int y) {
for (Position p : positions) {
if (!Objects.isNull(p)) {
System.out.println(p.getX() + " " + p.getY());
if (p.getX() == x && p.getY() == y) {
return p;
}
}
}
return null;
}
}
class Position {
private final int x;
private final int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public String toString() {
return "Position{" + "x=" + x + ", y=" + y + '}';
}
}
There is no way to do this in Java. You could possibly create your own class that contained an array of Position objects and provides e.g. get methods, but there is no way whatsoever to add methods to classes you do not control, including all array types.
I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.
I was reading a java book, where I came across this statement:
So, every subroutine is contained either in a class or in an object
I'm really confused why does it say "class or in an object"
I would like some explanation.
Let's try this example
public class Demo {
public static void classMethod() {
System.out.println("Call to static method");
}
public void objectMethod() {
System.out.println("Call to object method");
}
public static void main(String[] args) {
Demo demo = null;
demo.classMethod();
//demo.objectMethod();// throws NPE if uncommented
}
}
This code will work (even if the demo variable is null) because static method classMethod is contained within the class Demo. The commented line will throw a NullPointerException because the method objectMethod is not contained in the class but in the object so will need an instance of Demo class to call it.
Subroutine is a method written inside a class. We use them to do various tasks. That statement states that these methods/subroutines are written in an object or a class.
If we have an object instantiated, it will create new methods for every non-static method for that object which were defined in the class of the object. Hence those non-static methods/subroutines are in the object.
But if the class is a static class, we can't have any objects from it. But we can use subroutines/methods of that class. So, they are in a Class
That's what your statement says.
EDIT:
I thought to give an example for this.
public class ExampleClass {
public String getNonStaticString() {
return "This String is From Non-Static Method";
}
public static String getStaticString() {
return "This String is From Static Method"
}
}
Then, if you need to get the static String, all you have to do is
String staticString = ExampleClass.getStaticString();
Note that I havn't created an object from the ExampleClass Here. I just used the method.
But, if you need to get the String from the non-static method, you should instantiate an object first.
ExampleClass exampleObject = new ExampleClass();
String nonStaticString = exampleObject.getNonStaticString();
static methods also known as class method. Static method associated only with the class and not with any specific instance of that class(object).
So, every subroutine is contained either in a class or in an object
The statement is technically not 100% correct.
First of all, subroutines in java are commonly called methods. The following two terms are often used interchangeably:
Method: A subroutine working with an object instance, this.
Function: A subroutine not working with an object instance.
Here is an example scenario which should you get an idea what that means:
public class Circle {
//region static code
//we cannot call "this" in a static context, main(String[]) is no exception here
public static void main(String[] args) {
Circle a = new Circle(0, 0, 10);
Circle b = new Circle(10, 10, 2);
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("circumference of a = " + a.getCircumference());
System.out.println("circumference of b = " + b.getCircumference());
System.out.println("area of a = " + a.getArea());
System.out.println("area of b = " + b.getArea());
System.out.println("distance of a, b = " + distance(a, b));
System.out.println("a, b intersect = " + (intersects(a, b) ? "yes" : "no"));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to calculate their distance
public static double distance(Circle a, Circle b) {
return Math.sqrt(squared(a.x - b.x) + squared(a.y - b.y));
}
//we cannot call "this" in a static context, but we have the circles a, b as parameters we can use to check for an intersection
public static boolean intersects(Circle a, Circle b) {
return a.radius + b.radius > distance(a, b);
}
//we cannot call "this" in a static context, but we have the number x as parameter we can use to calculate the square of
public static double squared(double x) {
return x * x;
}
//we cannot call "this" in a static context, but we have the number radius as parameter we can use to check if its value is in range
public static void checkRadius(double radius) {
if(radius < 0) {
throw new IllegalArgumentException("radius must be >= 0");
}
}
//endregion
//region member / instance code
private double x;
private double y;
private double radius;
public Circle(double x, double y, double radius) {
checkRadius(radius);
this.x = x;
this.y = y;
this.radius = radius;
}
//region getters and setters
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getX() {
return x;
}
//we may refer to the instance variables with or without "this", but in this case we have two variables with name "x"
//if we write "x", the parameter is taken. for the circle's x coordinate, we need to clarify with "this.x"
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
checkRadius(radius);
this.radius = radius;
}
//endregion
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
public double getCircumference() {
return 2 * Math.PI * radius;
}
public double getArea() {
return Math.PI * squared(radius);
}
//we may refer to the instance variables with or without "this", sometimes it is necessary to clarify - see: setX(double)
#Override
public String toString() {
return "circle at [" + x + ", " + y + "] with radius " + radius;
}
//endregion
}
Output:
a = circle at [0.0, 0.0] with radius 10.0
b = circle at [10.0, 10.0] with radius 2.0
circumference of a = 62.83185307179586
circumference of b = 12.566370614359172
area of a = 314.1592653589793
area of b = 12.566370614359172
distance of a, b = 14.142135623730951
a, b intersect = no
i know that this question has been asked many types, but i am not getting trough the problem. So following. I have created a class that is creating array of 2 positions. The goal is to create point coordinates so i can generate several points later. Hier is my code
import java.util.Random;
public class Coor {
private static int[] coord;
public static int[] generate(){
coord = new int[2];
return coord;
}
public static void printX(){
System.out.println("X = " + coord[0] );
}
public static void printY(){
System.out.println("Y = " + coord[1] );
}
public static int randomFill(){
Random rand = new Random();
int randomNum = rand.nextInt(99);
return randomNum;
}
public static void main(String args[]) {
generate();
for(int i = 0; i < 2; i++){
coord[i] = randomFill();
}
printX();
printY();
}
}
So, this is working perfect, but what I want is to create the points in another class and to use them there, but I have no idea how to achieve this. I am new to java, and I have almost understood some examples in the oracle docs, but can not implement it. Can you please help me a little? I just need one example class which is obtaining the coordinates of the points, after that I can extend it alone for my needs.
You should not make your data static and you should provide a public constructor see below.
public class Coord {
private int[] coord;
public Coord(int x, int y) {
coord = new int[2];
coord[0] = x;
coord[1] = y;
}
public void printX(){
System.out.println("X = " + coord[0] );
}
public void printY(){
System.out.println("Y = " + coord[1] );
}
public static void main(String[] args) {
Coord c1 = new Coord(10, 11);
Coord c2 = new Coord(23, 14);
}
}
Can you help me find my error?
I'm trying to use these two methods here but my output is not working.
class Nine {
public static void Nine(String[] args) {
int x,y,z;
y = 3;
x = 7;
z = addEm(a, b);
System.out.println("answer= " +x);
}
public static addEm (double a, double b){
int c;
c = a+b;
}
}
Actually there are a lot of error in your code:
z=addEm(a, b);
here a and b are meaningless, you should use z=addEm(y,x); (if your intent is to sum three with seven)
System.out.println("answer= " +x);
I guess that you want to show the the results of the sum, therefore you should print z (and not x), so you should substitute with System.out.println("answer= " +z);
public static addEm (double a, double b) {
Here you missed the return type, and you need to consider also the type of parameters a and b. Since y,x and z are int, it is better if also a and b are int, and therefore specify also the return type as int:
public static int addEm (int a, int b) {
Or you can declare everything (y,x,z,a,b and return type) as a double: the important here is that they should be all of the same type. Moreover you miss also the return statement of the function addEm, that summarizing becomes:
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
And finally also the function
public static void Nine(String[] args)
it is not right named for an entry point: its names should be main.
So in conclusion, if you apply all the fix (by modifying as less as possible your original code) a code that compile, run and works following some 'logic' is:
class Nine {
public static void main(String[] args) {
int x, y, z;
y = 3;
x = 7;
z = addEm(y, x);
System.out.println("answer= " + z);
}
public static int addEm(int a, int b) {
int c;
c = a + b;
return (c);
}
}
Man, this is a very basic java lesson:
every prog need an entry point, which is in java:
public static void main(String args[]){}
And then your code will execute.
You're passing arguments a and b to addEm, but those variables aren't initialized. I'm expecting you wanted to pass x and y instead.
class Nine
{
public static void Nine(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " +x);
}
public static addEm (double a, double b)
{
int c;
c=a+b;
}
}
Your code will not work because your addEm method does not have any return type. In addition, the method you wrote takes Double params but while using you are trying to pass int to it. You also do not have any main method. I am assuming you misspelled or misunderstood the main method so below is the code which should work
class Nine
{
public static void Main(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " + x);
}
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
}