460 likes | 685 Views
Chapter 2- Variables and Expressions. Overview. Comments Variables Expressions and operators Strings Keyboard and Screen I/O Documentation. Comments. Why comments?.
E N D
Overview • Comments • Variables • Expressions and operators • Strings • Keyboard and Screen I/O • Documentation
Why comments? • We use comments when we want to put something in the program to help a human understand what they are reading, but we don’t need the computer to read the information. • Use comments whenever you think an area of code might need some extra explanation as to what it does, or what it is for. • They are also useful at the beginning of programs to identify the programmer and the function of the program.
2 kinds of comments • Single line comments - // • used to cause the computer to ignore everything from // to the end of the line. • Multiple line comments- /* some stuff */ • Computer will ignore everything between the /* and the */ marks, even if on separate lines. Good way of temporarily removing code from your program when trying to find errors.
Comment examples. /* Eric Davis Some commented program Still in the multiple line comment. */ public class commentProgram { public static void main(String [] args) { System.out.println(“Hi”); // print Hi. //another single line comment. } }
Comment guidelines • In TextPad, comments will usually be a different color than the rest of your code (green). • Use comments to explain what you are doing to anyone else that might have reason to read your code. • When in doubt, comment.
What are variables? • Variables are like storage boxes. They have a name written on the outside, and they have some space to store stuff. • In programming, these variables hold different kinds of data like numbers, characters, and truth values (true/false). • Every variable has a name, a type, and a value.
Variable names • Names can’t start with a digit, and can contain only letters, digits, and underscores. • It is a bad idea to have single-letter or short variable names. Try to give your variables useful descriptive names. • First word usually starts out lower-case, the beginning of every subsequent word is capitalized. • Good names • userInputChar1 • numberOfApples • totalDollars • Bad Names • 1userInput (invalid) • x • st
Variable types • The variables type determines what kind of data a variable can store. We will talk about 8 primitive types and one class type. • There are 4 integer types: byte, short, int, and long. int is the usual type for integers. • There are 2 decimal types: float and double. double is the usual type for decimal numbers. • There is 1 type for a single character, char. • There is 1 type for a true/false value, boolean. • There is 1 class type for holding sequences (or sentences) of characters, String.
Declaring variables • Before a variable is used, it must be declared, or given a name and type. • Write the type of variable first, followed by the names of one or more variables that you want to have that type. Type variableName1, variableName2,… ; int numberOfApples, numberOfStudents; char myGrade; double accountBalance,
Variable values • Once a variable has been declared, we can assign it a value. • We can only assign a value to a variable if the types match (or if a simple conversion exists). int numberOfStudents, numberOfApples; double accountBalance; numberOfStudents = 45; //the 45 is called a constant numberOfApples = 12; accountBalance = 12; //conversion accountBalance = 13.45;
Variable shortcut • We can do the process of declaring a variable and assigning it a value even quicker, in a single line: int numberOfApples = 45, numberOfStudents=15; This is equivalent to the following 3 lines: int numberOfApples, numberOfStudents; numberOfApples = 45; numberOfStudents = 15;
Converting variables • You can sometimes assign the value of one type of variable to another type of variable, if an automatic conversion will occur. • These automatic conversions occur from numeric data types that have less information to those that have more. Thus we can assign an integer value to a double variable, but not the other way around. • byte->short->int->long->float->double. Valid Not Valid int aNum = 1; long bNum = aNum; float cNum = bNum; double dNum = cNum; int aNum = 1.0; long bNum = 2.0; aNum = bNum;
Casting variables • When we want to copy the data from one type of variable to another, and no automatic conversion is possible, we can use something called casting. • To cast a variable to a new type, merely put the name of the type inside parentheses in front of the variable or constant you want to cast. Java will force the conversion for you (might cause some data loss). int aNum = (int) 2.5; //stores 2 as an int long bNum = (long)3.2; //stores 3 as a long aNum = (int)bNum; //now both hold 3, one //as an int, the other as a long
Expressions • Expressions are combinations of variables, constants, operators and other expressions that get evaluated. • Examples 2 + 4; //evaluates to 6. numberOfApples * 3; 2 + (6*4); 15; numberOfStudents/(numberOfApples *3 + 2);
Expressions and variables • Whenever a variable is being assigned a value, it is always an expression that is on the right side of the assignment statement. • The expression first gets evaluated, and it’s value is assigned to the variable. numberOfApples = numberOfStudents *3;
Expressions and operators • To create anything more than trivial expressions, we use operators to combine expressions, making them larger and more complex. • We have lots of operators available in Java: Math operators (*, +, etc.), Comparison operators (>=, ==, <), boolean operators (! (not)), and more.
Math operators • +, -, *, /, % • These operate much like they do in math. They are binary operators (they have two operands or arguments), so you have to have a constant, variable, or expression on either side of each. They return a number value. • +, -, * work like usual. They add, subtract, and multiply two operands. • / and % are a little different.
/ Division operator • The division symbol can do two types of division, integer division and floating division (real division). • If both arguments to the division sign are integers, then integer division is performed and no remainder is returned from the calculation (examples on next slide). • If one or more of the arguments are float or double types, then real division is performed like usual.
Integer division examples. int numApples = 45; int numStudents = 15; numApples/numStudents //3 numApples/(numStudents+1) //2 numApples/8 //5 //BOTH sides must be integer values! 4/2 //2 5/2 //2 10/3 //9 20/5 //4 21/5 //4 22/5 //4 23/5 //4 24/5 //4 25/5 //5
Real division examples 4/2.0 //2.0 5/2.0 //2.5 10.0/3.0 //9.333 20.0/5 //4.0 21/5.0 //4.2 22.0/5.0 //4.4 23.0/5 //4.6 24/5.0 //4.8 25/5.0 //5.0 int numApples = 45; double numStudents = 15.0; numApples/numStudents //3.0 numApples/(numStudents+1) //2.8125 numApples/8 //5 numApples/8.0 //5.625 (double)numApples/8 //5.625 Either side of the division must be a float or double value.
% Modulo operator • One might begin to wonder how you get the remainder from integer division. You get it from the modulo operator (%). • Examples: 4%2 //0 5%2 //1 10%3 //1 20%5 //0 21%5 //1 22%5 //2 23%5 //3 24%5 //4 25%5 //0
Comparison operators • ==(equals), >=(grtr than or equals), >, <=, <, !=(not equals) • Compares its two operands according to the operator. If the result is true, it returns the boolean value “true”, else it returns false. • Remember “equals” has 2 equal signs! int aNum = 5; double bNum = 10; boolean truth=aNum>bNum; //False bNum >= aNum //True 5==4 //False 5!=4 //True 5>=4 //True 5<=4 //False
Shortcut operators • There are two kinds of shortcut operators: modified assignment operators, and increment/decrement operators. • They aren’t necessary, but they are useful, and you should be able to understand them when you see them.
Modified assignment operators • Often we just need to change the value of a variable by some amount • The modified assignment operators exist for all of the math operators. aNum = aNum + 5; bNum = bNum -10; cNum = cNum *2; dNum = dNum / 3; fNum = fNum %12; aNum += 5; bNum -= 10; cNum *= 2; dNum /= 3; fNum %= 12;
Increment/Decrement operators • We need to add/subtract 1 from numbers so often, they made a shortcut for each of the operations. • ++ is the increment operator, put it before or after a variable to increase its value by 1. • -- is the decrement operator. Use just like the increment operator. int aNum = 3; aNum++; //now 4 ++aNum; //now 5 --aNum; //now 4 aNum--; //now 3
Before vs. After Increment/Decrement operators • If you put the increment operator before the variable, then it will increment the variable before returning the value of the variable. • If you put the increment operator after the variable, then the computer will first return the current value of the variable before incrementing. int aNum = 3; int bNum = aNum++; //bNum is 3, aNum is now 4. aNum = 3; bNum = ++aNum; //bNum and aNum are 4.
Precedence/Order of evaluations. • Just like in math, there is an order in which we evaluate expressions. • 3+4*5-8/4 • Parentheses override all natural precedence for the operators, so use parentheses when in doubt. • A table of the precedence of all operators in Java is in Appendix 2 (page 991).
Strings are different… • Strings are not like the primitive types. They are objects created from a class (Object-oriented). • Strings are long sequences or sentences of characters. • Whenever we include something in quotation marks (“ ,”), Java considers it a String. • We usually always are printing out Strings with the System.out.println command.
String Constants and Variables • We can store any String constant into a String variable. • We can then print out these variables to print out the string stored in them. String Hello = “Howdy there!”; System.out.println(Hello); //prints “Howdy there!” to the screen.
String concatenation • Concatenation is the act of gluing the beginning of one String onto the end of another. • We can concatenate a String, variable, or object onto the end of any String by using the “+” symbol. String Hello = “Howdy”; Hello = Hello + “ there”; //stores “Howdy there” int aNum = 6; Hello = “The number is: “ + aNum; //stores the string “The number is: 6”. System.out.println(“I see “ + 5 + “ birds”); //prints out “I see 5 birds” to the screen.
Comparing strings • Since Strings are objects, we do not compare them in the same way that we compare regular variables. • To compare two Strings we will have to use a method called “equals.” • To use methods we follow the calling object (the first object we want to perform an action on, in this case a comparison) with a dot and the method name String aString = “Howdy There.”; aString.equals(“Howdy”); //returns false aString.equals(“Howdy There.”); //returns true String bString = “Hello”; bString.equals(aString); //returns false
Other String methods • length()- returns the length of the String • equalsIgnoreCase(AnotherString) – returns true if the strings are equals without regards to the case of either. • charAt(integer) – returns the character located at the number indicated, given that the String starts at location 0. • A full collection of String methods can be found in the book on pages 82-84 or on the web at www.java.sun.com
Escape characters • To include certain characters in a String, we have to use an escape sequence. • Placing the escape sequence inside of a String constant will cause the special character to show up when the String is printed out. \” Double Quote \’ Single Quote \\ Backslash \n New line \r Carriage return \t Tab “Hello \t There” prints out as Hello There “Hello \n There” Hello There
Screen Output • System.out.println(someString) will output the String someString to the screen on its own line. It puts a new line character at the end of the String. • System.out.print(someString) will output the String someString to the screen. No new line character will be added. System.out.print(“Hello ”); System.out.println(“There”); System.out.println(“Fred”); Hello There Fred
Keyboard input. • Console input from a keyboard is a little difficult in Java. • Dr. Savitch created his own input class to make things much, much easier on the beginning student. It is called SavitchIn.java. • SavitchIn is not a part of standard Java, and you won’t see it used outside of this class. We will see more on how to read input the hard way in Chapters 9 and 12.
SavitchIn methods. • SavitchIn.readLineInt(); • SavitchIn.readLineLong(); • SavitchIn.readLineFloat(); • SavitchIn.readLineDouble(); • SavitchIn.readLineNonwhiteChar(); • SavitchIn.readLine();
Self-documenting code • You should write your code in such a manner that it almost documents itself. • This means good variable name choice, good tabbing/indenting, and not being afraid to use some whitespace (spaces/empty lines, etc.)
Comment like crazy. • Remember: though your code may be obvious to you, it probably isn’t to someone else. • Comment whenever something may be misunderstood or confusing to someone else.
Review • Comments • Variables • Expressions and operators • Strings • Keyboard and Screen I/O • Documentation