Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the difference between the two initialization: Object x = new String(); String x = new String();

Tags:

java

what's the difference between the two initialization:

Object x = new String(); 
String x = new String();

in java

thank!

like image 995
lys1030 Avatar asked Mar 28 '26 05:03

lys1030


2 Answers

Object x = new String(); // pointing to a String and saying - Hey, Look there! Its an Object
 String x = new String();// pointing to a String and saying - Hey, Look there! Its a String

More importantly : The methods of String that can be accessed depend on the reference. For example :

public static void main(String[] args) {
    Object o = new String();
    String s = new String();
    o.split("\\."); // compile time error
    s.split("\\."); // works fine

}
like image 151
TheLostMind Avatar answered Mar 29 '26 19:03

TheLostMind


There's no difference in the initializations, only in the declarations and therefore in the way the rest of your code sees the variables type.

like image 21
Smutje Avatar answered Mar 29 '26 21:03

Smutje