- 2

How to call a method in the System.out.println();.....?

Here is the code : public class Vechile{ int maxSpeed; String brand; public static void horn(){ System.out.println("Beeeeeeeeep!"); } } public class MyClass{ public static void main(String[] args){ Vechile car = new Vechile(); car.maxSpeed = 100; car.brand = "Mercedes Benz"; System.out.println("The Brand of The Car : "+car.brand); System.out.println("The Max Speed of The Car : "+car.maxSpeed); System.out.println("The Horn Sound of The Car : "+ car.horn()); car.horn(); } }

20th Feb 2019, 1:42 PM
Krishna Prasad
Krishna Prasad - avatar
2 Answers
20th Feb 2019, 2:27 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
0
Best way to call a method in print statement is : first type: make sure the method returns some value then call the method in the print statement. second Type: Store the return type in some variable in the main method , then print the variable Here is the code : public class Vechile{ int maxSpeed; String brand; public static String horn(){ String hornSound = "Beeeeeeeeep!"; return hornSound; } } public class MyClass{ public static void main(String[] args){ Vechile car = new Vechile(); car.maxSpeed = 100; car.brand = "Mercedes Benz"; System.out.println("The Brand of The Car : "+car.brand); System.out.println("The Max Speed of The Car : "+car.maxSpeed); System.out.println("The Horn Sound of The Car : "+ car.horn()); String sound = car.horn(); System.out.println("The Sound Method : "+sound); } }
20th Feb 2019, 1:59 PM
Krishna Prasad
Krishna Prasad - avatar