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.
Related
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.
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
"Non-static method cannot be referenced from a static context" error
(4 answers)
Closed 9 years ago.
I am trying to calculate the factorial of some integer number (from 0 to 21) by using recursive method. I created a separete method outside the main class. But while printing the factorial in main method it shows an error. How to fix that?
package looping;
import java.io.PrintStream;
public class Looping {
public long fact(long num)
{
if(num<=1)
return 1;
else
return num*fact(num-1);
}
public static void main(String[] args) {
for(int i=0;i<=21;i++){
System.out.printf("%d!=d\n",i,fact(i));
}
}
}
You can not call fact() method without creating object of Looping class.
public static void main(String[] args) {
Looping loop=new Looping()
for(int i=0;i<=21;i++){
System.out.printf("%d!=%d\n",i,loop.fact(i));
}
}
or another way is creating fact() as static method of the class.
public static long fact(long num)
{
if(num<=1)
return 1;
else
return num*fact(num-1);
}
static method only call static methods
so just declare your method static
public static long fact(long num){
}
There are two things you can do.
Either
(1) You can make fact a static method, by putting the word static after public in its declaration.
Or
(2) You can make an object of the Looping class and use it to run the calls to fact, like this.
public static void main(String[] args) {
Looping looping = new Looping();
for(int i=0;i<=21;i++){
System.out.printf("%d!=%d\n", i, looping.fact(i));
}
}
It doesn't make any difference which you choose, because an object of the Looping class doesn't have any fields, which means it doesn't carry around any data with it. It doesn't matter whether you make such an object or not; except for the fact that to use a non-static method, you need an object.
If the object had some fields, then a non-static method would be one that can refer to those fields. But since there are no fields, it makes no difference whether a method is static or not. Therefore, I'd probably choose option (1) here - just make the method static.
However, if, in the future, I want to have variations on the Looping class - that is, subclasses, each with a slightly different implementation of the fact method; then I really need to pick option (2). You can't really have different versions of a static method, within a subclass. When you write a class, you don't really know whether, in the future, you'll want some subclasses of it with slightly different behaviour. These may be subclasses that are going to be used in your program, or they may be things like mock subclasses that you use for testing.
Therefore, as a matter of course, it's always worth avoiding static methods. The only static method that any class ever needs to have is the main method. Any other static methods are likely to cause you problems, as your program grows and you have more and more classes. Static methods can make testing harder. They definitely make it more difficult to implement polymorphism.
I realise that this argument might be beyond where your current Java knowledge is. But it would be worthwhile understanding what's happening in option (2), and getting into the habit of using it, rather than making all of your methods static by default.
/inside the main/
Looping looping = new Looping();
for(int i=0;i<=21;i++){
System.out.printf("%d!=d\n",i,looping.fact(i));
}
static means "does not need to be inside an objekt created with new"
Non-static means you need to be inside such an object. this must be available.
it seems you forgot to create object of class
Looping loop=new Looping();
for(int i=0;i<=21;i++){
System.out.printf("%d!=d\n",i,loop.fact(i));
}
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.
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.
How and where should we use a Static modifier for:
1. Field and
2. Method?
For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()
But why is it a good practice?
Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by #duffymo, not in case of Math class).
UPDATE 1:
So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
There is only one 'copy' of a static field/method.
Static fields/methods cannot access non-static fields/methods.
There are several instances where you would want to make something static.
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
In C#, you can also have static classes which, as you might guess, contain only static members:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
Static uses less memory since it exists only once per Classloader.
To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)
Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:
a static field exists only once. So if you have a simple class (kinda pseudocode):
class Simple {
static int a;
int b;
}
and now you make objects with:
Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);
you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.
You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.
Hope that clears it up a little.
Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.
Most of the posts above are similar, but this post might offer some other insight. When to use Static Modifiers
Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.
For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have
public static int age = 25;
Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.
The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.
You can't instantiate an instance of java.lang.Math; there isn't a public constructor.
Try it:
public class MathTest
{
public static void main(String [] args)
{
Math math = new Math();
System.out.println("math.sqrt(2) = " + math.sqrt(2));
}
}
Here's what you'll get:
C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
Math math = new Math();
^
1 error
Tool completed with exit code 1
class StaticModifier
{
{
System.out.println("Within init block");//third
}
public StaticModifier()
{
System.out.println("Within Constructor");//fourth
}
public static void main(String arr[])
{
System.out.println("Within Main:");//second
//StaticModifier obj=new StaticModifier();
}
static
{
System.out.print("Within static block");//first
}
}