简体   繁体   中英

Why can't we cast string to stringbuffer?

What is the reason behind this:

Why this is not allowed StringBuffer sb=(String)"Java";

and this is allowed StringBuffer sb=new StringBuffer("Java");

String is an immutable class derived only from Object . Therefore you cannot cast it to another type

To get a StringBuffer from a String you must create a new StringBuffer instance with the String as an argument to the constructor as you have mentioned.

Java is a strongly-typed language.

This means that everything has a type. For example, Strings and Stringbuffers.

Casts have two major purposes. The first is on primitives, which are all numbers (except boolean). This is a conversion. The second is on objects. The only purpose is to cast an object to one of its subclasses. For example.

Object s = "";
int len = ((String) s).length();

StringBuffer and String are unrelated heigherarchically even though they may have similar purposes

Java does not support the casting of String to StringBuffer since String is an immutable object.

The Java API for StringBuilder informs us there is a constructor available to create a StringBuffer from a String object:

StringBuffer(String str)

In java object typecasting, one object reference can be type cast into another object reference. The cast can be to its own class type or to one of its classes in its sub class or super class hierarchy. You may look at the below snippet to get some understanding of how type casting works. In the below code, class B is a subclass (child) of class A.

class A{
}

class B extends A{
}

A a = new A();  
B b = new B();  

A a1 = (A)b;    //this is correct
B b1 = (B)b;    //this is correct

A a2 = (B)a;    //ClassCastException
B b2 = (A)a;    //Compile error

You may want to look at some of these - Conversions and Promotions and Java Cast and Conversions to get a better understanding of Java type conversion and promotion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM