0

I'm a Java beginner, and here's my issue : I don't understand why my output is "null" while implemanting my Print program. As I understand my code, it is supposed to display :" http://www.google.com". I tried with a StringBuilder, and I still have this problem. Could someone give me some help please ? Thanks

URL.java :

public class URL {

    String url;

    public void create(){
        url = new String();
        url+=("http://www.google.com");
    }

    public String geturl() {
         return this.url;
    } 

}

Print.java :

public class Print {

public static  void main(String[] args) throws Exception {
URL link = new URL();   
System.out.print(link.geturl());
}

}

2
  • FYI there is a built-in URL class Commented Nov 1, 2013 at 0:36
  • You should really construct your strings differently. String url = "http://www.google.com"; for example. Commented Nov 1, 2013 at 0:41

2 Answers 2

4

You need to call link.create(), or change the create() function to be a constructor instead. Like this:

public URL(){
    url = new String();
    url+=("http://www.google.com");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great ! Thank you very much for offering several options. The first one is actually the one I have to use for the rest of my exercise.
1

An even better approach is to initialize the url instance variable within a constructor. By doing that the url instance variable will automatically be initialize when you create an instance of URL class and you eliminate the need for the create method.

 public class URL{
     private String url;

     //Constructor
     public URL (){
        url = "http://www.google.com";
     }

     public String getUrl (){
        return url;
     }

 }

 public class Print{
      public static void main (String[] args){
         URL url = new URL ();
         System.out.println (url.getUrl());

      }
 }

1 Comment

Thank you Mario for your answer, that was exactly the kind of answer I was expecting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.