I wrote this in my main because I want to call this method bla_methods from my main.
I wrote an method called bla_methods already. The main isn't letting me call my bla_method.
Sorry, I should have clarified myself. But, thanks everyone!
bla_methods (one_data[], two_datas[], length);
then I get this error for one_data[] and two_datas[]
<<gradeabc.java:45: error: '.class' expected >>
You declare methods within your class, but outside of other methods (unless it's a method in an inner class)...
public static void bla_methods (String[] one_data, int[] two_datas, int length) {
// do something.
}
public static void main(String[] args) {
// ...
}
Should work.
No, Java doesn't allow you to define methods inside of other methods - main included.
Just put the method inside the same class as main.
You didn't specified the data type of the array, that's why you got the error.
private static void bla_methods (DATA_TYPE[] one_data, DATA_TYPE[] two_data, int length){
//your code
}
public static void main(String[] args){
bla_methods(a, b, c);
//
}
the "DATA_TYPE" int bla_method can be any data type. such as int, float etc. it can also be an Object of a class, such String...
Methods cannot be nested.
You can only create a method directly inside a class.
You have to understand a few things to be able to work in Java:
Everything, methods and members are parts of either a class or an object. By inside I mean they are inside their block, marked by {}.
A class is declared by the class keyword followed by the name of the class. Example: class foo {/*...*/}
An object is an instance of a class, which is usually instantiated by the new keyword. Example Foo bar = new Foo();
Members can be members of an object or a class (if they are static). They have a type and they might have an initial value. Example: Foo bar = new Foo();
Methods can be methods of an object or a class (if they are static). Methods have a return type, a parameter list and a block of their own, where the exact receipt/algorithm of the method is defined. Example: static public void main(String args[]){/*...*/}
Members represent the state of the object/class where they are applicable.
Methods represent the ability of the object/class where they are applicable.
A parameter is inside the brackets of a method, they have a type as well. Example: public static void main(String args[]){/*...*/}
A variable behaves almost like a member, but it is defined inside a method and is applicable only there.
I think you should read a tutorial, for example this one.
So, you did not associate a type to your variables/parameters and I doubt that your method was defined correctly.
Related
I don't understand why methods on arrays, in Java, have to be static. Static methods can only be used on static variables right? So this would mean arrays are static variables, variables shared by a class? But what class would this be?
Can someone help me understand this?
Edit: to be more specific, I am creating methods to act on arrays but if I just write "public int[] expandArr(int[]a, int v)" and I try to use this method in the main method, I get an error saying I can't make a static reference to a non-static method. When I write "public static int[] expandArr(int[]a, int v)" it works then.
I understand you cannot change the size of an array, the method I wrote makes a new array with increased size and copies the first one into it.
Thank you.
You say you tried to write this:
public int[] expandArr(int[]a, int v)
The thing is, you had to write it in some class, since you can't just have free-floating methods in your program. Therefore, it must operate on a instance of the class. For example:
public class MyProgram {
public int[] expandArr(int[]a, int v) { ... }
public static void main(String[] args) { ... }
}
expandArr requires an instance of MyProgram, since you didn't declare it to be static. And that has nothing to do with arrays. It would be the same if you wrote
public class MyProgram {
public String expandString(String s, int v) { ... }
public static void main(String[] args) {
String s = expandString(args[0], 1); // ILLEGAL
String s2 = args[0].expandString(1); // ILLEGAL
}
}
Although the first parameter of expandString is a String, this actually operates on a MyProgram, and you cannot use expandString without an instance of MyProgram to operate on. Making it static means that you can (the first use of expandString in my example would become legal.)
In general, you can't add methods to a class without modifying the source of that class. If you want to write a new method that does something with objects of a certain class C, and you can't modify class C (perhaps because it's in the Java library or someone else's library), then you'll need to put the method in some other class C2, and most of the time you will need to make the method static since it doesn't involve objects of class C2.
You can't call a non-static method from a static method unless you first instantiate the an object of the class.
e.g.
In class Whatever...
public boolean ok() {
return true;
}
public static void main(String[] args) {
Whatever w = new Whatever();
System.out.println(w.ok());
}
You cant call a non static method from a static context. A static method belongs to the class, non static or instance methods are copied to each instance of the class (they each have their own). If I have 10 instances of class A, and class A has a static method, which all of them share, then I try to invoke a non static method in class A from class A's static method, which instance of class A gets its method invoked? The behavior is undefined.
The question really has nothing to do with arrays.
This question is related: Can't call non static method
I think what you're referring to is the fact that you can't extend an array class and hence can't add a method to it:
// No way to do this
int[] array;
array.myMethod();
This means your only option is to make a static helper method somewhere:
// So you have to do this
int[] array;
Utils.myMethod(array);
class Utils {
static void myMethod(int[] array) {
...
}
}
An example of this is the Arrays class, which has lots of static methods for operating on arrays. Conceptually it would be clearer if these methods could be added to the array classes, but you can't do that in Java (you can in other languages like Javascript).
That is why we use other classes like the ArrayList to make them grow dynamically in size. At the core of an arraylist you will simply find an array that is renewed in size whenever the class figures out it necessary. If I'm understanding your question right.
Complete beginner here. I am trying to call a method from a class to run in the main class. But I cannot seem to figure out why it is not work. Here is how I am calling the class
public static void main(String[] args) {
findMP3Tracks FT = new findMP3Tracks();
FT.findMP3();
This is the class method i want to call
public static List<String> findMP3(String p)
{
List<String> foundMP3Tracks = new ArrayList<>();
try (DirectoryStream<Path> folderContents = Files.newDirectoryStream(Paths.get(p)))
{
//Look for
for (Path folderItem: folderContents){
if(Files.isDirectory(folderItem, LinkOption.NOFOLLOW_LINKS)) {
foundMP3Tracks.addAll(findMP3(folderItem.toString()));
}
else if(isValidMP3(folderItem.toString())) {
foundMP3Tracks.add(folderItem.toString());
}
}
}
Assuming findMP3(String) is a method inside the class findMP3Tracks (I would recommend you to follow Java conventions for class names), you may call it in the main as:
public static void main(String[] args) {
...
List<String> result = findMP3Tracks.findMP3("Name of MP3");
}
You may use the name of the class findMP3Tracks to invoke the method findMP3, because it is declared as static. So it's not necessary to create an instance to call it. (Of course you may want to create instances of that class for other operations)
Also, since findMP3 is returning a List<String>, you may want to store it in a variable (In the example result)
First, you don't need instances to call a static method, so this line
findMP3Tracks FT = new findMP3Tracks();
is useless, you can remove it.
Use (for example)
findMP3Tracks.findMP3("Some MP3 name");
Also you need to get the returned value, so it should be:
final List<String> mp3List = findMP3Tracks.findMP3("Some MP3 name");
PS: in Java by convention class names start with uppercase, I suggest you change findMP3Tracks class name to FindMP3Tracks
You've declared the method as
public static List<String> findMP3(String p)
which means (among other things) that when you call it, you're going to pass in a String argument. But you wrote
FT.findMP3();
where you're not passing in any argument at all. Something like
FT.findMP3("Hello");
would compile; or if you had a String variable whose value was the name of the MP3 that you wanted to search for, you could use that too. But the call to any method MUST match the declaration of that method.
The method findMP3 is declared as static. Static variables and methods are members of the class.
You can invoke it directly using the classname. So, it should be findMP3Tracks.findMP3()
Also, a word about the static method. If you do know that the behaviour of the method isnt different for different instances, then you might/can declare it as static. Although, it is a design decision that you would make. If it does behave differently based on the passed in parameter, it is better off to have a method which isnt static.
in java we are able to "invoke a static method with class name" and also "invoke a static method with an object"
what is the difference between "invoking a static method with class name" and "invoking a static method with an object" in java?
There is no difference but the recommendation is to call the static methods in a staic way i.e. using the ClassName. Generally static analayzers will report an error if you don't do so.
An important thing to understand here is that static method are stateless and hence calling them with an instance is confusing for someone reading your code. Because no matter what instance you use to call the static method, result will remain the same. This is because a static method belongs to a class but not to an object.
Internally, new ClassName().staticMethod(); is considered as ClassName.staticMethod(). So there is no difference. It just causes confusion.
Consider an example
public class StaticDemo {
static int staticVar = 10;
public static void main(String [] args){
System.out.println(new StaticDemo().staticVar);
System.out.println(StaticDemo.staticVar);
}
}
This outputs
10
10
`
even if you write new StaticDemo().staticVar, it will be considered as StaticDemo.staticVar. So there is no difference at all and always use the Class notation to avoid confusion.
There is no difference at all. But since static methods are at the class level, you can access them using the class name. Though invoking them using class object is possible, it creates a confusion. Why would you like to invoke them for every object if its value is going to be the same?
No, there is none. Apart from possible confusion... A reader of such code cannot reliably tell static from non static members/methods apart if you use an instance to access them:
public class X
{
public static final String foo = "foo";
public static String bar() { return "bar"; }
public static void main(final String... args)
{
final X x = new X();
System.out.println(X.foo); // "foo"
System.out.println(x.foo); // "foo" too -- same reference
System.out.println(X.bar()); // "bar"
System.out.println(x.bar()); // "bar" too -- same reference
}
}
As this is confusing, it is generally preferred to use the class to refer to such members/methods.
Static methods do NOT operate on a class. They are just bound to class instead of to member of that class. This means that they don't have access to any non static members of the class. Other than that, they are not very different than the non-static methods.
In SCJP guide book. having a example as following:
class Frog {
static int frogCount = 0; // Declare and initialize
// static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
}
class TestFrog {
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.print("frogCount:"+Frog.frogCount); //Access
// static variable
}
}
But just to make it really confusing, the Java language also allows
you to use an object reference variable to access a static member
Frog f = new Frog();
int frogs = f.frogCount; // Access static variable
// FrogCount using f
In the preceding code, we instantiate a Frog, assign the new Frog
object to the reference variable f, and then use the f reference to
invoke a staticmethod! But even though we are using a specific Frog
instance to access the staticmethod, the rules haven't changed. This
is merely a syntax trick to let you use an object reference variable
(but not the object it refers to) to get to a staticmethod or
variable, but the staticmember is still unaware of the particular
instance used to invoke the staticmember. In the Frog example, the
compiler knows that the reference variable f is of type Frog, and so
the Frog class staticmethod is run with no awareness or concern for
the Frog instance at the other end of the f reference. In other
words, the compiler cares only that reference variable f is declared
as type Frog.
I hope this will help you
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should a method be static?
Usually when writing a static method for a class, the method can be accessed using ClassName.methodName. What is the purpose of using 'static' in this simple example and why should/should not use it here? also does private static defeat the purpose of using static?
public class SimpleTest {
public static void main(String[] args) {
System.out.println("Printing...");
// Invoke the test1 method - no ClassName.methodName needed but works fine?
test1(5);
}
public static void test1(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
public void test2(int n1) {
System.out.println("Number: " + n1.toString());
}
//versus
private static void test3(int n1) {
System.out.println("Number: " + n1.toString());
}
}
I had a look at a few tutorials. E.g. http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
My understanding of it is that instead of creating an instance of a class to use that method, you can just use the class name - saves memory in that certain situations there is no point in constructing an object every time to use a particular method.
The purpose of the static keyword is to be able to use a member without creating an instance of the class.
This is what happens here; all the methods (including the private ones) are invoked without creating an instance of SimpleTest.
In this Example,Static is used to directly to access the methods.A private static method defeats the purpose of "Data hiding".
Your main can directly call test1 method as it is also Static,it dosn't require any object to communicate.Main cannot refer non-static members,or any other non-static member cannot refer static member.
"non-static members cannot be referred from a static context"
You can refer This thread for more info about Static members.
static means that the function doesn't require an instance of the class to be called. Instead of:
SimpleTest st = new SimpleTest();
st.test2(5);
you can call:
SimpleTest.test1(5);
You can read more about static methods in this article.
A question about private static has already been asked here. The important part to take away is this:
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state? -eljenso
static means that the method is not associated with an instance of the class.
It is orthogonal to public/protected/private, which determine the accessibility of the method.
Calling test1 from main in your example works without using the class name because test1 is a static method in the same class as main. If you wanted to call test2 from main, you would need to instantiate an object of that class first because it is not a static method.
A static method does not need to be qualified with a class name when that method is in the same class.
That a method is private (static or not) simply means it can't be accessed from another class.
An instance method (test2 in your example) can only be called on an instance of a class, i.e:
new SimpleTest().test2(5);
Since main is a static method, if you want to call a method of the class without having to instantiate it, you need to make those methods also static.
In regards to making a private method static, it has more readability character than other. There isn't really that much of a difference behind the hoods.
You put in static methods all the computations which are not related to a specific instance of your class.
About the visibility, public static is used when you want to export the functionality, while private static is intended for instance-independent but internal use.
For instance, suppose that you want to assign an unique identifier to each instance of your class. The counter which gives you the next id isn't related to any specific instance, and you also don't want external code to modify it. So you can do something like:
class Foo {
private static int nextId = 0;
private static int getNext () {
return nextId ++;
}
public final int id;
public Foo () {
id = getNext(); // Equivalent: Foo.getNext()
}
}
If in this case you want also to know, from outside the class, how many instances have been created, you can add the following method:
public static int getInstancesCount () {
return nextId;
}
About the ClassName.methodName syntax: it is useful because it specifies the name of the class which provides the static method. If you need to call the method from inside the class you can neglect the first part, as the name methodName would be the closest in terms of namespace.
To use a contrived example in Java, here's the code:
enum Commands{
Save("S");
File("F");
private String shortCut;
private Commands(String shortCut){ this.shortCut = shortCut; }
public String getShortCut(){ return shortCut; }
}
I have the following test/driver code:
public static void main(String args[]){
System.out.println(Commands.Save.getShortCut());
}
The question is:
In Java, when is the constructor for an enumerated constant invoked? In the above example, I am only using the Save enumerated constant. Does this mean that the constructor is called once to create Save only? Or will both Save and File be constructed together regardless?
The constructors are invoked when the enum class is initialized. Each constructor will be invoked, in member declaration order, regardless of which members are actually referenced and used.
Much like the static() {...} method, the constructors are invoked when the Enum class is first initialized. All instances of the Enum are created before any may be used.
public static void main(String args[]){
System.out.println(Commands.Save.getShortCut());
}
In this sample, the ctor for both Save and File will have completed before Save.getShortCut() is invoked.
They are invoked sequentially, as declared in the code.
Both will be created at the class initialization time as others said. I like to point out that this is done before any static initializers so you can use these enums in static block.