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());
}
}
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");
}
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());
}
}
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.