0
What's wrong with my code? final static keyword in java?
https://code.sololearn.com/cmHxcl6vkA4a/?ref=app I m using final static variable and a static block in my code. When i m calling my code by class reference, it prints the final static variable but don't run the static block?
5 Respuestas
+ 8
Becz you cannot load that class in main method thats way static block cant be called
Solution
System.out.println(new A().x);
Output
hello osama
10
+ 1
Anhjje 🐿 i m not using hello osama as string variable instead i m using a static block and static block can be called by class reference.
0
You are declaring x and calling it with A.x
The string is not included in x variable
I would do it like this:
class A{
final static int x=10;
static String y = "hello osama";
}
public class Program
{
public static void main(String[] args) {
System.out.println(A.x+" "+A.y);
}
}
0
Sumit Programmer😎😎 bro if i remove final keyword from the variable name then it's working fine. It's totally related to final keyword functionality.
0
Hmmm I don't know how static block is useful here osama siddique , sorry I can't help you :)