RUVIDEO
Поделитесь видео 🙏

java 37 | Strings in java | Why Strings are immutable in java | How to create Strings in java

At the end of this class students will be able to understand
What is string in java
How string can be created?
Why strings are immutable?

String is a sequence of characters
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string.

How to create String object
There are two ways to create String object:
By string literal
By new keyword
By string literal - Java String literal is created by using double quotes. For Example:
String s="welcome";  
string constant pool
Each time you create a string literal, the JVM checks the "string constant pool" first.
If the string already exists in the pool, a reference to the pooled instance is returned.
If the string doesn't exist in the pool, a new string instance is created and placed in the pool. For example:
String s1="Welcome";  
String s2="Welcome";//It doesn't create a new instance  

by new keyword
By new keyword
String s=new String("Welcome");//creates two objects and one reference variable  
In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal "Welcome" will be placed in the string constant pool.
The variable s will refer to the object in a heap (non-pool).

java program
public class StringExample{  
public static void main(String args[]){  
String s1="java";//creating string by java string literal  
char ch[]={'s','t','r','i','n','g','s'};  
String s2=new String(ch);//converting char array to string  
String s3=new String("example");//creating java string by new keyword  
System.out.println(s1);  
System.out.println(s2);  
System.out.println(s3);  
}}  


output
java
strings
example

Strings in Java are immutable; an immutable class is a class whose object cannot be modified.
The value of the immutable class object is initialized at the time of creation.
Immutable means once you create it, you can not change its size (like an array).
You can not change anything not even a character.

Advantages of immutable strings
String Pool Requirement - String pool is a specific storage area for string objects. If a string object is created and that string already exists, then, instead of creating a new object on the heap, the reference of the same object is returned. If string is mutable, then changing one reference will change the value for all the string objects.

Caching key - Immutable class is good for caching purpose because you need not worry about the value changes
Thread safe - It simplifies multithreaded programming since reading from a type that cannot change is always safe to do concurrently.
Security - Strings are widely used as parameters in network connections, file-openings, etc. If a string is mutable, then a connection or file would be changed which would lead to a serious security threat.
Memory efficient - It allows for a reduction of memory usage by allowing identical values to be combined together and referenced from multiple locations

In Java, string is basically an object that represents sequence of char values.
Strings can be created by using literal and new keyword
Strings are immutable

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «java 37 | Strings in java | Why Strings are immutable in java | How to create Strings in java», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.