1

I have tried it a permute method like in c(procedure) but it did't work also i don't understand why it must be static

  public class permute {
     public static void permute(int a,int b){
    int x=a;
    a=b;
    b=x;
}
    public static void main(String[] args){
    int a=2;int b=4;
    System.out.println("a= "+a+"b= "+b);
    permute(a,b);
    System.out.println("a= "+a+"b= "+b);


}

}

Majdi Chebil
  • 303
  • 3
  • 6

1 Answers1

-1

Your 'permute' method won't work in C either. Both C and Java are pass by value. You are only swapping the variables locally in that method. The swapped values are not reflected in the caller's copy of those variables.

For C, use pointers.

void permute(int * a, int * b).

For Java, use Integer objects instead of primitive int.

public static void permute(Integer a, Integer b)

Finally, if you don't want this method to be declared static in Java, you need to create an instance of your class and call the method on that object. You can't call a non-static method in a static context.

VHS
  • 9,534
  • 3
  • 19
  • 43
  • @MajdiChebil, if my answer helped, please do not forget to upvote it and mark it correct. – VHS Apr 08 '19 at 20:48
  • Just i would like to understand more why it's not possible to call a non static method in static contest – Majdi Chebil Apr 09 '19 at 11:26
  • @MajdiChebil ,that's by OOP design for Java. – VHS Apr 09 '19 at 17:45
  • Sorry , but it didn't work the permute method : public class permute { public static void permute(Integer a,Integer b){ int x=a; a=b; b=x; } public static void main(String[] args){ int a=2;int b=4; System.out.println("a= "+a+"b= "+b); permute(a,b); System.out.println("a= "+a+"b= "+b); } }a= 2 b= 4 a= 2 b= 4 – Majdi Chebil Apr 09 '19 at 19:01
  • In your `main` method, you need to declare a and b as `Integer`, not `int`. – VHS Apr 09 '19 at 20:06