Static block gets skipped basing on Main method - java

From the below program I have observed that
main() method must and should not required to be only in next level of main class
All Static blocks are not loaded first.
I would like to know why the static blocks are not loaded?
public class FunnyProgram {
static {
System.out.println("Loading first static block");
}
static class Inner {
static {
System.out.println("Loading first Inner static block first");
}
static class AgainInner {
static {
System.out.println("Loading second AgainInner static class first");
}
public static void main(String[] args) {
System.out.println("This funny program prints");
}
}
}
}

Related

How a static method call works in Java?

When calling out the function testFunc(), I am not using the syntax
Apples.testFunc(). Yet the code runs successfully. How so?
class Apples {
public static void main(String args[] ) {
testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
Since, the static method is in the same class. So, you don't need to specify the class name.
If it is in different class, then you need to specify the class name.
Remember: Non-static methods can access both static and non-static members whereas static methods can access only static members.
For example :
Calling a static method present in different class, you need to do like this :
import com.example.Test;
public class Apples {
public static void main(String args[]) {
Test.testFunc();
}
}
package com.example;
public class Test {
public static void testFunc() {
System.out.println("Hello world!");
}
}
Your function testFunc() is in same class where the function main is. So you don't need to use class name before function testFunc().
When the memory is allocated for the class, Static method or static variable is assigned memory within a class. So we can access static member function or data variable using class name.
we can call static function as below
class Main1 {
public static void main(String args[] ) {
Main1.testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
or
class Main1 {
public static void main(String args[] ) {
testFunc();
}
public static void testFunc() {
System.out.println("Hello world!");
}
}
the answer will be same, but when static function is in other class then we must use classname to call it

Unable to call function in java

When I try to call the lyrics function in this code, "invalid method declaration; return type required" occurs.
I'm learning java and very very new to it. I'm confused how to define the function and call the function so that code may run.
public class Main {
public static void main(String[] args) {
}
public void lyrics() {
System.out.println("some lyrics here");
}
lyrics();
}
Normally, one can't just invoke a method randomly in the body of the code. However, there is something called an initialization block (this gets run in the body of the constructors of the object). I think an example might clarify. Like,
public class Main {
public static void main(String[] args) {
new Main(); // <-- instantiate an instance of Main
}
public void lyrics() {
System.out.println("some lyrics here");
}
{ // <-- this is an initialization block
lyrics();
}
}
The above uses the default constructor, we can add an explicit one. Like,
public Main() {
super();
System.out.println("In Main constructor");
}
Note how the output changes.
They can also be static (and run when the class is first referenced). Like,
public class Main {
public static void main(String[] args) {
}
public static void lyrics() {
System.out.println("some lyrics here");
}
static {
lyrics();
}
}
Your code is nearly correct. Your lyrics() method must be static if you want to call it inside main method because main method is static. Non static members cannot be accessed from static method (without creating an instance to invoke it).
public class Main {
public static void main(String[] args) {
lyrics();
}
public static void lyrics() {
System.out.println("some lyrics here");
}
}
You can invoke non-static methods from static method by creating an instance of the class containing non-static method inside your main method as mentioned in comments by Elliott Frisch.
new Main().lyrics();
Since you're learning Java, you must remember that the only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
Or you can simply make your function static. Also, you need to call the function inside the main block.
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
Happy coding!
The method should be declared as static and function call should be within main method. The correct code should look like as follows:
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
You need to move the call to lyrics() into the main method where code is actually executed. Where you have it now, the compiler is expecting a new method defination.
public class Main {
public static void main(String[] args) {
// execution begins here.
new Main().lyrics();
}
public void lyrics() {
System.out.println("some lyrics here");
}
}
EDIT: created new class Main class to avoid errors.

Static block is not getting executed in case of anonymous objects

Why doesn't a static block in the class get executed when I don't create a reference variable for an object (anonymous) of that class?
For example, let us consider this simple class:
public class StaticDemo {
private static int x;
public static void display(){
System.out.println("Static Method: x = "+x);
}
static {
System.out.println("Static Block inside class");
}
public StaticDemo(){
System.out.println("Object created.");
}
}
Another class using it:
public class UseStaticDemo {
public static void main(String[] args) {
StaticDemo Obj = new StaticDemo();
Obj.display();
System.out.println("------------");
new StaticDemo().display();
}
}
Output:
Static Block inside class
Object created.
Static Method: x = 0
------------
Object created.
Static Method: x = 0
A static initializer block only runs once, when the class is loaded and initialized.
Also, static methods have absolutely no relation to any instances. Doing
new StaticDemo().display();
is pointless and unclear.

Can we have a static block within a main block i tried and got an error

In netbeans I am getting the error:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
at javaapplication3.NewClass4.main(NewClass4.java:20)
My code:
public class NewClass4
{
public static void main(String a[])
{
System.out.println("hello");
static
{
System.out.println("u");
}
}
}
static block is executed when the class is loaded. Mostly used for initializing static variables. You can have static block anywhere inside class body. But not inside a method
For eg, for a singleton class you can use it to initialize the instance
public class SingletonClass {
private static SingletonClass instance;
static {
instance = new SingletonClass();
}
}
Move it outside your main method:
public class NewClass4
{
static
{
System.out.println("u");
}
public static void main(String a[])
{
System.out.println("hello");
}
}

I want to print "Hello" even before main() is executed

I want to print "Hello" even before main() is executed in Java Program. Is there any way for doing this?
What you need is a static keyword. One of the options is to use static function as initializer to static variable.
class Main {
public static int value = printHello();
public static int printHello() {
System.out.println("Hello");
return 0;
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
value is a static variable so initialized before main function execution. This program prints:
Hello
Main started
Moreover, you can even simplify this by calling printHello() even without variable initialization like in the following:
static {
printHello();
}
public class Sample {
static {
System.out.println("Hello first statement executed first ");
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
Use a static block:
static {
System.out.println("hello");
}
public static void main(String[]args) {
System.out.println("After hello");
}
Output:
hello
after hello
public class Test {
static {
System.out.println("Hello");
}
public static void main(String[] args) {
System.out.println("Inside Main");
}
}
Outputs
Hello
Inside Main
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.
Apart from using static block, you can also try instrumentation and premain
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html
import java.io.*;
class ABCD {
public static int k= printit();
public static int printit(){
System.out.println("Hello it will be printed before MAIN");
return 0;
}
public static void main (String[] args) {
System.out.println("Main method is Executed");
}
}
Static variables are initialized in the start of execution of program . So to initialize it will call printit(); function which will be executed and "Hello it will be printed before MAIN" will be printed and in last function will return value '0' and finally after this main block will be executed.
Final Output :
Hello it willl be printed before MAIN
Main method is Executed
Here is another way:
class One{
public One() {
System.out.println("Before main");
}
}
class Two extends One{
public Two() {
super();
}
public static void main(String[] args) {
Object abj = new Two();
System.out.println("in the main");
}
}
Here in run configuration, class Two would be the main class.

Categories