Programming Principles Operators and Expressions.

Slides:



Advertisements
Similar presentations
Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
IntroductionIntroduction  Computer program: an ordered sequence of statements whose objective is to accomplish a task.  Programming: process of planning.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Data types, operations, and expressions Overview l Primitive Data Types l Variable declaration l Arithmetical Operations l Expressions.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
CS180 Recitation 3. Lecture: Overflow byte b; b = 127; b += 1; System.out.println("b is" + b); b is -128 byte b; b = 128; //will not compile! b went out.
Expressions An expression is a sequence of operands and operators that reduces to a single value expression operator operand An operator is a language-specific.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
JavaScript, Third Edition
1 MATERI PENDUKUNG OPERATOR Matakuliah: M0074/PROGRAMMING II Tahun: 2005 Versi: 1/0.
Chapter 2: Introducing Data Types and Operators.  Know Java’s primitive types  Use literals  Initialize variables  Know the scope rules of variables.
Chapter 4: Operators Department of Computer Science Foundation Year Program Umm Alqura University, Makkah Computer Programming Skills /1436.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
OperatorstMyn1 Operators The sequence in which different operators in an expression are executed is determined by the precedence of the operators. Operators.
CHAPTER:8 OPERATORS AND EXPRESSION IN C++ Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्सजेंड़र ) PGT(CS),KV JHAGRAKHAND.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 3: Data Types and Operators JavaScript - Introductory.
Operators Using Java operators An operator takes one or more arguments and produces a new value. All operators produce a value from their.
Department of Computer Engineering Computer Programming for International Engineers I NTERNATIONAL S CHOOL OF E NGINEERING C HULALONGKORN U NIVERSITY.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
15-Nov-15 All the Operators. operators.ppt 2 Precedence An operator with higher precedence is done earlier (precedes) one with lower precedence A higher.
Java Language Basics By Keywords Keywords of Java are given below – abstract continue for new switch assert *** default goto * package.
COM S 207 Literal, Operator, and Expression Instructor: Ying Cai Department of Computer Science Iowa State University
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Operators in JAVA. Operator An operator is a symbol that operates on one or more arguments to produce a result. Java provides a rich set of operators.
1 Lecture 5 More Programming Constructs Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
Software Technology - I Tools to do operations.....
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Expressions and Order of Operations Operators – There are the standard operators: add, subtract, divide, multiply – Note that * means multiply? (No times.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
 Array ◦ Single & Multi-dimensional  Java Operators ◦ Assignment ◦ Arithmetic ◦ Relational ◦ Logical ◦ Bitwise & other.
August 6, Operators. August 6, Arithmetic Operators.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
CompSci 230 S Programming Techniques
Chapter 2 Basic Computation
Chapter 7: Expressions and Assignment Statements
Lecture 3 Java Operators.
University of Central Florida COP 3330 Object Oriented Programming
Building Java Programs
Selections Java.
University of Central Florida COP 3330 Object Oriented Programming
Chapter 7: Expressions and Assignment Statements
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Primitive Data, Variables, Loops (Maybe)
Type Conversion, Constants, and the String Object
Java Programming: From Problem Analysis to Program Design, 4e
Operators and Expressions
Operators and Expressions
Escape Sequences What if we wanted to print the quote character?
All the Operators 22-Nov-18.
Building Java Programs
C Operators, Operands, Expressions & Statements
Building Java Programs Chapter 2
Expressions and Assignment
Building Java Programs
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Building Java Programs
Building Java Programs Chapter 2
OPERATORS in C Programming
Operator King Saud University
Building Java Programs
OPERATORS in C Programming
Presentation transcript:

Programming Principles Operators and Expressions

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

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;

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

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

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 , the numbers 47 and 3 are operands.

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

Arithmetic Operators OperatorUseDescriptionExample +x + y Adds x and yfloat num = ; // num=25 -x – y Subtracts y from xlong n = – 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

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

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

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.

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:

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.

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

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.

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:

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.

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

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

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

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.

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.

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.

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 = += -= *= /= %= &= ^= |= >= >>>=

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

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.

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.

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 }

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;

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.

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.

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.

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