Lab 04 Java - 2k21

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

UET TAXILA

CLO Learning Outcomes Assessment Item BT Level PLO


No.

1 Construct the experiments / projects of Lab Task, Mid Exam, Final


varying complexities. Exam, Quiz, Assignment, P2 3
Semester Project

2 Use modern tool and languages. Lab Task, Semester Project P2 5

3 Demonstrate an original solution of Lab Task, Semester Project


A2 8
problem under discussion.

4 Work individually as well as in teams Lab Task, Semester Project A2 9

Lab Manual - 4

OOP
3rdSemester Lab-4: Operators in Java

Laboratory 4:
Lab Objectives: After this lab, the students should be able to understand Java Math class and the
following Operators:

 Conditional
 Unary Operators
 Arithmetic
 Arithmetic Assignment
 Relational
 Logical
 Bitwise

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

Example:
import java.util.Scanner;
public class PassFail {
public static void main(String[] args) {
// take input from users
Scanner input = new Scanner(System.in);
System.out.println("Enter your marks: ");
double marks = input.nextDouble();

// ternary operator checks if marks is greater than 40


String result = (marks > 40) ? "pass" : "fail";

System.out.println("You " + result + " the exam.");


input.close();
}
}

Output:1

Output:2

Exercise:1

What will be the value of b after the execution of the following program?

public class Test {


public static void main(String args[]){

Engr. Sidra Lab 1


3rdSemester Lab-4: Operators in Java

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 );
}
}

2. Java Unary Operator:

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Exercise:2 (Java Unary Operator ++ and --)

In the following program, show the output of i:

class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i);
++i;
System.out.println(i); System.out.println(+
+i); System.out.println(i++);
System.out.println(i);
}
}

Exercise: 3 (Java Unary Operators ~,!)


Show the output of the following program:

public class UnaryOp_ex {


public static void main(String[] args) {
int a=10;
int b=-37;
boolean c=true;
System.out.println(~a);
System.out.println(~b);
System.out.println(!c);
} }

3. The Arithmetic Operators:


Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators: Assume integer variable A
holds 10 and variable B holds 20, then:

Engr. Sidra Lab 2


3rdSemester Lab-4: Operators in Java

Operator Description Example


+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder B % A will give 0
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19

Modulus Operator:

Java has one important arithmetical operator you may not be familiar with, % , also known as
the modulus or remainder operator. The % operator returns the remainder of two numbers.
For instance, 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1.

Note: The % operator can also be used with integers and floating-point types.

int x2=42;
double y3=42.25;

System.out.println("x2 mod 10 is " + x2 % 10);


System.out.println("y3 mod 10 is " + y3 % 10);

Output:

Exercise:4

Consider the following code snippet:

int i = 10;
int n = i++%5;
1. What are the values of i and n when the code is executed?
2. What are the final values of i and n if instead of using the postfix increment operator
(i++), you use the prefix version (++i)?

4. Compound assignment operators in Java:

Compound-assignment operators provide a shorter syntax for assigning the result of an


arithmetic or bitwise operator. They perform the operation on the two operands before
assigning the result to the first operand.

The following are all possible assignment operator in java:

Engr. Sidra Lab 3


3rdSemester Lab-4: Operators in Java

Exercise 5:

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op


(E2)), where T is the type of E1, except that E1 is evaluated only once.

short x1 = 4;
// x1=x1+6.6;
x1 += 6.6;
System.out.println("x1 is " + x1 + "!"); //10

Because here 6.6 which is double is automatically converted to short type without explicit
type-casting.
// Another example
byte b = 10;
//b = b + 10;
b += 10;
System.out.println(b); //20

When is the Type-conversion required?


When using normal assignment operator, we have to do type-casting to get the result.
In compound assignment operator type-casting is automatically done by compiler. In this
case, we don’t have to do type-casting to get the result.

5. Relational Operators:

The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.

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

Engr. Sidra Lab 4


3rdSemester Lab-4: Operators in Java

The result of these operations is a boolean value.

Any type in Java, including integers, floating-point numbers, characters, and Booleans can be
compared using the equality test, ==, and the inequality test, !=.

Only numeric types can be compared using the ordering operators. That is, only integer,
floating-point, and character operands may be compared to see which is greater or less than
the other.

6. The Logical Operators:

The Boolean logical operators shown below operate only on Boolean operands.
The following table lists the logical operators:

Operator Description
& Logical AND
| Logical OR
^ Logical XOR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT

Short-Circuit Logical Operators:

These logical operators are used to check whether an expression is true or false.

Example Meaning
Expression1 && Expression2 True only if both Expression1 and Expression2 are true
Expression1 || Expression2 True if either Expression1 or Expression2 is true

Assume Boolean variables A holds true and variable B holds false, then:
(A&&B ) is false and (A || B ) is true.

Exercise 6:

1. Evaluate the following Boolean expressions and prints their results.


Boolean b1, b2, b3;

Engr. Sidra Lab 5


3rdSemester Lab-4: Operators in Java

b1 = true || false;
b2 = b1 && (5 > 3);
b3 = b2 && (13 == 6);

2. What is the difference between following two statements?

Boolean b= (100>5) || (6*8>5);


Boolean b= (100>5) | (6*8>5);

7. The Bitwise Operators:

Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte. These operators act upon the individual bits of their operands. The
following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:

The Java Math Class:

The class Math, which is a part of the package java.lang provides methods for mathematical
functions like sine, cosine, logarithm, and so on. Most of its functions should be familiar to
students who have had a course in trigonometry. Some of the more common methods there
include:

Method Description
abs(x) Absolute value of x
sin(x) Sine of x (in radians)
cos(x) Cosine of x (in radians)
pow(x,y) x raised to power y
sqrt(x) Square root of x

Engr. Sidra Lab 6


3rdSemester Lab-4: Operators in Java

ceil(x) Smallest integer not less than x


floor(x) Largest integer not greater than x
round(x) Closest integer to x
min(x,y) Minimum of x and y
max(x,y) Maximum of x and y

In each of these methods, the arguments x and y, are real (double) values. (Any value that can
be promoted to a double value can be used as well.)

The definitions of these methods are stored the package java.lang so there is no need to do an
import.

To use a method, we need to add the name of the class it belongs to. For example, to compute
the sine of the variable x and place the result in y we would need to use

y = Math.sin(x);

LAB TASKS

1. Write a Java Program to find the result of the following Expressions. (Assume a=5
and b=4). Marks: 3
i. (a<<2)+(b>>2)
ii. (a++ != b++) && (a++ ==b++);
iii. (--a != --b) | (--a == --b);

2. Write a Java program to input several values into an array, verify that the length of
an array is between 1 and 100. If outside of that range, output an error message and
end the program, otherwise continue. Process the array by passing it to a method
that will compute and return the standard deviation of the values in the array.

The standard deviation first requires that you compute the average. Assuming our
array is values, and the average is avg, the standard deviation is computed as:

However, if n is 0 there are no values at all and if n is 1, you will get an error. So if n
is not at least 2, return the value -1000. This will indicate that there were not enough
values in the array to compute the stddev. Marks: 7

Expected Output is shown below:

Engr. Sidra Lab 7


3rdSemester Lab-4: Operators in Java

 Run the Code with the following 10 inputs and observe the result.

1
2
3
9
8
7
4
6
12
15

*********

Engr. Sidra Lab 8

You might also like