[go: up one dir, main page]

0% found this document useful (0 votes)
10 views59 pages

Methods

The document provides an overview of operators and methods in Java, detailing various types of operators including arithmetic, unary, assignment, relational, logical, ternary, bitwise, and shift operators. It also explains the concept of methods, differentiating between predefined and user-defined methods, and discusses static and instance methods, including their syntax and usage. Additionally, it covers parameter passing techniques and the implications of using static methods in Java.

Uploaded by

pps201003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views59 pages

Methods

The document provides an overview of operators and methods in Java, detailing various types of operators including arithmetic, unary, assignment, relational, logical, ternary, bitwise, and shift operators. It also explains the concept of methods, differentiating between predefined and user-defined methods, and discusses static and instance methods, including their syntax and usage. Additionally, it covers parameter passing techniques and the implications of using static methods in Java.

Uploaded by

pps201003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Operators and Methods

in java
Operators in java
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
Arithmetic operator
• * : Multiplication
• / : Division
• % : Modulo
• + : Addition
• – : Subtraction
Unary operator
• Unary operators need only one operand. They are used to increment, decrement, or negate a value.
• – : Unary minus, used for negating the values.
• + : Unary plus indicates the positive value (numbers are positive without this, however). It performs
an automatic conversion to int when the type of its operand is the byte, char, or short. This is called
unary numeric promotion.
• ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment
operators.
• Post-Increment: Value is first used for computing the result and then incremented.
• Pre-Increment: Value is incremented first, and then the result is computed.
• – – : Decrement operator, used for decrementing the value by 1. There are two varieties of
decrement operators.
• Post-decrement: Value is first used for computing the result and then decremented.
• Pre-Decrement: The value is decremented first, and then the result is computed.
• ! : Logical not operator, used for inverting a boolean value.
Assignment operator
• ‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, i.e. value given on the right-hand side of the operator is assigned to the
variable on the left, and therefore right-hand side value must be declared before using it or
should be a constant.
• +=, for adding the left operand with the right operand and then assigning it to the variable
on the left.
• -=, for subtracting the right operand from the left operand and then assigning it to the
variable on the left.
• *=, for multiplying the left operand with the right operand and then assigning it to the
variable on the left.
• /=, for dividing the left operand by the right operand and then assigning it to the variable
on the left.
• %=, for assigning the modulo of the left operand by the right operand and then assigning it
to the variable on the left.
Relational Operator
• ==, Equal to returns true if the left-hand side is equal to the right-hand side.
• !=, Not Equal to returns true if the left-hand side is not equal to the right-
hand side.
• <, less than: returns true if the left-hand side is less than the right-hand side.
• <=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
• >, Greater than: returns true if the left-hand side is greater than the right-
hand side.
• >=, Greater than or equal to returns true if the left-hand side is greater
than or equal to the right-hand side.
Logical operator

• &&, Logical AND: returns true when both conditions are true.
• ||, Logical OR: returns true if at least one condition is true.
• !, Logical NOT: returns true when a condition is false and vice-versa
Ternary operator
• The ternary operator is a shorthand version of the if-else statement. It has
three operands and hence the name Ternary.
• condition ? if true : if false
Bitwise operator
• These operators are used to perform the manipulation of individual bits of a
number. They can be used with any of the integer types.
• &, Bitwise AND operator: returns bit by bit AND of input values.
• |, Bitwise OR operator: returns bit by bit OR of input values.
• ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
• ~, Bitwise Complement Operator: This is a unary operator which returns
the one’s complement representation of the input value, i.e., with all bits
inverted.
Shift operator
• <<, Left shift operator: shifts the bits of the number to the left and fills 0
on voids left as a result. Similar effect as multiplying the number with some
power of two.
• >>, Signed Right shift operator: shifts the bits of the number to the right
and fills 0 on voids left as a result. The leftmost bit depends on the sign of the
initial number. Similar effect to dividing the number with some power of two.
• >>>, Unsigned Right shift operator: shifts the bits of the number to the
right and fills 0 on voids left as a result. The leftmost bit is set to 0.
Priority and association
Precedenc Operator Type Associativity
e
15 () Parentheses Left to Right
[] Array subscript
· Member selection
14 ++ Unary post-increment Right to left
-- Unary post-decrement
13 ++ Unary pre-increment Right to left
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise
(type) complement
Unary type cast
12 * Multiplication Left to right
/ Division
% Modulus
11 + Addition Left to right
- Subtraction
10 << Bitwise left shift Left to right
>> Bitwise right shift with
>>> sign extension
Priority and association
9 < Relational less than Left to right
<= Relational less than or
> equal
>= Relational greater than
instanceof Relational greater than or
equal
Type comparison (objects
only)
8 == Relational is equal to Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
1 = Assignment Right to left
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
Example problem
• What will be the output of the following
1) int x = 10, y = 5; int exp1 = (y * (x / y + x / y)); int exp2 = (y * x / y + y * x / y);
Output is 20, 20.
2) int x = 9, y = 12, z = 3; int exp1 = x - y/3 + z * 2 - 1; int exp2 = (x - y)/3 + ((z * 2) - 1);
Outputs are 10, 4.
3) int x = 9, y = 12; int a = 2, b = 4, c = 6; int exp = (3 + 4 * x)/5 - 10 * (y - 5) * (a + b +
c)/x + 9 * (4/x + (9 + x)/y);
-77.
4) int x = 9, y = 12; int a = 2, b = 4; boolean exp = 4/3 * (x + 34) < 9 * (3 + y * (2 + a)) / (a
+ b*y);
Output: false
int x = 1, y = 2, z = 5;
if(x == 1 || x > y || x > z)
{
System.out.println("One");
}
if(x == y || y == 2 || z == 5)
{
System.out.println("Two"); } if(x == y || y == z || z == x)
{
System.out.println("Three");
}

Output: One, Two


int x = 1, y = 2, z = 5;
System.out.println("x: " +(!((x + 2) == (1 + 2))));
if(!(x == y) && ((y + 5) > z) && (!((z - 3) == 0)))
{
System.out.println("Hello");
}
• Output: x: false, y: true, z>x: false, Hello.
• int x = 20, y = 30, z = 50; x += y; y -= x + z; z *= x * y;

• Output: x = 50, y = -70, z = -175000


• A collection of instructions that performs a specific task.
• Benefits
– Reusability
– Easy modification
– Readability
– Optimization
Types of method
• Predefined Method: method that is already defined in the Java class libraries
• known as the standard library method or built-in method
• length(), equals(), compareTo(), sqrt() etc.
• User-defined Method: The method written by the user or programmer
Syntax of user defined method
<access_modifier> <return_type> <method_name>( list_of_parameters)
{
//body
}
Parameter passing in methods
• Call by value
• Call by reference: not supported by java
– Ways to achieve call by reference: when we create a variable of class type,
the variable holds the reference to the object in the heap memory. This
reference is stored in the stack memory.
– when we pass the variable as an argument to a method, we inherently pass
a copy of the reference to the object in the heap memory.
– changes to the properties of the object inside the method are reflected
outside as well. This effectively means that objects are passed to methods
by use of call-by-reference.
– Changes to the properties of an object inside a method affect the original
argument as well.
Pass by value using java primitive
datatype
public class Main{
public static void main(String[] args) {
int a=10;
inc(a);
System.out.println(a);
}
public static void inc(int a) {
a=a+1;
System.out.println(a);
}
}
Pass by value using java object
public class Main{
public static void main(String[] args) {
Integer a=new Integer(10);
inc(a);
System.out.println(a);
}
public static void inc(Integer a) {
a=a+1;
System.out.println(a);
}
}
Way to achieve pass by reference using
object
public class Main{
int number=10;
public static void inc(Main ob)
{
ob.number++;
}
public static void main(String[] args) {
Main ob=new Main();
System.out.println(ob.number);
inc(ob);
System.out.println(ob.number);
}
}
Types of methods java
• Methods in Java can also be classified into the following types:
• Instance Method
• Static Method
Static keyword
• The static method in java and members in java can be accessed without creating the object of the
class.
• Example: A class 'Student' that contains all the necessary information like name, age, class, school
name, and rollno about the particular student that is studying in the school. Every object of the
class represents about the student, Now think which information is common in between of all the
students ?. The answer is School name.
• we can consider schoolname as a static variable. Because static members are equally shared
among all the objects of the class.
When to create static method
• "Does it make sense when you call a particular method without creating the
object of the class ". If yes, then the method should be static.
An example of class (non static)
class Box{
int width;
int height;
int length;
}
public class Main{
public static void main(String[] args) {
Box B1=new Box();
B1.width=2;
B1.height=3;
B1.length=4;
int volume=B1.width*B1.length*B1.height;
System.out.println(volume);
}
}
Static method (contd..)
• These are designed to be shared among all the instances of the same class and they are accessed by
the class name of the particular class.
• A static keyword is used for declaring the static method in java.
• Syntax to declare the static method:
Access_modifier static void methodName()
{
// Method body.
}
• To call static method
className.methodName();
Calling of static method
• To call static method
className.methodName();

class Main {
static void print() {
System.out.println("This the static method of the Main class");
}
public static void main(String[] args) {
Main.print();
}
}
When to use static method
• When the implementation of the particular method is not dependent on the instance variables and
instance methods, In this case we can make that method to be static.
• If the implementation of the code of the method is not changed by the instances of the class. In this
case, we can make the method a static method.
• If we want to define some utility functions such as user defined sorting method in the class, we
can define them using static concepts. Because the utility function can easily be shared among all
objects of the class due to the property of the static method.
Static Method in Java Examples
• Creating a Utility Class
Restrictions of Static Method in Java
• The static method cannot invoke the instance member as well as methods of the class. Because
static methods are accessed without the object reference of the class but we cannot access the
instance variables and method without an object reference. This will cause an error if we try to
access the instance variable or methods inside the static method.
• The static methods can only access only other static members and methods. Because static
members and methods are linked to the class during the compilation time that's why they can
access each other without creating the instance of the class.
features
• Rather than being an instance of a class, a static method in Java is a method
that is a part of the class itself.
• The method is available to each instance of the class.
• The method is available to each instance of the class. Without requiring the
class's object, static methods have access to class variables (static variables)
(instance).
• A static method can only access static data. It cannot access data that is
dynamic (instance variables).
• Static methods can be accessed directly in non-static methods as well as static
methods.
conclusion
• The static members and methods belong to the class rather than
the instance of the class.
• They are accessed by the name of the class.
• The keywords such as this and super are not used in the body of the static
method.
• The modification on the static field value is not allowed
example
public class Main{
int number=10;
public static void main(String[] args) {
Test ob=new Test();
} }
class Test{
int number=10;
static void inc() {
System.out.println(number);
}
}
Static method
• The static methods are the class methods and they don't belong to instances
of the class.
Instance method
• Non-static method that belongs to the class and its instance.
• Creating an object is necessary to call the instance method.
// Instance Method
Access_modifier void method_name()
{
body // instance area
}
Calling Instance Method:
• You can not call an instance method in the static method directly, so the
Instance method can be invoked using an object of the class. We know that
the java program’s execution starts from the main method and the main
method is static, so we can not directly call the instance method. We have to
create the class object; then, we can call the instance method in the main
method.
Example
import java.util.*;
public class Main{
public void Msg() {
System.out.println("Hello");
}
public static void Print() {
System.out.println("in print function");
}
public static int add(int a, int b) {
return a+b;
}
public static void main(String[] args) {
int res=Main.add(8,9);
System.out.println(res);
Print();
Main obj=new Main();
obj.Msg();
}
}
Types of method
• The accessor method is used to make the code more secure and increase its
protection level, accessor is also known as a getter. Getter returns the value
(accessors), it returns the value of data type int, String, double, float, etc. For
the convenience of the program, getter starts with the word “get” followed by
the variable name.
• The mutator method is also known as the setter. It sets the value for any
variable which is used in the programs of a class. and starts with the word
“set” followed by the variable name. Getter and Setter make the programmer
convenient in setting and getting the value for a particular data type. In both
getter and setter, the first letter of the variable should be capital.
Method Overloading
• it is possible to create methods that have the same name, but different
parameter lists and different definitions.
• In method overloading, we can create methods having the same name but
differ in the type, number, and/or sequence of parameters.
• When an overloaded method is invoked, Java uses
the type, number, and/or, sequence, or arguments as its guide to determine
which version of the overloaded method to call.
• When Java encounters a call to a method that is overloaded, it simply
executes the version of the method whose parameters match the arguments
used in the call.
Rules for method overloading
• The overloaded method must change the argument list (number of
parameters, data type, or sequence of parameters).
• The overloaded method can change the return type.
• The overloaded method can change the access modifier (the signature of the
function should be different).
Why overloading
• It is used when different objects are required to perform a similar set of tasks
but use different input parameters.
• For instance, in an e-commerce platform, there are different modes of
payment options like COD and UPI etc, all of which are overloaded to perform
a single function.
example
public class Main{
public int sum(int a, int b) {
return (a + b);
}
public int sum(int a, int b, int c) {
return (a + b + c);
}
public double sum(double a, double b) {
return (a + b);
}
public static void main(String args[]) {
Main s = new Main();
System.out.println(s.sum(3, 2));
System.out.println(s.sum(2, 2, 4));
System.out.println(s.sum(10.5, 20.5));
}
}
• Why Method Overloading is not possible by changing the return type of
method only?
• Type promotion and method overloading
Variable length argument
• public static void fun(int ... a) { // method body }
• int nums(int a, float b, double … c)
• Important Points regarding Varargs
• Vararg Methods can also be overloaded, but overloading may lead to ambiguity.
• Before JDK 5, variable length arguments could be handled in two ways: One was
using overloading, other was using array argument.
• There can be only one variable argument in a method.
• Variable argument (Varargs) must be the last argument.
Automatic type promotion in method
overloading
• Automatic type promotion: a small size datatype can be promoted to a large size
datatype
public void test(double a)
{
System.out.println("Method called");
}
public static void main(String args[])
{
test(2);
}
Automatic type promotion in method
overloading
• Only possible from small size datatype to higher size datatype but not from
higher size to smaller size.
Guess the output
public static void main(String[] args)
class TypePromotion { {

public static void test(int i) test('a');


{
test(2);
System.out.println("Automatic Type Promoted to Integer-" + i);
}
test(2.0f);
public static void test(double d) test(“Object as Parameter");
{ }
System.out.println("Automatic Type Promoted to Double-"
} + d);
}

public static void test(Object o)


{
System.out.println("Object method called");
Guess the output
public static void main(String[] args)
class AutomaticPromotion { {

public static void test(int i, double d) test(2,2.0);


{
System.out.println( test(2.0,2);
“Int-double");
} // test(2,2); error: reference to method is
ambiguous
public static void test(double d, int i)
{ }
System.out.println( }
"Double--int");
}
Hierarchy
Variable arguments
• show()
• show(10)
• show(10,20)
• show(10,20,30)
• In order to pass different number of argument to show different number I need
to create that many show function with varied number of argument in each
show() function
• Is there any way through which I can write only one method and it should work
for all the number of parameter
• Answer is variable length argument
Conditions to follow for variable length
argument
• All argument must be of same type
• Syntax: void show(int … x)
• The variables are combined into one array but that does not mean you will
capture it in the method in an array. So, to capture the parameter in method
you must use three dots.
• These three dots will even work for array
example
public class Main{
static void show(int ... x) {
for(int val:x) {
System.out.println("val: "+val);
}
}
public static void main(String[] args) {
show(10,20,30,40);
show(10,20);
show(10);
show(new int []{1,2,3,4,5});
}
}
Anonymous array
• Arrays having no name are called Anonymous arrays in java. This type of array
is used only when we require an array instantly. We can also pass this array to
any method without any reference variable.
• As anonymous arrays do not have reference variables, we can not access its
element, though we can use it entirely to meet our logic.
new int []{2,4,5,6,7};
• For Anonymous array creation, do not mention size in []. The number of values
passing inside {} will become the size.
More points
• Suppose the variable length argument takes one integer value compulsory
and next is variable length argument then the method can be defined as
follows
• void show(int arg1,int … arg2)
• In the above case show() will not work because at least one argument it needs
• show(10) will work and so on
• The variable length argument should be the last parameter always. Also, you
can not take many variable length argument.
• printf() in C uses ellipses since it takes one string argument and since you can
pass as many argument in printf().
example
public class Main{
static void show(int ... x) {
public static void main(String ... args) {
int sum=0; //System.out.println("Hello World");
for(int val:x) { show(10,20,30,40);
show(10,20);
System.out.println("val: "+val);
show(10);
} show(new int []{1,2,3,4,5});
int max=x[0]; }
}
System.out.println("max: "+max);
for(int val:x) {
sum=sum+val;
}
System.out.println("sum: "+sum);
}
constructor
• Constructors must have the same name as the class within which it is defined
it is not necessary for the method in Java.
• Constructors do not return any type while method(s) have the return type
or void if does not return any value.
• Constructors are called only once at the time of Object creation while
method(s) can be called any number of times.
• NOTE:
• A constructor in Java can not be abstract, final, static.
• Access modifiers can be used in constructor declaration to control its access i.e
which other class can call the constructor.
Types of constructor
• Default Constructor
• Parameterized Constructor
• Copy Constructor
• A constructor that has no parameters is known as default constructor provided
by compiler which is invisible.
• If we write a constructor with no arguments, the compiler does not create a
default constructor.
• If there is any argument passed in the constructor, It is being overloaded and
called a parameterized constructor.
• The default constructor changed into the parameterized constructor. But
Parameterized constructor can not change the default constructor.

You might also like