top of page
Writer's picturePraveen Mogan

Methods and Selection Statements

Java is such a versatile language. You can make your own methods, or groups of commands executable whenever you call it. Imagine if you could call you could tell a robot to clean your room, make your bed, and fold your clothes with just one command: that's the power of the method in Java.


Structure:

accessLevel static/nonstatic returnType name(parameter type varName)

{

//enter code here

//possible return type

}


Note: Don't use the word "non-static" just leave this field empty; also void means no return type


public void printDifference(int large, int small)

{

System.out.println(large-small);

}


public static int sum(int a, int b)

{

int sum = a+b;

return sum;

}


Why Use Methods?

Methods allow the user to call a function multiple times without having to write the code multiple times, decreasing the length of the program: readability. Furthermore, methods allow the programmer to change parts at one place, rather than at each instance of the function call: maintainability.


Selection Statements:

There are three major selection statements: if, else if, and else.

Essentially, a boolean expression is placed within parenthesis, leading the computer to decide whether to execute the following set of commands.


Note: modulus(%) returns the remainder


Examples:

int x = 4;

if(x%2==0)

System.out.println(x+" is odd.");

else if(x==0)

System.out.println("you entered 0.");

else

System.out.println(x + "is even.");

//output - 4 is odd; computers do what they tell you to do - they aren't that smart. Read carefully!


Note: brackets are not required if the statement is only one line, however, if there are multiple lines then you have to add brackets.

27 views0 comments

Recent Posts

See All

Strings

Comments


Post: Blog2_Post
bottom of page