Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
According to this post Global variables in Java it describes how to define a global variables in java by using static
public class Example {
public static int a;
public static int b;
}
But at same time in other post Why are there no global variables in Java? this question contradicts .
So my question is what exactly is global variable ?
Do java supports global variables ?if yes ,how?
if no ,why?
and how java global variables(if there are any) are different from c++ global variables?
I think that we can argue that there is no global keyword in java but your example can be treated like a global.
In most languages where you can define a global variable the problem is that they pollute the global namespace and name clashes can occur (like in php). In this regard there are no globals in java since there is no global namespace: variables are always in a class.
So the main thing is: there is no explicit globan in java and there is no globan namespace in java. This frees you from name clashes and accidental overwrites which is a good thing.
But there is nothing stopping you from creating a Global class with a lot of public static fields in it.
Please note that most guys (including me) would break both of your hands for doing so. :)
a gloabal variable is used by many functions without need to enter it in the input of these functions.
Expert advice to don't use them.
A global variable is a variable which can be accessed from anywhere (from any part of the program). Thus a public static variable in any Java class is global.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I realized that in many languages I have learned includes the keywords public and private, and I also found out that Lua's equivalent to private is local which got me thinking if there is also an equivalent in C and Python.
So is there an actual equivalent of Java's public and private in C and Python?
There is a naming convention for protected and private fields in Python:
A prefix of one underscore means protected, two underscores mean private. But this is not really enforced. More details here:
https://www.tutorialsteacher.com/python/private-and-protected-access-modifiers-in-python
Everything not prefixed with one or two underscores is public.
In C, global variables and functions can be accessed from functions in other source files unless they are declared static. Not exactly the same as private, but C is not object-oriented so the concept of a class does not exist here.
In python you can declare private members by putting dunders(double underscore) before member name, like this :
class Sample:
def __init__(self):
self.__private_mem = "Can be accessed only by member functions"
self.public_mem = "Can be accessed as object properties outside the class"
sample = Sample()
print(sample.public_mem)
print(sample.__private_mem) # will raise an Error
But, I guess there is no such thing in C language as it is not object oriented.
This question already has answers here:
Why is there a problem with a non-static variable being read from main?
(3 answers)
Closed 6 years ago.
I seem to have a dilemma. Sparing the complicated details of my project, i'm attempting to do the following. (excluding and replacing some code like imports and try-catch for simplicity)
1 public class Client
2 {
3 private Registry reg1;
4 private GameSessionInterface sesh1;
5
6 public static void main(String[] args)
7 {
8 reg1 = LocateRegistry.getRegistry(serverIP, 4200);
9 sesh1 = (GameSessionInterface)reg1.lookup("Session1");
10 }
11 }
On lines 8 and 9 i get the errors "Cannot make a static reference to the non-static field reg1" and "Cannot make a static reference to the non-static field sesh1" respectively.
if i declare reg1 and sesh1 inside of main, i don't get this issue. But i need at the very minimum sesh1 to be global so i can make methods accessing it outside of main.
I'm not 100% sure how RMI variables work in the JVM so I'm unsure whether it's safe to declare these as static. Logic would follow that since i'm not going to be making more than one instance of Client in the same JVM, it shouldn't matter, but considering this is a reference to a remote object, I didn't know if this would have some unseen side effects. I've searched for a while and no one seems to address this. But at the same time I can't seem to find examples of code with these declared statically, which also begs the question why can't I compile it as is when similar code exists elsewhere with non-static declarations made globally.
I'm REALLY new to RMI in java so if any of you with more RMI experience could shed some light on how all this interacts and why I might be getting this error, I would greatly appreciate it.
Thanks in advance!
RMI variables are no different from any other variables. You could for example have declared both variables as local within main().
However if you're creating a Registry with LocateRegistry.createRegistry(), it is essential to store it into a static variable. Otherwise it can be garbage-collected and disappear.
the question why can't I compile it as is when similar code exists elsewhere with non-static declarations made globally
No it doesn't. Look again. The rules for static and instance variables are the same throughout Java. RMI does not and cannot change that.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
In this simple program is this good practice or what?
Can we use the same name as that of class in variable? IF yes, is there some particular term to use it? Is it a good practice?
class test {
public static void main (String args[]) {
int test;
System.out.println(test);
}
}
It is perfectly fine from a language grammer - syntax perspective. The compiler does not mix Class name with a variable name, since both will be in different scope. Both mean different things to the compiler. So it is perfectly fine to have a variable name as the same as the Class name.
The next aspect is the readability and maintainability. In this aspect, it is a very bad practice to have both the same. Because human beings mistake one for another. The very question you had asked itself is a sign that it will be difficult to maintain and manage such a piece of code.
Moreover the program which you have provided will result in a compilation error saying test is not initialized.
There are well-defined naming conventions in Java. Class names should begin with capital letters and variables should begin with lower case letters. These rules are not enforced, so as you have discovered you can define a variable with the same name as a class. In any language, if two entities have the same name, the language designers have to make a decision about how to interpret that name. In this situation, the decision was taken that whenever the variable is in scope the name refers to the variable, not the class. As a result it is impossible to refer to the class by its simple name (you can still use its fully qualified name though). As a result it's called obscuring. You should not do it because people reading your code will get very confused if you don't follow the standard naming conventions. You should also not do it because the person reading your code may not know whether the name is referring to the variable or the class. There's no reason why they should know - this is a very obscure corner of Java and there's no reason to do it anyway.
For more information, Java Puzzlers by Bloch and Gafter includes a detailed discussion (p.180 - 182) of all the different types of name reuse in Java (overriding, hiding, overloading, shadowing and obscuring).
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I want to know why this problem occurs.
public class Sorter {
public static char[] selectSort(String targetStr) {
private char[] charArray = new char[targetStr.length()];
The problem occurs when the variable charArray is made private and there is a message:
Modifier 'private' not allowed here.
Can anyone explain to me thoroughly why this happens so that I can better handle them in the future?
You can't have access modifiers to method local variables.
All the method local variables are visible only inside the method.
You cannot use access modifiers with fields declared within method scope (i.e. local fields).
So neither private nor public nor protected.
Here is a tutorial on Java variables that broaches the subject.
That char array(charArray ) is already local to that method., You cannot access that outside of that method anyway. So access modifier doesn't make sense there.
Scope of that variable is only till that method it cant be used outside that so there is no need to give access specifier to it.
Any variable created inside a method is local to that method only and it cant be accesed outside.
Scope of that variable char Array is only till that method it cant be used outside that so there is no need to give access specifier to it.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After reading global-variables-in-java, I found it's not suggested to declare global
variables. However, what's a better approach if I want to declare constant variables viewed by all methods in all classes. How to make those variables' scope global? How and why, thank you!
if I want to declare constant variables viewed by all methods in all classes
If those are really constants, then public static final fields are perfectly fine.
What kind of data is this? Does it need to externally configurable (at run time or build time)? Does it need to computed at application startup? Does that computation require external resources (such as files or networks) that may be unavailable or slow?
Well, the variables are indicating the state, in different drawing state(draw, erase...).
Not sure I understand what that means exactly, but maybe you want to define an enum?
I don't want to pass lots of parameter each time
That is a bad argument to use global variables.
Maybe you want to combine multiple arguments in a holder object?
Or have stateful objects with methods (as opposed to stateless functions that take many parameters).
But I still have to new a class containing these constants.
No. You can do
public final class MyConstants{
public static final String MY_OAUTH_KEY = "ABCDEFGH";
// maybe this should come from pom.xml
public static final String APP_VERSION = "0.0.1";
}
and then use it from anywhere in your code
System.out.format("You are running version %s%n", MyConstants.APP_VERSION);