You are on page 1of 46

Subject Name Java Programming (CSE III Year)

Department of Computer Science & Engineering


Created By: Dr. Avinash Dwivedi

JIMS Engineering Management Technical Campus

Greater Noida, UP - 201303


(Affiliated to Guru Gobind Singh Indraprastha University, New Delhi)
Recognized u/s 2(f) by UGC & Accredited with ‘A’ Grade by NAAC
Participant of UNGC & UNPRME, New York
ISO 9001:2015 Quality Certified
Subject: Java Programming
Topic: Java Operators & Methods
List of Topics to be covered

 Operator in Java
 Java Operator Precedence
 Arithmetic Operator
 Relational Operators
 Bitwise Operator examples
 Methods in Java Programming Language
 Method definition
 Method Calling
 method returns nothing
Operator in Java

▰ Java provides a rich operator environment.


▰ An operator is a symbol that tells the computer to perform certain mathematical or logical manipulation.
▰ Operators are used in the program to manipulate data and variables. They usually form a part of the mathematical
or logical expression.
▰ Java operators can be divided into following categories:
▻ Arithmetic Operators
▻ Relational Operators
▻ Bitwise Operators
▻ Logical Operators
▻ Assignment Operators
▻ conditional operator
▻ Misc Operators
Java Operator Precedence
Operator Type Category Precedence
Unary Postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Arithmetic Operator

▰ The basic arithmetic operations in Java Programming are addition,


subtraction, multiplication, and division.

▰ Arithmetic Operations are operated on Numeric Data Types as expected.

▰ Arithmetic Operators can be Overloaded.

▰ Arithmetic Operators are “Binary” Operators i.e they operate on two


operands. These operators are used in mathematical expressions in the
same way that they are used in algebra.
 

Arithmetic Operator

Operator Description Example


+ (Addition) Adds two operands 5 + 10 =15
- (Subtraction) Subtract second operands from first. 10 - 5 =5
Also used to Concatenate two strings

* (Multiplication) Multiplies values on either side of the 10 * 5 =50


operator.
/ (Division) Divides left-hand operand by right- 10 / 5 =2
hand operand.
% (Modulus) Divides left-hand operand by right- 5 % 2 =1
hand operand and returns remainder.

++ (Increment) Increases the value of operand by 1. 2++ gives 3


-- (Decrement) Decreases the value of operand by 1. 3-- gives 2
Relational Operators

▰ Relational Operators are used to checking relation between


two variables or numbers.
▰ Relational Operators are Binary Operators.

▰ Relational Operators returns “Boolean” value .i.e it will


return true or false.

▰ Most of the relational operators are used in “If statement”


and inside Looping statement in order to check truthiness or
falseness of condition.
Relational Operators

Operators Descriptions Examples


== (equal to) This operator checks the value of two operands, if (2 == 3) is not true.
both are equal, then it returns true otherwise false.
!= (not equal to) This operator checks the value of two operands, if (4 != 5) is true.
both are not equal, then it returns true otherwise
false.
> (greater than) This operator checks the value of two operands, if (5 > 56) is not true.
the left side of the operator is greater, then it returns
true otherwise false.
< (less than) This operator checks the value of two operands if the (2 < 5) is true.
left side of the operator is less, then it returns true
otherwise false.
>= (greater than This operator checks the value of two operands if the (12 >= 45) is not true.
or equal to) left side of the operator is greater or equal, then it
returns true otherwise false.
<= (less than or This operator checks the value of two operands if the (43 <= 43) is true.
equal to) left side of the operator is less or equal, then it
returns true otherwise false.
Program: Relational Operator

▰ public class RelationalOperator {


Output
▰ public static void main(String args[]) {
p == q = false
▰ int p = 5;
p != q = true
▰ int q = 10;
p > q = false
p < q = true
▰ System.out.println("p == q = " + (p == q) );
q >= p = true
▰ System.out.println("p != q = " + (p != q) );
q <= p = false
▰ System.out.println("p > q = " + (p > q) );
▰ System.out.println("p < q = " + (p < q) );
▰ System.out.println("q >= p = " + (q >= p) );
▰ System.out.println("q <= p = " + (q <= p) );
▰ }
▰ }
Bitwise Operator examples

▰ class BitwiseAndOperator {
▰ public static void main(String[] args){
▰ int A = 10; // 1010
▰ int B = 3; // 0011
▰ int Y;
▰ Y = A & B; // 0010 =2 (decimal)
▰ System.out.println(Y);
▰ }
▰ }

▰ Output 2
Bitwise OR Operator examples

▰ class BitwiseOrOperator {
▰ public static void main(String[] args){

▰ int A = 10; // 1010


▰ int B = 3; // 0011
▰ int Y;
▰ Y = A | B; // 1011= 11 (Decimal)
▰ System.out.println(Y);

▰ }
▰ }
▰ Output
▰ 11
Unary Operators

▰ The unary operators require only one operand; they perform various operations
such as incrementing/decrementing a value by one, negating an expression, or
inverting the value of a boolean.

Operator Description
Unary plus operator; indicates positive value (numbers are
+
positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
Program: Unary Operator

▰ class UnaryDemo {
▰ public static void main(String[] args) {
▰ int result = +1; // result is now 1
▰ System.out.println(result);
▰ result--; // result is now 0
▰ System.out.println(result);
▰ result++;
▰ System.out.println(result); // result is now 1
▰ result = -result;
▰ System.out.println(result); // result is now -1
▰ boolean success = false;
▰ System.out.println(success); // false
▰ System.out.println(!success); // true
▰ }
Comparison of ++I and i++

The increment/decrement operators can be


applied before (prefix) or after (postfix) the
▰ class PrePostDemo { operand. The code result++; and ++result; will
▰ public static void main(String[] args){ both end in result being incremented by one.
▰ int i = 3; The only difference is that the prefix version (+
▰ i++; +result) evaluates to the incremented value,
▰ System.out.println(i); // prints 4
whereas the postfix version (result++)
▰ ++i;
evaluates to the original value.

If you are just performing a simple
▰ System.out.println(i); // prints 5
▰ increment/decrement, it doesn't really matter
▰ System.out.println(++i); // prints 6 which version you choose.
▰ System.out.println(i++); // prints 6 But if you use this operator in part of a larger
▰ System.out.println(i); // prints 7 expression, the one that you choose may make
▰ } a significant difference.
▰ }
Branching Statements

▰ class BreakDemo {
▰ public static void main(String[] args) {
▰ int[] arrayOfInts = { 32, 87, 3, 589,12, 1076, 2000,8, 622, 127 };
▰ int searchfor = 3;
▰ int i;
▰ boolean foundIt = false;
▰ for (i = 0; i < arrayOfInts.length; i++) {
▰ if (arrayOfInts[i] == searchfor) {
▰ foundIt = true;
▰ break;
▰ }
▰ }
▰ if (foundIt) {
▰ System.out.println("Found " + searchfor + " at index " + i);
▰ } else {
▰ System.out.println(searchfor + " not in the array");
▰ } }}
The continue Statement

▰ class ContinueS{
▰ public static void main(String[] args) {
▰ String searchMe = "peter piper picked a " + "peck of pickled peppers";
▰ int max = searchMe.length();
▰ int numPs = 0;

▰ for (int i = 0; i < max; i++) {


▰ if (searchMe.charAt(i) != 'p') // searching for p's
▰ continue;
numPs++; // process p's
▰ }
▰ System.out.println("Found " + numPs + " p's in the string.");
▰ }
▰ } // OUTPUT 9 P’s
The return Statement

▰ The last of the branching statements is the return statement.


▰ The return statement exits from the current method, and control
flow returns to where the method was invoked.

▰ The return statement has two forms: one that returns a value, and


one that doesn't. To return a value, simply put the value (or an
expression that calculates the value) after the return keyword.
▰ return ++count;
▰ The data type of the returned value must match the type of the
method's declared return value. When a method is declared void,
use the form of return that doesn't return a value.
▰ return;
The return Statement

▰ public class ReturnS{


▰ public int add() { // without arguments
▰ int a = 10;
▰ int b = 20;
▰ int c = a+b;
▰ return c;
▰ }
▰ public static void main(String args[]) {
▰ ReturnS s = new ReturnS();
▰ int add = s.add();
▰ System.out.println("The sum of a and b is: " + add);
▰ }
▰ }
The return Statement not returning any value

▰ public class ReturnS2{


▰ public void add() { // without arguments
▰ int a = 10;
▰ int b = 20;
▰ int c = a+b;
▰ System.out.println("The sum of a and b is: " + c);
▰ return ;
▰ }
▰ public static void main(String args[]) {
▰ ReturnS2 s = new ReturnS2();
▰ s.add();

▰ }
▰ }
▰ Can a function returns more than one
value?
Returning multiple values

▰ class ReturnArray {
▰ // Returns an array such that first element of array is a+b, and second element is a-b
▰ static int[] getSumAndSub(int a, int b)
▰ {
▰ int[] ans = new int[2];
▰ ans[0] = a + b;
▰ ans[1] = a - b;
▰ return ans; // returning array of elements
▰ }
▰ public static void main(String[] args)
▰ {
▰ int[] ans = getSumAndSub(100, 50);
▰ System.out.println("Sum = " + ans[0]);
▰ System.out.println("Sub = " + ans[1]);
▰ }}
Methods in Java Programming Language
Methods & Function in Java Programming
Function Method
a set of instructions that perform a task. a set of instructions that are associated with
an object.
Functions have independent existence. You Methods do not have independent
can define them outside of the class. existence. They are always defined within a
class, struct, or enum.
Functions are the properties of structured Methods are the properties of Object-
languages like C, C++, Pascal and object oriented language like C#, Java, Swift etc.
based language like JavaScript.
Note: There is no concept of function in
Java.
Functions don't have any reference variables. Methods are called using reference
variables.
Functions are a self describing piece of code. Methods are used to manipulate instance
variable of a class.
Functions are called independently. Methods are called using instance or object.
Methods in Java Programming Language

1. A method is a set of code which is referred to by name and can be called


(invoked) using method's name.
▰ A method in Java is a collection of instructions that performs a specific
task. It provides the reusability of code.
▰ We can also easily modify code using methods.
▰ A method acts on data and often returns a value.

▰ The use of methods will be our first step in the direction of modular
programming.

Method in Java

▰ A method is a block of code or collection of statements or a set of


code grouped together to perform a certain task or operation. It is used
to achieve the reusability of code.
▰ We write a method once and use it many times.

▰ We do not require to write code again and again.

▰ It also provides the easy modification and readability of code, just by


adding or removing a chunk of code.
▰ The method is executed only when we call or invoke it.

▰ The most important method in Java is the main() method


Method definitions

▰ Method definitions have four basic parts:

▰ The name of the method


▰ The type of object or base type this method returns
▰ A list of parameters
▰ The body of the method
Method Declaration
Method Signature & Access specifier

▰ Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.

▰ Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
▰ Public: The method is accessible by all classes when we use public specifier in our application.
▰ Private: When we use a private access specifier, the method is accessible only in the classes in which it is
defined.

▰ Protected: When we use protected access specifier, the method is accessible within the same package or
subclasses in a different package.
▰ Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Method related terms

▰ Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.

▰ Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its name.

▰ Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

▰ Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Types of Method

▰ There are two types of methods in Java:

▰ Predefined Method
▰ User-defined Method
Predefined Method

▰ In Java, predefined methods are the method that is already defined in


the Java class libraries is known as predefined methods.
▰ It is also known as the standard library method or built-in method.
▰ We can directly use these methods just by calling them in the
program at any point.
▰ Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc.

▰ Each and every predefined method is defined inside a class. Such


as print() method is defined in the java.io.PrintStream class. It prints
the statement that we write inside the method. For example,
print("Java"), it prints Java on the console.
Predefined Method program

▰ // Java.lang.Math Class need not to import

▰ public class Demo   
▰ {  
▰ public static void main(String[] args)   
▰ {  
▰ // using the max() method of Math class  
▰ System.out.print("The maximum number is: " + Math.max(9,7));  
▰ }  
▰ }  
Method Header
Explanation

▰ modifier ? It defines the access type of the method and it is optional to use.
▰ return type ? Method may return a value. It can be any data type.
▰ name of method ? This is the method name. The method signature consists of the
method name and the parameter list.
▰ Parameter List ? Parameter list may two type 1. formal parameter 2. actual
parameter. The list of parameters, it is the type, order, and a number of parameters
of a method. These are optional, the method may contain zero parameters.
▰ formal parameter - The variables defined in the method header are known as formal
parameters or simply parameters. A parameter is like a placeholder.
▰ actual parameter - When a method is invoked, you pass a value to the parameter.
This value is referred to as an actual parameter or argument.
▰ method body ? The method body defines what the method does with the
statements.
Method Call
Complete programming to calculate
largest number among two number

▰ class MethodsExample{
▰ public static void main(String args[])
▰ {
▰ int a = 15;
▰ int b = 8;
▰ int c = max(a, b);
▰ System.out.println("Largest Value = " + c);
▰ }
▰ public static int max(int numA, int numB) {
▰ int result;
▰ if (numA > numB){
▰ result = numA;
▰ }
▰ else{ result = numB; }
▰ return result;
▰ }}
Method Calling

▰ In a method definition, you define what the method is to do.


▰ To execute the method, you have to call or invoke it.
▰ There are two ways in which a method is called depending on whether
the method returns a value or not.

▰ method returns a value


▰ If a method returns a value, a call to the method is usually treated as a
value. and this value will store in a variable For example,

▰ int largestNumber = max(15, 8);


▰ calls max(15, 8) and assigns the result of the method to the variable
largestNumber.
Method Calling
Example
class MethodsExample{
▰ public static void main(String args[])
▰ {
▰ int a = 15;
▰ int b = 8;
▰ System.out.println("The largest number is " +max(a, b));
▰ }
▰ public static int max(int numA, int numB) {
▰ int result;
▰ if (numA > numB){
▰ result = numA;
▰ }
▰ else{
▰ result = numB;
▰ }
▰ return result; } }
method returns nothing

▰ class Methodscall{
▰ public static void main(String args[])
▰ {
▰ int a = 15;
▰ int b = 8;
▰ max(a, b); // function calling
▰ }
▰ public static void max(int x, int y) {
▰ int result;
▰ if (x > y){
▰ result = x;
▰ }
▰ else{ result = y; }
▰ System.out.println("The largest number is " +result);
▰ }}
Void Method

▰ public class VoidMethodExample {


▰ public static void main(String[] args) {
▰ System.out.print("You are ");
▰ printAge(78);
▰ System.out.print("You are ");
▰ printAge(15);
▰ }
▰ public static void printAge(double age) {
▰ if (age >= 90.0) { System.out.println("lagend Old"); }
▰ else if (age >= 60.0) { System.out.println("old"); }
▰ else if (age >= 40.0) { System.out.println("adult"); }
▰ else if (age >= 20.0) { System.out.println("young"); }
▰ else {
▰ System.out.println("boy");
▰ } }}
Passing Parameters by Value

▰ When you invoke a method with an argument, the


value of the argument is passed to the parameter.

▰ This is referred to as pass-by-value. When calling a


method, you need to provide arguments, which must
be given in the same order as their respective
parameters in the method signature.

▰ This is known as parameter order association


Parameter Passing

▰ public class SwappingExample {


▰ public static void main(String[] args) {
▰ int a = 3;
▰ int b = 4;
▰ System.out.println("Before swapping, a = " + a + " and b = " + b);
▰ swapFunction(a, b); // Invoke the swap method
▰ System.out.println("\n Now, Before and After swapping values will be same here :");
▰ System.out.println("After swapping, a = " + a + " and b is " + b);
▰ }
▰ public static void swapFunction(int a, int b) {
▰ System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
▰ // Swap a with b
▰ int c = a;
▰ a = b;
▰ b = c;
▰ System.out.println("After swapping(Inside), a = " + a + " b = " + b);
▰ }}
Parameter Passing

▰ public class Mathmax


▰ {
▰ int a, b;
▰ void sum1(int x, int y= 6) // The syntax of Java language doesn't allow you to //declare a method with a predefined value for a
parameter
▰ {
▰ a=x+y;
▰ b=x-y;
▰ System.out.println(a+" "+b);
▰ return;
▰ }
▰ public static void main(String[] args)
▰ {
▰ // using the max() method of Math class
▰ System.out.print("The maximum number is: " + Math.max(9,7));
▰ Mathmax m=new Mathmax();
▰ m.sum1(4,9); } }
Thank You !!

You might also like