Necessity of static block in Java - java

I found that in Java, there is a feature called static block, which includes code that is executed when a class is first loaded (I don't understand what 'loaded' means, does it mean initialized?). Is there any reason to do the initialization bit inside a static block and not in the constructor? I mean, even the constructor does the same thing, do all the necessary stuff when a class is first initialized. is there anything that the static block accomplishes which a constructor can't?

I first want to highlight one thing thing from your question:
the constructor does the same thing, do all the necessary stuff when a class is first initialized
This is incorrect. A constructor does all the initialization necessary when an instance of a class is created. No constructors execute when the class itself is first loaded into memory and initialized (unless an instance of the class happens to be created as part of the class initialization). This confusion (between initializing a class and initializing instances of the class) is probably why you are questioning the utility of static blocks.
If a class has static members that require complex initialization, a static block is the tool to use. Suppose you need a static map of some kind (the purpose is irrelevant here). You can declare it in-line like this:
public static final Map<String, String> initials = new HashMap<String, String>();
However, if you want to populate it once, you can't do that with an in-line declaration. For that, you need a static block:
public static final Map<String, String> initials = new HashMap<String, String>();
static {
initials.put("AEN", "Alfred E. Newman");
// etc.
}
If you wanted to be even more protective, you can do this:
public static final Map<String, String> initials;
static {
Map<String, String> map = new HashMap<String, String>()
map.put("AEN", "Alfred E. Newman");
// etc.
initials = Collections.unmodifiableMap(map);
}
Note that you cannot initialize initials in-line as an unmodifiable map because then you couldn't populate it! You also cannot do this in a constructor because simply calling one of the modifying methods (put, etc.) will generate an exception.
To be fair, this is not a complete answer to your question. The static block could still be eliminated by using a private static function:
public static final Map<String, String> initials = makeInitials();
private static Map<String, String> makeInitials() {
Map<String, String> map = new HashMap<String, String>()
map.put("AEN", "Alfred E. Newman");
// etc.
return Collections.unmodifiableMap(map);
}
Note, though, that this is not replacing a static block with code in a constructor as you proposed! Also, this won't work if you need to initialize several static fields in an interrelated way.
A case where a static block would be awkward to replace would be a "coordinator" class that needs to initialize several other classes exactly once, especially awkward if it involves dependency injection.
public class Coordinator {
static {
WorkerClass1.init();
WorkerClass2.init(WorkerClass1.someInitializedValue);
// etc.
}
}
Particularly if you don't want to hard-wire any dependence into WorkerClass2 on WorkerClass1, some sort of coordinator code like this is needed. This kind of stuff most definitely does not belong in a constructor.
Note that there is also something called an instance initializer block. It is an anonymous block of code that is run when each instance is created. (The syntax is just like a static block, but without the static keyword.) It is particularly useful for anonymous classes, because they cannot have named constructors. Here's a real-world example. Since (unfathomably) GZIPOutputStream does not have a constructor or any api call with which you can specify a compression level, and the default compression level is none, you need to subclass GZIPOutputStream to get any compression. You can always write an explicit subclass, but it can be more convenient to write an anonymous class:
OutputStream os = . . .;
OutputStream gzos = new GZIPOutputStream(os) {
{
// def is an inherited, protected field that does the actual compression
def = new Deflator(9, true); // maximum compression, no ZLIB header
}
};

Constructor is invoked while creating an instance of the class.
Static block is invoked when a classloader loads this class definition, so that we can initialize static members of this class.
We should not be initializing static members from constructor as they are part of class definition not object

Static initializer will run if we initialize a class, this does not require that we instantiate a class. But the constructor is run only when we make an instance of the class.
For example:
class MyClass
{
static
{
System.out.println("I am static initializer");
}
MyClass()
{
System.out.println("I am constructor");
}
static void staticMethod()
{
System.out.println("I am static method");
}
}
If we run:
MyClass.staticMethod();
Output:
I am static initializer
I am static method
We never created an instance so the constructor is not called, but static initializer is called.
If we make an instance of a class, both static initilizer and the constructor run. No surprises.
MyClass x = new MyClass();
Output:
I am static initializer
I am constructor
Note that if we run:
MyClass x;
Output: (empty)
Declaring variable x does not require MyClass to be initialized, so static initializer does not run.

The static initializer runs when the class is loaded even if you never create any objects of that type.
Not all classes are meant to be instantiated. The constructor might never be called. It might even be private.
You may wish to access static fields of the class before you run a constructor.
The static initializer only runs once when the class is loaded. The constructor is called for each object of that type you instantiate.

You can't initialize static variables with a constructor -- or at least you probably shouldn't, and it won't be particularly useful.
Especially when you're trying to initialize static constants that require significant logic to generate, that really ought to happen in a static block, not a constructor.

They're two separate things. You use a constructor to initialize one instance of a class, the static initialization block initializes static members at the time that the class is loaded.

The static block is reqly useful when you do have to do some action even if no instances is still created. As example, for initializing a static variable with non static value.

static block does different thing than constructor . Basically there sre two different concepts.
static block initializes when class load into memory , it means when JVM read u'r byte code.
Initialization can ne anything , it can be variable initialization or any thing else which should be shared by all objects of that class
whereas constructor initializes variable for that object only .

The static block is useful when you want to initialize static fields.

The static block is useful over constructors when you do have to do some action even if no instances is still created. As example, for initializing a static variable with non static value.

One way you can understand static block is;
It acts as a constructor. however, the difference between the two is
static block instantiates class or static variables while constructor is used to instantiate object variables
Consider the following class
public class Part{
String name;
static String producer;
public Part(String name){
this.name = name;
}
static {
producer = "Boeing";
}
}
objects created from this class will have producer set to Boeing but their name is different depending on the argument passed. for instance
Part engine = new Part("JetEngine");
Part Wheel = new Part("JetWheel");

Initializing static fields in the constructor is a big mistake. Yes, you can initialize static fields in the constructor. However, the static fields will reset their value every time an object is created.
public class StaticExample {
static int myStaticField;
public StaticExample(){
myStaticField = 10;
}
}
public class Solution {
public static void main(String[] args) {
StaticExample obj1 = new StaticExample();
StaticExample.myStaticField+= 80;
// this will print 90
System.out.println(StaticExample.myStaticField);
// creating new object will reset the static field
StaticExample obj2 = new StaticExample();
// this will print 10
System.out.println(StaticExample.myStaticField);
}
}
This is unexpected and unaccepted behavior for a static field. If you now change the initialization step from a constructor to a static block, you will get the correct values.
public class StaticExample {
static int myStaticField;
static {
myStaticField = 10;
}
}
public class Solution {
public static void main(String[] args) {
StaticExample obj1 = new StaticExample();
StaticExample.myStaticField+= 80;
// this will print 90
System.out.println(StaticExample.myStaticField);
// creating new object will NOT reset the static field
StaticExample obj2 = new StaticExample();
// this will print 90
System.out.println(StaticExample.myStaticField);
}
}

Related

Android "new" statement not working. Loop keeps using the same object [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 6 years ago.
I have been told several definitions for it, looked on Wikipedia, but as a beginner to Java I'm still not sure what it means. Anybody fluent in Java?
static means that the variable or method marked as such is available at the class level. In other words, you don't need to create an instance of the class to access it.
public class Foo {
public static void doStuff(){
// does stuff
}
}
So, instead of creating an instance of Foo and then calling doStuff like this:
Foo f = new Foo();
f.doStuff();
You just call the method directly against the class, like so:
Foo.doStuff();
In very laymen terms the class is a mold and the object is the copy made with that mold. Static belong to the mold and can be accessed directly without making any copies, hence the example above
The static keyword can be used in several different ways in Java and in almost all cases it is a modifier which means the thing it is modifying is usable without an enclosing object instance.
Java is an object oriented language and by default most code that you write requires an instance of the object to be used.
public class SomeObject {
public int someField;
public void someMethod() { };
public Class SomeInnerClass { };
}
In order to use someField, someMethod, or SomeInnerClass I have to first create an instance of SomeObject.
public class SomeOtherObject {
public void doSomeStuff() {
SomeObject anInstance = new SomeObject();
anInstance.someField = 7;
anInstance.someMethod();
//Non-static inner classes are usually not created outside of the
//class instance so you don't normally see this syntax
SomeInnerClass blah = anInstance.new SomeInnerClass();
}
}
If I declare those things static then they do not require an enclosing instance.
public class SomeObjectWithStaticStuff {
public static int someField;
public static void someMethod() { };
public static Class SomeInnerClass { };
}
public class SomeOtherObject {
public void doSomeStuff() {
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someMethod();
SomeObjectWithStaticStuff.SomeInnerClass blah = new SomeObjectWithStaticStuff.SomeInnerClass();
//Or you can also do this if your imports are correct
SomeInnerClass blah2 = new SomeInnerClass();
}
}
Declaring something static has several implications.
First, there can only ever one value of a static field throughout your entire application.
public class SomeOtherObject {
public void doSomeStuff() {
//Two objects, two different values
SomeObject instanceOne = new SomeObject();
SomeObject instanceTwo = new SomeObject();
instanceOne.someField = 7;
instanceTwo.someField = 10;
//Static object, only ever one value
SomeObjectWithStaticStuff.someField = 7;
SomeObjectWithStaticStuff.someField = 10; //Redefines the above set
}
}
The second issue is that static methods and inner classes cannot access fields in the enclosing object (since there isn't one).
public class SomeObjectWithStaticStuff {
private int nonStaticField;
private void nonStaticMethod() { };
public static void someStaticMethod() {
nonStaticField = 7; //Not allowed
this.nonStaticField = 7; //Not allowed, can never use *this* in static
nonStaticMethod(); //Not allowed
super.someSuperMethod(); //Not allowed, can never use *super* in static
}
public static class SomeStaticInnerClass {
public void doStuff() {
someStaticField = 7; //Not allowed
nonStaticMethod(); //Not allowed
someStaticMethod(); //This is ok
}
}
}
The static keyword can also be applied to inner interfaces, annotations, and enums.
public class SomeObject {
public static interface SomeInterface { };
public static #interface SomeAnnotation { };
public static enum SomeEnum { };
}
In all of these cases the keyword is redundant and has no effect. Interfaces, annotations, and enums are static by default because they never have a relationship to an inner class.
This just describes what they keyword does. It does not describe whether the use of the keyword is a bad idea or not. That can be covered in more detail in other questions such as Is using a lot of static methods a bad thing?
There are also a few less common uses of the keyword static. There are static imports which allow you to use static types (including interfaces, annotations, and enums not redundantly marked static) unqualified.
//SomeStaticThing.java
public class SomeStaticThing {
public static int StaticCounterOne = 0;
}
//SomeOtherStaticThing.java
public class SomeOtherStaticThing {
public static int StaticCounterTwo = 0;
}
//SomeOtherClass.java
import static some.package.SomeStaticThing.*;
import some.package.SomeOtherStaticThing.*;
public class SomeOtherClass {
public void doStuff() {
StaticCounterOne++; //Ok
StaticCounterTwo++; //Not ok
SomeOtherStaticThing.StaticCounterTwo++; //Ok
}
}
Lastly, there are static initializers which are blocks of code that are run when the class is first loaded (which is usually just before a class is instantiated for the first time in an application) and (like static methods) cannot access non-static fields or methods.
public class SomeObject {
private static int x;
static {
x = 7;
}
}
Another great example of when static attributes and operations are used when you want to apply the Singleton design pattern. In a nutshell, the Singleton design pattern ensures that one and only one object of a particular class is ever constructeed during the lifetime of your system. to ensure that only one object is ever constructed, typical implemenations of the Singleton pattern keep an internal static reference to the single allowed object instance, and access to that instance is controlled using a static operation
In addition to what #inkedmn has pointed out, a static member is at the class level. Therefore, the said member is loaded into memory by the JVM once for that class (when the class is loaded). That is, there aren't n instances of a static member loaded for n instances of the class to which it belongs.
Above points are correct and I want to add some more important points about Static keyword.
Internally what happening when you are using static keyword is it will store in permanent memory(that is in heap memory),we know that there are two types of memory they are stack memory(temporary memory) and heap memory(permanent memory),so if you are not using static key word then will store in temporary memory that is in stack memory(or you can call it as volatile memory).
so you will get a doubt that what is the use of this right???
example: static int a=10;(1 program)
just now I told if you use static keyword for variables or for method it will store in permanent memory right.
so I declared same variable with keyword static in other program with different value.
example: static int a=20;(2 program)
the variable 'a' is stored in heap memory by program 1.the same static variable 'a' is found in program 2 at that time it won`t create once again 'a' variable in heap memory instead of that it just replace value of a from 10 to 20.
In general it will create once again variable 'a' in stack memory(temporary memory) if you won`t declare 'a' as static variable.
overall i can say that,if we use static keyword
1.we can save memory
2.we can avoid duplicates
3.No need of creating object in-order to access static variable with the help of class name you can access it.

Serious confusion with Scanner.nextLine [duplicate]

I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone

itext error cannot access instance variable from static context using ObservableList [duplicate]

I've written this test code:
class MyProgram
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
But it gives the following error:
Main.java:6: error: non-static variable count cannot be referenced from a static context
System.out.println(count);
^
How do I get my methods to recognize my class variables?
You must understand the difference between a class and an instance of that class. If you see a car on the street, you know immediately that it's a car even if you can't see which model or type. This is because you compare what you see with the class "car". The class contains which is similar to all cars. Think of it as a template or an idea.
At the same time, the car you see is an instance of the class "car" since it has all the properties which you expect: There is someone driving it, it has an engine, wheels.
So the class says "all cars have a color" and the instance says "this specific car is red".
In the OO world, you define the class and inside the class, you define a field of type Color. When the class is instantiated (when you create a specific instance), memory is reserved for the color and you can give this specific instance a color. Since these attributes are specific, they are non-static.
Static fields and methods are shared with all instances. They are for values which are specific to the class and not a specific instance. For methods, this usually are global helper methods (like Integer.parseInt()). For fields, it's usually constants (like car types, i.e. something where you have a limited set which doesn't change often).
To solve your problem, you need to instantiate an instance (create an object) of your class so the runtime can reserve memory for the instance (otherwise, different instances would overwrite each other which you don't want).
In your case, try this code as a starting block:
public static void main (String[] args)
{
try
{
MyProgram7 obj = new MyProgram7 ();
obj.run (args);
}
catch (Exception e)
{
e.printStackTrace ();
}
}
// instance variables here
public void run (String[] args) throws Exception
{
// put your code here
}
The new main() method creates an instance of the class it contains (sounds strange but since main() is created with the class instead of with the instance, it can do this) and then calls an instance method (run()).
Static fields and methods are connected to the class itself and not to its instances. If you have a class A, a 'normal' (usually called instance) method b, and a static method c, and you make an instance a of your class A, the calls to A.c() and a.b() are valid. Method c() has no idea which instance is connected, so it cannot use non-static fields.
The solution for you is that you either make your fields static or your methods non-static. Your main could look like this then:
class Programm {
public static void main(String[] args) {
Programm programm = new Programm();
programm.start();
}
public void start() {
// can now access non-static fields
}
}
The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.
The lifecycle of a class, in broad terms, is:
the source code for the class is written creating a template or
pattern or stamp which can then be used to
create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
destroy the object reclaiming the resources it is holding such as memory during garbage collection.
In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.
The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.
So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.
However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.
import java.io.*;
class HelloWorld {
int myInt; // this is a class variable that is unique to each object
static int myInt2; // this is a class variable shared by all objects of this class
static void main (String [] args) {
// this is the main entry point for this Java application
System.out.println ("Hello, World\n");
myInt2 = 14; // able to access the static int
HelloWorld myWorld = new HelloWorld();
myWorld.myInt = 32; // able to access non-static through an object
}
}
To be able to access them from your static methods they need to be static member variables, like this:
public class MyProgram7 {
static Scanner scan = new Scanner(System.in);
static int compareCount = 0;
static int low = 0;
static int high = 0;
static int mid = 0;
static int key = 0;
static Scanner temp;
static int[]list;
static String menu, outputString;
static int option = 1;
static boolean found = false;
public static void main (String[]args) throws IOException {
...
Let's analyze your program first..
In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
The very basic thing is static variables or static methods are at class level. Class level variables or methods gets loaded prior to instance level methods or variables.And obviously the thing which is not loaded can not be used. So java compiler not letting the things to be handled at run time resolves at compile time. That's why it is giving you error non-static things can not be referred from static context. You just need to read about Class Level Scope, Instance Level Scope and Local Scope.
Now you can add/use instances with in the method
public class Myprogram7 {
Scanner scan;
int compareCount = 0;
int low = 0;
int high = 0;
int mid = 0;
int key = 0;
Scanner temp;
int[]list;
String menu, outputString;
int option = 1;
boolean found = false;
private void readLine() {
}
private void findkey() {
}
private void printCount() {
}
public static void main(String[] args){
Myprogram7 myprg=new Myprogram7();
myprg.readLine();
myprg.findkey();
myprg.printCount();
}
}
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
variables within a method can not be static
static fields, and methods must be invoked using the class-name e.g. MyProgram7.main(...)
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g.
Say, car has the property colour, and exhibits the behaviour 'motion'.
An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Before you call an instance method or instance variable It needs a object(Instance). When instance variable is called from static method compiler doesn't know which is the object this variable belongs to. Because static methods doesn't have an object (Only one copy always). When you call an instance variable or instance methods from instance method it refer the this object. It means the variable belongs to whatever object created and each object have it's own copy of instance methods and variables.
Static variables are marked as static and instance variables doesn't have specific keyword.
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a.
For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example:
Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error.
CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
This is bit diff to explain about static key word for all beginners.
You wil get to know it clearly when you work more with Classes and Objects.
|*| Static : Static items can be called with Class Name
If you observe in codes, Some functions are directly called with Class names like
NamCls.NamFnc();
System.out.println();
This is because NamFnc and println wil be declared using key word static before them.
|*| Non Static :Non Static items can be called with Class Variable
If its not static, you need a variable of the class,
put dot after the class variable and
then call function.
NamCls NamObjVar = new NamCls();
NamObjVar.NamFnc();
Below code explains you neatly
|*| Static and non Static function in class :
public class NamCls
{
public static void main(String[] args)
{
PlsPrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamObjVar.PrnFnc("Tst Txt");
}
static void PlsPrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
|*| Static and non Static Class inside a Class :
public class NamCls
{
public static void main(String[] args)
{
NamTicCls NamTicVaj = new NamTicCls();
NamTicVaj.PrnFnc("Tst Txt");
NamCls NamObjVar = new NamCls();
NamNicCls NamNicVar = NamObjVar.new NamNicCls();
NamNicVar.PrnFnc("Tst Txt");
}
static class NamTicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
class NamNicCls
{
void PrnFnc(String SrgPsgVal)
{
System.out.println(SrgPsgVal);
}
}
}
In the Java programming language, the keyword static indicates that the particular member belongs to a type itself, rather than to an instance of that type.
This means that only one instance of that static member is created which is shared across all instances of the class.
So if you want to use your int count = 0; in static void main() , count variable must be declared as static
static int count = 0;
In this Program you want to use count, so declare count method as a static
class MyProgram<br>
{
int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
Hear you can declare this method as a public private and protected also. If you are using this method you can create a secure application.
class MyProgram
{
static int count = 0;
public static void main(String[] args)
{
System.out.println(count);
}
}
This is because you do not create instance of the model class, you have to create instances every time you use non-static methods or variables.
you can easily fix this see below images
without making instance of class
My model class file
By just creating instance then use class non-static methods or variables easily error gone

Use of a private constructor

I'm a begginer programmer for Android and I found some code over the internet and I couldn't get what this "Class not meant to be instantiated" means?! Also what's the use of it. I would be very happy if somebody could help here.
public class Settings
{
//some code
private Settings() {} // Class not meant to be instantiated
//some code
}
The constructor is private so only the class itself can create instances. There are several reasons for doing this. A couple off the top of my head...
The class is a "utility" class that only contains static methods and so instantiating it would make no sense. As the class is commented "Class not meant to be instantiated" I guess this is the most likely reason.
The class itself controls its own lifecycle and provides methods for creating instances. For example if the class is a lazy singleton it might provide a method that creates an instance when first called and return this instance on subsequent calls.
It is a private constructor. This means that outside classes cannot create new instances using the default constructor.
A little more info
All Objects in Java have a default constructor:
public MyObject() {}
That is how you can have this class:
public class MyObject{}
and still be able to call:
MyObject mObj = new MyObject();
Private Constructors
Sometimes a developer may not want this default constructor to be visible. Adding any other constructor will nullify this constructor. This can either be a declared constructor with empty parameters (with any of the visibility modifiers) or it can be a different constructor all together.
In the case above, it is likely that one of the following models is followed:
The Settings object is instantiated within the Settings class, and is where all the code is run (a common model for Java - where such a class would also contain a static main(String[] args) method).
The Settings object has other, public constructors.
The Settings object is a Singleton, whereby one static instance of the Settings Object is provided to Objects through an accessor method. For example:
public class MyObject {
private static MyObject instance;
private MyObject(){}//overrides the default constructor
public static MyObject sharedMyObject() {
if (instance == null)
instance = new MyObject();//calls the private constructor
return instance;
}
}
This inner construct
private Settings() {}
is a constructor for Settings instances. Since it is private, nobody can access it (outside of the class itself) and therefore no instances can be created.
The constructor is private so its not meant to be called by anything outside of the class
It's not a nested class, it's a constructor. A private constructor means that you can't construct instances of this class from outside, like this:
Settings s = new Settings(); //Compilation error! :(
Now, if a class can't be instantiated, what could it be for? The most likely reason for this is that the class would return instances of itself from a static method, probably as a singleton. The settings are normally global to the program, so a singleton pattern really fits here. So there would be a static method that goes kind of like this
static private TheOnlySettings = null;
static public getSettings()
{
if(TheOnlySettings == null)
TheOnlySettings = new Settings(); //Legal, since it's inside the Settings class
return TheOnlySettings;
}
See if that's indeed the case.
As other have mentioned, a class having private constructors cannot be instantiated from outside the class. A static method can be used in this case.
class Demo
{
private Demo()
{
}
static void createObjects()
{
Demo o = new Demo();
}
}
class Test
{
public static void main (String ...ar)
{
Demo.createObjects();
}
}
We can have private constructor . Below program depicts the use of private constructor with a static function
class PrivateConstructor {
private:
PrivateConstructor(){
cout << "constructor called" << endl;
}
public:
static void display() {
PrivateConstructor();
}
};
int main() {
PrivateConstructor::display();
}

Java initialization order issue, static vs instance fields

The program below prints:
my name is:null
my name is:null
Someclass static init
AFAIK when a class is first loaded static blocks and fields are always initialized first, instance blocks and fields second. Therefore variables "objectName1" and "objectName2" should be initialized first, instance variable "list" second...but the ouput obviously contradicts this theory... Can anyone explain the program behavior (I'm not looking for a critique of the design in itself btw) ?
import java.util.ArrayList;
import java.util.List;
public class Main2{
public static void main (String[] args){
SomeClass.getInstance();
}
}
class SomeClass {
private static final SomeClass instance = new SomeClass();
public static SomeClass getInstance(){
return instance;
}
static {
System.out.println ("Someclass static init");
}
private static String objectName1 ="test1";
private static String objectName2 ="test2";
#SuppressWarnings("serial")
private List<SomeObject> list=
new ArrayList<SomeObject> () { {
add (new SomeObject(objectName1));
add (new SomeObject(objectName2));
}};
}
class SomeObject {
String name;
SomeObject (String name){
this.name = name;
System.out.println ("my name is:" +name);
}
}
Static blocks are initialized in order (so you can rely on the ones above in the ones below). By creating an instance of SomeClass as your first static initializer in SomeClass, you're forcing an instance init during the static init phase.
So the logical order of execution of your code is:
Load class SomeClass, all static fields initially defaults (0, null, etc.)
Begin static inits
First static init creates instance of SomeClass
Begin instance inits for SomeClass instance, using current values for static fields (so objectName1 and objectName2 are null)
Load SomeObject class, all static fields initially default (you don't have any)
Do SomeObject static inits (you don't have any)
Create instances of SomeObject using the passed-in null values
Continue static inits of SomeClass, setting objectName1 and objectName2
To make this work as you may expect, simply put the inits for objectName1 and objectName2 above the init for instance.
As suggested moving this line:
private static final SomeClass instance = new SomeClass();
after these:
private static String objectName1 ="test1";
private static String objectName2 ="test2";
should fix the problem.
On first look I was pretty surprised about the behavior myself, but on second thought, it is quite trivial to explain:
private static final SomeClass instance = new SomeClass();
is part of the static initialization of SomeClass. As you create an instance before initialization has completed, the class is not yet completely initialized. When you replace the System.out.println(...); with something like new Exception().printStackTrace(); you get this (note that I put all classes as static nested classes into Main)
at Main$SomeObject.<init>(Main.java:37) // new Exception().printStackTrace();
at Main$SomeClass$1.<init>(Main.java:26) // add(new SomeObject(...))
at Main$SomeClass.<init>(Main.java:23) // list = new ArrayList()
at Main$SomeClass.<clinit>(Main.java:10) // instance = new SomeClass()
at Main.main(Main.java:6) // SomeClass.getInstance();
As you see, execution still is inside Main$SomeClass.<clinit> (the class initialization), hence SomeClass is not completely initialized.
As a side note: the best way to implement Singleton pattern is to avoid it completely. The second best most likely is using enum (at least it's Josh-Bloch-approved)
class enum SomeClass {
instance;
// snip
}
The first thing that executes is probably the static initializer of the instance variable. This causes the list to be initialized using the (uninitialized) objectName1 and objectName2 variables. After that, it proceeds to initialize objectName1 and objectName2.
If you move the declaration of instance to the end of SomeClass it will probably do what you're expecting.

Categories

Resources