3. Methods
Srinivas Prasad K T
Engineering Manager @ Decathlon Technology || Ex Harman || Ex E2Open || Oracle Java? || Spring Boot? || WDIO? || Playwright? || Java Script & Type Script? || Scrum? || Gatling? || AI? || Tricentis Tosca? || ACCELQ?
Operators
Operators are used to manipulate the variables;
Java provides rich set of operators.
We can divide all the java operators into the following groups,
Based on the number of operands, operator can be of the following three types.
Unary Operator:-
Binary Operator:-
Ternary operator:-
Arithmetic Operators:
Assignment Operators:
?Relational Operators:
Logical Operators:
Instanceof Operator:
Instanceof operator is written as:
public class Sample?
{
public static void main(String args[])
{
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;??
System.out.println( result );
}
}
Output: true
Conditional Operator (? : ):
public class Sample?
{
public static void main(String args[])
{
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " +? b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
Output: Value of a is: 30
Value of b is: 20
Precedence of Java Operators:
Note IMP: What will be output for the following statements??
- In the first case, both 10 and 0 are integer type.
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(10/0);
}
}
Output:?
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.CoreJava04.Pattrens.Simple.main(Simple.java:8)
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(10/0.0);
}
}
Output: Infinity
public class Sample
{
public static void main(String[] args)?
{
System.out.println(-10.0/0);
}
}?
Output: Infinity
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(-10/0.0);
}
}
Output:? -Infinity
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(-10.0/0);
}
}
Output:? -Infinity
Note: - In the above two cases, if we are dividing the integral arithmetic values by? ? ? ? ? ? 0 we will get runtime arithmetic exceptions
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(0/0);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.CoreJava04.Pattrens.Simple.main(Simple.java:8)
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(0.0/0);
}
}??
Output:
?? NaN
public class Sample?
{
public static void main(String[] args)?
{
System.out.println(-0/0.0);
}
}
Output: NaN
Methods/Functions
Advantage of Methods/Functions
A method definition consists of a method header and a method body. Here are all the parts of a method:
In java there are twelve modifiers are available, they are:
Return type may be any data type:
Programs:
public class Sample
{
static void Demo()
{
System.out.println("Running demo() method...");
System.out.println("This method return void...");
return;
}
public static void main(String[] args)?
{
System.out.println("Program starts...");
Demo(); // Method Invocation
System.out.println("Program endss...");
}
}
Output:
Program starts...
Running demo() method...
This method return void...
Program ends...
public class ArgumentMethod
{
public static void main(String[] args)
{
System.out.println("Program starts...");
Demo(10);// Method invocation
System.out.println("Program endss...");
}
static void Demo(int a)//Parameterized method?
{
System.out.println("Running Demo() method...");
int res;
res = a * a;
System.out.println("Value of A is: "+a);
System.out.println("Value of res is:"+res);
return;
}
}
Output:
Program starts...
Running Demo() method...
Value of A is: 10
Value of res is:100
Program ends...
public class ReturnMethod?
{
static int Demo(int a)
{
System.out.println("Running Demo() method...");
int res;
res = a * a;
System.out.println("Value of A is: "+a);
return res;// returning a value?
}
public static void main(String[] args)
{
System.out.println("Program starts...");
int retValue;
retValue = Demo(14); // Method invocation?
System.out.println("The value of retValue is: "+retValue);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running Demo() method...
Value of A is: 14
The value of retValue is: 196
Program ends...
public class MultipleArguments?
{
static int add(int a, int b)
{
System.out.println("Running add() method...");
System.out.println("The value of A is: "+a);
System.out.println("The value os B is: "+b);
int res = a + b;
return res;
}
public static void main(String[] args)
{
System.out.println("Program starts...");
int sum;
sum = add(12, 15);// Method invocation?
System.out.println("The sum of two number is: "+sum);
// We can directly call the method as below
System.out.println("The sum of two numbers is: "+add(10,15));
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running add() method...
The value of A is: 12
The value os B is: 15
The sum of two number is: 27
Running add() method...
The value of A is: 10
The value os B is: 15
The sum of two numbers is: 25
Program ends...
public class AreaOfCircle
{
static double pi = 3.14;
static double areaOfCircle(double radius)
{
double area;
area = pi radius radius;
return area;
}
static double circumference(double radius)
{
double cirCum;
cirCum = 2 pi radius;
return cirCum;
}
public static void main(String[] args)?
{
System.out.println("Program starts...");
double area = areaOfCircle(1.2);
System.out.println("Area of circle is: "+area);
double cirCumference = circumference(1.2);
System.out.println("Circumference of a circle is: "+cirCumference);
System.out.println("Program ends...");
}
}
Output:
Program starts...
Area of circle is: 4.521599999999999
Circumference of a circle is: 7.536
Program ends...
Control Statements
Note: All the programs we have written till now had a sequential flow of control i.e. the statements were executed line by line from the top to bottom in an order. Nowhere were any statements skipped or a statement executed more than once. We will now look into how this can be achieved using control structures.
These control structures can be classified into two groups:
Selection or decision making statements
Programs:?
public class If?
{
public static void main(String[] args)?
{
System.out.println("Program starts...");
int num = 7;
//Take decision whether num is above 7 or below 7
if(num>7)
{
//if body will gets executed only when condition is true
System.out.println("Number is above 7 ");
}
else
{
// else body will be executed when condition is false
System.out.println("Number is below 7");
}
System.out.println("Program ends...");
}
}
Output:
Program starts...
Number is below 7
Program ends...
public class IfElseIf
{
public static void main(String[] args)
{
System.out.println("Program starts...");
int num = 7;
//Take decision whether num is above 7 or below or equal to 7
if(num>7)
{
//if body will gets executed only when condition is true
System.out.println("Number is above 7 ");
}
else if(num == 7)
{
// statements will be executed when condition is true
System.out.println("Number is equal to 7");
}
else
{
// statements will be executed when condition is false
System.out.println("Number is below 7");
}
System.out.println("Program ends...");
}
}
Output:
领英推荐
Program starts...
Number is equal to? 7
Program ends...
Break Keyword:
Syntax:
break;
public class Break
{
public static void main(String args[])
{
System.out.println("Program starts...");
int[] numbers ={10,20,30,40,50};
for(int x : numbers)
{
if(x ==30)
{
break;
}
System.out.print( x );
System.out.print("\n");
}
System.out.println("Program ends...");
}
}
Output:
Program starts...
10
20
Program ends...
Continue Keyword:
Syntax:
continue;
public class Continue
{
public static void main(String args[])
{
System.out.println("Program starts...");
int[] numbers ={10,20,30,40,50};
for(int x : numbers)
{
if( x ==30){
continue;
}
System.out.print( x );
System.out.print("\n");
}
System.out.println("Program ends...");
}
}
Output:
Program starts...
10
20
40
50
Program ends...
Switch Statement
Syntax:
The syntax of enhanced for loop is:
switch(expression){
case value :
//Statements
break;//optional
case value :
//Statements
break;//optional
//You can have any number of case statements.
default://Optional
//Statements
}
The following rules apply to a switch statement:
? The variable used in a switch statement can only be a byte, short, int, or char.
? You can have any number of case statements within a switch. Each case is followed by the value to be
???Compared to and a colon.
? The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
? When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
? When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
? Not every case needs to contain a break. If no break appears, the flow of control will fall throughto subsequent cases until a break is reached.
? A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.
public class SwitchDemo
{
public static void main(String[] args)
{
int month = 9;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
Output: September
Loop Statements?
For loop:
?Syntax:??
for (initialization; Condition; Increment/decrement)
{
//Statements
}
Here is the flow of control in for loop:
? The initialization step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.
? Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement past for loop.
? After the body of for loop executes the flow of control jumps back up to the update statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a
Semicolon appears after the Boolean expression.
? The Boolean expression is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then update step, then Boolean expression). After the Boolean expression is false, the for loop terminates.
Programs:?
public class SimpleFor
{
public static void main(String[] args)
{
System.out.println("Program starts...");
for(int i=0; i<=4; i++)
{
System.out.println("Running for loop body:");
System.out.println("Value of i is: "+i);
}
System.out.println("Program ends...");
}
}
Output:
Program starts...
Running for loop body:
Value of i is: 0
Running for loop body:
Value of i is: 1
Running for loop body:
Value of i is: 2
Running for loop body:
Value of i is: 3
Running for loop body:
Value of i is: 4
Program ends...
public class ForLoop
{
public static void main(String[] args)
{
System.out.println("Program starts...");
System.out.println("Printing the square value of first five numbers:");
for(int i=1; i<=5; i++)
{
System.out.println("Value of "+i+" is: "+(i*i));
}
System.out.println("Program ends...");
}
}
Output:
Program starts...
Printing the square value of first five numbers:
Value of 1 is: 1
Value of 2 is: 4
Value of 3 is: 9
Value of 4 is: 16
Value of 5 is: 25
Program ends...
public class NestedLoop
{
public static void main(String[] args)
{
System.out.println("Program starts...");
for(int i=1; i<=5; i++)
{
System.out.println("Running Outer Loop: ");
for(int j=1;j<=3;j++)
{
System.out.println(" Running innner loop:");
}
}
System.out.println("Program ends...");
}
}
Program starts...
Running Outer Loop:?
???????????Running innner loop:
???????????Running innner loop:
???????????Running innner loop:
Running Outer Loop:?
???????????Running innner loop:
???????????Running innner loop:
???????????Running innner loop:
Running Outer Loop:?
???????????Running innner loop:
???????????Running innner loop:
???????????Running innner loop:
Running Outer Loop:?
???????????Running innner loop:
???????????Running innner loop:
???????????Running innner loop:
Running Outer Loop:?
???????????Running innner loop:
???????????Running innner loop:
???????????Running innner loop:
Program ends...
public class DiamondForLoop
{
public static void main(String[] args)
{
for(int i=1; i<=10; i++)
{
for(int k=1;k<=i;k++)
{
System.out.print(k);
}
System.out.println();
}
}
}
Output:
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
While Loop
A while loop is a control structure that allows you to repeat a task a certain number of times.
Syntax:
While (Condition)
{
//Statements
}
public class SimpleWhile
{
public static void main(String args[])
{
System.out.println("Program starts...");
int x =10;
while( x <20)
{
System.out.print("value of x : "+ x );
x++;
System.out.print("\n");
}
System.out.println("Program ends...");
}
}
Output:
Program starts...
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Program ends...
Do while Loop:
Syntax:
do
{
//Statements
}while(Condition);
public class DoWhile
{
public static void main(String args[])
{
char d = 'a';
do
{
System.out.println(d);
d++;
}while(d <= 'z');
}
}
Output: It will print from a to z
public class SimpleDoWhile
{
public static void main(String args[])
{
System.out.println("Program starts...");
int x =10;
do{
System.out.print("value of x : "+ x );
x++;
System.out.print("\n");
}while( x <20);
System.out.println("Program ends..");
}
}
Output:
Program starts...
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Program ends.
?