Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

View RSS Feed

JD1's Personal Development Blog

Methods With Parameters

Rate this Entry
Discussed in my last post was how we implement multiple classes and execute methods from within these classes via the main class. We can actually send variables from the main class into a method of the secondary class and then use those variables as desired. We do this through the use of parameters. Let me show you what I mean. Here's class2 and what it does.

public class class2{
	public void class2Method(String name){
		System.out.println("Hello "+name);
	}
}

You'll notice that we have included String name as our parameters this time round. That's because, we want to get the string 'name' from our main class and output its value. Seems simple enough right? All we have to do now is tell our class1 to send this variable through. Here's class1, containing our main method.

class class1{
	public static void main(String args[]){
		System.out.println("This code is executed via the main method in class1!");
		class2 class2Object=new class2();
		String name="Tony";
		class2Object.class2Method(name);
	}
}

You'll notice that we've created a new class2 object named class2Object. This allows us to use class2 and execute code from within. Next, we created a new string variable called name. This is the variable we want to send through to the second class. We've assigned it a value of 'Tony'. We can send this variable through to the second class by using our class2 object, a dot separator, the method from within class2 that we want to output, and the parameter of 'name' (the variable we're sending).

So long as the variable you use in class2Object.class2Method(name);, which would be 'name', matches the variable used in public void class2Method(String name){, you should be right to go ahead and use this variable from within class2.
Categories
Uncategorized

Comments