Question:
help writing static methods in JAVA?
2009-01-23 06:22:24 UTC
i have to write a program which takes a sentence (string) as input, and prints out various statistics about the sentence. the words counted by the program must only be valid words and it must be written using static methods. if anyone could help me it would be great! i'm only really stuck on the methods part the rest is fine...
Five answers:
deonejuan
2009-01-23 06:45:13 UTC
Just put the keyword "static" in front of your method.



static means the method will not be instintated. In English that means the variables and methods with the static modifyer load first into memory. Just about all the methods of Math are static thus we can use Math.PI, Math.Random().



If a class is not made into an Object with the keyword 'new' then you MUST use static. Many single-class programs with just a main() do not instiantate the class. main() is static for several reasons.



class StaticExample {

public static void main(String [] args) {

String s = "This is a happy string";

}

}

static is not needed because it is inside the main()



class StaticExample1 {

static String s = "This is a lessor string";

public static void main(String[] args) {

System.out.println( s );

}

}



class StaticExample2 {

pubic static void main(String[] args) {

String s = "Happy string";

System.out.println("The length of " + s +" is " + getLen(s) );

}

static private int getLen(String sentence) {

return sentence.length();

}

}

// and finally, as an Object

class StaticExample3 {

String s;



public StaticExample3() {

s = "The last of the happy strings";

showLength();

public static void main( String[] args ) {

new StaticExample3();

}

private void showLength() {

System.out.println("The length of + s + " is " + s.length() );

}

}



the last example makes an Object and that copies all the vars and methods into memory ... except main(); Because we have an Object we have methods, states, and values we can use with dot notation. If we don't have an Object we must use the code as it is read in, thus static. Finally, static is used to indicate a CONSTANT and by coder convention the label-name for a constant is CAPS. ex. static double TRUNICATED_PI = 3.1457;
Max
2009-01-23 06:27:51 UTC
You have to be a little more specific than that.

What kind of data types are you using?

Why do you have to use static methods?

In theory, using static methods in a single class is just like using non-static methods, only you have one instance of them in the whole class.
Jard
2016-02-04 07:56:55 UTC
writing static methods java
2014-11-16 00:59:31 UTC
extremely tough thing. do a search at search engines like google. it could actually help!
2016-02-26 04:08:17 UTC
public static double myAverage(int a,int b) { double c=0; c=(a+b)/2.0; return c; }


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...