PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Types and Arithmetic Operators
Types, Variables and Operators Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2013.
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 Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
10-Jun-15 Introduction to Primitives. 2 Overview Today we will discuss: The eight primitive types, especially int and double Declaring the types of variables.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
Review… Yong Choi BPA CSUB. Access Modifier public class HelloWorldApp –More detailes of Java key (reserved) wordJava key (reserved) word –The keyword,
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and 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.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
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.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Chapter 2 Data Types, Declarations, and Displays
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
1 Chapter Two Using Data. 2 Objectives Learn about variable types and how to declare variables Learn how to display variable values Learn about the integral.
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Expressions, Data Conversion, and Input
***** SWTJC STEM ***** Chapter 2-3 cg 29 Java Operators Recall Java’s programming components: Packages - Collection of classes (Programs) Classes - Collections.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
PHY281Variables operators and math functions Slide 1 More On Variables and Operators, And Maths Functions In this section we will learn more about variables.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Java Data Types. Primitive Data Types Java has 8 primitive data types: – char: used to store a single character eg. G – boolean: used to store true or.
Basic Notions Review what is a variable? value? address? memory location? what is an identifier? variable name? keyword? what is a legal identifier? what.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CH2 – Using Data. Constant Something which cannot be changed Data Type Format and size of a data item Intrinsic Data Types Pg. 47 – Table 2-1 Basic ones.
Chapter 2: Using Data.
CPS120: Introduction to Computer Science
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Primitive Variables.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
CPS120: Introduction to Computer Science Operations Lecture 9.
CHAPTER 4 GC 101 Data types. DATA TYPES  For all data, assign a name (identifier) and a data type  Data type tells compiler:  How much memory to allocate.
Operators Precedence - Operators with the highest precedence will be executed first. Page 54 of the book and Appendix B list C's operator precedence. Parenthesis.
Computer Engineering 1 st Semester Dr. Rabie A. Ramadan 3.
Primitive Variables.
Copyright Curt Hill Variables What are they? Why do we need them?
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSM-Java Programming-I Spring,2005 Fundamental Data Types Lesson - 2.
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
1 2. Program Construction in Java. 01 Java basics.
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.
1.  Algorithm: 1. Read in the radius 2. Compute the area using the following formula: area = radius x radius x PI 3. Display the area 2.
Chapter 2 Variables.
Expressions.
Expressions.
BASIC ELEMENTS OF A COMPUTER PROGRAM
2.0 FUNDAMENTALS OF JAVA PROGRAMMING LANGUAGE
Multiple variables can be created in one declaration
Assignment and Arithmetic expressions
Identifiers - symbolic names
Java Programming: From Problem Analysis to Program Design, 4e
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Chapter 2 Edited by JJ Shepherd
Chapter 2: Basic Elements of Java
Chapter 2 Variables.
C Operators, Operands, Expressions & Statements
Expressions and Assignment
Primitive Types and Expressions
Chapter 2 Variables.
Presentation transcript:

PHY-102 SAPVariables and OperatorsSlide 1 Variables and Operators In this section we will learn how about variables in Java and basic operations one can perform on them:  Variables  Constants  Assignment Statements  Arithmetic Operations  Displaying Variables  The pitfalls of Integer Division  Type Conversion  Incrementing and Decrementing  Operator Precedence  Assignment Operators  Other Operators

PHY-102 SAPVariables and OperatorsSlide 2 Variables Variables are names that refer to memory locations where information can be stored. The value of variables can be changed. All variables must be declared before use. int a = 5; This creates a variable called a, sets aside memory for it and writes 5 in that memory location. Variable names have to start with a letter, underscore _ or dollar $. Can have numerals in the name but not at the front i.e. 1a is not allowed but a1 is OK. Variable names are Case Sensitive - myVar and myvar are different variables. Java keywords such as int, class public etc are not allowed as variable names. Memory This creates a variable called myVar, sets aside memory for it but does not put a value in it. int myVar; myVar a

PHY-102 SAPVariables and OperatorsSlide 3 Integer Variables byte - holds values from -128 to +127, takes up 1 byte (8 bits). short - holds values from to , takes up 2 bytes (16 bits). int - holds values from to , takes up 4 bytes (32 bits). long - holds values from to , takes up 8 bytes (64 bits). byte smallerValue; short pageCount; int wordCount; long bigValue; Note: Conventional to start with lower case but to Capitalise any words within the name.

PHY-102 SAPVariables and OperatorsSlide 4 Floating Point Variables float - holds values from -3.4E38 (-3.4x10 38 ) to +3.4E38 (+3.4x10 38 ), takes up 4 bytes (32 bits). The smallest non zero number is  1.4E-45 (  1.4x ). Values have approximately 7 digit accuracy. double - holds values from -1.7E308 (-1.7x ) to +1.7E3-8 (+1.7x ), takes up 8 bytes (64 bits). The smallest non zero number is  4.9E-324 (  4.9x ). Values have approximately 17 digit accuracy. float speedofLight = 2.998E8; double electronMass = 9.109E-31; For scientific applications suggest you stick to int and double.

PHY-102 SAPVariables and OperatorsSlide 5 Other Variables boolean - holds values true or false, takes up 1 bit. char - holds a single character a to z, A to Z, number 0 to 9 or other symbol *, $ / etc, takes up 1 byte (8 bits). String- holds a group of characters, takes as much memory as necessary. boolean gameOver = false; char key = 'H'; String courseName = "Scientific Application Programming"; Note: Capital S for string (it's an Object not a simple variable)

PHY-102 SAPVariables and OperatorsSlide 6 Constants Constants are declared like normal variables but have the keyword final in front to indicate that the value cannot change. final double PI = ; Note: Conventional to capitalise constant names final double PI = ;... PI = 62.3; This would give an error

PHY-102 SAPVariables and OperatorsSlide 7 Assignment Statements The simplest assignment just gives a variable some value. sum = 0; numberofTries = 10; Other assignments consist of a variable name followed by an assignment operator followed by a mathematical expression. sum = sum + 1; total = a + b; Takes the value of sum, adds one to it and stores the result back in sum. Takes the values of a and b, adds them together and stores the result in total. Operator

PHY-102 SAPVariables and OperatorsSlide 8 Arithmetic Operators + Addition total = total + number; - Subtraction * Multiplication / Division % Remainder numberLeft = total - used; cost = items * price; mean = total / number; remainder = 245 % 3; Takes the value of total, adds number to it and stores the result back in total. Takes the value of total, subtracts used from it and stores the result in numberLeft. Takes the value of items, muliplies it by price and stores the result in cost. Takes the value of total, divides by number and stores the result in mean. Be CAREFUL with INTEGERS! Takes 245, divides by 3 and stores the remainder (2) in remainder. Spaces not necessary but makes it easier to read.

PHY-102 SAPVariables and OperatorsSlide 9 Displaying Variables In applets, we use the method drawString from the graphics class to display text on the screen: g.drawString("Hello World!", 50, 50); We can also use the + operator to join two strings together and display them: g.drawString("Hello" + " World!", 50, 50); These give the same result Hello World! If the + operator acts on a string and a number, the number is converted from its binary representation to its character representation and then joined (concatenated) to the string. You can then display the whole thing with drawString: int result = 5; g.drawString("Result = " + result, 50, 50); This can be any string "Result" is not related to your variable result result is converted from 0101 to "5" and joined to "Result = " to give Result = 5 You must have at least one real string otherwise the number will be passed directly as a number to drawString and the compiler will complain. This does not work: g.drawString(result, 50, 50); 

PHY-102 SAPVariables and OperatorsSlide 10 Example Calculation import java.awt.*; import java.applet.Applet; public class Calculation extends Applet { public void paint(Graphics g) { int length;// declarations int breadth; int area; length = 20;// assignments breadth = 10; area = length * breadth; // * means multiply g.drawString("Area is " + area, 100, 100); } This example calculates the area of a rectangle:

PHY-102 SAPVariables and OperatorsSlide 11 Using Expressions Any expression that gives a result can be used where a variable of the same type as the result can be used: int x = 50; int y = 100; g.drawString("Hello World!", 50, 100); g.drawString("Hello World!", x, y); g.drawString("Hello World!", 5*10, 10+90); g.drawString("Hello World!", x, 2*x); These all write Hello World! at the same point on the display

PHY-102 SAPVariables and OperatorsSlide 12 Integer Division If you divide two integers, the answer will be truncated to an integer value - this is usually NOT what you want. import java.awt.*; import java.applet.Applet; public class IntDiv extends Applet { public void paint(Graphics g) { int i = 2/3; double d1 = 2/3; double d2 = 2.0/3.0; g.drawString("i = " + i, 50, 50); g.drawString("d1 = " + d1, 50, 75); g.drawString("d2 = " + d2, 50, 100); } Try this:

PHY-102 SAPVariables and OperatorsSlide 13 import java.awt.*; import java.applet.Applet; public class IntDiv extends Applet { public void paint(Graphics g) { int i = 2/3; double d1 = 2/3; double d2 = 2.0/3.0; g.drawString("i = " + i, 50, 50); g.drawString("d1 = " + d1, 50, 75); g.drawString("d2 = " + d2, 50, 100); } Integer Division Divides 2 by 3 then truncates it to store it as an integer. Since the RHS are both integers does an integer division as before. Then converts the result to a double.

PHY-102 SAPVariables and OperatorsSlide 14 Type Conversion Sometimes you need to convert from one type to another. This is called casting and is done by putting the required type in brackets before the variable. double d1 = (double)2/3; int i = 2; double x; x = (double)i; This can be used to solve the integer division problem: Converts (casts) i to a double. Converts integer 2 to a double 2.0 before the division. The result is then a double. If you do the reverse and cast a double to an integer you truncate it and lose the decimal places. double x = 2.4; int i; i = (int)x; i becomes 2 and the 0.4 is lost.

PHY-102 SAPVariables and OperatorsSlide 15 Incrementing and Decrementing A common task is to increase a number by 1 (incrementing) or decrease it by 1 (decrementing). There are two operators for this: ++ Increment -- Decrement total = total + 1;total++; is equivalent to total = total - 1;total--; is equivalent to

PHY-102 SAPVariables and OperatorsSlide 16 Prefix and Postfix int x = 3; int y = 3; int pre = ++x * 10; int post = y++ * 10; g.drawString("pre = " + pre + " x = " + x, 50, 50); g.drawString("post = " + post + " y = " + y, 50, 75); pre = 40 x = 4 post = 30 y = 4 Increments x before multiplication. Increments y after multiplication. To avoid confusion suggest you stick to postfix and don't use it in expressions. int post = y * 10; y++; If the ++ or -- comes after the variable (postfixed) the number is updated after any calculation. If they come before the variable (prefixed) the number is updated before the calculation.

PHY-102 SAPVariables and OperatorsSlide 17 Operator Precedence int y = 10; int x = y * 3 + 5; 10 x 3 = 30 plus 5 = 35 or = 8 x 10 = 80? Answer 35. The following order (precedence) is used:  Incrementing and Decrementing first then  Multiplication, Division and Remainder then  Addition and Subtraction then  The equals sign to set a value. Operators with equal precedence are evaluated left to right int x = 4; int number = ++x * * 10 /2; 5 x 6 = = 50 4 x 5 = 20 If you want to change the precedence use brackets ( ). int y = 10; int x = y * (3 + 5); Now gives 80 What value is x?

PHY-102 SAPVariables and OperatorsSlide 18 Assignment Operators In addition there are a set of 'assignment and operator' operators of the form = These are equivalent to = y = x; The simple assignment operator = sets the variable on the left of the = sign to the value of the variable or expression on the right of the = sign. x += 2; x -= 2; x *= 2; x /= 2; x %= 2; are equivalent to x = x + 2; x = x - 2; x = x * 2; x = x / 2; x = x % 2; myRatherLongName += 2;myRatherLongName = myRatherLongName + 2;

PHY-102 SAPVariables and OperatorsSlide 19 Other Operators In addition there are: Comparison Operators - used to compare variables or objects < less than <= less than or equal to > greater than >= greater or equal to == equal to != not equal to Logical Operators - used to perform logical operations && AND || OR Bitwise Operators - used to perform binary operations. We shall use some of these when we make decisions later on.