Download presentation
Presentation is loading. Please wait.
Published byPearl Laura Richard Modified over 8 years ago
1
Programming Principles Operators and Expressions
2
Assignment Operator Assigning a value to a variable seems straightforward enough; you simply assign the stuff on the right side of the ‘ = ‘ to the variable on the left. Below statement 1 assigning value 10 to variable x and statement 2 is creating String object called name and assigning value “Amir” to it. Statement 1: x = 10; Statement 2: String name = new String(“Amir”);
3
Compound Assignment Operators Some time we need to modify same variable value and reassigned it to same reference variable. Java allows you to combine assignment and addition operators using a shorthand operator. For example, the preceding statement can be written as: - i += 8;
4
Compound Assignment Operators OperatorNameExampleEquivalent += Addition assignment i+=5;i=i+5 -= Subtraction assignment j-=10;j=j-10; *= Multiplication assignment k*=2;k=k*2; /= Division assignment x/=10;x=x/10; %= Remainder assignment a%=4;a=a%4
5
package operatorsdemo; public class AssignmentOperatorDemo { public static void main(String[] args) { //Literal Primitive Assignment byte b = 25; System.out.println(“Primitive byte Assignment- ”+ b); //Assigning one primitive to another primitive byte c =b; System.out.println(“Primitive byte Assignment from another byte variable- ” + c); //Literal assignment based on arithmetic operation int a = 23+b; System.out.println(“Primitive int Assignment from arithmetic operation- ”+ a); //Implicit Casting of variable x and y short s = 45; int x = b; int y = s; System.out.println(“Implicit Casting of byte to int- ”+ x); System.out.println(“Implicit Casting of short to int- ”+ y); //Short-Hand Assignment Operators int i = 10; i+=10; System.out.println(“Addition Operator- ”+ i); i-=10; System.out.println(“Subtraction Operator- ”+ i); i*=10; System.out.println(“Multiplication Operator- ” + i); i/=10; System.out.println(“Division Operator- ” + i); i/=10; i%=3; System.out.println(“Remainder Operator- ” + i); }
6
Arithmetic Operators We can use arithmetic operators to perform calculations with values in programs. Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. A value used on either side of an operator is called an operand. For example, in below statement the expression 47 + 3, the numbers 47 and 3 are operands.
7
Arithmetic Operators The arithmetic operators are examples of binary operators because they require two operands. 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. int a = 47 + 3;
8
Arithmetic Operators OperatorUseDescriptionExample +x + y Adds x and yfloat num = 23.4 + 1.6; // num=25 -x – y Subtracts y from xlong n = 12.456 – 2.456; //n=10 -x Arithmetically negates xint i = 10; -i; // i = -10 *x * y Multiplies x by y int m = 10*2; // m=20; /x / y Divides x by yfloat div = 20/100 ; // div = 0.2 %x % y Computes the remainder of dividing x and yint rm = 20/3; // rm = 2
9
package operatorsdemo; public class ArithmeticOperatorDemo { //Demonstrate the basic arithmetic operators. public static void main(String args[]) { // arithmetic using integers System.out.println(“Integer Arithmetic”); int i = 1 + 1; int n = i * 3; int m = n / 4; int p = m – i; int q = -p; System.out.println(“i = “ + i); System.out.println(“n = “ + n); System.out.println(“m = “ + m); System.out.println(“p = “ + p); System.out.println(“q = “ + q);
10
// arithmetic using doubles System.out.println(“\nFloating Point Arithmetic”); double a = 1 + 1; double b = a * 3; double c = b / 4; double d = c – a; double e = -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); }
11
Relational Operators The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here: The outcome of these operations is a boolean value.
12
Relational Operators The relational operators are most frequently used in the expressions that control the if statement and the various loop statements. The following are relational operators supported by Java language. Assume A holds 10 and variable B holds 20. Then:
13
Relational Operators OperatorDescriptionExample == Checks if the values of two operands are equal or not, if yes then condition becomes true. (A == B) is not true. != Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (A != B) is true. > 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. < 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. >= 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. <= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (A <= B) is true.
14
public class Test { public static void main(String args[]) { int a = 10; int b = 20; System.out.println(“a == b = “ + (a == b) ); System.out.println(“a != b = “ + (a != b) ); System.out.println(“a > b = “ + (a > b) ); System.out.println(“a < b = “ + (a < b) ); System.out.println(“b >= a = “ + (b >= a) ); System.out.println(“b <= a = “ + (b <= a) ); }
15
Logical Operators A logical operator (sometimes called a “Boolean operator”) in Java programming is an operator that returns a Boolean result that’s based on the Boolean result of one or two other expressions.
16
Logical Operators Sometimes, expressions that use logical operators are called “compound expressions” because the effect of the logical operators is to let you combine two or more condition tests into a single expression. The following table lists the logical operators: Assume Boolean variables A holds true and variable B holds false, then:
17
Logical Operators OperatorDescriptionExample && Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (A && B) is false. || Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (A || B) is true. ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.
18
public class Test { public static void main(String args[]) { boolean a = true; boolean b = false; System.out.println(“a && b = “ + (a&&b)); System.out.println(“a || b = “ + (a||b) ); System.out.println(“!(a && b) = “ + !(a && b)); }
19
The Conditional Operator Conditional operator is also known as 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
20
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 ); }
21
Operator Precedence Now that you’ve learned how to declare and initialize variables, you probably want to know how to do something with them. Learning the operators of the Java programming language is a good place to start. Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result.
22
Operator Precedence As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence. 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.
23
Operator 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.
24
Operator Precedence OperatorsPrecedence Postfix expr++, expr-- Unary ++expr -- expr +expr – expr ~ ! Multiplicative * / % Additive + - Shift > >>> Relational = instanceof Equality == != bitwise AND & bitwise exclusive OR ^ bitwise inclusive OR | logical AND && logical OR || Ternary ? : Assignment = += -= *= /= %= &= ^= |= >= >>>=
25
public static void main(String[] args) { int a = 1; int x = ++a + a++; System.out.print(x); // Prints 4 } int a = 1; int b = 3; int c = 5; int x = a + b * c; System.out.println(x);
26
Implicit Type Conversions Conversion between data types can be done in two ways by casting: –Implicit casting doesn’t require a casting operator. This casting is normally used when converting data from smaller integral types to larger or derived types to the base type. int x = 123; double y = x; –In the above statement, the conversion of data from int to double is done implicitly, in other words programmer don’t need to specify any type operators.
27
Implicit Type Conversions –Explicit casting requires a casting operator. –This casting is normally used when converting a double to int or a base type to a derived type. double y = 123; int x = (int)y; –In the above statement, we have to specify the type operator (int) when converting from double to int else the compiler will throw an error. –You can learn more about casting here.
28
public class Demo { public static void main(String args[]) { char ch1 = ‘A’; double d1 = ch1; System.out.println(d1); // prints 65.0 System.out.println(ch1 * ch1); // prints 4225, 65 * 65 double d2 = 66.0; char ch2 = (char) d2; System.out.println(ch2); // prints B }
29
The Cast Operator Type cast – To assign a value of one primitive numeric type a more narrow type, e.g. long to int, an explicit cast operation is required, e.g. long a = 5; int b = (int)a;
30
Expressions Regular expression is used to perform many string related operations. This is the way to manipulate different kind of operations like search, edit and manipulating string can be performed by the regular expression. It has both type characters (literal characters and meta characters). In this section, you will learn how to search a string from the given string exactly.
31
Expressions Program Result: –Following program gives you the search facility in which it takes two string/text. –One is searched in another one text or string and tells you for the occurrence of the given string for searching into a long string. –If the string does not lies in the given string from which the string has to be searched.
32
Expressions Pattern: –This is the class of the java.util.regex package which is the compiled representation. –Specified string is first compiled into an instance of this class. –The pattern to be used to create a matcher object which finds the character sequences for the regular expression. Matcher: –This is also a class of java.util.regex package which is used to match character sequence.
33
import java.util.regex.*; import java.io.*; public class SearchProgram{ public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print(“Enter string in which we have to search: ”); String string = in.readLine(); System.out.print(“Enter string to search: ”); String str = in.readLine(); Pattern pattern = Pattern.compile(str); Matcher matcher = pattern.matcher(string); int a = 0; while(matcher.find()){ a = a + 1; } if(a == 0) System.out.println(“Word not found.”); else System.out.println(“Occurrence of the word is: ” + a); }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.