system.out.println statement outside any method in java - java

My question is can't we write an output statement outside the main in java? If I enclose it in { } braces then I don't get error, but if I directly write it, I get an error. why so?
public class abc
{
int a=3;
int b=0;
System.out.println("this statement gives error"); //Error!!
{System.out.println("this works fine");}
public static void main(String args[]) {
System.out.println("main");
abc t=new abc();
}
}
I tried writing it in main, it works. Why doesn't it work without a method?

When you enclose it in braces, you are putting it in an initializer block, which runs when the class is instantiated. No statements except variables declarations/initialization may take place outside of methods or initialization blocks in Java.

A Class can only have attributes or methods.
A class is the blueprint from which individual objects are created.
int a=3; // attributes
int b=0; // attributes
System.out.println("this statement gives error"); //Error!!
{System.out.println("this works fine");} // init block whenever an object is created.
// since it is inside { }

{...} is called an instance initializer . It runs in addition to the constructor each time an instance object is created .
static{...} is another type of block that is called Static Initializer it is when you add a static keyword before { } . This static initializer only runs when the class is first loaded.
So you can write code in these two block and class member functions.
Other than that the only place left is meant for the class data members declaration and initialization.

Basics/Fundamentals
Java Class contains only member functions and class variables and few other exceptions like instance initliazer, static blocks etc.
You can't just sprinkle executables(like System.out.println()) anywhere you wish inside Class.
Instance initliazer
{...} in Java is instance initializer which gets called whenever an object is created. Because it is instance initializer, it actually gets called before constructor.
You can write System.out.println() inside {...} or instance initializer.
Static block
static{...} is called static block in Java, which contains lines of code which gets called ONLY ONCE when the class is loaded by JVM.
Again, You can write System.out.println() inside {...} or static block.
Simple executable example below
public class JavaExample {
public JavaExample (String name){
System.out.println("Inside constructor" + name);
}
{
System.out.println("Inside instance initializer");
}
static{
System.out.println("Inside static block");
}
//System.out.println("Will give error"); //ERROR
public static void main(String[] args) {
JavaExample obj1 = new JavaExample ("obj1");
JavaExample obj2 = new JavaExample ("obj2");
System.out.println("Inside the public static void main");
}
}
Output
> Inside static block
> Inside instance initializer
> Inside constructor: obj1
> Inside instance initializer
> Inside constructor: obj2
> Inside the public static void main
Please note the order of execution.
Static block (gets called once when JVM loads Class, hence first of all)
Instance initializer (before the call of any object instantiation)
Constructor (during object creation/initialization)

Related

How is it possible to create object in Class definition itself?

I have some doubt on how this works, consider a simple Java program:
package com.example;
public class Test {
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
public void print() {
System.out.println("This is demo");
}
}
This is pretty straightforward program.
However, I have doubt at (1). We are creating an instance of Test, but this is still in the definition of Class Test. How is this possible?
Any explanation to help this would be great.
The instance will be created at run-time.
By then, compile-time is over and all of the code of your application (including all class definition) will be "ready".
Even if you call a constructor of a class that has not been encountered by the JVM up to that point, it will dynamically load the class (in its entirety) before executing the constructor call. Note that a) this might actually fail at run-time, in which case you get a ClassNotFoundError, and b) that cannot happen in your case, because you are calling the constructor of the class from itself (so it must have been loaded already).
The compiler does not run any of your code (not even things like static initializers) during compilation.
But it does make sure (during compilation) that every method or constructor that you are trying to call does in fact exist. Again, this could theoretically fail at runtime (if you mess up class files), in which case you would get a NoSuchMethodError.
First We have to Compile this Porgram using javac After Compilation It will give a Class File.
Now time to Execute Your Class Using java which Invokes JVM and load the Class File to the Class Loader.
java fileName.Class
And here
public static void main(String[] args) {
Test t = new Test(); (1) <---- How is this possible
t.print();
}
All we know static Content (either it is Variable or Method In Java) Of class loaded when ClassLoader loads a Class
As You see Main Method is a static Method. and So, It will Automatically Load into the ClassLoader with class File.
Now JVM First find the public static void main(String... args) in class. Which is a static Content means Its a part of Class but not a part of Class Instance. There is no need of Class Instance to Invoke this MainMethod`.
main(String... args) will be Invoked without getting Instance of the Class. In that Main Method , Your Class is Getting Instantiated
Test t = new Test(); \\here t is reference Variable to Test Class Object.
Now Because Class is loaded into the class Loader new Test(); will create a New Object in Heap memory Area of JVM and your method
public void print() {
System.out.println("This is demo");
}
will be invoked using t.print() Which is a Instance Method (Not Static), So It needs Class Instance to Invoke print() Method.
Q: Test t = new Test(); (1) <---- How is this possible
A: Because of the "static" in public static void main(String[] args)
The "static" means that method "main()" is independent of any specific class object.
You can create any class object you want - including a new "Test" object.
One of the benefits of defining "main" to be static is that you can use "main()" as a test method for the class. Each class can have it's own "main", and you can test each class individually by specifying that class in your Java command line.
For example:
public class MyClass {
public int add2(int n) {
return n + 2;
}
public static void main (String[] args) {
MyClass unitTest = new MyClass ();
System.out.println ("add2(2)=" + unitTest.add2(2));
System.out.println("Expected result=4");
}
}
Then test as follows:
javac MyClass.java
java MyClass
add2(2)=4
Expected result=4
This question has actually been asked and answered many times. For example:
Why is the Java main method static?
==================================================================
Here are a few more examples that illustrate the point:
public class CreateMyself {
private int value = 0;
private static CreateMyself m_singleton = null;
// EXAMPLE 1: You can legally create an instance in the constructor ...
public CreateMyself () {
value++;
// CreateMyself o = new CreateMyself (); // BAD!!! This will cause infinite recursion and crash your stack!!!
System.out.println ("Leaving constructor, value=" + value + "...");
}
// EXAMPLE 2: You can legally create another instance in a normal class member
public void createAnother() {
// But ... WHY??? Is there anything you can't do directly, in your own instance?
CreateMyself newInstance = new CreateMyself ();
System.out.println ("Leaving createAnother, value=" + value + "...");
}
// EXAMPLE 3: This is a common idiom for creating a "singleton"
// NOTE: for this to work, you'd also make the constructor PRIVATE (or protected), so the client *must* call "getInstance()", instead of "new".
public static CreateMyself getInstance () {
if (m_singleton == null) {
m_singleton = new CreateMyself ();
}
System.out.println ("returning singleton instance...");
return m_singleton;
}
// EXAMPLE 4: Creating an instance in "static main()" is a common idiom
public static void main (String[] args) {
CreateMyself newInstance = new CreateMyself ();
newInstance.createAnother ();
}
}
There are many other possible uses. For example, maybe you'll have a static method that does a database lookup and returns a list matching objects.
Note that most of the cases where it's really useful for a class to have a method where it creates an instance of itself are probably static methods.

Java - Method executed prior to Default Constructor [duplicate]

This question already has answers here:
Are fields initialized before constructor code is run in Java?
(5 answers)
Closed 7 years ago.
I'm learning java and accidentally I came across following code where default constructor is executed after the method.
public class ChkCons {
int var = getVal();
ChkCons() {
System.out.println("I'm Default Constructor.");
}
public int getVal() {
System.out.println("I'm in Method.");
return 10;
}
public static void main(String[] args) {
ChkCons c = new ChkCons();
}
}
OUTPUT :
I'm in Method.
I'm Default Constructor.
Can anyone please explain me why this happened?
Thanks.
Instance variable initialization expressions such as int var = getVal(); are evaluated after the super class constructor is executed but prior to the execution of the current class constructor's body.
Therefore getVal() is called before the body of the ChkCons constructor is executed.
Constructor is called prior to method. The execution of method occurs after that which is a part of object creation in which instance variables are evaluated. This could be better understand from following code.
class SuperClass{
SuperClass(){
System.out.println("Super constructor");
}
}
public class ChkCons extends SuperClass{
int var = getVal();
ChkCons() {
System.out.println("I'm Default Constructor.");
}
public int getVal() {
System.out.println("I'm in Method.");
return 10;
}
public static void main(String[] args) {
ChkCons c = new ChkCons();
}
}
The above code has following output
Super constructor
I'm in Method.
I'm Default Constructor.
Here the compiler automatically adds super(); as the first statement in ChkCons() constructor, and hence it is called prior to the getVal() method.
We can refer the following oracle documentation on Initializing instance variables (Emphasis is mine):
Initializing Instance Members
Normally, you would put code to initialize an instance variable in a
constructor. There are two alternatives to using a constructor to
initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static
initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here }
> The Java compiler copies initializer blocks into every constructor.
Therefore, this approach can be used to share a block of code between
multiple constructors.
A final method cannot be overridden in a subclass. This is discussed
in the lesson on interfaces and inheritance. Here is an example of
using a final method for initializing an instance variable:
class Whatever {
private varType myVar = initializeInstanceVariable();
protected final varType initializeInstanceVariable() {
// initialization code goes here
}
}
https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
Whenever you create an instance of a class instance variables are initialized first followed by execution of the Constructor
Ref : Are fields initialized before constructor code is run in Java?
public class InitializerIndex {
public InitializerIndex() {
// TODO Auto-generated constructor stub
System.out.println("Default Constructor");
}
static {
System.out.println("Static Block one");
}
{
System.out.println("Init one");
}
void letsRoll() {
}
public static void main(String[] args) {
new InitializerIndex().letsRoll();
new InitializerIndex().letsRoll();
}
{
System.out.println("Init Two");
}
static {
System.out.println("Static Block two");
}
}
Will have following output:
Static Block one
Static Block two
Init one
Init Two
Default Constructor
Init one
Init Two
Default Constructor
First all the static content is loaded, then the instance content. Static content is loaded only once.
Even when two objects are created, the static block is called only when the first object is created.
Also, at the time of object creation or in constructors, if you want to use methods like this
int var = getVal();
You should use static methods.
It's because you are initializing the method into a field using int var = getVal();, so it will execute before constructor call.
Static block have the first priority, it executes during loading of class.

Static reference and using Objects which have been initialized outside of a main?

I have a question concerning the use of objects...
I have a class called Area which contains a few methods. I want to access these methods in another class in which an Area object is created.
public class calcAreaObj {
Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Why is it when the class is created as above I get an error("Cannot make a static reference to non-static field areaObj. But when the source code is written such that the Area object is initiaized inside the main statement as below there are no errors...
public class calcAreaObj {
public static void main(String[] args){
Area areaObj = new Area();
areaObj.area(2,3,4);
}
}
Is this because in the first case the Area object is initialized outside of a static statement? If so, why does this matter?
This is because when defined at class scope, areaObj is specific to each instance of calcAreaObj. That's not really what you want, since main is a static method (and so doesn't have an instance of calcAreaObj associated with it). You can either use the second code sample you posted, or you can modify the first one as follows:
public class calcAreaObj {
static Area areaObj = new Area();
public static void main(String[] args){
areaObj.area(2,3,4);
}
}
Additionally, if areaObj doesn't have any state, in this case, you could always declare Area.area as static.
In the first example areaObj is a non-static member of calcAreaObj. This means it can only be accessed using an instance of calcAreaObj.
new calcAreaObj().areaObj.whatever(); //this will work
calcAreaObj.areaObj; //areaObj isn't a static member, won't work
In short: the non-static member doesn't even exist as long as you haven't created an instance of calcAreaObj. In the second example, it's in scope of the method and thus accessible.
For the first situation your creating a local variable for the class which has no relation with the object used in the main. Therefore you have to initialize the object again in the main.
There is a rule: that any block has it's own variables. So if you initialize a variable in block and try to use it outside the block that will give you an error.
For example:
public static void main(String [] arg){
{ Area a = new Area(); }
double number = a.area
}
this doesn't work ...
I wish it is clear

Regarding static and final variable effect on class

If you execute this program you will get only the i value but not SIB, my question is when class loading into the memory SIB should execute and should give ooutput, but here I am getting only the i value? Then keep one method in class test then call that method from another class then you will get output of SIB, i method ( keep method also as static final)
class Test
{
static final int i =3;
static
{
System.out.println("SIB");
}
{
System.out.println("IIB");
}
}
class A1
{
public static void main(String[] args)
{
System.out.println(Test.i);
}
}
A static final variable is a compile-time constant and its value is copied into the other class referencing it. Therefore your class Test won't load and no initializers will be executed. When the variable is only static, then the class must be loaded to read the current value and your SIB block will be executed. The IIB block will be executed only when you instantiate Test with new Test().

Java syntax question

What does
static{
//something
}
declared inside a class definition body mean?
public class A extends B{
static {
C.register(new C(A.class,
(byte) D.x.getCode()) {
public DataSerializable newInstance() {
return new A();
}
}
);
}
}
The static block is called a "static initialization block." It is very similar to a regular constructor except that it can only initialize static variables.
I have found it to be useful when initialization of some static variable may throw an exception that you would like to handle or at least log. It is especially useful in the initialization of static final variables.
You may read more about static initialization blocks here: Initializing Fields
It executes a block of code without requiring an instance of this class, i.e. as soon as the class loader loads the class.
That becomes a static initialisation block, which can be written as a static method.
It's a static initializer. It's run once the class is loaded and it's results can be stored in static members. It's used to initialize static members that require more than the regular new Xyz() (like Lists or Maps)...
It's a static initializer. It lets you specify things that happen at the time that the class is loaded, before any instance is created.
If an exception is thrown from a static initializer it's very confusing, it's hard to tell where it came from. Anything that you do in a static initializer should have a try-catch around it and have the exception get logged. It's a good language feature to avoid if you can.
It means that you will have this section which is inside the static block extecuted FIRST on load of the class into the JVM.
Execute the following simple program might make things clearer
public class Test123 {
static{
System.out.println("Hello from static block");
}
public static void main(String[] args) {
System.out.println("In main");
}
}
The output to the above will be
Hello from static block
In main

Categories

Resources