Q1.
package x.y.z;
public class Employee {
static {
System.out.println("sb1");
}
private static int id;
}
package a.b.c;
public class App {
public static void main(String[] args){
Employee.id = 20;
}
}
// will this compile?
Answer : No
Fix below:
package x.y.z;
public class Employee {
static {
System.out.println("sb1");
}
public static int id; // 2. make id as public so that it can be accessible inside App class
}
package a.b.c;
import x.y.z.Employee; // 1. add import statement as App and Employee in different packages
public class App {
public static void main(String[] args){
Employee.id = 20;
}
}
--------------------------------------------------------------------
Q2.
package x.y.z;
public class Employee {
static {
System.out.println("sb1");
}
public static int id;
}
package a.b.c;
import x.y.z.Employee;
public class App {
public static void main(String[] args){
Employee#id = 20;
}
}
// Will this code compile? NO
Answer: id is a static resource inside Employee class. it must be accessed
using . operator instead of #
-----------------------------------------------------------
Q3.
package x.y.z;
public class Employee {
static {
System.out.println("sb1");
}
public static int id=4;
static {
m1(id);
id=5;
}
public static void m1(int i){
System.out.println(i*i);
}
}
package a.b.c;
import x.y.z.Employee;
public class App {
public static void main(String[] args){
Employee.id = 20;
}
}
// what is the output?
sb1
16
--------------------------------------------------------------
Q4.
package x.y.z;
public class Employee {
static {
System.out.println("sb1");
}
public static int id=4;
static {
m1();
id=5;
}
public static void m1(){
System.out.println(id*id);
}
}
package a.b.c;
import x.y.z.Employee;
public class App {
public static void main(String[] args){
Employee.m1(); // [sb1, 16], 25
Employee.id=7;
Employee.m1(); // 49
}
}
// what is the output?