Lecture 04
Lecture 04
Methods in JAVA
What is a Method ?
What is a Method
eg:
1 int number = 7;
2 System.out.println(number);
value-returning methods
General format
A MUST KNOW
SYNTAX
Details…
A VERY CRUCIAL
DIAGRAM
Example…
Example of value returning Method
Example…
Public class test{
public static void main(String[] args){
int a=10, b=5;
int sum=a+b; CHECK THIS CODE OUT
SON!
System.out.prinln(a+b);
int diff=a-b;
System.out.println(a-b);
int mult=a*b;
System.out.println(a*b);
What if I want to add c=15
}
What kind of method is this example??
Real life Example…
Bosses are hiring assistant to do job for them This is called
Method in Java
Boss:
Public static void main(String [] args)
{
add();
}
Assistant:
A GOOD UNDERSTANDING OF
VARIABLES TYPES IS NEEDED
More Example
Boss says:
Public static void main(String [] args)
{
add(3,5);
}
Assistant: the Assistant is very smart
Continue…
Boss:
Public static void main(String [] args)
{
add(3,5);
}
Assistant:
What will be the output of the following code?
public class LoopCall
{
public static void main(String[] args)
{
System.out.println("Hello from the main method.");
for (int i = 0; i < 5; i++)
displayMessage();
System.out.println("Back in the main method.");
}
public static void displayMessage()
{
System.out.println("Hello from the displayMessage method.");
}
Check your understanding
public class DeepAndDeeper
{
public static void main(String[] args)
{
System.out.println("I am starting in main.");
deep();
System.out.println("Now I am back in main.");
}
public static void deep()
{
System.out.println("I am now in deep.");
deeper();
System.out.println("Now I am back in deep.");
}
public static void deeper()
{
System.out.println("I am now in deeper.");}}}
Types of Methods
Passing Arguments to a Method
System.out.println("Hello");
short s = 1;
displayValue(s); // Converts short to int
byte b = 2;
displayValue(b); // Converts byte to int
However, Java will not automatically convert an
argument to a lower-ranking data type.
This means that a long, float, or double value cannot
be passed to a method that has an int parameter
variable.
double d = 1.0;
displayValue(d); // Error! Can’t convert double to int.
passing Multiple Arguments