This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
public class Test{
int Trails;
int Days
public static void main (String []args){
if(args.length!=0){
numT = Integer.parseInt(args[0]);
numD = Integer.parseInt(args[1]);
}
Trails=numT;
Days=numD;
}
}
I am trying to get input from the command line and then store them into globals but because they are being done in the main, it wants me to make everything static. Is there another way I should be doing this so that I can then do things with the data?
The main(String[] args) method gets invoked by the JVM "statically" and no actual object gets created. But there isn't any reason against creating an object of the enclosing class as such:
public class Test{
int Trails;
int Days
public static void main (String[] args){
//Create object of type Test
Test t = new Test();
if(args.length!=0){
t.Trails = Integer.parseInt(args[0]);
t.Days = Integer.parseInt(args[1]);
}
}
}
Of course, you can also pass the parameters through a constructor as such:
public class Test{
int Trails;
int Days
public Test(int numT, int numD){
Trails = numT;
Days = numD;
}
public static void main (String[] args){
int numT;
int numD;
if(args.length!=0){
numT = Integer.parseInt(args[0]);
numD = Integer.parseInt(args[1]);
//Create object here
Test t = new Test(numT, numD);
}
}
}
public class Test{
int Trails;
int Days
public static void main (String []args){
if(args.length!=0){
Test test = new Test();
test.Trails= Integer.parseInt(args[0]);
test.Days= Integer.parseInt(args[1]);
}
}
You need an object to work with instance variables
You need to pass them to an object instance that has a constructor or a method that accepts those command line args, then sets its instance variables (say, trails and days) in the constructor or method. The only way to have instance variables is to have an instance of an object. Also, note that you shouldn't capitalize variable names. The convention is to use camelCase with the first letter being lowercase. Class names start with a capital letter.
You're confusing the object notion with the static method concept:
you can have many instances of objects like Test (test2, test2, etc...) each instance will have its own life: in real life the analogy is having many cars (instances) of the class (toyota corolla) for example: all cars are made as described by the model sepecification (the class)
Then you have static methods which are methods that do not use a concrete instance: for example: security ckecks can be a static method: many cars come through a unique security check (that is not a function you can launch from within your car: it's not depending on the instance)
You can use this sample to understand better
public class Test{
int trails;
int days;
public String toString() {
return "trails :"+ trails +", days : "+ days;
}
}
public class Launcher{
public static void main (String []args){
if(args.length!=0){
Test test = new Test();
test.trails= Integer.parseInt(args[0]);
test.days= Integer.parseInt(args[1]);
Test test2 = new Test();
test2.trails= 5;
test2.days= 2;
Command cmd = new Command();
cmd.doSomething(test);
cmd.doSomething(test2);
cmd.doSomething(test);
}
}
}
public class Command {
Test lastTested;
public void doSomething(Test data) {
lastTested = data;
System.out.println( "working with "+ lastTested );
}
}
In the example above, you create an instance of Test that you fill with data.
Then you create an instance of Command, that will save in its state the last executed Test instance, then print the test instance data through its toString() method.
You can create a second instance of Test with other data and pass it to the same cmd (Command instance's method doSomething()). You will then see that the instance that is inside cmd changed, but getting back to your first instance test kept the values as expected
Related
class Test {
int instance_variable ;
static int static_variable = 15;
Test(int abc){
this.instance_variable = abc;
}
static void sget (){
System.out.println(static_variable);
}
void get(){
System.out.println(this.static_variable + " from static ");
System.out.println(instance_variable + " from instance ");
this.static_variable = 90;
}
}
public class ABC {
public static void main(String[] args) {
Test t1 = new Test(10);
Test t2 = new Test(13);
t1.get();
t2.get();
// Output
// 15 from static from obj
// 10 from instance from obj
// 90 from static from obj
// 13 from instance from obj
}
}
As you can see I am able to use this.static_variable.
I have debugged the program and I have seen this doesn't not contain static variable when how it is able to give value of static variable?
It should throw error on this line and I am also able to print a static variable from instance method void get .
There is no point of error in the above code.Static members always have global scope. Passing value to global variable using constructor is nothing wrong at all.Even not refering through this keyword will also yield the same result. 'this' keyword points to instance variable inshort global variable.So. the same definition of this will be maintained for static variable too.
If final variable is initialized in parameterized constructor and data is assigned through constructor args then final value seems to be changing here for every object.
public class Test {
final int k;
Test(int i){ this.k=i;}
public static void main(String[] args) {
for(int i=1;i<=5;i++){
Test t= new Test(i);
System.out.println(t.k);}
}
}
Is the final variable not changable at instance level alone or across all instance it should be constant.?
The final variable is assigned to the instance.
If you create multiple instances of the Test class, they will have their own version of the final variable.
If the final variable is static, it will be only be set once for all the instances.
In your code, you are creating five separate instances of Test and each one has its own instance variable k. To see that these are distinct, you can modify your code to something like this:
public class Test {
final int k;
Test(int i){ this.k=i;}
public static void main(String[] args) {
Test[] tests = new Test[5];
for(int i=0; i<tests.length; i++){
tests[i] = new Test(i+1);
}
for (Test t : tests) {
System.out.println(t.k);
}
}
}
Output:
1
2
3
4
5
"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.
I am facing a roadblock with static methods.
How do I call this method ?
How do Pass the array to another class , so I can edit the array.
Thank you
import java.util.Scanner;
class getArray {
public static void change(String x[]){
Scanner keyboard = new Scanner(System.in);
String dayName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
String[] day = new String[7];
for(int i=0;i<7;i++){
System.out.print(dayName[i]+ " ");
day[i] = keyboard.nextLine();
String str = (dayName[i]+" "+day[i]);
x[i] = str;
}
System.out.println(" ");
for(int j=0;j<7;j++){
System.out.println(x[j]);
}
}
}
class toParse{//would parse the integer out from String[x]
}
class averageTemp{//calculate average of weather
}
public class UniSeven2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
}
As pointed out in the comment, try not using static method. That said:
import java.util.Scanner;
class getArray {
public String change(String x[]){
Scanner keyboard = new Scanner(System.in);
String dayName[] = {"Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
String[] day = new String[7];
String str;
for(int i=0;i<7;i++){
System.out.print(dayName[i]+ " ");
day[i] = keyboard.nextLine();
str = (dayName[i]+" "+day[i]);
x[i] = str;
}
return str;
}
}
You can now access the "modified" String from whatever class you want.
Static methods belong to the Class itself, rather than the instances created by the class. Hence, when calling static method from outside it's class you would call it at the class level.
So, say we have the following..
MyClass {
public static void myStaticMethod(int[] myIntArray) {
//Do something
}
public void myNonStaticMehtod(int[] myIntArray) {
//Do something
}
}
When calling these methods from another class they would be called in the following ways..
Non static method
Because the non static method belongs to a given instance of a class, we must first make an instance of the class and call the method from the instance.
int[] myIntArray = new int[4];
MyClass myClass = new MyClass();
myClass.myNonStaticMethod(myIntArray);
Static method
The Static method belongs to the Class itself and should be called from the class level rather than from an instance of the class.
int[] myIntArray = new int[4];
MyClass.myStaticMethod(myIntArray);
On an unrelated note, the classes you are creating seem that they should be methods instead. Thinking in terms of object oriented programming, a class is the framework for an object, such as a car or person. The methods of that class should represent some action that these objects can perform. for example car.speedUp() speeds up a car, or car.getSpeed(), which gets the current speed of the car.
Hope this was helpful!
Edit: Added arrays as method parameters to help answer your second question.
I have created an example class for my problem below.
public class testClass {
public void testMethod()
{
int testInteger = 5;
}
String testString = "Hello World" + testInteger;
}
I have an integer inside a method and a string that is in no method as seen above. I want the string to get the integer that inside the method but it cannot. Can someone please help explain why that is so and tell me how to make the string the integer. thanks.
For example:
public class testClass {
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
String testString = "Hello World" + testMethod();
}
The integer is a variable inside the method; it has scope of the method which means it can't be accessed from outside the method. The String is a field; it has scope of the class, so it can be accessed from anywhere inside the class including inside the method.
It's basic Java... the testInteger is defined in the method so not available out of the method. You could let the method return an int (being your testInteger) and call that method.
You cannot access a local variable from another method without returning it.
public int testMethod()
{
int testInteger = 5;
return testInteger;
}
Then you can get the value by calling the method (assuming you have an instance of your class in a reference instance),
String testString = "Hello World" + instance.testMethod();
From The Java Tutorials: Variables,
Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.
Lets break down your code to see what is going on
you have such a function
public void testMethod()
{
int testInteger = 5;
}
as you see the return type is void so nothing will be return to anywhere that is called this method.
you have this line after your testMethod
String testString = "Hello World" + testInteger;
first it looks odd why?
because you do not have any main method so I do not know how your code runs
but Imagine you have main method like this
public static void main(String[] args){
String testString = "Hello World" + testInteger;
}
second, you did not even call your testMethod in order to utilize it inside your main method
Issues
1. you did not call your testMethod at all
2. Even if you called it, it would not help you because your return type is void
3. you need main method in order your code to be ran
Remedies
1. change your return type to int
your function signature:
public int testMethod()
2. if you want to use your method, you have to use it in your main method like
for example:
String testString = "Hello World" + testMethod();
3. do not forget to have your main method because it is necessary for your code to be ran
your main method signature is
public static void main(String[] args)