Q: How to subtract or add two coordinates I am trying to subtract and add two coordinates of two cities. I would like to do this in a void method. What are your suggestions, how should I do this?
For example:
I would like to subtract coordinates of city1 (x1, y1) with city2(x2, y2) and then call it in main class. So how to do it?
I have written this code below, but it is not working or I don't know how to call it...
Main class:
public class Main {

public static void main(String[] args) {
    
        Coordinates paris = new Coordinates(48.830103, 2.562957);
        Coordinates rioDeJaneiro = new Coordinates(-22.492147, -43.143827);

Coordinates class:
 public class Coordinates {

    private double latitude;
    private double longitude;

    public Coordinates(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    public double getLatitude() {
        return this.latitude;
    }

    public double getLongitude() {
        return this.longitude;
    }

     public void subtract(Coordinates otherCoordinates) {
           new Coordinates(this.latitude - otherCoordinates.getLatitude(),
                            this.longitude - otherCoordinates.getLongitude());
     }


A: your code won't work as you expect. 
Your subtract method supposed to be something like below
public void subtract(Coordinates otherCoordinates) {
                this.latitude = this.latitude- otherCoordinates.getLatitude();
                this.longitude = this.longitude- otherCoordinates.getLongitude();
 }

if latitude and longitude are immutable then
public Coordinates subtract(Coordinates otherCoordinates) {
           return  new Coordinates(this.latitude - otherCoordinates.getLatitude(), 
                                    this.longitude - otherCoordinates.getLongitude());
  }


A: That works.  Another way is:
public static void subtract(Coordinates city1, Coordinates city2, Coordinates result) {
            result.longitude =  city1.getLongitude() - city2.getlongitude());
            result.latitude = city1.getLatitude() - city2.getLatitude();
}


However, your posted solution with a modification is best (as has been pointed out).
public Coordinates subtract(Coordinates otherCoordinates) {
            return new Coordinates(this.latitude - otherCoordinates.getLatitude(), 
                    this.longitude - otherCoordinates.getLongitude());
}


In the later case and presuming that subtract is a method in the Coordinates class you would call it as follows:
Coordinates city1 = new Coordinates(...);
Coordinates city2 = new Coordinates(...);

Coordinates result = city1.subtract(city2);

