Keywords vs literals
Keywords are words that are used as part of code structure, like for
or while
. They change how compiler handle code.
Literals, like true, false and null, are the values that can be assigned but their names are restricted in the same way that keywords are. E.g. you can not name a variable using literals.
Why String is immutable?
Security:
- String is widely used as parameter for many java classes, e.g. network connection, opening files. Lots of information are stored as string and therefore will not be easily changed.
- String are sued in java classloader. String is immutable that correct class will be loaded.
- It is safe for multithreading and a single string instance can be shared across different threads. String are thread safe.
Efficiency:
Since String is immutable, its hashcode is cached at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.
String pool is possible only because String is immutable is java, this way Java Runtime saves a lot of java heap space because different String variables can refer to same String variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected to other variables also.
there is a concept called Marker interface which will not have any methods.
These interfaces will not have any methods. And once a class implements these inbuilt marker interfaces,
the JVM will allow certain special capabilities.
Examples are Serializable, Cloneable and RandomAccess.