Passing String as parameter to a method

11 February 2012 By Nithya Vasudevan 18,477 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×

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


Tags: , , ,