Question

For the code below I have created an instance variable with class name as return type

class classtype{
    static classtype x;

    public static void main(String...a){
         System.out.println(x);
    }
}

Above code outputs to null indicating that this instance variable having class name as return type holds string type values and obviously but when i try to initialize it

static classtype x="1";

it gives type mismatch error found in java.Lang.String

please if anyone can explain

Was it helpful?

Solution

Error1:

x="1";

You cannot do that

Because Classtype is not a String type.

Error2:

Printing null

class Classtype{
         static Classtype x = new Classtype();
         public static void main(String...a){
         System.out.println(x);
         }
       }

Make sure that System.out.println(x); here by default prints the Objects toString method.

Since your x haven't initialize it is null now.

So as per print(println invokes print) method

Prints a string. If the argument is null then the string "null" is printed. Otherwise, the string's characters are converted into bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

To print require String ovveride the toString method in Classtype class. And follow the java naming conventiones. Class names starts with caps.

With all your code becomes

public class Classtype {


        static Classtype x = new Classtype();
        public static void main(String...a){
        System.out.println(x);

      }

        @Override
        public String toString() {
        // TODO Auto-generated method stub
        return "This is ClassType toString";
        }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top