- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Non static blocks in Java.
A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
Example
public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
Output
Hello this is a static block This is main method
Instance initialization blocks
Similar to static blocks, Java also provides instance initialization blocks which are used to initialize instance variables, as an alternative to constructors.
Whenever you define an initialization block Java copies its code to the constructors. Therefore you can also use these to share code between the constructors of a class.
Example
public class Student { String name; int age; { name = "Krishna"; age = 25; } public static void main(String args[]){ Student std = new Student(); System.out.println(std.age); System.out.println(std.name); } }
Output
25 Krishna
In a class, you can also have multiple initialization blocks.
Example
public class Student { String name; int age; { name = "Krishna"; age = 25; } { System.out.println("Initialization block"); } public static void main(String args[]){ Student std = new Student(); System.out.println(std.age); System.out.println(std.name); } }
Output
Initialization block 25 Krishna
You can also define an instance initialization block in the parent class.
Example
public class Student extends Demo { String name; int age; { System.out.println("Initialization block of the sub class"); name = "Krishna"; age = 25; } public static void main(String args[]){ Student std = new Student(); System.out.println(std.age); System.out.println(std.name); } }
Output
Initialization block of the super class Initialization block of the sub class 25 Krishna
Advertisements