Passing String as parameter to a method

String objects are immutable in Java; a method that is passed a reference to a String object cannot change the original object.

package com.ibytecode.strings.parampassing;
public class PassingStringToMethod {

	public static void main(String[] args) {
		String str = "Hello";
		System.out.println("In main: Before Passing String " +
					"to method: " + str);
		method(str);
		System.out.println("In main: After returning " +
					"from method: " + str);
	}

	public static void method(String strTest) {
		strTest += " World";
		System.out.println("In method(): " + strTest);
	}
}

In main: Before Passing String to method: Hello
In method(): Hello World
In main: After returning from method: Hello


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.