Can I use non static variable in static method in java? - java

"write a program in java that declare a class with one integer data member and two member functions in() and out() to input and output data in data member."
My current code is as follows.
import java.util.Scanner;
public class Operator
{
static int a;
public static void input() {
Scanner in=new Scanner(System.in);
System.out.println("Enter the number:");
a=in.Nextint(); //Here is problem
}
public static void output() {
System.out.println("Number is:" + a);
}
public static void main(String[] args)
{
input();
output();
}
}

You seemed to be confused w.r.t instance variables and local variables.
You can always declare a "local variable" inside a static method.
main() for example is a static function and we always declare variables inside it.
So your creation of a variable "in" of type Scanner inside input() function is perfectly fine.
However, you "cannot" access instance variables and instance methods from static methods.
This post on stack overflow gives a full and complete answer: Can non-static methods modify static variables
As far as your code is concerned, there's a minor error in the code.
The function call to read an integer is "nextInt" and not "Nextint". Java generally uses camel-case to define all its methods. So be careful with the method usage.
The modified code should be this:
class Operator
{
static int a;
public static void input() {
Scanner in=new Scanner(System.in);
System.out.println("Enter the number:");
a=in.nextInt(); //this is nextInt and NOT Nextint
}
public static void output() {
System.out.println("Number is:" + a);
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
input();
output();
}
}

short answer - NO
reason is simple too, that is - it will violates the definition of static i.e. accessible in other class without creating a object(also called instance) of the class.
But, what if we try to do static variable in a non-static method ?
In that case, YES we can do that. Because we have to create a instance (object) of the class to use that method. So, that doesn't violates the definition.

Related

call variable from another class

static int input;
Scanner scn = new Scanner(System.in);
public BusGenerator(Depot depot)
{
this.depot = depot;
}
public int getinput()
{
return input;
}
public void run()
{
System.out.println("Enter Number of Buses:" );
input = scn.nextInt();
}
I have a class called BusGenerator and from here i ask the user about the number of Bus and the system scans it and save it in the variable called "Input".
I have another class called Depot and i want to call the variable "Input" from the Class depot. Is there a way to do that?
As the code is, you can simply use BusGenerator.input in the Depot class to refer to it (as pointed out in the comments).
However, since you've already defined a getter for this variable, it might be more consistent to make input private and refer to it with the public getter/setter methods.

Method help- beginners mistakes

import java.util.*;
public class Problem5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Number();
}
}
public int Number() {
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
I'm having a lot of trouble writing methods in terms of the method signature.
The errors I'm getting typically involve "error: class, interface, or enum expected" on the receiving or returning types.
In this case, the errors are on the returning aspect in the method signature and then later within the method when trying to return an int.
Can anyone could explain what I'm doing wrong?
Normally I would reformat the code in a question, but since half of your problem is caused by the fact that the code is not indented, I will reformat it in my answer.
Here's your code reformatted:
import java.util.*;
public class Problem5
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Number();
}
}
public int Number()
{
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
Now it is easy to see that your Number() method is not inside the class definition.
Also, to call your Number() method from a static method, you need to make your Number() method static also.
And thirdly, you need to pass the scanner variable into your Number() method.
Here's the resulting fix:
import java.util.*;
public class Problem5
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
Number(scanner);
}
public static int Number(Scanner scanner)
{
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
}
Edit Lastly, as #AndyTurner and #javaguy point out, use Java naming standards - variables and method names start with a lower case letter.
You can't write methods outside the class definition, which you could not spot because of poor indentation of the code, so add your Number() method inside your Problem5 class as shown below:
public class Problem5 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Number(scanner);
}
public static int Number(Scanner scanner) {
System.out.println("please enter a one digit number");
int placeholder = scanner.nextInt;
return placholder;
}
}
Also, note that Number() method should be static in order call it from static main() method. Also, you need to pass the scanner object to the Number() method as an argument (shown above).
As a side note, ensure that you follow Java naming standards i.e., method names start with lowercase like number(), but not like Number()

Java Language | Error :- non-static variable scan cannot be referenced from a static context [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
import java.util.Scanner;
class Program
{
public static void main(String[] args)
{
Customer customer = new Customer();
Customer.method();
}
}
class Customer
{
**Scanner scan = new Scanner(System.in);**
public static void method()
{
System.out.print("Name : "); // error **non-static variable scan cannot be referenced from a static context**
String name = scan.nextLine();
}
}
Question :- while creating an Scanner class object outside the method() there is an compilation error :- non-static variable scan cannot be referenced from a static context but when i define it inside the method() it is working without error Why ?
Question :- How to create Scanner class Object that every class can use that single object which is defined at one place in a program. Is this possible ?
If you want to access the Scanner from a static method, Scanner itself has to be defined static. If you want everybody to have access to the Scanner on the Customer class, define it as public static.
You may want to read up on OOP principles and on the static keyword in Java.
For your first question, you are trying to access a non static variable from a static method. Static methods can be called without having an instance of the class. However, non static variable are created per instance of the class.
For your second question, you can either make your scanner static, and if you want it to be used from multiple classes, then make it public.
class Customer
{
static Scanner scan = new Scanner(System.in);
public static void method()
{
System.out.print("Name : ");
String name = scan.nextLine();
}
}
Please check below possible 2 solutions
Solution 1
Scanner scan = new Scanner(System.in);
public void method()
{
System.out.print("Name : ");
String name = scan.nextLine();
}
Solution 2
static Scanner scan = new Scanner(System.in);
public static void method()
{
System.out.print("Name : ");
String name = scan.nextLine();
}

What is RIWO (Read Indirectly Write Out) state

I was reading about the static flow control and came across the RIWO concept. Can someone explain this with simple terminology and perhaps a code sample?
This is related to the error "Illegal forward reference".
Relevant link.
After going through some material and discussing with couple of guys offline i found out the following information.
When a java class is getting executed there are few steps which JVM performs few steps sequentially.
Identify the static members from top to bottom.
Executes static variables assignments and static blocks from top to bottom.
Executes the main method.
During these phases there is one such state called RIWO(Read Indirectly Write Only) for a static variable.
During RIWO a variable cannot be accessed directly with its reference. Instead we need to use an indirect way to call certain variables.
for example:
class Riwo
{
static int i = 10;
static
{
System.out.println(i);
}
}
In the above case the output is 10.
class Riwo {
static int i = 10;
static {
m1();
System.out.println("block1");
}
public static void main(String... args) {
m1();
System.out.println("block main");
}
public static void m1() {
System.out.println(j);
System.out.println("block m1");
}
static int j = 20;
static {
System.out.println("end of code");
}
}
In the above case the output is
0
block m1
block1
end of code
20
block m1
block main
class Riwo
{
static
{
System.out.println(i);
System.out.println("block1");
}
static int i = 10;
public static void main(String... args)
{
System.out.println("main block");
}
}
In the above case we get the following compile time error
Riwo.java:5: illegal forward reference
System.out.println(i);
That means we cannot read a static variable directly when it is in RIWO state.We should call the variable indirectly using a method.
Static variable have two states
RIWO (Read Indirectly Write Only)
RW(Read Write).
RIWO:
Before assigning original value to static variable, variable state is called as RIWO state.
RW:
After assigning original value to static variable, variable state is called as RW state.
Static variable have two type of reading
Direct Read
InDirect Read
Direct Read:
Reading static variable from static block directly is called direct reading.
InDirect Reading:
Reading static variable from static block by calling another method is called indirect reading.
Direct Read Example:
Note: when static variable in RIWO state we cant perform Direct Reading.
class DirectReadingExample{
static {
System.out.println("i==="+i);
}
//i is in RIWO state
static int i=100;
//i is in RW State
}
Output:
compile time Error:illegal forward reference.
InDirect Read Example:
Note: when static variable in RIWO state we can perform InDirect Reading.
class InDirectReadingExample{
static {
m1();
}
static m1(){
System.out.println("i===="+i);
}
//i is in RIWO state
static int i=100;
//i is in RW State
}
Output:
i===0
If a variable is just identified by JVM and the original value is not
yet assigned, then the variable is said to be in the RIWO(Read Indirectly Write Only) state.
The following code is legal:
class Test{
static int num=10;
static
{
System.out.print(num);
System.exit(0);
}
}
output:
10
The code below will produce a compile time error(illegal forward reference)
class Test{
static
{
System.out.print(num);
}
static int num=10;
}
//Produces Compile time error
The code below is legal:
class Test{
static
{
int x=readVar();
}
static int readVar(){
System.out.println(num);
return 0;
}
static int num=10;
static
{
System.out.print(num);
}
}
output:
0
10
In this case, we're not performing a direct read, but rather an indirect
read via a method call. The variable num is identified by JVM - step 1.
Then the default value 0 is assigned to num at that time.

How do I fix the error where I cannot make a static reference to a non-static input field?

I am learning java. I wrote the following code but I am getting this error "cant make a static reference to a non static input field" in Arrayfunction(), when I try to take input. Why is this so and How can I fix it?
import java.util.*;
public class MultidimArrays {
Scanner input= new Scanner(System.in);
public static void main(String args[])
{
int array[][]= new int[2][3];
System.out.println("Passing array to a function");
Arrayfunction(array);
}
public static void Arrayfunction(int array[][])
{
System.out.println("Inside Array function");
for(int i=0;i<array.length;i++)
{
for(int j=0;j<array[i].length;j++)
{
System.out.println("Enter a number");
array[i][j]=input.nextInt();// error
}
}
}
Scanner is not defined as static therefore is in the wrong scope
Either create the Scanner instance inside Arrayfunction or create your scanner with
private static Scanner input= new Scanner(System.in);
A non static reference is tied to the instances of the class. While all static code is tied to the class itself.
You must add the static keyword.
input in your class is an instance variable (since it's not defined as static), which means that each instance of MultidimArrays has one of it's own. static fields or methods (often referred to as "class variables/methods" are shared between all instances of a class.
Since Arrayfunction is static, it cannot refer to instance members of its class - there is no way for it to know which MultidimArray to use. You can either solve this by making input itself static, or by removing the static qualifier from ArrayFunction and create an instance of your class:
public static void main(String args[])
{
int array[][] arr = new int[2][3]; //typo here, variable needs a name :)
System.out.println("Passing array to a function");
MultidimArray ma = new MultidimArray();
ma.Arrayfunction(arr);
}
The reason for this error is: As you have not created the object the non-static variable input does not exist, so you can not use it.
To fix it you can make input as static
static Scanner input= new Scanner(System.in);
either make your Scanner static and use it inside the static methods or create an instance of the class an access scanner from your static method.
static Scanner input= new Scanner(System.in);
public static void Arrayfunction(int array[][])
{
System.out.println("Enter a number");
array[i][j]=input.nextInt();// error
}
OR
Scanner input= new Scanner(System.in);
public static void Arrayfunction(int array[][])
{
System.out.println("Enter a number");
array[i][j]=new MultidimArrays().input.nextInt();// error
}

Categories