• No results found

Unit-4 / Java Programming - I

N/A
N/A
Protected

Academic year: 2021

Share "Unit-4 / Java Programming - I"

Copied!
18
0
0

Loading.... (view fulltext now)

Full text

(1)

Scanner Object (last heading of unit-3)

A Scanner object in Java is an instance of the java.util.Scanner class. To put it simply, we use Scanner objects in order to get input from the user.

To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.

To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort() To read strings, we use nextLine(). To read a single character, we use next().charAt(0).

next() function returns the next token/word in the input as a string and charAt(0) funtion returns the first character in that string.

Example1:

// Java program to read data of various types using Scanner class. import java.util.Scanner;

public class ScannerDemo1 {

public static void main(String[] args) {

// Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in);

// String input

String name = sc.nextLine();

// Character input

char gender = sc.next().charAt(0);

// Numerical data input

// byte, short and float can be read // using similar-named functions. int age = sc.nextInt();

(2)

double cgpa = sc.nextDouble();

// Print the values to check if input was correctly obtained. System.out.println("Name: "+name);

System.out.println("Gender: "+gender); System.out.println("Age: "+age);

System.out.println("Mobile Number: "+mobileNo); System.out.println("CGPA: "+cgpa);

} }

Example2

// Java program to read some values using Scanner // class and print their mean.

import java.util.Scanner;

public class ScannerDemo2 {

public static void main(String[] args) {

// Declare an object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in);

// Initialize sum and count of input elements int sum = 0, count = 0;

// Check if an int value is available while (sc.hasNextInt())

{

// Read an int value int num = sc.nextInt(); sum += num;

count++; }

int mean = sum / count;

System.out.println("Mean: " + mean); }

(3)

Unit 4: Operators

 Operator in java is a symbol that is used to perform operations.

 Java provides a rich operator environment. Most of its operators can be divided into the following four groups:

 Arithmetic operators  Bitwise operators  Relational operators  Logical. Operators

 Java also defines some additional operators that handle certain special situations

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:

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, a subset of int.

The basic arithmetic operations—addition, subtraction, multiplication, and division—all behave as you would expect for all numeric types. The unary minus operator negates its single operand. The unary plus operator simply returns the value of its operand. Remember that when the division operator is applied to an integer type, there will be no fractional component attached to the result.

(4)

 The modulus operator, %, returns the remainder of a division operation. It can be applied to floating-point types as well as integer types.

Arithmetic Compound Assignment Operators

Java provides special operators that can be used to combine an arithmetic operation with an assignment.

Operator Description Example

= Simple assignment operator. Assigns values from right side operands to left side operand.

C = A + B will assign value of A + B into C

+= Add AND assignment operator. It adds right operand to the left operand and assign the result to left operand.

C += A is equivalent to C = C + A

-=

Subtract AND assignment operator. It subtracts right operand from the left operand and assign the result to left operand.

C -= A is equivalent to C = C – A

*=

Multiply AND assignment operator. It multiplies right operand with the left operand and assign the result to left operand.

C *= A is equivalent to C = C * A

/= Divide AND assignment operator. It divides left operand with the right operand and assign the result to left operand.

C /= A is equivalent to C = C / A

%= Modulus AND assignment operator. It takes modulus using two operands and assign the result to left operand.

C %= A is equivalent to C = C % A

Increment and Decrement Operators

 The ++ and the – – are Java’s increment and decrement operators

 The increment operator increases its operand by one. The decrement operator decreases its operand by one.

 These operators are unique in that they can appear both in postfix form and prefix form Post-Increment : Value is first used for computing the result and then

incremented.

(5)

Post-decrement : Value is first used for computing the result and then decremented.

Pre-Decrement : Value is decremented first and then result is computed. // Java program to illustrate

// unary operators (++ and --) public class Operators

{

public static void main(String[] args) {

int a = 20, b = 10, c = 0, d = 20, e = 40;

// pre-increment operator // a = a+1 and then c = a; c = ++a;

System.out.println("Value of c (++a) = " + c);

// post increment operator // c=b then b=b+1 c = b++; System.out.println("Value of c (b++) = " + c); // pre-decrement operator // d=d-1 then c=d c = --d; System.out.println("Value of c (--d) = " + c); // post-decrement operator // c=e then e=e-1

c = e--; System.out.println("Value of c (e--) = " + c); } } Output Value of c (++a) = 21 Value of c (b++) = 10 Value of c (--d) = 19 Value of c (e--) = 40

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.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

(6)

a = 0011 1100 b = 0000 1101

 All of the integer types are represented by binary numbers of varying bit widths.  All of the integer types (except char) are signed integers. This means that they can

represent negative values as well as positive ones.

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

The Bitwise Logical Operators

The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation. Assume A stores 60 ( binary: 0011 1100) and B stores 13(binary: 0000 1101)

Operator Description Example

& (bitwise and)

Binary AND Operator copies a bit to the result if it exists in both operands.

(A & B) will give 12 which is 0000 1100

| (bitwise or) Binary OR Operator copies a bit

if it exists in either operand. (A | B) will give 61 which is 0011 1101

^ (bitwise XOR)

Binary XOR Operator copies the bit if it is set in one operand but not both.

(A ^ B) will give 49 which is 0011 0001

~ (bitwise compliment)

Binary Ones Complement Operator is unary and has the effect of 'flipping' bits.

(~A) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.

(7)

// Java program to illustrate // bitwise operators

public class BitwiseOperators {

public static void main(String[] args) { int a = 5; int b = 7; // bitwise and // 0101 & 0111=0101 System.out.println("a&b = " + (a & b)); // bitwise or // 0101 | 0111=0111 System.out.println("a|b = " + (a | b)); // bitwise xor // 0101 ^ 0111=0010 System.out.println("a^b = " + (a ^ b)); // bitwise complement // ~0101=1010 System.out.println("~a = " + ~a); // can also be combined with

// assignment operator to provide shorthand // assignment // a=a&b a &= b; System.out.println("a= " + a); } }

(8)

Output : a&b = 5 a|b = 7 a^b = 2 ~a = -6 a= 5 Shift Operators

 These operators are used to shift the bits of a number left or right. Syntax:

number shift_op number_of_places_to_shift;

The Signed Left Shift operator (<<)

 Signed Left Shift takes two operands. It takes the bit pattern of the first operand and shifts it to the left by the number of places given by the second operand.

 Shifts the bits of the number to the left and fills 0 on voids left as a result.

 For example 5 << 3: What happens in this case?

 Every bit in the binary representation of the integer 5 is shifted by 3 positions to the left. All the places on the left are padded by zeros. That is:

00000000 00000000 00000000 00000101

becomes

00000000 00000000 00000000 00101000

 You can note that the integer result of 5 << 3 is 40.

 That shows that shifting a number by one is equivalent to multiplying it by 2, or more generally left shifting a number by n positions is equivalent to multiplication by 2^n.

(9)

The Signed Right Shift operator (>>)

 Signed right shift moves all the bits by given number of positions to the right. However, it preserves the sign. Positive numbers remain positive and negative ones remain negative.

 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 initial number.

 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, which, in binary, is :

Similar to left shift, the right shift of n positions is equivalent to division by 2^n. Or division by 2^n -1 in case of odd numbers.

The Unsigned Right Shift operator (>>>)

 Unlike the signed shift, the unsigned one does not take sign bits into consideration, it just shifts all the bits to the right and pads the result with zeros from the left. That means that for negative numbers, the result is always positive.

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

 Signed and unsigned right shifts have the same result for positive numbers. // Java program to illustrate

// shift operators

public class BitwiseShiftOperators {

public static void main(String[] args) {

int a = 5; int b = -10;

// left shift operator

// 0000 0101<<2 =0001 0100(20) // similar to 5*(2^2)

System.out.println("a<<2 = " + (a << 2)); // right shift operator

// 0000 0101 >> 2 =0000 0001(1) // similar to 5/(2^2)

(10)

// unsigned right shift operator System.out.println("b>>>2 = " + (b >>> 2)); } } Output : a<<2 = 20 b>>2 = -3 b>>>2 = 1073741821

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.

Operator Description Example

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2 >>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2 &= Bitwise AND assignment operator. C &= 2 is same as C = C & 2 ^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2 |= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

(11)

//Java Program to demonstrate Compound Assignment Operators public class CompoundAssignment {

public static void main(String args[]) { int a = 10;

int b = 20; int c = 0;

c = a + b;

System.out.println("c = a + b = " + c );

//To illustrate Arithmetuc Compound Assignment Operators c += a ; System.out.println("c += a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a ; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c /= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c );

(12)

//To illustrate Bitwise Compound Assignment Operators c <<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c &= a ; System.out.println("c &= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a ; System.out.println("c |= a = " + c ); } } Output: c = a + b = 30 c += a = 40 c -= a = 30 c *= a = 300 c /= a = 1 c %= a = 5 c <<= 2 = 20 c >>= 2 = 5 c >>= 2 = 1 c &= a = 0 c ^= a = 10

(13)

Relational Operators

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

 A relational operator compares two values and determines the relationship between them

The outcome of these operations is a boolean value.

The relational operators are most frequently used in the expressions that control the if statement and the various loop statements.

 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

There are following relational operators supported by Java language.(Assume variable A holds 10 and variable B holds 20)

Operator Description Example

== (equal to) Checks if the values of two operands are equal

or not, if yes then condition becomes true. (A == B) is not true.

!= (not equal to)

Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.

(A != B) is true.

> (greater than)

Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.

(A > B) is not true.

< (less than)

Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.

(A < B) is true.

>= (greater than or equal to)

Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.

(A >= B) is not true.

<= (less than or equal to)

Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

(14)

Boolean Logical Operators

 The Boolean logical operators shown here operate on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value.

 The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and !false == true

Short-Circuit Logical Operators

 Java provides two interesting Boolean operators not found in some other computer languages. These are secondary versions of the Boolean AND and OR operators, and are commonly known as short-circuit logical operators.

 As you know, the OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in false when A is false, no matter what B is.

 If you use the || and && forms, rather than the | and & forms of these operators, Java will not bother to evaluate the right-hand operand when the outcome of the expression can be determined by the left operand alone. This is very useful when the right-hand operand depends on the value of the left one in order to function properly.

 They are used extensively to test for several conditions for making a decision.

Note:

& and | are applicable for integral as well as boolean data types but && and || are applicable for only boolean type.

(15)

The Assignment Operator

The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other computer language. It has this general form:

var = expression;

Here, the type of var must be compatible with the type of expression.

The assignment operator does have one interesting attribute that you may not be familiar with: it allows you to create a chain of assignments. For example, consider this fragment:

int x,y,z;

x=y=z=100;//set x,y and z to 100

This fragment sets the variables x, y, and z to 100 using a single statement. This works because the = is an operator that yields the value of the right-hand expression. Thus, the value of z = 100 is 100, which is then assigned to y, which in turn is assigned to x. Using a “chain of assignment” is an easy way to set a group of variables to a common value.

The Ternary (?) operator

 Java includes a special ternary (three-way) operator that can replace certain types of if then- else statements. This operator is the ?.

 Ternary operator is a shorthand version of if-else statement. It has three operands and hence the name ternary. General format is-

expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated. Both expression2 and expression3 are required to return the same (or compatible) type, which can’t be void.

public class Test {

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

} }

(16)

Output

Value of b 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 .  Precedence and associative rules are used when dealing with hybrid expressions

involving more than one type of operator. In such cases, these rules determine which part of expression to consider first as there can be many different valuations for the same expression.

 For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into 7.

 The operators in the following table are listed according to precedence order. The closer to the top of the table an operator appears, the higher its precedence.

 Operators with higher precedence are evaluated before operators with relatively lower precedence. Operators on the same line have equal precedence.

 When operators of equal precedence appear in the same expression, a rule must govern which is evaluated first. All binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.

(17)

Using Parentheses

Parentheses raise the precedence of the operations that are inside them. This is often necessary to obtain the result you desire. For example, consider the following expression:

a>> b+3

This expression first adds 3 to b and then shifts a right by that result. That is, this expression can be rewritten using redundant parentheses like this:

a>> (b+3)

However, if you want to first shift a right by b positions and then add 3 to that result, you will need to parenthesize the expression like this:

(a>> b)+3

(18)

expression can be difficult to understand. Adding redundant but clarifying parentheses to complex expressions can help prevent confusion later. For example, which of the following expressions is easier to read?

a | 4 + c >> b & 7 (a |(((4 + c) >> b) & 7))

Note: parentheses (redundant or not) do not degrade the performance of your program. Therefore, adding parentheses to reduce ambiguity does not negatively affect your program.

References

Related documents

False text messages, they are mathematical in one condition is true, and learning a true is not be a is too many cases, undeclared variables before type.. But does there any

A) In products sweetened with aspartame, malic acid is used to balance the sweet aftertaste of aspartame and enhance the fruit flavor. This is especially effective in

&gt;= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. a &gt;= b is

The inherited value for Temp is passed to the left operand while that value, incremented by one, is passed to the right operand, since the location T&lt;n+1&gt; is not available for

of the area.. 4 Yannick Bidel et al. a) Picture of the atom gravimeter on the motion simulator. b) Programmed translation on the motion simulator along the three axes. c)

If a student repeats a course, all grades for the course are calculated into the GPA and listed on the academic record; however, only the course earning the first passing grade

If (i) the Final Value of one Index is greater than its Initial Value and the Final Value of the other Index is equal to its Initial Value or is less than its Initial Value by up to

number of if statement is greater than multiple conditions using vlookup will treat text while this excel if statement greater than nesting if.. You could use the below formula as