Calling method in main method - java

I want this code to generate a random number between one and five and then, using that number, chose a symbol out of my arraylist and print it. Whenever I try to call the printSymbol() method it tells me to change it and the arraylist to static. When I do it gives me two errors on the method call line in my main method and the line where it says that String y = list.get(x); I want to know how to make it so I can call this method and get it to print String y for me.
import java.util.*;
import java.lang.Math;
public class study {
public static void main(String[] args) {
printSymbol();
}
ArrayList<String> list = new ArrayList<String>();
public void addSymbols(){
list.add("あ");
list.add("い");
list.add("う");
list.add("え");
list.add("お");
}
public String printSymbol(){
int x=(int) Math.floor(Math.random()*5)+1;
String y = list.get(x);
return y;
}
}

You're messing up by mixing static and non-static contexts.
The printSymbol() method is part of the class study. (Use Study instead, that's the proper convention. For more information on these conventions, look here).
The main method is in a static context. This means that you need to make an object of the class Study and then call the printSymbol method on that object.
public static void main(String[] args)
{
Study study = new Study(); // create a new object of the class Study
study.printSymbol(); // call the printSymbol method on this object
}
You could also make the printSymbol() method and the ArrayList static, but that is bad practice in Java, which is an object oriented language.

Your main method is static, which means it can be called without creating an object. Main methods always have to be static, because on startup of the program you don't have an object yet.
The thing about static methods is, you can only access other static members from it unless you create an object you work with.
You have two possible solutions:
Make the other members static, which I wouldn't recommend as you are already using a field, or use an object:
public static void main(String[] args) {
study myObject = new study();
study.printSymbol();
}

import java.util.*;
import java.lang.Math;
public class study {
public static void main(String[] args) {
study newStudy = new study();
newStudy.addSymbols();
newStudy.printSymbol();
}
ArrayList<String> list = new ArrayList<String>();
public void addSymbols(){
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
}
public String printSymbol(){
int x=(int) Math.floor(Math.random()*4)+1;
String y = list.get(x);
return y;
}
}
Your random was also wrong, its needs to be Math.random()*4.
I just replaced your symbols with ASCII for my machine to understand.

Like every one suggested, avoid static method and create an object then call your methods.
And dont forget to add the symbols to the arraylist, you can do it in the constructor or in the main method after creating the object and before calling printSymbol()
public static void main(String[] args) {
new study().printSymbol();
}
public study() {
// add symbols to the array list
addSymbols();
}
Or
public static void main(String[] args) {
study s = new study();
// add symbols to the array list
s.addSymbols();
s.printSymbol();
}
Also by convention Classnames should start with an upser case letter.

main is a static method and from it you may either call static methods, or you have to create an instance of the class and call instance methods of it. Also in your case list is an instance variable and thus it can not be accessed from static methods.
I believe the best option for you is to do something like:
public static void main(String[] args) {
study s = new study();
s.printSymbol();
}
Also please use capital names for classes.

public `static` String printSymbol(){
public `static` void addSymbols(){
The main method is in static context, so all other method its calling needs to be as well.

Related

what is the name of such invocation "variable.methodName(data);" ? [duplicate]

See the code snippets below:
Code 1
public class A {
static int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
short s = 9;
System.out.println(add(s, 6));
}
}
Code 2
public class A {
int add(int i, int j) {
return(i + j);
}
}
public class B extends A {
public static void main(String args[]) {
A a = new A();
short s = 9;
System.out.println(a.add(s, 6));
}
}
What is the difference between these code snippets? Both output 15 as an answer.
A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.
Example:
class Foo {
int i;
public Foo(int i) {
this.i = i;
}
public static String method1() {
return "An example string that doesn't depend on i (an instance variable)";
}
public int method2() {
return this.i + 1; // Depends on i
}
}
You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();
Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:
MyClass.myMethod();
this.myMethod();
myMethod();
Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:
MyClass boston = new MyClassConstructor();
boston.myMethod("bostonURL");
MyClass miami = new MyClassConstructor();
miami.myMethod("miamiURL");
MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.
If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.
Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();
A static method belongs to the class
and a non-static method belongs to an
object of a class. That is, a
non-static method can only be called
on an object of a class that it
belongs to. A static method can
however be called both on the class as
well as an object of the class. A
static method can access only static
members. A non-static method can
access both static and non-static
members because at the time when the
static method is called, the class
might not be instantiated (if it is
called on the class itself). In the
other case, a non-static method can
only be called when the class has
already been instantiated. A static
method is shared by all instances of
the class. These are some of the basic
differences. I would also like to
point out an often ignored difference
in this context. Whenever a method is
called in C++/Java/C#, an implicit
argument (the 'this' reference) is
passed along with/without the other
parameters. In case of a static method
call, the 'this' reference is not
passed as static methods belong to a
class and hence do not have the 'this'
reference.
Reference:Static Vs Non-Static methods
Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.
A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.
In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.
Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -
A static method belongs to the class and a non-static method belongs to an object of a class.
I am giving one example how it creates difference between outputs.
public class DifferenceBetweenStaticAndNonStatic {
static int count = 0;
private int count1 = 0;
public DifferenceBetweenStaticAndNonStatic(){
count1 = count1+1;
}
public int getCount1() {
return count1;
}
public void setCount1(int count1) {
this.count1 = count1;
}
public static int countStaticPosition() {
count = count+1;
return count;
/*
* one can not use non static variables in static method.so if we will
* return count1 it will give compilation error. return count1;
*/
}
}
public class StaticNonStaticCheck {
public static void main(String[] args){
for(int i=0;i<4;i++) {
DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
System.out.println("static count position is " +p.getCount1());
System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());
System.out.println("next case: ");
System.out.println(" ");
}
}
}
Now output will be:::
static count position is 0
static count position is 1
static count position is 1
next case:
static count position is 1
static count position is 1
static count position is 2
next case:
static count position is 2
static count position is 1
static count position is 3
next case:
If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
Basic difference is non static members are declared with out using the keyword 'static'
All the static members (both variables and methods) are referred with the help of class name.
Hence the static members of class are also called as class reference members or class members..
In order to access the non static members of a class we should create reference variable .
reference variable store an object..
Simply put, from the point of view of the user, a static method either uses no variables at all or all of the variables it uses are local to the method or they are static fields. Defining a method as static gives a slight performance benefit.
Another scenario for Static method.
Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructor and so the static method.
Here, we have private constructor and using static method we are creating a object.
Ex::
public class Demo {
private static Demo obj = null;
private Demo() {
}
public static Demo createObj() {
if(obj == null) {
obj = new Demo();
}
return obj;
}
}
Demo obj1 = Demo.createObj();
Here, Only 1 instance will be alive at a time.
- First we must know that the diff bet static and non static methods
is differ from static and non static variables :
- this code explain static method - non static method and what is the diff
public class MyClass {
static {
System.out.println("this is static routine ... ");
}
public static void foo(){
System.out.println("this is static method ");
}
public void blabla(){
System.out.println("this is non static method ");
}
public static void main(String[] args) {
/* ***************************************************************************
* 1- in static method you can implement the method inside its class like : *
* you don't have to make an object of this class to implement this method *
* MyClass.foo(); // this is correct *
* MyClass.blabla(); // this is not correct because any non static *
* method you must make an object from the class to access it like this : *
* MyClass m = new MyClass(); *
* m.blabla(); *
* ***************************************************************************/
// access static method without make an object
MyClass.foo();
MyClass m = new MyClass();
// access non static method via make object
m.blabla();
/*
access static method make a warning but the code run ok
because you don't have to make an object from MyClass
you can easily call it MyClass.foo();
*/
m.foo();
}
}
/* output of the code */
/*
this is static routine ...
this is static method
this is non static method
this is static method
*/
- this code explain static method - non static Variables and what is the diff
public class Myclass2 {
// you can declare static variable here :
// or you can write int callCount = 0;
// make the same thing
//static int callCount = 0; = int callCount = 0;
static int callCount = 0;
public void method() {
/*********************************************************************
Can i declare a static variable inside static member function in Java?
- no you can't
static int callCount = 0; // error
***********************************************************************/
/* static variable */
callCount++;
System.out.println("Calls in method (1) : " + callCount);
}
public void method2() {
int callCount2 = 0 ;
/* non static variable */
callCount2++;
System.out.println("Calls in method (2) : " + callCount2);
}
public static void main(String[] args) {
Myclass2 m = new Myclass2();
/* method (1) calls */
m.method();
m.method();
m.method();
/* method (2) calls */
m.method2();
m.method2();
m.method2();
}
}
// output
// Calls in method (1) : 1
// Calls in method (1) : 2
// Calls in method (1) : 3
// Calls in method (2) : 1
// Calls in method (2) : 1
// Calls in method (2) : 1
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.
i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.
Notice that static vars can also be used to share information across all instances

java: Access objects in different methods

How can I access objects created in one method in other methods?
I want to do this so that I don't have create the same object over and over again every time I create a new method, and want to use that object within it. This is the class I am working on:
import BrandPhone.*;
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
}
}
If I try and access the object color in another new method like the method initialise seen below, I get an error saying "cannot find symbol":
import BrandPhone.*;
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
}
public void initialise() {
color.setNum(120); // This gives an error
}
}
To try and solve this issue, I decided to try and declare the object names as class variables at the beginning of the class, outside of any method. This produces errors saying "non- static variable ('object name') cannot be references from a static context".
import BrandPhone.*;
public class Test {
Phone myPhone;
Color color;
public static void main(String[] args) {
// Creating the object.
myPhone = new Phone(); // Produces error.
//Creating another object.
color = myPhone.getColor(); // Produces error.
}
public void initialise() {
color.setNum(120);
}
}
To attempt to solve this issue, I changed the method so that instead of public static void main(String[] args) {...} I made it public void newObjects() {...}. This produces yet another error when I try to run it, saying "Class "Assignment.Test" does not have a main method."
I'm very new to Java, so I'm not sure how to tackle this- do all classes have to have a main method in the form of public static void main(String[] args) {...}? If so, could I not just start with a main method and leave it empty, and then continue on to make new methods?
Im not fully sure what your are trying to do. But color.setNum(120) should work if you do it after you declared and initialised color.
Color color = myPhone.getColor();
color.setNum(120);
You should also provide your Phone and Color class files, to provide an encapsulated look of your project. However, based on your main; the following will work. If you make a static call from the the main() the other method should also be static if also in the Test class. Instantiate your object, Color, and then make your method call to your setter method; color.setNum(120);
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
color.setNum(120);
}
You are trying to access the color variable out of scope, you can pass it directly to the method (shown below), set it as a static variable or just call setNum in your main() method.
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
initialise(color);
}
public static void initialise(Color colorToSet) {
colorToSet.setNum(120);
}
}

Java static main also codingBat

public class CodingBat {
public static void main(String[] args) {
System.out.println(sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b) {
return 2*a + 2* b;
} else{
return a + b;
}
}
}
So I made this code, and I'm really confused why it doesn't work unless I write static between the public int sumDouble, because I was practicing on codingBat, and to answer the question they did not involve static, but then how do they test code. Do they use the main? I mean you have to to get the code running right?
So to my knowledge, static means that every object of this class will all contain the same value.But I don't see the relevance of this error.
"Cannot make a static reference to the non-static method"
Thank you for your help :D
and I'm really confused why it doesn't work unless I write static
between the public int sumDouble,
Yes, static is required
Since the main method is static and the sumDouble() method is not, you can't call the method without creating object of class. You cannot refer non-static members from a static method.
Either make method static or create object as below and then access method.
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
Refer here for more
Either you call it through a static context, meaning like you do (or, from another class, by: ClassName.methodName(); )
Or, you have to call it as an instance method, which it is, if you don't declare it static.Then, however, you'll need an instance to call it through:
public static void main(String[] args){
CodingBat cB = new CodingBat();
System.out.println(cB.sumDouble(5,5));
}
You need to create an object in order to use this method
public class CodingBat {
public static void main(String[] args){
CodingBat obj = new CodingBat();
System.out.println(obj.sumDouble(5,5));
}
public int sumDouble(int a, int b) {
if( a ==b){
return 2*a + 2* b;}
else{
return a + b;}
}
}

Can not make static reference to non static method? [duplicate]

This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .

Java - making a static reference to the non-static field list

I've just been experimenting and found that when I run the rolling code, it does not compile and I can't figure out why.
My IDE says 'Cannot make a static reference to the non-static field list', but I don't really understand what or why this is. Also what else does it apply to, i.e.: is it just private variables and or methods too and why?:
public class MyList {
private List list;
public static void main (String[] args) {
list = new LinkedList();
list.add("One");
list.add("Two");
System.out.println(list);
}
}
However, when I change it to the following, it DOES work:
public class MyList {
private List list;
public static void main (String[] args) {
new MyList().exct();
}
public void exct() {
list = new LinkedList();
list.add("One");
list.add("Two");
System.out.println(list);
}
}
static fields are fields that are shared across all instances of the class.
non-static/member fields are specific to an instance of the class.
Example:
public class Car {
static final int tireMax = 4;
int tires;
}
Here it makes sense that any given car can have any number of tires, but the maximum number is the same across all cars.
If we made the tireMax variable changeable, modifying the value would mean that all cars can now have more (or less) tires.
The reason your second example works is that you're retrieving the list of a new MyList instance. In the first case, you are in the static context and not in the context of a specific instance, so the variable list is not accessible.
In the first example you are calling non-static field from static content, which is not possible.
In the second one you are calling ext function on MyList object, which has access to that field.

Categories