-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path27_Static.java
More file actions
135 lines (101 loc) · 2.44 KB
/
27_Static.java
File metadata and controls
135 lines (101 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.util.*;
class Solution {
static int x;
// constructor is executed only when an object is created.
Solution(){
System.out.println("Constructor");
}
// static is executed automatically.
static{
System.out.println(x);
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
// Solution obj1 = new Solution();
}
}
class Solution1 {
static int x;
// constructor is executed only when an object is created.
Solution(){
System.out.println("Constructor");
}
// static is executed automatically even before the main function.
static{
System.out.println("Static Block Started");
System.out.println(x);
}
// Initialiser block: Executed automatically just before constructor.
{
System.out.println("Initialiser Block");
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Main Started");
Solution obj1 = new Solution();
}
// Output:
// Static Block Started
// 0
// Main Started
// Initialiser Block
// Constructor
}
class Solution2 {
// Multiple static blocks : Allowed
static {
System.out.println("Static0");
}
static {
System.out.println("Static1");
}
static {
System.out.println("Static2");
}
// Using initialiser without constructor: Multiple initialiser allowed but no use without object.
{
System.out.println("Init0");
}
{
System.out.println("Init0");
}
{
System.out.println("Init0");
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
}
}
class Solution3 {
static int x = 21;
// Multiple static blocks : Allowed
static {
System.out.println("Static0");
}
static {
System.out.println("Static1");
}
static {
System.out.println("Static2");
}
{
System.out.println("Init0");
x++;
}
{
System.out.println("Init0");
x++;
}
{
System.out.println("Init0");
x++;
}
Solution(){
System.out.println("Constructor");
System.out.println(x); // prints 24;
}
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
Solution obj1 = new Solution();
}
}