• Post Reply Bookmark Topic Watch Topic
  • New Topic

Understanding static in java  RSS feed

 
Aminul Islam
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am new in learning Java and the below program I am not understanding properly specially this part of the program. Also what is the benefit to use static in java?

My doubt part:
=========



Sample Program:


Regards
Aminul
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

The short answer to what the benefit is? A very simple short answer: there isn't one.

Slightly longer answer
you should use the keyword static rarely. For a field: it means you have one per class, irrespective of the number of instances created. Things static belong to the class, not the object. Call static members by
MyClass.MyStaticMember
not by the object name.
As for static methods, there is somewhere on the Ranch a very dubious classification of methods: here. Have a look at that. Remember interface methods (as Rob Spoor pointed out there) are never static.

Remember that static methods in interfaces were introduced in Java8 after that thread was written.
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want something which is not related to the instances, or which represents a function (look at this logarithm method), it might well be static.
If you pass a number to that logarithm method, you will always get the same result, so it does not depend on there being an instance of Math, so it is static. You might try creating an instance of the Math class, but you won't manage it.

I added code tags to your post. Always use them: doesn't it look better now I also moved your comments onto new lines because they were so long.

What you showed is called a static initialiser. It is used for initialising static fields. I think you should initialise instance fields in the constructor and static fields when they are declared or in an initialiser.Here list is now a read‑only List set up in the loop, then copied in such a way that no changes can be made outside the static initialiser. Since tempList will go out of scope, list can never be changed again.

You can read a bit about initialisers here, and also in the Java Language Specification, though that may be difficult to understand.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!