1 / 19

Variables and Operators

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

Download Presentation

Variables and Operators

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 Variables and Operators

  2. 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 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. This creates a variable called a, sets aside memory for it and writes 5 in that memory location. int a = 5; a Memory myVar int myVar; This creates a variable called myVar, sets aside memory for it but does not put a value in it. Variablenames 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. Variables and Operators

  3. Integer Variables Integer Variables byte - holds values from -128 to +127, takes up 1 byte (8 bits). short - holds values from -32768 to +32767, takes up 2 bytes (16 bits). int - holds values from -2147483648 to +2147483647, takes up 4 bytes (32 bits). long - holds values from -9223372036854775808 to +9223372036854775807, 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. Variables and Operators

  4. Floating Point Variables Floating Point Variables float - holds values from -3.4E38 (-3.4x1038) to +3.4E38 (+3.4x1038), takes up 4 bytes (32 bits). The smallest non zero number is 1.4E-45 (1.4x10-45). Values have approximately 7 digit accuracy. double - holds values from -1.7E308 (-1.7x10308) to +1.7E3-8 (+1.7x10308), takes up 8 bytes (64 bits). The smallest non zero number is 4.9E-324 (4.9x10-324). 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. Variables and Operators

  5. Other Variables 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. Note: Capital S for string (it's an Object not a simple variable) boolean gameOver = false; char key = 'H'; String courseName = "Scientific Application Programming"; Variables and Operators

  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 = 3.141592654; Note: Conventional to capitalise constant names final double PI = 3.141592654; ... ... ... PI = 62.3; This would give an error Variables and Operators

  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. Takes the value of sum, adds one to it and stores the result back in sum. sum = sum + 1; Takes the values of a and b, adds them together and stores the result in total. total = a + b; Operator Variables and Operators

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

  9. Displaying Variables In applets, we use the method drawString from the graphics class to display text on the screen: These give the same result Hello World! 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); 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); Variables and Operators

  10. Example Calculation This example calculates the area of a rectangle: 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); } } Variables and Operators

  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 Variables and Operators

  12. Integer Division If you divide two integers, the answer will be truncated to an integer value - this is usually NOT what you want. Try this: 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); } } Variables and Operators

  13. Integer Division 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); } } 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. Variables and Operators

  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. int i = 2; double x; x = (double)i; Converts (casts) i to a double. This can be used to solve the integer division problem: Converts integer 2 to a double 2.0 before the division. The result is then a double. double d1 = (double)2/3; 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. Variables and Operators

  15. total++; total--; is equivalent to is equivalent to total = total + 1; total = total - 1; 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 Variables and Operators

  16. Prefix and Postfix 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. Increments x before multiplication. 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 y after multiplication. To avoid confusion suggest you stick to postfix and don't use it in expressions. int post = y * 10; y++; Variables and Operators

  17. 30 + 20 = 50 5 x 6 = 30 4 x 5 = 20 int x = 4; int number = ++x * 6 + 4 * 10 /2; Operator Precedence int y = 10; int x = y * 3 + 5; What value is x? 10 x 3 = 30 plus 5 = 35 or 3 + 5 = 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 If you want to change the precedence use brackets ( ). int y = 10; int x = y * (3 + 5); Now gives 80 Variables and Operators

  18. Assignment Operators 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. y = x; In addition there are a set of 'assignment and operator' operators of the form <variable> <operator> = <expression or value> These are equivalent to <variable> = <variable> <operator> <expression or value> x = x + 2; x = x - 2; x = x * 2; x = x / 2; x = x % 2; x += 2; x -= 2; x *= 2; x /= 2; x %= 2; are equivalent to myRatherLongName += 2; myRatherLongName = myRatherLongName + 2; Variables and Operators

  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. Variables and Operators

More Related