LESSON 3
Methods
Software Engineering
2022 – 2023 a.y.
Methods
p u b lic s tatic v oid m a in (S tr in g []
a rg u m e n ts ) {
S y s te m . o u t. p r in tln (“ h i” );
}
Adding Methods
p u b lic s tatic v oid N A M E ( ) {
S TAT E M EN T S ;
}
to c a ll a m e th od :
N A M E ();
class NewLine {
public static void NewLine () {
[Link](“”);
}
public static void threeLines () {
newLine(); newline(); newline();
}
public static void main (String[] args) {
[Link](“Line 1”);
threeLines();
[Link](“Line 2”);
}
}
Parameters
p u b lic s tatic v oid N A M E ( T Y PE N A M E ) {
S TAT E M EN T S ;
}
to c a ll:
N A M E ( E X PR E SSI O N );
class Square {
public static void printSquare (int x) {
[Link](x*x);
}
public static void main (String[] args) {
int value = 2;
printSquare(value);
printSquare(3);
printSquare(value*2);
}
}
class Square2 {
public static void printSquare (int x) {
[Link](x*x);
}
public static void main (String[] args) {
printSquare(“hello”);
printSquare(5.5);
}
}
What’s wrong
here?
class Square3 {
public static void printSquare (double x) {
[Link](x*x);
}
public static void main (String[] args) {
printSquare(5);
}
}
What’s wrong
here?
Multiple
Parameters
... ... ... N AM E ( T Y PE N A M E , T Y PE
NAME) {
S TAT E M EN T S ;
}
To c a ll:
N A M E ( arg 1, arg 2 );
class Multiply {
public static void times (double a, double b) {
[Link](a*b);
}
public static void main (String[] args) {
times(2, 2);
times(3, 4);
}
}
What’s wrong
here?
Return Values
p u b lic s tatic T Y PE N A M E ( ) {
S TAT E M EN T S ;
re tu rn EX PR E SS IO N ;
}
v o id m e an s ” n o ty p e ”
class Square3 {
public static void printSquare (double x) {
[Link](x*x);
}
public static void main (String[] args) {
printSquare(5);
}
}
class Square4 {
public static double square (double x) {
return x*x;
}
public static void main (String[] args) {
[Link](square(5));
[Link](square(2));
}
}
Variable Scope
Variables live in the block ({}) where
they are defined (scope)
Method parameters are like defining a
new variable in the method
class SquareChange {
public static void printSquare (int x) {
[Link](“printSquare x = “ + x);
x = x * x;
[Link](“printSquare x = “ + x);
}
public static void main (String[] args) {
int x = 5;
[Link](“main x = “ + x);
printSquare(x);
[Link](“main x = “ + x);
}
}
class Scope {
public static void main (String[] args) {
int x = 5;
if (x == 5) {
int x = 6;
int y = 72;
[Link](“x = “ + x + “y
= “ + y);
}
[Link](“x = “ + x + “y = “ +
y);
}
}
THANK
YOU!
ANY QUESTIONS?
[Link]@[Link]
Abdurasul Bobonazarov