Does Java have an equivalent keyword to static in C? [duplicate] - java

This question already has answers here:
How do I create a static local variable in Java?
(8 answers)
Closed 6 years ago.
I know that in C, when the keyword static is used on a local variable, it causes that variable to remain initialized between function calls (i.e. when the variable goes out of scope). For example:
int myFunction() {
static int i = 3;
i++;
return i;
}
If myFunction() is called twice, it will return 4 the first time and 5 the second time (because i keeps its value between the two calls rather than being reinitialized the second time).
My question is this: does Java have an equivalent keyword to static in C? Java also has the keyword static, but it is used completely differently than in C.

Not exactly, but a private static class level variable will almost do the same thing.
But
it will be visible to all other methods of the class as well
it will be initialized not on first method call, but when the class itself is loaded
I suppose that is workable.

All variables in a method are local to the function and placed on the stack. The closest you have is a static variable in a class.
If you make the variable private and place the method in a class of it's own you will achieve much the same result.
(With a private constructor)

It's somewhat similar to the private keyword, as in C a static global variable or a function is visible only in the file it's declared in...
So that's probably the closest you will find :)

No, because all methods and functions are bound to classes in Java, so there is no "global space" as there is in C. The static keyword in Java has different semantics.
See the docs for static and this post for more detail on the differences.

Java uses static in a different manner. To get the same result you want here, you should use a private field instead.

Related

can a method be declared with static type argument in java ? if no, why? [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 6 years ago.
can a method be declared with static type argument in java ? if no, why?
ex:
class A
{
void m(static int x)
{
System.out.println(x);
}
}
I don't believe this is possible and I cannot think of any valid use case for doing it.
It may make sense to make the method static in order to implement a singleton pattern.
class A
{
static void m(int x)
{
System.out.println(x);
}
}
Then it could be used without having to instantiate A as follows:
A.m(1);
Alternatively you might want to make x immutable to avoid unexpected behavior. This would be done using "final" as follows:
class A
{
void m(final int x)
{
System.out.println(x);
}
}
But making x static would serve no purpose.
No it won't be allowed (compiler error) and it makes sense as well. The static keyword means that a variable will have only one instance in its scope and that instance is invisible outside that scope. Neither of this makes sense for a function argument.
§6.7.5.3/2: "The only storage-class specifier that shall occur in a parameter declaration is register."
Static members are considered as class level members and gets loaded
in memory during class loading, which means it is desirable that it
shouldn't have dependency on the class instances.
So your class has member method m which need a parameter to be passed to execute the method body.
If you declare a static member for it that doesn't make any sense
because it doesn't have any existence outside the method, class has no
information about it load time which severely violates all the rules stated
above.

Why is the "this" keyword final in Java? [duplicate]

This question already has answers here:
Why is assignment to 'this' not allowed in java?
(7 answers)
Closed 8 years ago.
It seems a thing that almost no one has realized, but the "this reference" in Java is final. In a normal programming day I thought I could redefine the entire instance by redefining the this reference inside the own class:
public void method() {
this = new MyObject("arg1", arg2, arg3); //it throws a compile error
}
Why the this reference is final in Java?
The problem is not that this is a final reference - it's not itself a reference at all. this is a keyword that "denotes a value that is a reference to the object for which the instance method or default method was invoked" (JLS §15.8.3).
Furthermore, it wouldn't make sense to reassign it in the sense that a variable can be reassigned. Remember that reassigning a reference changes only that reference, and not other references that might point to the same object. So reassigning this would not only be insane but also useless.
I find this question interesting from a theoretical point of view.
From a technical point of view this cannot work, as in Java we have pass-refererence-by-value ( http://www.javaworld.com/article/2077424/learn-java/does-java-pass-by-reference-or-pass-by-value.html ) and cannot swap out objects where some other parts of code hold a reference to that object -- i.e. a true swap method is not possible in Java (see the linked article).
While you could theoretically reassign this, all other references to the object would not change and make the operation pretty senseless.
The closest thing you can achieve is a copy constructor.
this is not a variable you can assign a value to. It is a built-in expression returning the object that is the context for the method currently executing.
While re-assigning this might be useful for some nice hacks, it would mess up all kind of things.
The this keyword is used to provide a reference to the current object within its class. Mostly, it is used to clarify scope issues with local variables which have the same identifier as a class member. E.g.
public void function (int param) {
this.param = param
}
Reassigning it to another object goes beyond the task assigned to the keyboard. What you want to do, (reassing a reference) can be achieved on the upper context, i.e. the context in which the object was created (and a reference to it was assigned).
Wrong thinking about this. this is just a keyword(not variable) in java which referenced to current instance and its a compilation restriction that keyword(any not only this) can not be initialized.

what's Inlining in Java? Is there any relation between final keyword and Inlining? [duplicate]

This question already has answers here:
Inlining in Java
(8 answers)
Closed 8 years ago.
Is it an example of inlining?
final class Executive extends Manager
{
public raiseSalary(int byPercent)
{
return salary;
}
}
Is it an example of inlining?
No, it's not.
Is there any relation between final keyword and Inlining?
Kind of. Read this:
Contrary to the implication of many tips, methods declared as final
cannot be safely inlined by the compiler, because the method could
have a non-final declaration at runtime.
To see why, suppose the compiler looks at class A and subclass B, and
sub-subclass C and sees a final method in A which it inlines into C.
But then at runtime the versions loaded for A and B are different and
the method is not final in A, and overridden in B. Then C uses the
incorrectly inlined version.
From http://www.javaperformancetuning.com/tips/final.shtml
No, that it's not 'Inlining'.
Inlining is when the compiler decide to replace your function call with the body of the function.
Read here for full example https://stackoverflow.com/a/3925068/3743987
Java compiler does not inline final classes or methods. You can check this article.
As I know, inlining is applied to primitive constant statements. For example, the Java compiler replaces all the occurrences of MY_NUMBER constant below with 10 during the compilation phase. Therefor, at runtime, Java does not need to make memory access to read the value of MY_NUMBER.
private static final int MY_NUMBER = 10;

What's the difference between the static variable and the global variable (Java)? [duplicate]

This question already has answers here:
Difference between static and global variable in Java
(5 answers)
Closed 6 years ago.
I'm so confused by the difference between static variables and the global variables. When I browsing a Java textbook today, my eyes were caught by "Variables declared as static are, essentially, global variables. When an object is declared, no copy of a static variable is made." I am crystal clear about why static variable is shared by all objects in its class, but I don't get why static variables are global variables. In my understanding, the static variables could be only considered as "global" in its class.
Static variables can (and should) be accessed using Class.Variable.
A static variable will always be available globally if they're public.
public class MyClass {
public static int X = 5;
}
Can be accessed everywhere the class is available using
MyClass.X
There's no actual 'global' keyword or anything, but it's close to its intention.
I think your book is (wrongly) using global as an easier way to describe a variable tied to a class.
For instance, take this class:
public class Apple {
private static int numberOfApples = 0;
public Apple() {
numberOfApples++;
System.out.println(numberOfApples);
}
}
Each time an Apple is created it will increment the numberOfApples variable and print it out. If you create two Apple objects then it will print:
1
2
The static variable in this case is globally shared by all Apple instances which may be what it means, but that is because it's tied to the class. This is different than a global variable in other languages.
edit: As others have mentioned, you can access a static variable without any instantiations of the class. If I made numberOfApples public and printed it out before creating any Apple instances then it would print 0. Similarly, after creating two Apple classes and then having both objects be destroyed, I could print numberOfApples and it would say 2.
Static: there exists exactly one variable with that name. (while instance variables exist for every instance)
Global: Static and visibility is public.
Hence, every global variabel must be static.
Example of a global variable is: java.lang.System.out
What's the difference between the static variable and the global variable (Java)?
The difference is that global variables don't exist in Java. Your book shouldn't even have mentioned them.
As far as i Know, memory is allocated by object which is declared in main which calls the method. If it invokes a non-static variable, then it is initialized everytime it is invoked. On the other hand, memory is allocated for static variable once only then whenever it is called it's value remains same.

final variable in methods in Java [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why would one mark local variables and method parameters as “final” in Java?
I was checking some Java code, I am not good at java at least have some knowledge what final does such as sealed classes, readonly fields and non-overridable methods but this looks weird to me, declaring a variable final in methods:
private static void queryGoogleBooks(JsonFactory jsonFactory, String query) throws Exception {
// Set up Books client.
final Books books = Books.builder(new NetHttpTransport(), jsonFactory)
.setApplicationName("Google-BooksSample/1.0")
.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) {
BooksRequest booksRequest = (BooksRequest) request;
booksRequest.setKey(ClientCredentials.KEY);
}
})
.build();
Could you tell me what the meaning of final is in this context?
Here is the complete code:
http://code.google.com/p/google-api-java-client/source/browse/books-cmdline-sample/src/main/java/com/google/api/services/samples/books/cmdline/BooksSample.java?repo=samples
It simply makes the local variable books immutable. That means it will always be a reference to that same Book object being created and built, and cannot be changed to refer to another object, or null.
The Book object itself is still mutable as can be seen from the sequence of accessor calls. Only the reference to it is not.
In this case, final Books books simply means that books must be assigned a value exactly once.
I like to use the final keyword like this as it shows intent of the variable, which I find to be valuable information when looking at code as it removes yet another variable from the situation...so to speak.
If I don't mark a variable as final then it stands out as something to keep my eye on because it's going to change values sometime soon. This information is helpful while, for example, stepping through the code in the debugger or refactoring & moving around code.
For further reading on all things final: The Final Word On the final Keyword
This likewise makes the variable reference read-only. Usually, this is to protect the code from accidentally modifying a variable that must not change.
I'm pretty sure it means nothing more than the variable books cannot be overwritten later on in the method.
This code is using anonymous class JsonHttpRequestInitializer, where it refers to the local variable in method queryGoogleBooks, the problem in this kind of situation is that the queryGoogleBooks method could return before initialize method of the JsonHttpRequestInitializer is completed, where it could cleanup the variable and could cause the initialize method of JsonHttpRequestInitializer to fail. So it is required to declare the variables as final in this type of situations. For more details refer to,
Cannot refer to a non-final variable inside an inner class defined in a different method

Categories