Learn Pain Less

HomeOur TeamContact
Java
What is the use of static Block in JAVA
Pawneshwer Gupta
Pawneshwer Gupta
March 21, 2015
1 min

Table Of Contents

01
Static block in java
02
Why we use Static block instead of Constructor?
What is the use of static Block in JAVA

Static block in java

Static block is called when class initialized. Which means whenever your class is loaded Static block will be called.You can also call it static initializer block. Its same like as constructor. But difference is that in static block you can initialize static members of class.

Example of static block

public class{
private static List<String> items = new ArrayList<>();
static {
items.add("Java");
items.add("Android");
items.add("PHP");
items.add("My SQL");
}
}

As you can see in above example that you can declare variable globally but you can’t initialize them inline. To initialize them inline we use Static block.

Why we use Static block instead of Constructor?

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 (add,put etc.) will generate an exception.

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Tags

startstatic blockjava tutorial

Share


Pawneshwer Gupta

Pawneshwer Gupta

Software Developer

Pawneshwer Gupta works as a software engineer who is enthusiastic in creating efficient and innovative software solutions.

Expertise

Python
Flutter
Laravel
NodeJS

Social Media

Related Posts

Working with Files, Folders java
Working with Files, Folders java
March 25, 2015
1 min
Learn Pain Less  © 2024, All Rights Reserved.
Crafted with by Prolong Services

Quick Links

Advertise with usAbout UsContact Us

Social Media