Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Help me in understanding Parameters in Method

Why is that some methods have some parameters while others have nothing between parenthesis?

2 Answers

Evelina Yankova
Evelina Yankova
5,869 Points

Some methods require additional arguments in order to execute the code. Let’s say you want to know if the number your user inputs is even or odd . Your final result will depend on your user’s input. A method will look like this

boolean isEven(int x){ if(x%2==0) return true; else return false; }

this means that whenever you want to check the number your method has to receive it as an argument. Your method processes the passed value and uses it to generate the final result.

Thanx for the answer.. i have 1 more problem about Constructors and "new"

Why is it used?

help me understand this

Evelina Yankova
Evelina Yankova
5,869 Points

Classes consist of member variables and methods. A constructor is a method with a name identical to the class name. The constructor initializes the object when it's created, or sets initial values to its variables when the object is created (or include other code that needs to be executed in order to initially set up your new object). Imagine you have a class named Vehicle to describe a vehicle with two variables passengers and fuel. And you want to set those variables each time you create a new object. Your class will look like this

class Vehicle{ int passengers; int fuel;

Vehicle(int p, int f) { passengers = p; fuel = f; }

}

Each time you create an object of type Vehicle you have to pass values for the number of passengers and the fuel it holds. Using constructor prevents you from some mistakes like missing to set some of the variables. To create the new Vehicle object you add the following code:

Vehicle minivan = new Vehicle(7,12); //create new Vehicle object,call the constructor and set passenger to 7 and fuel to12

Vehicle sportscar = new Vehicle(2,14);//create new Vehicle object,call the constructor and set passenger to 2 and fuel to 14.

As far as I understand it, those would be considered "optional" parameters which may or may not take in a variety of arguments.