300 likes | 446 Views
Variables & Datatypes. Java (like virtually all programming languages) supports the concept of variables. You probably are familiar with the concept of variables from algebra, such as x = 3
E N D
Variables & Datatypes SE-1010Dr. Mark L. Hornick
Java (like virtually all programming languages) supports the concept of variables • You probably are familiar with the concept of variables from algebra, such as x = 3 Where the variable x in this case represents the integer 3 (initially), but can be reassigned to represent another value at any time. SE Focus Dr. Mark L. Hornick
Brainstorm • v = 3.14 • w = 1/3 • u = 1 • c = sin(w) + cos(z) • y2 = -1 • z = 1 + y Suppose these are algebraic equalities. What type of numbers do the variables represent? SE Focus Dr. Mark L. Hornick
Variables in Java are a similar concept, but different If we want to use a variable x to represent an integer value of 3, we write int x = 3; In Java, we have to declare the datatype (i.e. the kind of value) that the variable will represent. In this case, “int” means that x can represent only integer values[of a specific range]. We say that x is the identifier (i.e. the name) of the variable Note the semicolon; This is required in Java! SE Focus Dr. Mark L. Hornick
In Java, we can arbitrarily make up [nearly] any name we like to use as a variable identifier, provided we follow a few rules: • An identifier may consist of a sequence of one or more letters, digits, underscores, and dollar signs ( e.g. my_1st_$ ) • The first character in a Java identifier is generally a letter, rarely an underscore or dollar sign, and may not be a digit: • x_1 (ok) • $y2 (ok, but unconventional) • _z3 (ok, but unconventional) • 1w (illegal) • Uppercase and lowercase letters are distinguished; the following are treated as 3 different identifiers: • myValue • Myvalue • MyValue • No spaces are allowed in an identifier. • A Java Reserved Word may not be used as an identifier. SE FocusDr. Mark L. Hornick
Java’s reserved words cannot be used as identifiers abstract default if private this boolean do implements protected throw break double import public throws byte else instanceof return transient case extends int short try catch final interface static void char finally long strictfp volatile class float native super while const for new switch continue goto package synchronized SE FocusDr. Mark L. Hornick
Java supports various “built-in” primitivedatatypes There are six numericdatatypes in Java: • byte • short • int • long • float • double byte, short, int, andlong represent integer values floatanddoublerepresent real values
Numeric values have a limited range of allowed values Why do you think there are four differentdatatypes just to represent integer values? SE-1010Dr. Mark L. Hornick
There are generally accepted rules for naming Java variables that will represent primitivedatatypes Use a lowercase letter for the first letter of a variable identifier, uppercase for subsequent words Use nouns or noun phrases to represent things that have values • x • areaCircle • sumOfValues Identifiers that begin with uppercase letters (or are all uppercase letters) areused for other Java elements we’ll see later on… Good variable names convey a logical meaning asto the type of data the variables represent. SE-1010Dr. Mark L. Hornick
Don’t use verbs, adverbs, adjectives or meaningless names for variable identifiers • getIt • Quickly • happy • FredFlintstone • iDontLikeBeets Names like these don’t convey any meaning to the reader of a program. SE-1010Dr. Mark L. Hornick
In Java, a variablecan be also represent many non-primitive datatypes… String s; This declares a variables of datatypeString. String is another predefined, non-primitive Java datatype. What kind of values can be held by this type of variable??? SE 1011Dr. Mark L. Hornick
The Stringdatatype is a built-in class (from the java.lang package) that represents a sequence of characters String s1 = “a”; String s2 =“SE-1011”; String s3 =“123”; String s4 =“This is a 6 word string.”; String s5 = “”; There is no fundamental restriction on the maximum length of a Java String String sequences are surrounded by double-quotes How does this differ from a int that represents 123? This represents an emptyString SE-1010Dr. Mark L. Hornick
The char primitive datatype represents only a single character char c1 =‘1’; char c2 =‘a’; char c3 =‘?’; char c4 =‘B’; char c5 =‘%’; How does this differ from a int that represents 1? Characters are surrounded by single-quotes SE-1010Dr. Mark L. Hornick
Use escape sequences to represent special characters char c1 = ‘\t’; // tab char c2 =‘\n’; // newline char c3 =‘\r’; // carriage return char c4 =‘\”’; // double-quote char c5 =‘\’’; // single quote char c5 =‘\\’; // backslash Escape sequences are two-characters consisting of the backslashfollowed by an escape code SE-1010Dr. Mark L. Hornick
Escape sequences can be used in Strings too String hello = “Hello \nWorld”; System.out.println( hello ); NOTE: PowerPoint uses distinct single- and double-quote characters that do not appear on your keyboard! SE-1010Dr. Mark L. Hornick
The booleandatatype represents only two logical values: true and false • booleanisOff= true; • booleanisCold = false; true and false are both Java reserved words The booleandatatype is named after George Boole, an English mathematician/logician who developed Boolean algebra SE-1010Dr. Mark L. Hornick
Repeat: You must declare a variable’s datatype in Java before you can use that variable • int x; • Stringname; • char c1; • booleanisDone; • floatsomeValue; • doubleareaCircle; x, name, c1, isDone, someValue, and areaCircleare all identifiers that represent only specific types of data. So, you cannot assign a numeric value to name, nor can you assign a character string value to x. SE-1010Dr. Mark L. Hornick
Variables can be initialized at the same time as they are declared • int x = 0; • Stringname = “Mark”; • char c1 = ‘a’; • booleanisDone= false; • floatsomeValue = 3.14F; • doubleareaCircle = 2.6; The value of a variable can be reassigned at any time, even when it’s initialized. SE-1010Dr. Mark L. Hornick
A constant is a value that cannot be changed after initialization • final int ZERO = 0; • final StringYES = “Yeah”; • final char QUESTION = ‘?’; • final boolean OFF = false; • final float E = 2.17F; • final doublePI= 3.1416; The value of a constant must be assigned at initialization, and cannot be reassigned afterwards. SE-1010Dr. Mark L. Hornick
Arithmetic operators in Java areused on numeric datatypes (byte, short, int, long, float, and double) SE-1010Dr. Mark L. Hornick
Examples of arithmetic expressions and assignment using the binary arithmetic operators*, +, -, / and% int x = 1; int y = x+1; x = x+3-y; int z = x*y*2; z = (x+y)*2+4; // note use of () int w = 4/2+5-3; w = 5 % 2; SE-1010Dr. Mark L. Hornick
Increment and Decrement arithmetic operators • The ++ and -- unary operators are used to increment or decrement the value of a variable by 1. • x++; // increments x by 1 • ++x; // ditto • --x; // decrements x by 1 • x--; // ditto SE-1010Dr. Mark L. Hornick
Arithmetic Expressions Precedence rules for arithmetic operators and parentheses SE-1010Dr. Mark L. Hornick
Integer Overflow • The range of an int is -32768 to +32767 • So what happens when you add 1 to an int holding a value of 32767?? SE-1010Dr. Mark L. Hornick
Integer Division • Integers variables can only hold whole values, so what happens if you do the following? int x = 2; int y = 3; int z = x/y; // what is the result? SE-1010Dr. Mark L. Hornick
Variable values can be assigned (and re-assigned) as the result of various operations int radius = 3; floatareaCircle = radius * 3.14159; radius = 4; areaCircle = radius * 3.14159; Declaration and assignment of radius Declaration and assignment of areaCircle Reassignment of previously declared radius Reassignment of previously-declared areaCircle SE-1010Dr. Mark L. Hornick
Q: Would it make sense to declare areaCircleto be an int? int radius = 3; intareaCircle = radius * 3.14159; radius = 4; areaCircle = radius * 3.14159; Declaration and assignment of radius Declaration and assignment of areaCircle Reassignment of previously declared radius Reassignment of previously-declared areaCircle SE-1010Dr. Mark L. Hornick
Details: Primitive variables vs. non-primitive (object) variables The only difference between a variable for a primitive and a variable for objects is the contents in the memory locations. For primitives, a variable contains the numerical value itself. For objects (like Strings), a variable contains an address where the object is stored. str1 <Memory address of String object> x 10 Stringobject SE-1010Dr. Mark L. Hornick
Can we use arithmetic operators (like + or -) on object variables? String s1 = “se”; String s2 = “1011”; String output = s1 + s2; // does this work?? SE-1010Dr. Mark L. Hornick
The only operator defined by Java for a String variable is “+” The “+” operator, when used to “add” Strings, actually causes the Strings to be concatenated String s1 = “se”; String s2 = “1010”; String output = s1 + s2; // output is “se1010” The only operator defined by Java for an object variable is “+”, and it only works on String objects SE-1010Dr. Mark L. Hornick