error when calling a void function [duplicate] - java

This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Cannot make a static reference to the non-static method
(8 answers)
Closed 8 years ago.
public class Makakiesmarkou {
void swap(int i, int j, int[] arr) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
public void MySort(int[] T)
{
for(int m=0; m<T.length-1; m++)
{
int j=m;
for(int k=m+1; m<T.length-1; k++)
{
if(T[k]<T[j])
j=k;
}
swap(T[j], T[m], T);
}
}
public static void main(String[] args) {
int[] pin= new int[50];
MySort(pin);
System.out.println(Arrays.toString(pin));
}
}
the error when i call MySort in the main class is "non static method MySort[int[]] cannot be referenced from a static context"
what am i doing wrong?

You can either do what Salah said, or you can instantiate your class and call MySort on that:
public static void main(String[] args) {
int[] pin= new int[50];
Makakiesmarkou m = new Makakiesmarkou();
m.MySort(pin);
System.out.println(Arrays.toString(pin));
}

You need to change the declaration of your method to be static like:
public static void MySort(int[] T)
static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().
So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance. So in my opinion only reason which make sense to disallow non static or instance variable inside static context is non existence of instance.
Read more here

Related

Scope of statics and key word "this" in java [duplicate]

This question already has answers here:
Why can't we use 'this' keyword in a static method
(9 answers)
Closed 5 years ago.
I have a question about this fragment of code :
public class Inner {
static int a;
public static void main(String[] args) {
a = 0;
}
public static void g() {
this.a = 0;
}
}
`
Why we can't use "this.a" in static method, but we can use "a" without "this"?
Photo of compilation error: https://www.dropbox.com/s/5q6y3ldsf37p0h3/%D0%97%D0%BD%D1%96%D0%BC%D0%BE%D0%BA%20%D0%B5%D0%BA%D1%80%D0%B0%D0%BD%D0%B0%202017-05-27%2017.28.34.png?dl=0
Because this points to an instance of the class, in the static method you don't have an instance.
The this keyword refers to the current instance of the class. Static member functions do not have a this pointer
You'll notice the definition of a static member is
Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object
Which is why this has nothing to point to.

assigning final keyword using a methofd [duplicate]

This question already has answers here:
How does the "final" keyword in Java work? (I can still modify an object.)
(20 answers)
Why instance variables get initialized before constructor called?
(2 answers)
Closed 6 years ago.
I was just playing with final keyword and observed the below behavior, here i am assigning a final variable using a method and the method is getting called before the constructor
public class Test {
final int i=init(1);
Test(){
System.out.println("Inside Constructor");
}
public int init(int i){
System.out.println("Inside Method");
return i;
}
public static void main(String [] args){
Test i=new Test();
System.out.println(i.i);
}
The Output of the following code is as below
Inside Method
Inside Constructor
1
I know final variable needs to be assigned before the constructors completes and this is what is happening here
What i am unable to find is that how can a method be called before a constructor, i really appreciate any explanation for this
It has nothing to do with finalkeyword. Try below(just removed final ) output will be same. Basically instance variable will be initialized first then constructor is called
public class Test {
int i = init(1);
Test() {
System.out.println("Inside Constructor");
}
public int init(int i) {
System.out.println("Inside Method");
return i;
}
public static void main(String[] args) {
System.out.println("start");
Test i = new Test();
System.out.println(i.i);
}
}
Now why and how instance variable get initialized before constructor see Why instance variables get initialized before constructor called?
If you change your constructor to
Test(){
super();
System.out.println("Inside Constructor");
}
and set a debug point to super(); you will see that the constructor gets called before the init(1);. It just gets called before your System.out.println("Inside Constructor");.
You can also write:
public class Test {
final int i;
Test(){
super();
i = init(1);
System.out.println("Inside Constructor");
}
public int init(int i){
System.out.println("Inside Method");
return i;
}
public static void main(String [] args){
Test i=new Test();
System.out.println(i.i);
}
}
This behaviour in the code is correct and has nothing to do with your analysis about the final key word...
init(1); is a method that is getting called as soon the class is constructing an instance...
there fore all inside the method will be executed even before the constructor...

Whats wrong with the given Java Code [duplicate]

This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 7 years ago.
Code is
public class ctorsandobjs {
private int a;
public int b;
public ctorsandobjs(String arg)
{
System.out.println("I got " + arg);
}
public void add(int a,int b)
{
System.out.println("Addition is " + String.valueOf(a+b));
}
public static void main(String args[])
{
ctorsandobjs c = new ctorsandobjs("You");
c.a = 12;
c.b = 15;
add(c.a,c.b); //compiler shows error here
}
}
I am using Eclipse Luna IDE and JDK 8 ...
can you tell me why compiler is showing error here.....
"Cannot make a static reference to a non static method add(int,int) from the type ctorsandobjs"
I am new to JAVA...
and if possible suggest a solution
add is a non-static method and so you have to invoke it from the object of a class
You have to do:
c.add(c.a, c.b);
You cannot reference non-static members (private int a; public int b) from within a static function.
The add method is not a static method, so you need to call it on an instance of the class ctorsandobjs, for example like this:
c.add(c.a,c.b);

How do I call a non static method from a main method? [duplicate]

This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 7 years ago.
For example, I am trying to do something like this
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
I get an error telling me that I can't reference non-static variables from static enviorments. So if that is true how would I ever utilize a non static method inside of a main?
You can't. A non-static method is one that must be called on an instance of your Test class; create an instance of Test to play with in your main method:
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
arr = new int[] { 1, 2, 3, 4, 5 };
Test test = new Test();
test.arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
You can call non-static method only using a class instance, so you have to create it using new keyword.
public class Something {
public static void main(String args[]) {
Something something = new Something();
something.method1();
new Something().method2();
}
public void method1() {
}
public void method2() {
}
}
new Something().method1() or new Something().method2()
In short you can't. As main is a special case (i.e. entry point of which there an only be one) you can't have anything other than static methods, variables in main.
As per your new example the solution will be:
public class Test {
public static void main(String args[]) {
int[] arr = new int[5];
new Test().arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
Or you can move
int[] arr = new int[5];
to the static section like
public class Test {
static int[] arr;
public static void main(String args[]) {
arr = new int[5];
new Test().arrPrint(arr);
}
public void arrPrint(int[] arr) {
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
}
}
But the second one smells really bad from point of good programming practices
Non static methods need to be invoked on instance of class. To create instance use new keyword like
Test instance = new Test();
now you will be able to invoke methods on instance like
instance.arrPrint(arr);
non-static -> property of the object
static method -> property of the class it-self.
So when there is no static keyword in a method/variable declaration you CAN NOT invoke/make reference to that method/variable without any instance of the class from a static context.
As everyone else suggested create a new instance(new Test()) of the main class in main method and invoke non-static arrPrintmethod.

Why am I receiving a "non static variable" error when calling this Java class? [duplicate]

This question already has answers here:
"non-static variable this cannot be referenced from a static context"?
(7 answers)
Closed 10 years ago.
Receiving error non static variable this cannot be referenced from a static context when compiling the following code; what is the problem?
class bwCalc {
class Tst{
public void tst() {
byte[] data = new byte[1024];//1 kb buffer
int count;
long startedAt = System.currentTimeMillis();
while((System.currentTimeMillis()-startedAt)<1) {
System.out.println("hello\n");
}
}
}
public static void main(String argc[]) {
Tst c = new Tst();
c.tst();
}
}
You need the Outer class instance.
bwCalc b = newbwCalc ();
Tst c = b.new Tst();
c.tst();
Or simply make the inner class static.
The Tst class should be static, because it's not attached to a particular instance of bwCalc.

Categories