3. Methods

3. Methods

Operators

  • An operator is a symbol that allows a programmer to perform certain operation like (arithmetic and logical) on data and variables (operands).

Operators are used to manipulate the variables;

Java provides rich set of operators.

We can divide all the java operators into the following groups,

  1. Arithmetic operators
  2. Assignment operators
  3. Relational operators
  4. Logical operators
  5. Instance of (instanceof) operator
  6. Conditional operators

Based on the number of operands, operator can be of the following three types.

  1. Unary operator
  2. Binary operator
  3. Ternary operator

Unary Operator:-

  • It takes one operand,?
  • Such as, ++x, y--, here x and y are variables and ++ and - - are operators

Binary Operator:-

  • It takes two operands,
  • Such as, x<y, x+y etc, here a & y are variables while < and + are operators

Ternary operator:-

  • It takes three operands,
  • Such as, Z = (a < b)? a : b;?
  • Here x y and z are variables and <? : are operators.??

Arithmetic Operators:

  • Arithmetic operators are used in mathematical expressions.
  • The following table lists the arithmetic operators:

  • Assume integer variable A holds 10 and variable B holds 20, then:

Assignment Operators:

  • There are following assignment operators supported by Java language:

?Relational Operators:

  • There are following relational operators supported by Java language
  • Assume variable A holds 10 and variable B holds 20, then:

Logical Operators:

  • The following table lists the logical operators:
  • Assume Boolean variables A holds true and variable B holds false, then:

Instanceof Operator:

  • This operator is used only for object reference variables. The operator checks whether the object is of a particular type (class type or interface type).

Instanceof operator is written as:

  • ( Object reference variable ) instanceof? (class/interface type)

  • If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface type on the right side, then the result will be true. Following is the example:

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 (? : ):

  • Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as:
  • variable x = (expression) ? value if true : value if false

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:

  • Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:
  • For example, x = 7 + 3 2; here x is assigned 13, not 20 because the operator has higher precedence than +, so it first gets multiplied with 3*2 and then added into 7.
  • Here, operators with the highest precedence appear at the top of the table, and those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Note IMP: What will be output for the following statements??

  1. System.out.println(10/0);
  2. System.out.println(10/0.0);
  3. System.out.println(0/0);
  4. System.out.println(0/0.0);

  1. First case:

- In the first case, both 10 and 0 are integer type.

  • Generally we divide integer value by another integer the output will be integer only, but if we divide a value by zero, we will get infinity. But in integral arithmetic (i.e. if we use byte, short, int and long to declare a value that we called as integral arithmetic), there is no way to represent the infinity.
  • So because of this, when we run this statement immediately we will get the run time exception (Arithmetic exception division by the zero)

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)

  1. Second case:

  • In the second case we were dividing the integer type by double type; the output will be floating value. In this case of floating point arithmetic, there is way to represent the infinity.?
  • If we run this statement, we won’t get the runtime exception but we will get infinity as output.

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

  • The above infinity we call as a positive 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

  • In the above two programs we are dividing the negative value by a integer 0 if we run this program we will get negative infinity as output.

Note: - In the above two cases, if we are dividing the integral arithmetic values by? ? ? ? ? ? 0 we will get runtime arithmetic exceptions

  • But if we divide the decimal value we won’t get exception instead we will get infinity if it is a positive values, - infinity if it is a negative values.

  1. Third case:

  • In third case, we are dividing zero by zero, both are integral arithmetic values.
  • In general mathematics if we divide zero by zero, output will be ‘un-defined’ but in java there is no way to define ‘un-defined’, if we run that statement than we will get arithmetic exception.

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)

  1. Fourth case:

  • If are dividing decimal zero by integer zero, in traditional mathematics it will be undefined but in java for floating arithmetic there is a way to define the undefined, if we run that statements, the output will be ‘NaN’.

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

  • Methods are a block which contains set of statements which gets executed whenever it is called.
  • A Java method is a collection of statements that are grouped together to perform an operation.

Advantage of Methods/Functions

  • Code Reusability
  • Code Optimization

  • The syntax to develop a method is,

A method definition consists of a method header and a method body. Here are all the parts of a method:

  • ?Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.

In java there are twelve modifiers are available, they are:

  • Public
  • Protected
  • default
  • Private
  • Static
  • Abstract
  • Final
  • Synchronized?
  • Native
  • Strictfp
  • Transient
  • Volatile

  • Return Type: A method may return a value. The return value type is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the return value type is the keyword void.

Return type may be any data type:

  • Int
  • Double
  • String etc.?

  • ?Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.
  • Arguments/Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method Body: The method body contains a collection of statements that define what the method does.?
  • Every method should have a return statement. If a method doesn’t return any value then such methods should be declared as void return type.
  • We can develop a method without arguments.
  • Calling a method for execution is known as method invocation. Whenever a method is invoked JVM executes the method statements sequentially.?

Programs:

  • Sample Method which doesn’t return anything.

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...

  • Program to develop a method which takes arguments and return void.

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...

  • Program to take an argument and return a value.

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...

  • Program to take a multiple arguments?

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

  • Java Control statements?control the order of execution in a java program, based on data values and conditional logic.

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:

  1. Selection statements/Decision making statements And Transfer statements/Branching statements
  2. Repetition statements/Loop statements

Selection or decision making statements

  • Decision making statements are used to whether or not a particular statements or a group of statements should be executed.
  • I.e. when we want to execute some set of statements based on the condition that time we go for using the decision making statements.
  • We use this statements to take decision and then execute the statements
  • Following are the decision making statements

  • If statements? - if-else, if-else-if, nested-if :? An if statement consists of a Boolean expression followed by one or more statements
  • Switch 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:

  • The break keyword is used to stop the entire loop. The break keyword must be used inside any loop or a switch statement.
  • The break keyword will stop the execution of the innermost loop and start executing the next line of code after the block.

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:

  • The continue keyword can be used in any of the loop control structures. It causes the loop to immediately jump to the next iteration of the loop.
  • In a for loop, the continue keyword causes flow of control to immediately jump to the update statement.
  • ?In a while loop or do/while loop, flow of control immediately jumps to the Boolean expression.

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

  • Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths.
  • A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

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?

  • There may be a situation when we need to execute a block of code several number of times and is often referred to as a loop.
  • I.e. when we want to execute some set of statements repetitively, than we go for looping statements.
  • Following are the looping statements which is used to execute the code repetitively,?- for loop- for-each loop- while loop- do-while loop

For loop:

  • A for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
  • A for loop is useful when you know how many times a task is to be repeated.

?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
}        

  • When executing, if the condition result is true, then the actions inside the loop will be executed. This will continue as long as the expression result is true.
  • Here, key point of the while loop is that the loop might not ever run. When the expression is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

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:

  • A do while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax:

do

{

//Statements

}while(Condition);        

  • Notice that the condition appears at the end of the loop, so the statements in the loop execute once before the Boolean is tested.
  • If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the loop execute again. This process repeats until the Boolean expression is false.

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.

?

要查看或添加评论,请登录

Srinivas Prasad K T的更多文章

社区洞察

其他会员也浏览了