What is Block in JAVA…?

Block in java

BLOCK IN JAVA:-

A block in Java is a group of one or more statements enclosed in braces.A block start with ( { ) and ends with ( } ).

A block statement is generally used to group together several statements, so they can be used in a situation that requires you to use a single statement.

Java support two types of block in java

1)Static Block

2)Non-static Block

Static Block

  • Static keyword can be used with class, variable, method and block.
  • Static block is used for initializing the static variables.
  • The static block will be called only once and it will be the first time you are accessing the class.
  • If the block declared with the static keyword is known as the static block.
  • Static block always executes before the main method called by JVM.
  • The existence of the main method always checks before executing the static block(1.8.0 JDK).
  • Static block always execute for a single time only

PROGRAM

class Test

{

static                     //Static Block

{

System.out.println("I am in static block");

String x[]={"1","2"};

main(x);

}

public static void main(String[] args)

{

System.out.println("main()...."+args[0]);

}

}

O/P

I am in static block

main()….1

Non-static Block

  • The block declares without any static keyword is called nonstatic block.
  • Nonstatic blocks are the class level block which does not have the prototype
  • The block will execute before constructor called by the user.

PROGRAM

class Test

{

Test()

{

System.out.println("i am in constructor");

}

static

{

System.out.println(" i  am in static block");

}

public static void main(String[] args)

{

System.out.println("i  am in main method");

Test t1=new Test();

}

{

System.out.println(" i am in nonstatic block");

}

}

O/P I am in static block

I am in the main method

I am in nonstatic block

I am in constructor

 

 

basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community

One thought on “What is Block in JAVA…?

  • August 15, 2018 at 2:06 pm
    Permalink

    “Good information. Lucky me I recently found your website by accident (stumbleupon). I’ve book-marked it for later!”

    Reply

Leave a Reply

shares