Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Beginning Java and the fly likes static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "static methods" Watch "static methods" New topic

static methods

kalai sundar
Ranch Hand

Joined: May 25, 2005
Posts: 69
In my program i use static variables.For eg if the static variable is public static int i =10; i use this variable with many instances,so if make any change in one instance , that changes will be reflected in other instance too, here is the sample code

public class sample1 {
public static int i = 10;

public sample1() {

public static void main(String[] args) {
sample1 s = new sample1();
sample1 s1 = new sample1();
System.out.println("The value of s1 is"+s1.i);
System.out.println("The value of s is"+s.i);
s.i = 19;
System.out.println("The value of s"+s.i);
System.out.println("The value of s1"+s1.i);



in same way i want to do for static methods, how i can do, vat will be use of using static methods.

Steve Simon Joseph Fernandez
Ranch Hand

Joined: Jul 17, 2005
Posts: 35

You wouldn't want to use static methods for the same reason that you use static variables. Anyways, static methods are used when you need utility functions or helper methods - for e.g. Integer.parseInt() - the main attraction of these methods, as you already have noticed, is that you can use them without instantiating an object of that class. And to code them, you don't have to do anything special - just include the static keyword in the method header.

Rohit Kharat

Joined: Jul 20, 2005
Posts: 3
i would like to share an example form application I am developing.
Here we are using static variables and directly accessing them using class name ClassName.staticVarName

In this case we are using static variables to declare constants.

public class MyConstants{
public static final String ADDRESS = "address";

[note: final variable's value can't be changed once assigned.]

Similarly we will have many other constats we need to use.

You can get the constant value as MyConstants.ADDRESS
Rohit Kharat

Joined: Jul 20, 2005
Posts: 3
Also additional info abt static variables.

there are 4 parts sections in memory
| Stack Area | <-local variables
| Heap Area | <-dynamically allocated stuff
| Data section | <-global/ STATIC data
| Code section |

Data section contains all our commonly shared data. i.e global variables & static variables. So static variables act like global variables.
I agree. Here's the link:
subject: static methods
It's not a secret anymore!