Site icon TestingDocs.com

How to pass String variable to a Java method

Introduction

In this tutorial, we will learn how to pass a String variable to a java method. We will define a method that takes a String parameter and we will invoke the method from the main method.

Method signature

public static void myMethod(String fname) ;

The method takes the String parameter and then appends additional text to the string and then outputs the value to the console. The method is invoked from the method by passing some sample strings with male names.

Java Program

/*********************************************************** 
 * * MethodStringsDemo.java 
 * * @program : Java program using method for strings 
 * * @web : www.testingdocs.com 
 * * @version : 1.0 
 * ************************************************************/ 

public class MethodStringsDemo { 
  public static void myMethod(String fname) {
    System.out.println("The value passed to the method is =: " + fname); 
  } 

  public static void main(String args[]) {
    myMethod("John"); 
    myMethod("Williams");
    myMethod("David"); 
  } 
}

 

Program Output

The value passed to the method is =: John
The value passed to the method is =: Williams
The value passed to the method is =: David

Screenshot

 

Exit mobile version