0% found this document useful (0 votes)
4 views

Lecture 3 Operators in Java

The document outlines the content of a programming lecture focused on Java, covering topics such as primitive data types, variable declaration, user input methods, and operators. It includes example programs demonstrating user input and arithmetic operations, as well as explanations of operators like increment, decrement, and bitwise operations. Additionally, it discusses operator precedence, arithmetic overflow, and provides practice problems for students to solve.

Uploaded by

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

Lecture 3 Operators in Java

The document outlines the content of a programming lecture focused on Java, covering topics such as primitive data types, variable declaration, user input methods, and operators. It includes example programs demonstrating user input and arithmetic operations, as well as explanations of operators like increment, decrement, and bitwise operations. Additionally, it discusses operator precedence, arithmetic overflow, and provides practice problems for students to solve.

Uploaded by

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

6/13/2020

IN2203

Fundamentals of
Programming (Java)

Instructor
Dr. Muhammad Waqar
muhammad.aslam@purescollege.ca

An Overview of Lecture 2
We discussed the following in lecture2
Tests
• Primitive Data types, byte, short, int, long, float, double, char,
boolean, String
• Declaration of variables, variable scope
• Escape Sequences
• Type Promotion and Casting

1
6/13/2020

Getting Input from User


• We can ask the user to specify the value of variable during execution rather
than initializing it ourselves during writingTests
a program.

• Different kind of packages are available for getting input from user including
Bufferreader class, Scanner class and Console class.

• Whichever class you use you will have to first import its package and then
will have to instantiate an object to use methods of that class.

• An example is given on next page which used Scanner class to get input from
user and then displays input using println.

Program for Getting Input from User


import java.util.Scanner;

public class GetInputFromUser { Tests


public static void main(String args[]) {

Scanner input = new Scanner(System.in);


System.out.print("Please enter an integer: ");
int number1 = input.nextInt();
System.out.println("You entered int " + number1);
System.out.print("Please enter a float: ");
float number2 = input.nextFloat();
System.out.println("You entered float "+number2);
}
}

2
6/13/2020

Practice Program
Write a program which asks user to enter radius. Then it
calculates the area of circle using radius and prints the area
Tests
on screen. The output of program should be as shown
below.

Practice Program Code


public class Example1 {

Tests
public static void main(String args[]) {

Scanner input = new Scanner(System.in);


final double PI = 3.1416; // final is used for constant
System.out.print("Please enter radius of circle: ");
double radius = input.nextDouble();
double area = PI*radius*radius;
System.out.println("Area of circle is "+area);
}
}

3
6/13/2020

Operators
• Operators are used to apply some operation on variables and values.
• The value or variables are called operands, while the operation (to be
performed between the two operands) isTests
defined by an operator
• Java provides a rich operator environment.
• Most of its operators can be divided into the following four groups:
arithmetic, bitwise, relational, and logical.
• Java also defines some additional operators that handle certain special
situations.

Arithmetic Operators
• The operands of the arithmetic operators must be of a numeric type. You
cannot use them on boolean types, but you can use them on char types,
since the char type in Java is, essentially,Tests
a subset of int.

4
6/13/2020

A simple program using arithmetic operators


class Example2 {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic"); Tests
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = c- d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
}
}

10

Simple Arithmetic Problems


What is the value in i after executing the following program segments?

1- int i = 12; 4- int i = 12;


Tests
int j = 5; int j = 20;
i = i / j; int k = 5;
i = i * 6 + j / 2 - k;
2- int i = 12;
int j = 5;
i = i % j;

3- int i = 10;
int j = 5;
i = i / j;

10

5
6/13/2020

11

Operators Precedence

Tests

11

12

Arithmetic Overflow
What is the final value stored in i in this program? Is this what you expected?
Tests
class Test {
// A program to demonstrate integer overflow

public static void main(String[] args) {


int i = 2000000000;
int j = 2000000000;
i = i + j;
System.out.println("i + j = " + i);
}
}

12

6
6/13/2020

13

Modulus Operator
• The modulus operator, %, returns the remainder of a division operation.
• It can be applied to floating-point types as well as integer types.
Tests
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + (x % 10));
System.out.println("y mod 10 = " + (y % 10));
}
}

13

14

Arithmetic Compound Assignment Operators


• Java provides special operators that can be used to combine an arithmetic
operation with an assignment. Statements like the following are quite common in
programming:
Tests
• a = a + 4;
• In Java, you can rewrite this statement as shown here:
• a += 4;
• This version uses the += compound assignment operator. Both statements perform
the same action: they increase the value of a by 4.
• Compound assignment can be applied to any operator e.g. a *= 4 (is same as a=
a*4;) a/=4 (a= a/4), a%=4 (a=a%4) etc.
• The compound assignment operators provide two benefits. First, they save you a bit
of typing, because they are “shorthand” for their equivalent long forms. Second,
they are implemented more efficiently by the Java run-time system than are their
equivalent long forms.

14

7
6/13/2020

15

Arithmetic Compound Assignment Operators


What will be the values in a, b and c after executing these commands?
Tests
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;

15

16

Increment and Decrement Operator


• The ++ and the – – are Java’s increment and decrement operators.
• The increment operator increases its Tests operand by one. The decrement
operator decreases its operand by one. For example, this statement:
• x = x + 1;
can be rewritten like this by use of the increment operator:
• x++; // is same as x = x+1;

Similarly, this statement:


• x - - // is same as x = x-1;

16

8
6/13/2020

17

Increment and Decrement Operator


• These operators are unique in that they can appear both in postfix form, where
they follow the operand as just shown, and prefix form, where they precede the
operand.
Tests
• In the prefix form, the operand is incremented or decremented before the value
is obtained for use in the expression.
• In postfix form, the previous value is obtained for use in the expression, and
then the operand is modified.
x = 42;
y = ++x;
• In this case both x and y get 43 as x is incremented first and then stored in y.
x = 42;
y = x++;
• In this case x gets 43 and y gets 42 as x is stored in y first and then incremented.

17

18

Increment and Decrement Operator


class IncDec {
public static void main(String args[]) {
int a = 1;
Tests
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

18

9
6/13/2020

19

The Bitwise Operators


• Java defines several bitwise operators that can be applied to the integer types,
long, int, short, char, and byte. These operators act upon the individual bits of
their operands.
Tests

19

20

Binary numbers and 2’s complement


• Since the bitwise operators manipulate the bits within an integer, it is important
to understand what effects such manipulations may have on a value.
• Specifically, it is useful to know how Java stores integer values and how it
Tests
represents negative numbers.

• byte x = 42 ( is same as 00101010 in binary)


• Java uses an encoding known as two’s complement, which means that negative
numbers are represented by inverting (changing 1’s to 0’s and vice versa) all of
the bits in a value, then adding 1 to the result.
• For example, –42 is represented by inverting all of the bits in 42, or 00101010,
which yields 11010101, then adding 1, which results in 11010110, or –42.
• To decode a negative number, first invert all of the bits, then add 1. For
example, –42, or 11010110 inverted, yields 00101001, or 41, so when you add
1 you get 42.

20

10
6/13/2020

21

The Bitwise Logical Operators


• The bitwise logical operators are &, |, ^, and ~. The following table shows the
outcome of each operation.
Tests

• The bitwise complement, the unary NOT operator, ~, inverts all of the bits of its
• operand.
• For example, the number 42, which has the following bit pattern: 00101010
becomes 11010101 after the NOT operator is applied.

21

22

An example using unary NOT


class Example {
public static void main(String args[]) { Tests

byte x = 0b00101010;
byte y = (byte) ~x;
System.out.println("x = " + x);
System.out.println("y = " + y);
}
}

22

11
6/13/2020

23

The Bitwise AND


• The AND operator, &, produces a 1 bit if both operands are also 1. A zero is
produced in all other cases. Tests

00101010 42
& 00001111 15
00001010 10

class BitwiseAND {
public static void main (String[] args) {
int number1 = 42, number2 = 15, result;
result = number1 & number2;
System.out.println(result);}
}

23

24

The Bitwise OR
• The OR operator, |, combines bits such that if either of the bits in the operands
is a 1, then the resultant bit is a 1, as shown here:
Tests

00101010 42
| 00001111 15
00101111 47

class BitwiseOR {
public static void main(String[] args) {
int number1 = 42, number2 = 15, result;
result = number1 | number2;
System.out.println(result);}
}

24

12
6/13/2020

25

The Bitwise XOR


• The XOR operator, ^, combines bits such that if exactly one operand is 1, then
the result is 1. Otherwise, the result is zero.
• The following example shows the effect ofTeststhe ^.
• The example also demonstrates a useful attribute of the XOR operation.
Notice how the bit pattern of 42 is inverted wherever the second operand
has a 1 bit. Wherever the second operand has a 0 bit, the first operand is
unchanged.

00101010 42
^ 00001111 15
00100101 37

Write a program which uses inverting bit property of bitwise xor to take one’s
complement.

25

26

Taking Two’s complement using XOR


class Test {
public static void main(String args[]) { Tests

byte x = 0b00101010;
byte y = (byte) (x^0b11111111);
byte z = (byte) (y + 1);
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
}
}

26

13
6/13/2020

27

The Left Shift


• The left shift operator, <<, shifts all of the bits in a value to the left a specified
number of times. It has this general form:
value << num Tests

• Here, num specifies the number of positions to left-shift the value in value
• For each shift left, the high-order bit is shifted out (and lost), and a zero is
brought in on the right.
• This means that when a left shift is applied to an int operand, bits are lost
once they are shifted past bit position 31. If the operand is a long, then bits
are lost after bit position 63.
• Java’s automatic type promotions produce unexpected results when you are
shifting byte and short values. In order to use shift on byte, you have to do
casting to byte again after operation.

27

28

The Left Shift on byte


// Left shifting a byte value.
class ByteShift {
public static void main(String args[]) { Tests

byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}

28

14
6/13/2020

29

The Left Shift to multiply by 2


// Left shifting as a quick way to multiply by 2.
Tests

class MultByTwo {
public static void main(String args[]) {
byte num = 32;
num = (byte) (num << 1);
System.out.println(num);
num = (byte) (num << 1);
System.out.println(num);}
}}}

29

30

The Right Shift


• The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times.
int a = 32; Tests
a = a >> 2; // a now contains 8
• When a value has bits that are “shifted off,” those bits are lost. For example,
the next code fragment shifts the value 35 to the right two positions, which
causes the two low-order bits to be lost
int a = 35;
a = a >> 2; // a still contains 8
• When you are shifting right, the top (leftmost) bits exposed by the right shift
are filled in with the previous contents of the top bit. This is called sign
extension and serves to preserve the sign of negative numbers when you
shift them right. For example, –8 >> 1 is –4,

30

15
6/13/2020

31

The Unsigned Right Shift


• The >> operator automatically fills the high-order bit with its previous
contents each time a shift occurs. This preserves the sign of the value.
• Sometimes this is undesirable. This situation
Tests is common when you are
working with pixel-based values and graphics.
• Java’s unsigned, shift-right operator, >>>, always shifts zeros into the high-
order bit.

int a = -1;
a = a >>> 24;
Here is the same operation in binary form to further illustrate what is
happening:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an int

31

32

Bitwise Operator Compound Assignments


• All of the binary bitwise operators have a compound form similar to that of
the algebraic operators, which combines the assignment with the bitwise
operation.
Tests
• For example, the following two statements, which shift the value in a right by
four bits, are equivalent:
a = a >> 4;
a >>= 4;
• Likewise, the following two statements, which result in a being assigned the
bitwise expression a OR b, are equivalent:
a = a | b;
a |= b;

32

16
6/13/2020

Thank You

33

17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy