Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 401
ADABALA MADHUGHNEA SAI Avatar asked Dec 08 '22 10:12

ADABALA MADHUGHNEA SAI


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

}
like image 51
Ralph Aouad Avatar answered Feb 09 '23 01:02

Ralph Aouad


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();
}
like image 44
Majed Badawi Avatar answered Feb 09 '23 01:02

Majed Badawi