Java initializing object - Static vs non-Static access - java

I haven't been coding anything for a while now and I decided to practice a bit. I came up with this issue at the very beginning of my program and I spent last night trying to figure out or find a way around this problem but I didn't get any expected results.
First, let's see the class:
public class Task {
private static int priority;
private static int taskTime;
private static boolean solved;
public void setPriority(int p){this.priority = p;}
public void setTasktime(int t){this.taskTime = t;}
public void setSolved(boolean s){solved = s;}
public int getPriority(){return this.priority;}
public int getTaskTime(){return this.taskTime;}
public boolean getSolved(){return this.solved;}
public Task(int p, int t){
this.priority = p;
this.taskTime = t;
this.solved = false;
}
public static class ComparePriority implements Comparator<Task>{
#Override
public int compare(Task t1, Task t2){
return Integer.compare(t1.getPriority(), t2.getPriority());
}
}
}
Now, this is the piece of code I am trying to run:
public class main {
public static void main(String[] args) {
Task t1 = new Task(20,1);
Task t2 = new Task(13,2);
Task t3 = new Task(10,5);
ArrayList<Task> t = new ArrayList<Task>();
t.add(t2);
t.add(t3);
t.add(t1);
System.out.println("List size: " + t.size());
System.out.println("T1 object's priority: " + t1.getPriority());
System.out.println("T2 object's priority: " + t2.getPriority());
System.out.println("T3 object's priority: " + t3.getPriority());
for(int i=0;i<t.size();i++){
System.out.println("Current object task time: "+ t.get(i).getTaskTime());
System.out.println("Current index:" + i);
}
Collections.sort(t, new Task.ComparePriority());
for(int i=0;i<t.size();i++){
System.out.println("Current object task time (post sort): " + t.get(i).getTaskTime());
System.out.println("Current index: " + i);
}
}
I understand that these attributes were defined in a static way and I should be accessing them as Class.method();
If I were to instantiate 3 objects (as used as example up above), is there any way to access them statically but still get every piece of information read from the object to be unique instead of "the same"?
Also why is accessing them non-statically discouraged?

You are asking for contradicting things.
access them statically
contradicts
still get every piece of information read from the object to be unique instead of "the same"
If you wish the former, you should expect the same value to be seen by all instances.
If you wish the latter, don't define them as static.
As for accessing them non-statically, as far as I know it makes no difference. They only reason I'd avoid accessing static members non-statically (i.e. by dereferencing an object of that class) is readability. When you read object.member, you expect member to be a non-static member. When you read ClassName.member you know it's a static member.

When a static method is called, it deals with everything on the class-level, rather than the object-level. This means that the method has no notion of the state of the object that called it - it will be treated the same as for every object that calls it. This is why the compiler gives a warning. It is misleading to use a static method with the form a.Method() because it implies that the method is invoked on the object, when in the case of static methods, it is not. That's why it's bad practice to call a static method on an instance of an object.

I think you misunderstand the difference between class variable and static variable. Program has only one value for static variable mean while every object has it own value for a class variable. It is also considered misleading to use this with static members.

Accessing them non-statically is not discouraged at all in programming, but actually encouraged. If you want to access things non-statically, try putting that code in another class in a method. Then in this class put
public static void main(String[] args) {
AnotherClass ac = new AnotherClass();
ac.initializeProcess()
}
I don't know why people like downgrading questions, I guess they think they were never new at all.
Update:
Static objects don't get thrown in the garbage-collector too quickly but it is saved as long there are references to it; static objects can cause memory issues

Related

A reference to primitive type in Java (How to force a primitive data to remain boxed)

I would like to pass a reference to a primitive type to a method, which may change it.
Consider the following sample:
public class Main {
Integer x = new Integer(42);
Integer y = new Integer(42);
public static void main(String[] args) {
Main main = new Main();
System.out.println("x Before increment: " + main.x);
// based on some logic, call increment either on x or y
increment(main.x);
System.out.println("x after increment: " + main.x);
}
private static void increment(Integer int_ref) {
++int_ref;
}
}
The output running the sample is:
x Before increment: 42
x after increment: 42
Which means int_ref was past to the function by value, and not by reference, despite my optimistic name.
Obviously there are ways to work around this particular example, but my real application is way more complex, and in general one would imagine that a "pointer" or reference to integer would be useful in many scenarios.
I've tried to pass Object to the function (then casting to int), and various other methods, with no luck. One workaround that seems to be working would be to define my own version of Integer class:
private static class IntegerWrapper {
private int value;
IntegerWrapper(int value) { this.value = value; }
void plusplus() { ++value; }
int getValue() { return value; }
}
Doing this, and passing a reference to IntegerWrapper does work as expected, but to my taste it seems very lame. Coming from C#, where boxed variable just remain boxed, I hope I just miss something.
EDIT:
I would argue my question isn't a duplicate of Is Java "pass-by-reference" or "pass-by-value"?, as my question isn't theoretical, as I simply seek a solution. Philosophically, all method calls in all languages are pass-by-value: They either pass the actual value, or a reference to the value - by value.
So, I would rephrase my question: What is the common paradigm to workaround the issue that in java I'm unable to pass a reference to an Integer. Is the IntegerWrapper suggested above a known paradigm? Does a similar class (maybe MutableInt) already exist in the library? Maybe an array of length 1 a common practice and has some performance advantage? Am I the only person annoyed by the fact he can store a reference to any kind of object, but the basic types?
Integer is immutable, as you may notice.
Your approach with private static class IntegerWrapper is correct one. Using array with size 1 is also correct, but in practice I have never seen using array for this case. So do use IntegerWrapper.
Exactly the same implementation you can find in Apache org.apache.commons.lang3.mutable.MutableInt.
In your example you also can provide Main instance to the static method:
public class Main {
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
incrementX(main);
}
private static void incrementX(Main main) {
main.x++;
}
}
And finally, from Java8 you could define an inc function and use it to increment value:
public class Main {
private static final IntFunction<Integer> INC = val -> val + 1;
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
main.x = INC.apply(main.x);
}
}

Does Java support static variables inside a function to keep values between invocations?

https://stackoverflow.com/a/572550/1165790
I want to use this feature in Java because the function that I'm designing is called rarely (but when it is called, it starts a recursive chain) and, therefore, I do not want to make the variable an instance field to waste memory each time the class is instantiated.
I also do not want to create an additional parameter, as I do not want to burden external calls to the function with implementation details.
I tried the static keyword, but Java says it's an illegal modifier. Is there a direct alternative? If not, what workaround is recommended?
I want it to have function scope, not class scope.
I want it to have function scope, not class scope.
Then you are out of luck. Java provides static (class scoped), instance and local variables. There is no Java equivalent to C's function-scoped static variables.
If the variable really needs to be static, then your only choice is to make it class scoped. That's all you've got.
On the other hand, if this is a working variable used in some recursive method call, then making it static is going to mean that your algorithm is not reentrant. For instance, if you try to run it on multiple threads it will fall apart because the threads will all try to use the same static ... and interfere with each other. In my opinion, the correct solution would be either to pass this state using a method parameter. (You could also use a so-called "thread local" variable, but they have some significant down-sides ... if you are worrying about overheads that are of the order of 200 bytes of storage!)
How are you going to keep a value between calls without "wasting memory"? And the memory consumed would be negligible.
If you need to store state, store state: Just use a static field.
Caution is advised when using static variables in multi-threaded applications: Make sure that you synchronise access to the static field, to cater for the method being called simultaneously from different threads. The simplest way is to add the synchronized keyword to a static method and have that method as the only code that uses the field. Given the method would be called infrequently, this approach would be perfectly acceptable.
Static variables are class level variables. If you define it outside of the method, it will behave exactly as you want it to.
See the documentation:
Understanding instance and Class Members
The code from that answer in Java...
public class MyClass {
static int sa = 10;
public static void foo() {
int a = 10;
a += 5;
sa += 5;
System.out.println("a = " + a + " sa = " + sa);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
foo();
}
}
}
Output:
$ java MyClass
a = 15 sa = 15
a = 15 sa = 20
a = 15 sa = 25
a = 15 sa = 30
a = 15 sa = 35
a = 15 sa = 40
a = 15 sa = 45
a = 15 sa = 50
a = 15 sa = 55
a = 15 sa = 60
sa Only exists once in memory, all the instances of the class have access to it.
Probably you got your problem solved, but here is a little more details on static in Java. There can be static class, function or variable.
class myLoader{
static int x;
void foo(){
// do stuff
}
}
versus
class myLoader{
static void foo(){
int x;
// do stuff
}
}
In the first case, it is acting as a class variable. You do not have to "waste memory" this way. You can access it through myLoader.x
However, in the second case, the method itself is static and hence this itself belongs to the class. One cannot use any non-static members within this method.
Singleton design pattern would use a static keyword for instantiating the class only once.
In case you are using multi-threaded programming, be sure to not generate a race condition if your static variable is being accessed concurrently.
I agree with Bohemian it is unlikely memory will be an issue. Also, duplicate question: How do I create a static local variable in Java?
In response to your concern about adding an additional parameter to the method and exposing implementation details, would like to add that there is a way to achieve this without exposing the additional parameter. Add a separate private function, and have the public function encapsulate the recursive signature. I've seen this several times in functional languages, but it's certainly an option in Java as well.
You can do:
public int getResult(int parameter){
return recursiveImplementation(parameter, <initialState>)
}
private int recursiveImplementation(int parameter, State state){
//implement recursive logic
}
Though that probably won't deal with your concern about memory, since I don't think the java compiler considers tail-recursive optimizations.
The variables set up on the stack in the recursive call will be function (frame) local:
public class foo {
public void visiblefunc(int a, String b) {
set up other things;
return internalFunc(a, b, other things you don't want to expose);
}
private void internalFunc(int a, String b, other things you don't want to expose) {
int x; // a different instance in each call to internalFunc()
String bar; // a different instance in each call to internalFunc()
if(condition) {
internalFunc(a, b, other things);
}
}
}
Sometimes state can be preserved by simply passing it around. If required only internally for recursions, delegate to a private method that has the additional state parameter:
public void f() { // public API is clean
fIntern(0); // delegate to private method
}
private void fIntern(int state) {
...
// here, you can preserve state between
// recursive calls by passing it as argument
fIntern(state);
...
}
How about a small function-like class?
static final class FunctionClass {
private int state1; // whichever state(s) you want.
public void call() {
// do_works...
// modify state
}
public int getState1() {
return state1;
}
}
// usage:
FunctionClass functionObject = new FunctionClass();
functionObject.call(); // call1
int state1AfterCall1 = functionObject.getState1();
functionObject.call(); // call2
int state1AfterCall2 = functionObject.getState1();

Is static bad? How to remove static variables?

I have some code that I am working on. It's basically takes in user input and creates a directed graph. One person can travel one way, the other person the opposite. The output is the overlap of where they can visit.
I have most everything working the way that I want it to, but I am concerned with the use of static that I have. I don't seem to fully understand it and no matter where I look, I can't find out its exact use OR how to get rid of it.
Could someone please help me to understand what static is and why it would be helpful?
Also, would it be better to move most the code from MAIN to helper methods? If I do this I have to move all my variables from main to the top of the class and then they all have to be declared as static?!
The reason everything has to be static is because you aren't creating any objects. If you were to create an object by calling new in your main method, you could use non-static variables on that object. This isn't really a good place to give you a tutorial on why you might want to use object-oriented design; you can find one of those online to read (a commenter above gave a possible reference). But the reason everything has to be static is because it's all just running from the main method, which is always static in java. If you were to call new somewhere, you could use non-static variables.
Static makes a method or a variable accessible to all the instances of a class. It's like a constant, but for classes. To make it more easy to understand some code will do the work:
public class Example {
public static int numero;
}
public class Implementation {
public static void main (String args[]) {
Example ex1 = new Example();
Example ex2 = new Example();
Example.numero=10;
System.out.println("Value for instance 1 is: " + ex1.numero);
System.out.println("Value for instance 2 is: " + ex2.numero);
}
}
Running the follwing code will output:
Value for instance 1 is: 10
Value for instance 2 is: 10
Because you set the static variable numero (number in italian) to 10.
Got it?
It looks like a lot of your static methods (findNodeInList, etc) all take the ArrayList (which represents a map) as their first argument. So instead of having it static, you could have a class Map, which stores a list of nodes and has methods on them. Then the main method would read the input, but not have to manage any nodes directly. e.g:
class Map {
ArrayList<Node> nodes;
public void addNode(Node n) { nodes.add(n); }
public int findNodeInList(String s) { ... }
...
public static void main(String[] args) {
Map peggyMap = new Map();
Map samMap = new Map();
// Read the data
samMap.add(new Node(...));
}
}
This keeps all the stuff to do with nodes/maps well encapsulated and not mixed in with stuff to do with reading the data.
Static is useful if you going to be using the class/method throught out your program and you don't what to create a instance every time you need to use that method.
For ex
public class StaticExample {
public static void reusable() {
//code here
}
}
It means you can use it like this
StaticExample.reusable();
and you don't have to create an instance like this
StaticExample staticExample = new StaticExample();
staticExample.reuseable();
I hope this help you decide whether to use static or not.

Is using static private methods really faster/better than instance private methods?

What I'm asking is whether there is a difference between doing this:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
And this:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private static boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
I actually use option 1 as it seems more natural to me.
So is there a style/convention/performance difference between the first and the second way ?
Thanks,
As suggested in the comments I tested it, in my benchmarks the dynamic method is faster.
This is the test code:
public class Tests {
private final static int ITERATIONS = 100000;
public static void main(String[] args) {
final long start = new Date().getTime();
final Service service = new Service();
for (int i = 0; i < ITERATIONS; i++) {
service.doImportantBlStuff(new SomeDto());
}
final long end = new Date().getTime();
System.out.println("diff: " + (end - start) + " millis");
}
}
This is the service code:
public class Service {
public void doImportantBlStuff(SomeDto dto) {
if (checkStuffStatic(dto)) {
}
// if (checkStuff(dto)) {
// }
}
private boolean checkStuff(SomeDto dto) {
System.out.println("dynamic");
return true;
}
private static boolean checkStuffStatic(SomeDto dto) {
System.out.println("static");
return true;
}
}
For 100000 iterations the dynamic method passes for 577ms, the static 615ms.
This however is inconclusive for me since I don't know what and when the compiler decides to optimize.
This is what I'm trying to find out.
Performance wise: The difference, if any, is negligible.
The rule of thumb is to declare your method static if it doesn't interact with any members of its class.
If the result of the function does not depend on anything but the arguments, it should be static. If it depends on an instance, make it an instance member.
It's not about performance; it's about semantics. Unless you're calling this function a million times a second, you will not notice a performance difference, and even then the difference won't be significant.
It all depends on the context. Generally static methods/variables are declared in a class so that an external class can make use of them.
If you are making a call to a local method then you should generally use instance methods rather than making static calls.
FYI, your syntax for calling the static method from an instance method is wrong. You have to supply the class name.
If your method requires instance data or calls to other instance methods, it must be an instance method.
If the function only depends on its arguments, and no other static data, then it might as well be an instance method too - you'll avoid the need to repeat the class name when you invoke the static function.
IMHO, there's no particular need to make the function static unless:
it's callable from other classes (i.e. not private), and
it doesn't refer to instance variables, and
it refers to other static class data
It might, it might not. It might be different between different executions of your code.
Here's the only thing that you can know without digging into the Hotsport code (or the code of your non-Hotspot JVM):
The static method is invoked with invokestatic, which does not require an object reference.
The instance private method is invoked with invokespecial, which does require an object reference.
Both of those opcodes have a process for resolving the actual method to invoke, and those processes are relatively similar (you can read the specs). Without counting the instructions of an actual implementation, it would be impossible to say which is faster.
The invokespecial pushes an extra value onto the stack. The time to do this is counted in fractions of a nanosecond.
And making all of this moot, Hotspot has a wide range of optimizations that it can perform. It probably doesn't have to do the actual method resolution more than once during your program's run. It might choose to inline the method (or it might not), but that cost would again be roughly equivalent.
According to me NO binding of static method is same as non-static private i.e early binding.
.
Compiler actually adds code of method (static or non-static private) to your code while creating it's byte code.
Update : Just came through this article. It says instance methods binding is dynamic so if method is not non-static private then. Your static method is faster.
I checked, I hope it does what you wanted to know, the code won't be beautiful:
public class main {
#SuppressWarnings("all")
public static void main(String[] args) {
main ma = new main();
int count = Integer.MAX_VALUE;
long beg = (new Date()).getTime();
for (int i = 0; i < count; i++) {
ma.doNothing();
}
System.out.println("priv : " + new Long((new Date()).getTime() - beg).toString());
beg = (new Date()).getTime();
for (int i = 0; i < count; i++) {
doNothingStatic();
}
System.out.println("privstat : " + new Long((new Date()).getTime() - beg).toString());
}
private void doNothing() {
int i = 0;
}
private static void doNothingStatic() {
int i = 0;
}
}
results:
priv : 1774
privstat : 1736
priv : 1906
privstat : 1783
priv : 1963
privstat : 1751
priv : 1782
privstat : 1929
priv : 1876
privstat : 1867
It doesn't look like dependent on static - nonstatic private method. I am sure the differences are coming from the current burden of the machine.
I take part in coding competitions and I have observed, that non-static methods are faster(however minimal) than the static methods. Of course, it depends on your use and the what the situation demands, but the static methods gives poorer performance as compared to non-static ones. By convention, you can use static methods for the ease of code, but creating an instance of the class and calling the method will give better performance.

Simulate the effect of a static C variable in Java method

In Java can a method have anything close to a static variable in C?Although Java doesn't provide one
That is,it would be initialized only once and keep latest value in subsequent recursive invocations
I could pass it back to the method to have the latest value and achieve 'initalize only once' based on some condition which holds true only once
int fun(.....,Nthcall,PseudoStatic)
{if(NthCall==1)
PseudoStatic=10
//rest of code
Pseudostatic=100
fun(.....,Nthcall+1,PseudoStatic)
}
Isn't there something better?
Why not just declare a variable static to the class ? See the tutorial on instance and class variables for more info.
Note that this isn't thread-safe if multiple threads use the same class. and consequently you may be better off defining a class member variable per invocation.
We can do something like this
public void test()
{
StaticVar<Integer> s1 = new StaticVar<Integer>(){};
StaticVar<Long> s2 = new StaticVar<Long>(){};
Integer v1 = s1.get();
System.out.println(v1);
s1.set( v1==null? 1 : v1+1 );
Long v2 = s2.get();
System.out.println(v2);
s2.set( v2==null? 1 : v2*2 );
}
public abstract class StaticVar<V>
{
public V get()
{
return (V)class2value.get(this.getClass());
}
public void set(V value)
{
class2value.put(this.getClass(), value);
}
static WeakHashMap<Class,Object> class2value = new WeakHashMap<>();
}
It's not thread safe though. We can simply add synchronized(class2value). Or use a weak concurrent hash map.

Categories