0

I have declared variable on top after import

String sk5;

putted value in sk5

sk5 = s.substring(s.lastIndexOf("-")+1).replace("]", "");

        System.out.println("Checking sk5->"+sk5);

It is printing value well, but when I am using this variable in other function it prints NULL. please suggest me how to solve this.

user3675069
  • 53
  • 1
  • 10

3 Answers3

1

The most common cause for this problem is the assumption that all sk5 variables are the same. If you have multiple variables, or multiple instances, you actually have multiple fields/variables with the same name.

The simplest way to check this is to look at what your code is doing when you step thorugh it in your debugger.

enter image description here

You can see in the following example, you have three variables called sk5 with three different values.

class MyClass {
   int sk5;

   public static void main(String... s) {
     MyClass a = new MyClass(), b = new MyClass();
     a.sk5 = 1;
     b.sk5 = 2;
     int sk5 = 3;
     System.out.println(a.sk5+" " + b.sk5 + " " + sk5);
   }
}

prints

1 2 3 
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

i assume you want to define a class variable, so you should use

public static String sk5;

BUT defining a public static variable which is not final is a bad code style. If you want to use class variables in other classes, you should implement a getter-Method like

private static String sk5;

public static String getSk5(){
   return sk5;
}

and still a static variable is not the best. Try to check Singleton instead, depending on our usecase it could make sence

from my point of view the best is to define

private String sk5;

public String getSk5(){
   return sk5;
}

so you can call

TestClass s = new TestClass();
String t = s.getSk5();
Community
  • 1
  • 1
Markus Lausberg
  • 12,177
  • 6
  • 40
  • 66
-1

Are you using C#?

Normally, global variables are defined direclty after Class definition as shown here:

    class MyNewClass{
     public string newglobalval;
   public MyNewClass(){
    newglobalval = "Hello";

}

  public void ShowGlobalVal(){
    Console.Write(newglobalval);

} }

Edit: Well, someone was faster, however the variable doesnt need to be static.

Peace.

Thomas
  • 1