Actually we have learned that static variable does not change its value and it is not possible to change the value of a static variable. But in this post you can learn an example in java on how to change the value of a static variable by using a method in java.
InitializeByMethod.java
package com.udhaya;
class StaticDemo {
static String name;
public static void staticVariable() {
name = name + " " + "kumar";
System.out.println("Value of static variable after method calling"
+ name);
}
}
public class InitializeByMethod {
public static void main(String[] args) {
System.out.println("Initial value of static variable"
+ StaticDemo.name);
StaticDemo.name = "udhaya";
System.out.println("Value of static variable after initialization"
+ StaticDemo.name);
StaticDemo.staticVariable();
}
}
InitializeByMethod.java
package com.udhaya;
class StaticDemo {
static String name;
public static void staticVariable() {
name = name + " " + "kumar";
System.out.println("Value of static variable after method calling"
+ name);
}
}
public class InitializeByMethod {
public static void main(String[] args) {
System.out.println("Initial value of static variable"
+ StaticDemo.name);
StaticDemo.name = "udhaya";
System.out.println("Value of static variable after initialization"
+ StaticDemo.name);
StaticDemo.staticVariable();
}
}
No comments:
Post a Comment