I am at beginner stage in learning java, I made a program for bubble sort. Code is as follows
package bubblesort;
public class Bubblesort {
public static void main(String[] args) {
int[] arr = new int[] {10,20,40,30,50};
arr = BubbleSort(arr);
for(int i:arr) {
System.out.println(i " ");
}
}
public static int[] BubbleSort(int[] arr) {
int temp;
for(int i = 0;i<arr.length;i ) {
for(int j =i 1;j<arr.length;j ) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
}
My question is as following : "Since a static method can only take static data variables as parameters, then why 'BubbleSort' function in my program is not reporting any error because of arr not being a static variable ?"
CodePudding user response:
Since a static method can only take static data variables as parameters
Incorrect.
A static method can only directly reference other static members, not instance members. This refers to class-level fields, methods, etc.
But any method can accept as a parameter/argument any value you pass to it. And can internally declare and use any local variable it wants.
CodePudding user response:
A static method can only access static members of its containing type. So in your case the BubbleSort method cannot access any instance fields or methods of the BubbleSort class. Arguments and local variables are of course always allowed.
CodePudding user response:
Static methods neither know nor care where the parameters came from in the first place. It doesn't matter that it's a local variable because it has a reference to the array.
What you actually can't do is "directly" refer to instance methods or fields from a static method because, by definition, it needs a specific instance to call those methods on.
