티스토리 뷰

JAVA

String class in Java

seoca 2019. 1. 20. 16:27



String class in java 


- case sensitive (lower case gives an error)

- no need 'new' keyword 

- It restricts the creation of a string instance consisting of the same string.

It does not allow changes to the data in the String instance.




If you want to make variables that hold the strings, you need to create object first.


1
2
3
4
5
6
7
class Student
{
    public static void main(String[] args)
    {
        String hello = new String("Hello Java"// use 'new' keyword to create new object
    }
}
cs



Luckily we do not need 'new' keyword when we use String class. Java made it easier because we use it a lot


1
2
3
4
5
6
7
8
class Student
{
    public static void main(String[] args)
    {
        String hello = String("Hello Java");
        System.out.println(hello);    
    }
}
cs



no need to initialize it immediately. We can use it like primitive data types.


1
2
3
4
5
6
7
8
9
10
class Student
{
    public static void main(String[] args)
    {
        String hello;
        hello = "Hello Java ";
 
        System.out.println(hello);    
    }
}
cs



String initialization

what is the difference between 'String hello = "";' and 'String hello = null' ?;

String hello = ""; // preferred way to initialize.  It has zero characters and it is doing an operation on it, 


String hello = null// no references to it, therefore, it will give you NPE(NullPointerException









Reference

https://www.edureka.co/blog/java-string/

https://www.w3resource.com/java-tutorial/exploring-methods-of-string-class.php

https://www.geeksforgeeks.org/different-ways-for-integer-to-string-conversions-in-java/

'JAVA' 카테고리의 다른 글

What's the difference between two different List declaration?  (0) 2019.02.02
Upcasting (Object type casting) in java  (0) 2019.01.30
Collection framework - ArrayList  (0) 2019.01.17
abstract & Interface in java  (0) 2019.01.17
toString method  (0) 2019.01.08