This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Why is String final in Java?
I'm just wondering why java.lang.String is made final? Is it to prevent from being inherited? Why?
Yes indeed. This allows code in security managers and classloaders to work with the String type without having to worry that it's actually dealing with a malicious subclass that's specifically designed to trick it into allowing evil code through.
You should not be extending the string class. Just write your own methods in some other class that manipulate strings.
The reason is that the string class is a stable one which should not be tampered with as you may re-define some methods which would have unknown side effects on some other transactions.
Aside from security aspects that were already mentioned, I suspect performance was another important reason. For older JVMs especially final classes (where all methods are final by definition) made it much easier to inline code on-the-fly. And since String is one of most heavily used objects, which affects overall performance of many applications, this was seen as an area where improvements would have big overall effect.
Related
This question already has answers here:
Does use of final keyword in Java improve the performance?
(14 answers)
Closed 7 years ago.
Now, I recently ran into a recommendation that you should use the keyword final as wide as possible. This is good in order to prevent a programmer from shooting his own leg - that is, reassign the variable that should not be reassigned.
But, does it serve any other goal? That is, can JVM use information about the final variables in order to optimize the bytecode somehow, so it would ran faster (build a better pipelining or use it in a multithreaded environment)? Or is just a syntactic sugar that minimizes the possibility of errors during code development?
IBM states:
Like many myths about Java performance, the erroneous belief that declaring classes or methods as final results in better performance is widely held but rarely examined. The argument goes that declaring a method or class as final means that the compiler can inline method calls more aggressively, because it knows that at run time this is definitely the version of the method that's going to be called. But this is simply not true. Just because class X is compiled against final class Y doesn't mean that the same version of class Y will be loaded at run time. So the compiler cannot inline such cross-class method calls safely, final or not. Only if a method is private can the compiler inline it freely, and in that case, the final keyword would be redundant.
As far as variables go, Java is smart enough to figure that a variable is not being changed anywhere in the method, and use this knowledge for optimization purposes. It does not need you to mark a variable final in order to know that.
Methods are a slightly different story: when you mark a method final, Java can invoke such method faster, because it no longer needs to check for its overrides. Still, hotspot is smart enough to figure out that there are no overrides, with or without the use of final.
Generally, though, this recommendation is intended to make your code easier to read and understand by others: making a variable final tells you readers that you are making a constant; making a class final tells your readers that the class is not designed for inheritance; making a method final tells your readers that the logic of that method should stay invariant across the inheritance hierarchy. In the long run, this information is more valuable than the potential to optimize your running code.
I think this recommendation is a bit too unspecific.
For example; I would recommend to avoid using final on classes and methods by default (because final classes break unit tests, respectively force you to use specific unit test frameworks to overcome final methods/classes).
I also find that using final for method parameters is just a waste of "screen space" (and thus: wasting "energy" on the side of the reader).
On the other hand, having only final attributes for classes can turn objects of such classes into immutable thingies; and that is a good thing.
As you see; there are many pros and cons on the usage of final; and I think that "readability" most often wins over "potential" performance improvements.
final methods may or may not be inlined by the JVM until they after they are loaded by the JVM. So, if you're sure the method is not going to be redefined, mark it as final.
Constants should always be static final since they will be immutable and jvm does not need to keep track of these variables since they will never change.
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
I've seen some legacy code that uses lengthproperty on some objects and others that uses length() method. Currently I'm working with a NodeList from the org.w3c.dom package and I found that it have the getLength() method to get the numbers of elements.
My Question is how as Java developer I can know how to determine when to use length, length(), size(), getLength()? obviously it depends of the object type and the API is there for read... but the point is how the Java Development select which of that implements in their classes.
Note: In the Question When to use .length vs .length() Makoto answer's indicates that .length is a property on arrays. That isn't a method call, and length() is a method call on String. But, why is the reason? why not use ever a method or ever a property for maintain the consistency around all the API.
how would Java developers select which of [the methods] to implement in their classes?
When you implement classes that contain other objects, it's almost always going to be size(), the method provided by theCollection interface.
As far as other choices go, you should avoid exposing member variables, even final ones, because they cannot be accessed through an interface. Java gets away with it for arrays because of some JVM trickery, but you cannot do the same. Hence, length should be out: it remains in Java because it's not possible to change something that fundamental that has been in the language from day one, but it's definitely not something one should consider when designing new classes.
When you implement your own type that has length (say, a rectangle or a line segment) you should prefer getLength() to length() because of Java Beans naming conventions.
obviously it depends of the object type and the API is there for read...
You already have answered your question yourself: look in the API documentation of whatever class you are using.
but the point is how the Java Development select which of that implements in their classes.
The classes in Java's standard library have been developed over a long period of time by different people, which do not always make the same choice for the name of methods, so there are inconsistencies and unfortunately you'll just have to live with that.
There is no clear rule, otherwise we wouldn't see such a mixup in the jdk itself. But here are some things to consider when making such a design decision.
Don't worry to much. It is a minor thing and won't make to much of a difference. So when you think longer then 5 minutes about this, you are probably wasting money already.
Use getters when a frameworks need them. Many frameworks depend on the getter style. If you need or want such frameworks to work nicely with your class it might be beneficial to use that style.
Shorter is better. the 'get' part doesn't increase clarity. It just generates to characters of noise to the source code, so if you don't need it for some reason, don't use it.
Methods are easier to evolve. Length is often a quantity that is not set directly but somehow computed. If you hide that behind a method it gives you the flexibility to change that implementation later on, without changing the API.
Direct field accesses should be a tiny bit faster, but if you aren't working on high volume online trading or something, the difference isn't even worth thinking about. And if you do you should do your own measurements before making a decision. The hotspot compiler will almost for sure inline the method call anyways.
So if there aren't any external forces driving you in a different direction I would go with 'length()'
According to OOPS principles, length should be attribute and getLength() should be method. Also length attribute should be encapsulated should be exposed through methods, so getLength() sounds more appropriate.
Unfortunately not all Java library classes follow standards. There are some exceptions and this is one among them.
In a pure OO language it should be probably always a method like length(). So in a class hierarchy you can override the attribute length.
But Java is not pure OO. And the main reason for fields (.length) vs method (length()) is/was performance issues.
And even Sun/Oracle programmers did some bad class design.
This question already has answers here:
Java double checked locking
(11 answers)
Closed 8 years ago.
There's a common belief and multiple sources (including wiki) that claim this idiom to be an anti-pattern.
What are the arguments against using it in production code given the correct implementation is used (for example, using volatile)
What are the appropriate alternatives for implementing lazy initialization in a multithreaded environment ? Locking the whole method may become a bottleneck and even while modern synchronization is relatively cheap, it's still much slower especially under contention. Static holder seems to be a language-specific and a bit ugly hack (at least for me). Atomics-based implementation seems not be so different from traditional DCL while allowing multiple calculations or requires more complicated code. For example, Scala is still using DCL for implementing the lazy values while proposed alternative seems to be much more complicated.
Don't use double checked locking. Ever. It does not work. Don't try to find a hack to make it work, because it may not on a later JRE.
As far as I know, there is no other save way for lazy initialization than locking the whole object / synchronizing.
synchronized (lock) {
// lookup
// lazy init
}
For singletons the static holder (as #trashgod mentioned) is nice, but will not remain single if you have multiple classloaders.
If you require a lazy singleton in a multi-classloader environment, use the ServiceLoader.
This question already has answers here:
Why is the String class declared final in Java?
(16 answers)
Closed 9 years ago.
As i was told this is important String Interview question in Java, which starts with discussion of " What is String ", how String is different in java than in C or C++ and then you are asked about immutable objects and you're asked the main question: " Why String is immutable or final in Java ".
Can you share your Ideas ?
Thanks in advance.
It is mainly for security reasons. String is used as parameter in network connection, database url etc. It can be easily attacked if it is mutable
Immutability of String solves some synchronization issues, it makes the String thread safe
To support StringPool facility
To cache the hashcode of String
To support class loading mechanism in which String is used as arguments. String being mutable results in wrong class being loaded
The two main reasons why strings are immutable in many modern languages, including Java, are security and performance (or, more precisely, chance for optimizations).
The fact that strings are final is to ensure their immutability (by forbidding anyone from extending them and making them mutable again).
The most important reason is security.
A lot of security risks would appear if a malicious thread could gain a reference to a mutable String, which is about to be passed into a method that has to validate the String before it performs an important operation. It would be possible for the thread to change the string after it was validated, and then the operation would be carried out using a dangerous String.
Another reason of Why String is immutable in Java is to allow String to cache its hashcode
As mentioned above - the most important reason - security & thread safety.
Consider a scenario, in a banking application for money transfer - the beneficiary account number is defined in a string as "0789567345".
If by mistake/intentionally this acc. number is changed, money will go to a wrong account.
Another scenario - if someone change the class name anywhere between processing as ..
getClass().getName().subString(0, 5);
The Class loader will simply say 'Class Not Found
This question already has answers here:
Why is the String class declared final in Java?
(16 answers)
Closed 9 years ago.
I am new to Java and while I was reading through Java language I got into two doubts. Though I referred many websites and but still I am not very clear.
Why string class is immutable ? I saw some examples with new File(str) which leads to security threat, but I don't understand how if string is immutable, it will help this scenario.
Another doubt is why wait, notify and notifyall should be inside synchronized block. I know if not it throws illegalMonitorException. But I want to know the technical background why it should be in synchronized block and why not without in synchronized block wait and notify can have same behavior.
Why string class is immutable?
The question of why strings are immutable in Java is an old one, and it's been much debated. In my book, I'd say they are immutable because they should be immutable ;). That might sound like a cop out, but let me explain.
Most simply, strings are used all over the place, if they were mutable that would require a lot of baggage everywhere for making defensive copies and dealing with synchronization and so on. Making them immutable, and then having helpers for mutating them like StringBuilder/StringBuffer is a much better design choice (and a common choice in several languages, not just Java).
Second, everything should be immutable, unless there is a very good reason to justify mutability. Many many problems disappear with immutable classes (esp. pertaining to concurrency). See Effective Java: "Classes should be immutable unless there's a very good reason to make them mutable. If a class cannot be made immutable, limit its mutability as much as possible."
Third, strings are used in the internals of Java, such as the class loading mechanism. Making them immutable makes internal processes simpler, and prevents some security issues. (Another example, String constants are "interned" in Java for performance reasons: http://en.wikipedia.org/wiki/String_interning, and this is, again, much more sane with an immutable type.)
All in all there were probably several reasons the designers chose to make strings immutable in Java and as a day to day programmer it helps you out (as do the utils around creating new strings, like StringBuilder).
Why wait, notify and notifyall should be inside synchronized block?
Here's some info on that one: wait(), notify() and notifyAll() inside synchronized statement.
Basically it makes no sense for a thread to "notify" or "wait" unless it already owns the object's monitor.
In general though, if you are new to Java, you might want to also look at some of the newer utils relating to concurrency in java.util.concurrent: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html. Often you can rely on these classes and avoid hand coding synchronization, which is notoriously difficult and error prone.