I have a class with static variables as:
class Commons {
public static String DOMAIN ="www.mydomain.com";
public static String PRIVATE_AREA = DOMAIN + "/area.php";
}
And if I try to change DOMAIN from an Android Activity (or another java class) at runtime, the DOMAIN variable change but PRIVATE_AREA don't change. Why?
This is because the assignment of static fields happens once the class is loaded (occurs only one time) into the JVM. The PRIVATE_AREA variable will not be updated when the DOMAIN variable is changed.
public class Test {
public static String name = "Andrew";
public static String fullName = name + " Barnes";
public static void main(String[] args){
name = "Barry";
System.out.println(name); // Barry
System.out.println(fullName); // Andrew Barnes
}
}
I suggest that you use the following structure.
public class Test {
private static String name = "Andrew";
public static String fullName = name + " Barnes";
public static void setName(String nameArg) {
name = nameArg;
fullName = nameArg + " Barnes";
}
}
Test2.java
public class Test2 {
public static void main(String[] args){
System.out.println(Test.fullName); // Andrew Barnes
Test.setName("Barry");
System.out.println(Test.fullName); // Barry Barnes
}
}
This is because Static variables are initialized only once , at the start of the execution.
See more at: http://www.guru99.com/java-static-variable-methods.html
PRIVATE_AREA did't change because it is set on declaration time. When You change DOMAIN, it has no effect on PRIVATE_AREA.
Maybe it is better to work with setter(...) and getter() Methods and local variables. On getting PRIVATE_AREA You create the retrun value again.
Assignment of variable happens at the load time of class thats why after that if you change the value of one static variable, it will not reflect there where it is assigned to another variable
Related
I am trying to learn how constructors work and I have been trying to debug this simple java program but I cannot get it to run. Eclipse simple refuses to acknowledge its presence and just runs an earlier project. Any ideas would be very gratefully received - I am struggling to see what I have done wrong.
package timber;
public class Person {
private String firstName;
private String lastName;
private String address;
private String username;
public Person(String personFirstName, String personLastName, String personAddress, String personUsername)
{
firstName = personFirstName;
lastName = personLastName;
address = personAddress;
username = personUsername;
}
public void displayPersonDetails()
{
System.out.println("Name: " + firstName + " " + lastName);
System.out.println("Address: " + address);
System.out.println("Username: " + username);
}
}
I then have a second class that contains the main method
package timber;
public class PersonExample {
public void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
}
could you please add static in main method :-
public static void main(String[] args) {
Person dave = new Person("Dave", "Davidson", "12 Main St.", "DDavidson");
dave.displayPersonDetails();
}
Your main method always needs to be static.
See Why is the Java main method static?
Replace,
public void main(String[] args)
with
public static void main(String[] args)
Your main method needs to be 'static'. Why? If you want to call a method in Java, there are two ways
Create an instance of class and use that object to call it's methods
Make a method 'static' so that you can call the method using the class name and no instance creation needed.
The 'main' method, if non-static (like in your case) you have to create an instance of it's class to call. But, where would you create an instance of that class, where your main method is residing? Create another class and call from there? and create yet another class to call this class? It will never end. I mean there has to be a starting point right?
By giving the method the name 'main' and by adding the keyword 'static' in it's signature, you help JVM call that method without the need to an create instance.
Just change
public void main(String[] args)
to
public static void main(String[] args)
Everything is fine you have just missed the static keyword .
Instead of
public void main(String [] args)
Use
public static void main(String[] args)
I have a static variable and a local variable in static function with same name.
In that function how can I access to static variable.
static String s = "class level";
static private void mx(String s)
{
System.out.println(s); // i want class level
}
With the name of the class at the left:
ClassName.s=...;
Just use it's full name: ClassName.s
Within the function, using just "s" will be the local static variable. To access a static member (function or class) you can call it using
Classname.membername
In your case, if you wanted to print the local variable, you would use
System.out.println(s);
as you have rightly done.
Say your entire thing is wrapped in a class called "Test". So,
Class Test{
static String s = "Global";
static private void mx(String s)
{
System.out.println(s); // i want global
}
}
So, in order to print both the Strings (local s, and "global" s),
Class Test{
static String s = "Global";
static private void mx(String s)
{
System.out.println(s); //prints local s
System.out.println(Test.s); //prints "global" s
}
}
I still cannot fully understand this static and non static.
public static void main(String args[]){
staticClass.setString("hey there");
System.out.println(staticClass.getString2());
//expecting to be blank
NonStaticCalling nonStaticCalling = new NonStaticCalling();
}
static String aw = "";
public static void setString(String a){
aw =a;
}
public String getString(){
return aw;
}
public static String getString2(){
return aw;
}
public class NonStaticCalling {
staticClass staticClass = new staticClass();
public NonStaticCalling(){
staticClass.getString();
System.out.println(staticClass.getString());
}
}
If i understand correctly. I declare a new object nonstaticcalling. So i assume that the value of the output from that class is "" (blank)
Can someone give me a better exmaple? thanks
When a static variable is set, it is the same for all instances of the class. Static variables are also known as "class variables". I think your confusion is actually about the variable more so than the methods. Take this example with no static variables as a simple example. "name" is the same for all instances of the class "myName" (sorry should've made it capital since it's a class name).
public class myName {
public static String name;
public void setName(String newName) {
name = newName;
}
public String getName() {
return name;
}
public static void main(Strings args[]) {
myName first = new myName();
myName second = new myName();
first.setName("hello");
System.out.println(second.getName()); //prints hello
}
}
Static variables are created only one for all the objects of that StaticClass so you're return the same static variable from newly created object.
For one, you can call
NonStaticCalling.getString2()
but not
NonStaticCalling.getString()
A static method can be called without instantiating the class.
SomeName.setString("hey there");
System.out.println(SomeName.getString2());
//expecting to be blank
SomeName object = new SomeName();
object.setString2("hey there");
System.out.println(object.getString());
public class SomeName
{
static String aw = "";
String aw2 = "";
public SomeName()
{
}
public static void setString(String a){
aw =a;
}
public void setString2(String a){
aw2 =a;
}
public String getString(){
return aw;
}
public static String getString2(){
return aw;
}
}
This will print what you got! so the difference is that in one you are using a static property of the class, this means that if you change it, it changes for every other object using it in the future!
In the second one you are using an "object" or an instance of the class, this means that all variables are only set to that object while it lives! If you create a new one you will have to set up aw2 again for it!
I have a simple problem that I've been stuck on for some time and I can't quite find the answer to. Basically, I'm creating an object and trying to access the variables without using static variables as I was told that is the wrong way to do it. Here is some example code of the problem. I receive an error in the first class that can not be resolved to a variable. What I would like to be able to do is access t.name in other methods outside of the main, but also in other classes as well. To get around this previously I would use Test2.name and make the variable static in the Test2 class, and correct me if I'm wrong but I believe that's the wrong way to do it. Any help would be greatly appreciated =)
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
public class Test2 {
String name;
public Test2 (String nm) {
name = nm;
}
}
I see others have posted code snippets, but they haven't actually posted why any of this works (at the time of this writing.)
The reason you are getting a compilation error, is that in your method
public static void main(String[] args) {
Test2 t = new Test2("Joe");
}
Variable t's scope is just that method. You are defining Test2 t to only be in the main(String[] args) method, so you can only use the variable t in that method. However, if you were to make the variable a field, like so, and create a new instance of the Test class,
public class Test {
Test2 t;
public static void main(String[] args) {
Test test = new Test();
test.t = new Test2("Joe");
test.displayName();
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Then you should no longer be getting any compilation errors, since you are declaring the variable t to be in the class Test scope.
You may give the reference to your test object as an argument to method displayName:
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println("Name2: " + test.name);
}
}
Note: I also made displayName a static method. From within your main method you can only access static methods without reference.
Modify the Test class to this
public class Test {
private static Test2 t;
public static void main(String[] args) {
t = new Test2("Joe");
}
public void displayName() {
System.out.println("Name2: " + t.name);
}
}
Use a getter for your purpose. This is a side solution to your problem, but generally this is how you should retrieve instance variables, using getters.
public class Test {
public static void main(String[] args) {
Test2 t = new Test2("Joe");
displayName(t);
}
public static void displayName(Test2 test) {
System.out.println(test.getName());
}
}
public class Test2
{
private String name;
public Test2 (String nm)
{
name = nm;
}
public String getName()
{
return name;
}
}
Always remember, variables in your class should be private. That protects it from access from outside the class. Hence, getters are the only way to access them. And setters or constructors to initialize them.
Fewer statics the better I reckon.
I would Instantiate Test and call displayName on the instance of it, then pass the instance of Test2 to displayName.
But it does depend on what the overall aim is
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 5 years ago.
class Singer
{
String name;
String album;
public Singer(){
name="Whitney Houson";
album="Latest Releases";
}
public static void main(String[] args)
{
System.out.println("Name of the singer is "+name);
System.out.println("Album Information stored for "+album);
}
}
When i run this code i am finding error which says that non static variable name cannot be referenced from a static context
That's because the variables name and album do not exist in the main procedure, because it's static, which means it cannot access instance-level members. You will need an instance of the Singer class, like this:
public static void main(String[] args) {
Singer s = new Singer();
System.out.println("Name of the singer is " + s.name);
System.out.println("Album information stored for " + s.album);
}
However, unless you declare your name/album members with a public access modifier, the above code will fail to compile. I recommended writing a getter for each member (getName(), getAlbum(), etc), in order to benefit from encapsulation. Like this:
class Singer {
private String name;
private String album;
public Singer() {
this.name = "Whitney Houston";
this.album = "Latest Releases";
}
public String getName() {
return this.name;
}
public String getAlbum() {
return this.album;
}
public static void main(String[] args) {
Singer s = new Singer();
System.out.println("Name of the singer is " + s.getName());
System.out.println("Album information stored for " + s.getAlbum());
}
}
Another alternative would be to declare name and album as static, then you can reference them in the way you originally intended.
A non-static member or class needs to be instanced in order to exist. Then, accessing a non-static member or object from a static member does not guarantee that this member or object is instantiated, then access to it is impossible.
You will need to create an instance of your non-static object within your static context to make it.
class Singer {
String name;
String album;
// You will need the following to make your code compile,
// and the call to these getters within your 'main' function.
public getName() {
return name;
}
public getAlbum() {
return album;
}
public Singer() {
name="Whitney Houson";
album="Latest Releases";
}
}
public static void main(String[] args) {
Singer singer = new Singer();
System.out.println("Name of the singer is " + singer.getName());
System.out.println("Album Information stored for " + singer.getAlbum());
}
This way, you include the instantiation of the Singer object into a static object, thuis assuring it is instantiated properly before it is accessed.
Main is a static method. Instance variables (variables defined in the class but not marked as static) cannot be accessed from a static method without referencing an instance of the class.
public static void main(String[] args)
{
Singer singer = new Singer();
System.out.println("Name of the singer is " + singer.name);
System.out.println("Album Information stored for " + singer.album);
}
One option is what Chris Hutchinson mentioned. The other one is to declare them static.
main is a static method. So name and album have to be declared as static.
private static String name;
private static String album;
To expand more on Chris' answer, you can technically have as many instances of the Singer class as your memory can support, but there is only ever one instance of the main function running. This means that attempting to access those variables from the static function means it has no idea which instance of the variable it should be accessing, hence the error.
You can make the variables local to the main function, but that would probably defeat the purpose of the program then since logic would dictate there can be more than one singer (most likely). A better plan of attack would be to create a generic class that houses the main function, and then create a Singer class within that (or elsewhere) and instantiate X instances of that class in your main function and go from there.