Почему string final java

Why to declare a String (as final) and then use it?

Does it improve the performance even in a slightest way? I have read a few questions on stack overflow (String and final, Does it make sense to define a final String in Java?) but no one got around to answering this questions update question.

meta bit: the reason that no one ever answered it was that extensions to existing questions really don’t make for good questions. Things like ‘Update’ and ‘Edit’ are signs of a creeping question (what if the creeping question is a dup? or if someone answers the update but not the original? or the original but not the update? — followup questions in new questions is the best policy)

Every read-only string that is used more than once can savely be put into a static final field, if only to avoid mis-typing errors or to be able to refactor. For literals that are only used once I think it doesn’t really matter.

2 Answers 2

At runtime, it does not make a difference.

The point is readability — as a member variable, it likely is declared at the beginning of the class’ source code, and making it static means it doesn’t have to be allocated for each new instance of the class.

Читайте также:  Php тип переменной null

Making it final signifies to the reader that the value will not change (to the compiler too, but that’s less important here).

This way, there are no «magic values» buried in the implementation, and if a change is desired to the «constant», it only needs to be changed in one place.

This basically mimics what a C programmer would do with a #define.

final fields have many benefits!

Declaring fields as final has valuable documentation benefits for developers who want to use or extend your class — not only does it help explain how the class works, but it enlists the compiler’s help in enforcing your design decisions. Unlike with final methods, declaring a final field helps the optimizer make better optimization decisions, because if the compiler knows the field’s value will not change, it can safely cache the value in a register. final fields also provide an extra level of safety by having the compiler enforce that a field is read-only.

Don’t try to use final as a performance management tool. There are much better, less constraining ways to enhance your program’s performance. Use final where it reflects the fundamental semantics of your program: to indicate that classes are intended to be immutable or that fields are intended to be read-only.

Before declare final fields, you should ask yourself: does this field really need to be mutable?

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.24.43543

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Почему string final java

Вопрос глуппый но задам. Сборщик мусора не сходит сума при работе с immutable? Наример нам приходится в программе таскать ‘с собой’ масивы строк и паралельно в них менять значения. Это жесть какая нагрузка на железо.

 public static void main(String[] args)

Вывод: I love Java I love Java Честно говоря, не понимаю, что удивительного в этом коде? Код же выполняется сверху вниз. А тут четверть статьи этому посвятили) Я так понимаю, что если я в конце в коде напишу: System.out.println(str1);, то вывод будет: I love Java I love Python Или я что-то не так понял?

Ведьмаку заплатите – чеканной монетой, чеканной монетой, во-о-оу Ведьмаку заплатите, зачтется все это вам

Всё что я должен понять из этой статьи: final для класса — класс нельзя наследовать, final для метода — метод нельзя переопределять, final для переменной — нельзя изменять первое присвоенное значение (сразу присваивать не обязательно), имя пишется капсом, слова через нижний пробел. Объекты всех классов обёрток, StackTrace, а также классы, используемые для создания больших чисел BigInteger и BigDecimal неизменяемые. Таким образом, при создании или изменении строки, каждый раз создаётся новый объект. Кратко о String Pool: Строки, указанные в коде литералом, попадают в String Pool (другими словами «Кэш строк»). String Pool создан, чтобы не создавать каждый раз однотипные объекты. Рассмотрим создание двух строковых переменных, которые указаны в коде литералом (без new String).

 String test = "literal"; String test2 = "literal"; 

При создании первой переменной, будет создан объект строка и занесён в String Pool. При создании второй переменной, будет произведён поиск в String Pool. Если такая же строка будет найдена, ссылка на неё будет занесена во вторую переменную. В итоге будет две различных переменных, ссылающихся на один объект.

Мало примеров и в целом, недосказано. Под конец вскользь упомянут String Pool, а что это не объясняется. Статья озаглавлена какFinal & Co, а по факту пару примеров по строкам, ну, такое. Это называется собирались пироги печь, а по факту лепёшки лепим. В любом случае, конечно, спасибо за труд. Но, гораздо лучше про строки написано здесь: Строки в Java (class java.lang.String). Обработка строк в Java. Часть I: String, StringBuffer, StringBuilder (более детальная статья на Хабре).

Получается мы не можем создать поле какого нибудь класса не константой public static final String name = «Амиго»; обязательно только так? => public static final String CHARACTER_NAME = «Амиго»; или можно написать и так и так?

«В прошлых лекциях мы видели простой пример наследования: у нас был родительский класс Animal, и два класса-потомка — Cat и Dog» ?! А была лекция о наследовании?! Может быть я где-то пропустил, поделитесь ссылкой, пожалуйста 🙂

Источник

Why String is Immutable or Final in Java? Explained

The string is Immutable in Java because String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client’s action would affect all other clients. For example, if one client changes the value of the String «Test» to «TEST», all other clients will also see that value as explained in the first example. Since caching of String objects was important for performance reasons this risk was avoided by making the String class Immutable. At the same time, String was made final so that no one can compromise invariant of String class like Immutability, Caching, hashcode calculation, etc by extending and overriding behaviors. Another reason why the String class is immutable could die due to HashMap.

Since Strings are very popular as the HashMap key, it’s important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Since HashMap works in the principle of hashing, which requires the same has value to function properly. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String were modified after insertion, potentially losing the value object in the map.

If you are an Indian cricket fan, you may be able to correlate with my next sentence. The string is VVS Laxman of Java, i.e. very very special class. I have not seen a single Java program that is written without using String. That’s why a solid understanding of String is very important for a Java developer.

Important and popularity of String as data type, transfer object, and the mediator has also made it popular in Java interviews. Why String is immutable in Java is one of the most frequently asked String Interview questions in Java, which starts with a discussion of, what is String, how String in Java is different than String in C and C++, and then shifted towards what is an immutable object in Java, what are the benefits of an immutable object, why do you use them and which scenarios should you use them. This question sometimes also asked, «Why String is final in Java».

On a similar note, if you are preparing for Java interviews, I would suggest you take a look at the Java Programming interview exposed book, an excellent resource for senior and mid-level Java programmers. It contains questions from all important Java topics including multi-threading, collection, GC, JVM internals, and frameworks like Spring and Hibernate, as shown below:

Why String is Final in Java? Answered

As I said, there could be many possible answers to this question, and the only designer of the String class can answer it with confidence. I was expecting some clue in Joshua Bloch’s Effective Java book, but he also didn’t mention it. I think the following two reasons make a lot of sense on why String class is made immutable or final in Java:

1. String Pool

Imagine String pool facility without making string immutable, it’s not possible at all because in the case of string pool one string object/literal e.g. «Test» has referenced by many reference variables, so if any one of them change the value others will be automatic gets affected i.e. let’s say

String A = "Test" String B = "Test"

Now String B called, » Test».toUpperCase() which change the same object into «TEST», so A will also be «TEST» which is not desirable. Here is a nice diagram that shows how String literals are created in heap memory and String literal pool.

Why String is Immutable or Final in Java

2. Security

String has been widely used as a parameter for many Java classes like for opening network connection, you can pass hostname and port number as a string, you can pass database URL as a string for opening database connection, you can open any file in Java by passing the name of the file as an argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat, I mean someone can access any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access to that file.

Because of immutability, you don’t need to worry about that kind of threat. This reason also gels with, Why String class is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

3. Thread safety

Since String is immutable it can safely share between many threads which are very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, which means you don’t need to synchronize String operation externally. Another important point to note about String is the memory leak caused by SubString, which is not a thread-related issue but something to be aware of.

4. Caching

Another reason Why String is immutable in Java is to allow String to cache its hashcode, being immutable String in Java caches its hashcode, and do not calculate every time we call the hashcode method of String, which makes it very fast as a hashmap key to be used in hashmap in Java.

This one is also suggested by Jaroslav Sedlacek in the comments below. In short, because String is immutable, no one can change its contents once created which guarantees the hashCode of String to be the same on multiple invocations.

5. Class Loading

Another good reason Why String is immutable in Java suggested by Dan Bergh Johnsson in comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.

Had String been mutable, a request to load » java.io.Writer » could have been changed to load » mil.vogoon.DiskErasingWriter «

In short, Security and String pool being the primary reasons for making String immutable, I believe there could be some more very convincing reasons as well, Please post those reasons as comments and I will include those on this post.

By the way, the above reason holds good to answer, another Java interview question «Why String is final in Java». Also to be immutable you have to be final so that your subclass doesn’t break immutability. what do you guys think?

And, if you prefer to watch than read then you can also check out this tutorial on our Youtube channel where we have talked about why String is Immutable and Final in Java. If you haven’t subscribed to our Youtube channel and want to receive notifications about new tutorials, you can subscribe to our Youtube channel here.

Thanks for reading this article so far. If you like this Java interview question and my explanation then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. — If you are new to Java programming and want to learn Java from scratch then you can also check out these best websites to learn Java Programming and development for free. It’s a great collection of online learning platforms for Java developers.

Источник

Оцените статью