Results 1 to 20 of 20
Thread: static keyword
- 01-08-2011, 07:38 PM #1
Member
- Join Date
- Oct 2010
- Posts
- 80
- Rep Power
- 0
static keyword
Hello.
I am new to java. I thought you only put one static statement in the code, "public static void main(String[] args)"
But this code has more than one static statement.
What is the difference between the first 2 static statements & the ""public static void main(String[] args)" statement? Why have both? Why not put the 1st two static statements under the public static... statement? Is this example trying to show me different ways of using static? Thanks In Advance.
Java Code:import java.util.*; public class Ex2_26 //Pg. 75 { // Beginning of class static final int NUMBER = 12; static Scanner console = new Scanner(System.in); public static void main(String[] args) { int firstNum; int secondNum; firstNum = 18; System.out.println("Line 11: firstNum = " + firstNum); // output the value of firstNum System.out.print("Line 12: Enter an integer: "); secondNum = console.nextInt(); // read & store the integer into the variable secondNum System.out.println(); System.out.println("Line 15: secondNum = " + secondNum); firstNum = firstNum + NUMBER + 2 * secondNum; System.out.println("Line 17: The new value of " + "firstNum = " + firstNum); } }
- 01-08-2011, 08:41 PM #2
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
Hey lala, good question. It helps so much to understand the logic doesn't it?
Anyway I am relatively new to understanding this subject so I will do my best.
Perhaps its trying to show you that those must be static in order for the main method to use them. Here is something more simple to look at.
pubNum is not accessible. but the staticNum which is static is.
Also you cannot declare a public private or static variable in the main method.
Why is the main method static? This is probably out of my league right now.Java Code:public class TestClass { static int staticNum = 12; public int publicNum = 24 public static void main(String[] args) { System.out.println(staticNum); [COLOR="Red"]// this works[/COLOR] System.out.println(publicNum); //[COLOR="Red"] this does NOT work. [/COLOR] } }
I tried googling it and found some interesting stuff. It just seems a bit out of my league right now.
- 01-08-2011, 08:52 PM #3
- Join Date
- Jan 2011
- Location
- Richmond, Virginia
- Posts
- 3,069
- Blog Entries
- 3
- Rep Power
- 7
Im also fairly new but here is what I have to say. I believe this is a fairly accurate explanation, although, I am sure a more experienced programmer will explain it better.
Static allows a method to be used by multiple objects.
Lets say you create a static method called Print, which really just allows you to use the words print("some item"); instead of System.out.println("blah"); in order for the static item to be used anywhere it needs to be static.
To create the print method you would create a class called Print which has all the overloaded definitions of print. Normally if you wanted to use a method from a class, you would have to create an instance of that class:
static allows you to use the method without an instance of the object.Java Code:Print x = new Print();
The static keyword is a bit challenging for me to explain, I understand it though.
The €œstatic€ Keyword In Java
This link might be useful to you.
static comes in handy for utility type methods:
You can make a call to that method without creating an object first.Java Code:class RandomClass { public static int mult3(int x, int y, int z) { return x * y * z; } } public class Blah { public static void main(String[] args) { System.out.println(mult3(10, 20, 5); } }Last edited by sunde887; 01-08-2011 at 08:58 PM.
- 01-08-2011, 09:03 PM #4
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
It really can get pretty complex trying to explain static.
When you are dealing with multiple classes and polymorphism, I can see where static really gets useful.
Have you messed with multiple classes and creating objects yet?
If not that's ok. You can practice LOTS of stuff without understanding static. Once you start learning more basics you go back to an area you were having trouble and for some reason it makes more sense.
- 01-08-2011, 11:47 PM #5
Senior Member
- Join Date
- Nov 2010
- Posts
- 210
- Rep Power
- 3
- 01-09-2011, 11:34 PM #6
Member
- Join Date
- Oct 2010
- Posts
- 80
- Rep Power
- 0
static keyword
Thanks for responding AcousticBruce, IronLion, & sunde887.
Great input, & lots for me to gnaw on. :-) As my foray ino the world of Java progresses, I'm sure I will understand better.
Thanks again. :)
- 01-10-2011, 06:57 AM #7
Member
- Join Date
- Jul 2010
- Posts
- 12
- Rep Power
- 0
Hello lala,
' static ' is a keyword used to represent a class level variable or method .
You can access those variables or methods by using your classname directly.
Even you can access them by the object of that class like nonstatic members.
But the main difference between static & non static variables & methods is :
In static mode :
the change updated by one object can reflect to the value which will be used by all rest of the objects...
where as , the nonstatic variables are concern , there is a seperate copy for each and every object...
Here the key points which can helps you a lot ...
1.
From non static block , you can access both static & nonstatic members of the class.
2 . From the static block , you can access only static members of the class.
Here members in the sense , both variables and methods ....
- 01-10-2011, 10:14 PM #8
Member
- Join Date
- Oct 2010
- Posts
- 80
- Rep Power
- 0
static keyword
Thanks AnanthNag.
Soooo, in my example why have both? Why not put the 1st two static statements under the public static... statement?
Thanks
- 01-10-2011, 11:24 PM #9
Member
- Join Date
- Oct 2010
- Posts
- 80
- Rep Power
- 0
static keyword (ahhhhh... i get it)
After more reading & playing, i get "static".
thanks everyone.
- 01-10-2011, 11:43 PM #10
It's no public static statement but a method-declaration (of the main method).
The first two static declarations (and initializations) are global statics. They have (if properly declared private which they are not) global scope in the class (now in the package). Maybe console needs applicationwide scope, than make it public. Other variables, like firstnum, have method-scope. There is no limit on the number of statics as you suggested, but most variables are bound to instances of a class, not to the Class as such, like others explained already.
There are properties of cats in general (mean and furry) and of a particular cat (sweet).
- 01-11-2011, 12:24 AM #11
Member
- Join Date
- Oct 2010
- Posts
- 80
- Rep Power
- 0
(Solved) static keyword
yes, yes Jodokus. I'm grinning from ear to ear, because i understand what u r saying.
The 1st two static static statements will be accessible throughout the program.
Ahhhhh...Understanding. It's a beautiful thing.
- 01-11-2011, 07:45 AM #12
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
Hey Lala,
This might help you see static in a new light.
there is two variable one is static inGarage and one public thisType. Notice how one counts up an inGarage keeps going up while thisType is doesn't. This is because thisType is not static and has a separate thisType varaible for each object. There is only one static variable inGarage that they all share.
I used polymorphism to extend Vehicle class, that is what all the extra classes are for... if you do not understand this topic, do not worry, just worry about the static and public variables at least in this example :)
Vehicle class code.Java Code:public class Main { public static void main(String[] args) { System.out.println(); Vehicle[] vehicle = new Vehicle[5]; vehicle[0] = new Car(); vehicle[1] = new Truck(); vehicle[2] = new Truck(); vehicle[3] = new Truck(); vehicle[4] = new Van(); System.out.println(); System.out.printf("You have %d total vehicles", Vehicle.inGarage); System.out.println(); } }
Java Code:public class Vehicle { public int thisType = 0; // change this from public to static if you want. static int inGarage = 0; // if you change this you get an error because of Vehicle.inGarage in main method. Vehicle() { inGarage++; thisType++; System.out.printf("%d new %s and ", thisType, this.getClass().toString().substring(6)); System.out.printf("%d total", inGarage); System.out.println(); } } class Van extends Vehicle { } class Car extends Vehicle { } class Truck extends Vehicle { }Last edited by AcousticBruce; 01-11-2011 at 02:22 PM.
- 01-11-2011, 10:54 AM #13
@AcousticBruce:
At first I thought your program was wrong (I looked at the code and thought, "this isn't working", only then I saw that you instructed OP to change static for public). Now I think it's confusing because the variable is called "carsInGarage" in stead of "vehiclesOfThisKindInGarage".
@OP:
public static variables have a special role because once initialized they are seen everywhere and always in your program ("always" means: you don't first have to make a new class instance to access the variable).
There are also static methods. They are often little tool-methods found in libraryclasses and just do something irrespective of the containing class, like in the old days before Object Oriented Programming.
- 01-11-2011, 12:33 PM #14
As everyone is going static, I would like to discuss one more use of static keyword.
There are "static" initializers in java, also known as static blocks. They get loaded at the time of class loading and can be used for class initialization stuff as per your need.
The syntax is,
Java Code:static { }
Have a look at the following simple example,
The main method does nothing, but when you run this, the contents inside static block will get executed.Java Code:public class StaticInitializer { public static void main(String args[]) { } static { System.out.println("I will load before anything else in this class."); } }
Just for fun,
GoldestJava Is A Funny Language... Really!.gif)
Click on * and add to member reputation, if you find their advices/solutions effective.
- 01-11-2011, 02:13 PM #15
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
I can see where you are coming from. The main idea was to just count the new Vehicles. When it is static it does just that.
i just edited the code so it makes more sense... please let me know if this is confusing, that is the last thing I wanted to do.
Main
Java Code:public class Main { public static void main(String[] args) { System.out.println(); Vehicle[] vehicle = new Vehicle[5]; vehicle[0] = new Car(); vehicle[1] = new Truck(); vehicle[2] = new Truck(); vehicle[3] = new Truck(); vehicle[4] = new Van(); System.out.println(); System.out.printf("You have %d total vehicles", Vehicle.inGarage); System.out.println(); } }
Vehicle and extending classes
Java Code:public class Vehicle { public int thisType = 0; // change this from public to static. static int inGarage = 0; // Vehicle() { inGarage++; thisType++; System.out.printf("%d new %s and ", thisType, this.getClass().toString().substring(6)); System.out.printf("%d total in garage.", inGarage); System.out.println(); } } class Van extends Vehicle { } class Car extends Vehicle { } class Truck extends Vehicle { }Last edited by AcousticBruce; 01-11-2011 at 02:24 PM.
- 01-11-2011, 05:17 PM #16
Hello AcousticBruce
I'm very confused, but not about your new code, that looks good.
No offence, but I'm confused because your code in the thread upon which I reacted has also changed in the new version. That version had no subclasses and made new Vehicles. I keep rechecking. Have senior members the power to change history in the thread? I really not get it.
- 01-11-2011, 06:12 PM #17
Hello AcousticBruce
Correction, I made a mistake. I see that I too have the power to edit my contributions. (I'm rather new to forums.) But is it the right way to do? Should a thread not mirror the history of discussions, except gross (writing-)errors? No one now knows what I reacted on.
But maybe now I'm going to correct stupid embarrassing remarks I made in other threads ;>)Last edited by Jodokus; 01-11-2011 at 06:21 PM. Reason: tread to thread
- 01-11-2011, 06:19 PM #18
Member
- Join Date
- Oct 2010
- Posts
- 80
- Rep Power
- 0
(solved) static keyword
Acoustic, i will check out your code and let you know the results.
Many thanks
- 01-11-2011, 06:58 PM #19
Senior Member
- Join Date
- Dec 2010
- Location
- Indiana
- Posts
- 202
- Rep Power
- 3
- 01-11-2011, 08:06 PM #20
Similar Threads
-
Can't make static reference to non-static method -> huh?! Simple car prgm
By enerj in forum New To JavaReplies: 7Last Post: 09-24-2010, 05:09 AM -
non-static variable grade cannot be referenced from a static context
By pictianpravin in forum New To JavaReplies: 3Last Post: 02-11-2010, 09:59 AM -
use of static keyword
By venkatallu in forum New To JavaReplies: 2Last Post: 06-25-2009, 07:53 AM -
Error: Non-static method append(char) cannot be referenced from a static context
By paul in forum Advanced JavaReplies: 1Last Post: 08-07-2007, 05:05 AM -
Error: non-static variable height cannot be referenced from a static context at line
By fernando in forum AWT / SwingReplies: 1Last Post: 08-01-2007, 09:25 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks