DEV Community

SILAMBARASAN A
SILAMBARASAN A

Posted on

String In Java

String:
A String in java is a object to store a sequence of characters,
enclosed in double quotes. String is class in java.

String is immutable in Java.

Why : in Java Create once, can't modified.

can't modified means. String age = 19; once age assigned 19. java create memory for that data 19. age reference pointing 19. if you change age = 20; . java doesn't not show error. because, immutable means java create new memory for data 20. now age reference pointing new memory 20. exactly immutable means can't modify existing memory, whenever change value String, that's create new memory.

String in java package Java.lang.

  • package => package is group of multiple related classes.

In java you can create string in two ways :

1. using String literal
if string create using literal, those datas will store in scp (String constant pool) memory.

String name="Silambarasan";
Enter fullscreen mode Exit fullscreen mode
  1. using new keyword

if string create using new keyword those datas will store in heap memory.


String obj1 = new String();
Enter fullscreen mode Exit fullscreen mode

the heap and String constant pool are two different memory in java.

Heap

  • A heap in Java is a memory area used to store objects and instance variables during program execution.

  • It is created when the Java Virtual Machine (JVM) starts.

  • It is shared among all threads and managed automatically by the Java Garbage Collector.

  • Heap is a memory area in Java where object created using the new keyword are stored.

Example

new Student()
new Car()
new String()
Enter fullscreen mode Exit fullscreen mode

Java usually creates the object in heap memory.

Then What Stores in Stack?

Stack stores:

  • local variables
  • method calls
  • reference variables

Example

int a = 10;
Enter fullscreen mode Exit fullscreen mode

a directly stores value in stack because it is a primitive datatype.

String constant pool

It is a special memory area inside the heap where Java stores string literals to save memory.

Why SCP is Used

  • Reduces memory usage
  • Improves performance
  • Avoids creating duplicate string objects.

How it works (scp) :

If String create using Literals String name1 = "simbu"; , java will create memory for "simbu" in scp. name1 pointing "simbu" in scp. now we create name2 = "simbu", java did't create memory for that, because if same ("simbu") data already in scp, that reference (name2) pointing the existing memory.

Top comments (0)