No output while using static methods inside a class(the class which has no main function in it)

Viewed 60

THIS IS MY MAIN CLASS:

public class App {
    public static void main(String[] args){
        Student s1=new Student();
        
    };
    };

THIS IS THE CREATED CLASS:

class Student {
    public static void f1(){
        f2();
    }
    public static String f2(){
        
        return "hello";
    }
    public Student(){
        f1();
    }

}

Now , as i have created an object s1 in main class, the constructor is called ,which has f1() , so f1() is called , now f1() has f2(), so f2() is called , so i think "hello" must be printed but the output is not printed at all(nothing is printed). Can anyone please explain what the reason could be?

5 Answers

There is a difference between printing and returning a value. If you want it to get printed, you should try doing something like this:

class Student {
    public static void f1(){
        f2();
    }
    public static void f2(){
        
        System.out.print("hello");
    }
    public Student(){
        f1();
    }

}

f2() is returning the String, but f1 is not printing it:

public static void f1(){
    System.out.println(f2());
}
public static String f2(){    
    return "hello";
}
public Student(){
    f1();
}

To be printed at the Console Log you should try: System.out.println("Hello");

You are returning the value not printing it.

You have to use System.out.println("Hello") instead of return "hello";

I method....

Since the f2 method has a return type, in order to get the value obtained from it, make a reference of the type that is compatible with the return type and write the word hello using the same reference code as follows

class Student {
public static void f1(){
    String x=f2(); //method calling
    System.out.println(x);

}
public static String f2(){
    
    return "hello";
}
public Student(){
    f1();
}

}

II method......

You can try this way...

class Student {
public static void f1(){
    
    System.out.println(f2());//calling method

}
public static String f2(){
    
    return "hello";
}
public Student(){
    f1();
}}
Related