Java class init block

Java default Initialization of Instance Variables and Initialization Blocks

When it comes to Java programming, you should know the rules of default initialization of instance variables as well as how initialization blocks work. And in this article, I’m happy to discuss with you about this topic in Java.

1. Default Initialization of Instance Variables in Java

When you declare a variable without assigning it an explicit value, the Java compiler will assign a default value. Let’s consider the following example:

public class DefaultVarInit < int number; // number will have default value: 0 float ratio; // default value: 0.0 boolean success; // default value: false String name; // default: null Object obj; // default: null public void print() < System.out.println("number = " + number); System.out.println("ratio = " + ratio); System.out.println("success = " + success); System.out.println("name = " + name); System.out.println("obj brush:text">number = 0 ratio = 0.0 success = false name = null obj = null

NOTE: This default initialization applies for instance variables, not for method variables. For variables in method, we have to initialize them explicitly.

  • Integer numbers have default value: 0
    • for int type: 0
    • for byte type: (byte) 0
    • for short type: (short) 0
    • for long type: 0L
  • Floating point numbers have default value: 0.0
    • for float type: 0.0f
    • for double type: 0.0d
  • Boolean variables have default value: false
  • Character variables have default value: ‘\u0000’
  • Object references have default value: null
Читайте также:  Php локальная область видимости

2. Default Initialization of Arrays in Java

An array is an object, hence the default value of an uninitialized array (member variable) is null. For example:

String[] names; // default is null

When the size of an array is initialized, then its components will have default values specified by the rules above. For example:

String[] names = new String[5]; // all 5 String elements are null by default int[] numbers = new int[10]; // all 10 integer elements are zeroes by default

NOTE: The default initialization of array components is the same, regardless of the array itself is member variable or local variable.

3. Instance Initialization Blocks in Java

In Java, we can put a piece of code inside a block enclosed within < and >. Let’s look at the following example:

public class Dog < // begin instance initialization block < System.out.println("Dog's Instance Init Block"); >// end instance initialization block public Dog() < System.out.println("Dog's constructor"); >>

As you can see, the code between the < and >is called instance initialization block, which is executed every time an instance of the class is created and after the call to super() in the constructor. For example, if we instantiate a new Dog object like this:

Dog's Instance Init Block Dog's constructor

There can be multiple instance initialization blocks in a class, and they are executed in the order they appear. Consider the following example:

public class Cat < < System.out.println("Cat's Instance Init Block #1"); >public Cat() < System.out.println("Cat's Constructor"); > < System.out.println("Cat's Instance Init Block #2"); >public void foo() < System.out.println("Cat's Foo"); >>
Cat's Instance Init Block #1 Cat's Instance Init Block #2 Cat's Constructor

4. Static Initialization Blocks in Java

public class Bird < // begin static initialization block static < System.out.println("Bird's Static Init Block"); >// end static initialization block public Bird() < System.out.println("I'm a bird"); >>

Unlike instance initialization blocks, a static block is executed only once when the class is first loaded, whereas an instance initialization block is executed every time an instance is created.

There can be multiple static initialization blocks in a class, and they are executed in the order they appear.

Note that static initialization blocks are always executed before instance initialization blocks (but only once).

Let’s see the following example:

public class Bird < static < System.out.println("Bird's Static Init Block #1"); >public Bird() < System.out.println("I'm a bird"); > < System.out.println("Bird's Instance Init Block #1"); >public void fly() < System.out.println("I'm flying"); > < System.out.println("Bird's Instance Init Block #2"); >static < System.out.println("Bird's Static Init Block #2"); >>
Bird's Static Init Block #1 Bird's Static Init Block #2 Bird's Instance Init Block #1 Bird's Instance Init Block #2 I'm a bird

I hope you have learned something new about variable default initialization and instance and static initialization blocks in this article.

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment

Comments

Who will assign the default values for global variables.?
According to my study constructor will assign the default values .?
But how it will assign is my doubt.?
Please can you clarify my doubt.

CodeJava.net shares Java tutorials, code examples and sample projects for programmers at all levels.
CodeJava.net is created and managed by Nam Ha Minh — a passionate programmer.

Copyright © 2012 — 2023 CodeJava.net, all rights reserved.

Источник

Initializing Fields

As you have seen, you can often provide an initial value for a field in its declaration:

public class BedAndBreakfast < // initialize to 10 public static int capacity = 10; // initialize to false private boolean full = false; >

This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.

Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.

Static Initialization Blocks

A static initialization block is a normal block of code enclosed in braces, < >, and preceded by the static keyword. Here is an example:

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

There is an alternative to static blocks — you can write a private static method:

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

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:

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:

This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems.

Previous page: Understanding Class Members
Next page: Summary of Creating and Using Classes and Objects

Источник

Java’s init blocks

Java allows you to use the so called “init blocks”. You can declare static and instance init blocks. The static init blocks will run exactly once, when the ClassLoader loads the class that declares it, and the instance init blocks run everytime you construct a new object, after the actual constructor ran.

The general order of execution is like this:

  1. Once the class gets loaded by the ClassLoader, it runs every static init block once, in the order of their declaration
  2. When you construct a new instance using the constructor, it first runs the constructor’s code, followed by every init block in the order of their declaration

Here’s a small example class:

public class Test < static < System.out.println("This is the static init block. All the code here runs once when you the ClassLoader loads the class."); > < System.out.println("This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran."); >static < System.out.println("This is another static init block."); printSomething(); > < System.out.println("This is another instance init block."); >public Test() < System.out.println("This is a no-args constructor."); >public Test(String anUnusedString) < System.out.println("This is a constructor with a String parameter."); printSomething(); >public static void printSomething() < System.out.println("I am printing something."); >>

How let’s imagine that we have another class that simply constructs a few instances of the above class:

If you would now run TestE.main(String…), you’d get the following output:

This is the static init block. All the code here runs once when you the ClassLoader loads the class. This is another static init block. I am printing something. This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran. This is another instance init block. This is a no-args constructor. This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran. This is another instance init block. This is a constructor with a String parameter. I am printing something. This is an instance init block. It gets called every time you create a new instance of this class, AFTER the normal constructor's code ran. This is another instance init block. This is a no-args constructor.

Join my Discord Server for feedback or support. Just check out the channel #programming-help 🙂

Источник

Java class init block

instance initializer block

Rules for instance initializer block :

  1. The instance initializer block is created when instance of the class is created.
  2. The instance initializer block is invoked after the parent class constructor is invoked (i.e. after super() constructor call).
  3. The instance initializer block comes in the order in which they appear.

Program of instance initializer block that is invoked after super()

Output:parent class constructor invoked instance initializer block is invoked child class constructor invoked

Another example of instance block

parent class constructor invoked instance initializer block is invoked child class constructor invoked parent class constructor invoked instance initializer block is invoked child class constructor invoked 10

Youtube

For Videos Join Our Youtube Channel: Join Now

Feedback

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью