920 likes | 930 Views
Learn about mixed type expressions, casting, unary operators, and Java keywords in this informative Java programming session with Professor McLeod. Understand how to handle different types in expressions and execute casting operations. Enhance your skills in initializing variables, using operators, and controlling program flow.
E N D
Last Time • Built “HelloWorld.java” in BlueJ (and Eclipse). • Looked at Java keywords. • Primitive types. • Expressions: Variables, operators, literal values, operator precedence. CISC101 - Prof. McLeod
Today • Lab 1 and Assignment 1 are posted. • A few more things to do with expressions: • Mixed type expressions • Casting – automatic (implicit) and explicit • Unary operators • Other assignment operators • Screen Input/Output. • Variable Scope • Conditional (or “if” statements) – if we have time… CISC101 - Prof. McLeod
Mixed Type Expressions • So far, we have been careful to have expressions where all the types match. • For example: double rectArea = 4.1 * 5.2; • rectArea contains 21.32 • Operators will only work when the values on both sides of the operator are of the same type. CISC101 - Prof. McLeod
Mixed Type Expressions, Cont. • Suppose the expression is: double rectArea = 4 * 5.2; • 4 is an int literal and 5.2 is a double literal. • What do you think will happen? • 4 is changed - “cast” - to be a double literal and the evaluation proceeds. This is called “implicit” casting, and it happens automatically. CISC101 - Prof. McLeod
Mixed Type Expressions, Cont. • What will happen with: double rectArea = 4 * 5; • Both 4 and 5 are int literals. • The * operation results in 20 • The int value 20 is cast to 20.0 and stored in rectArea. CISC101 - Prof. McLeod
Mixed Type Expressions, Cont. • So mixing int literals in expressions with double’s is not a problem, as long as the result is being saved in a double. • int’s will be automatically cast to double’s (an “implicit cast”), this is also called a “widening” cast. • What about: int area = 4 * 5.2; • 4 * 5.2 will evaluate to a double. • Java will not compile this statement. Why not? CISC101 - Prof. McLeod
Mixed Type Expressions, Cont. • Java will refuse to try and store the double (10.4) in a variable of type int. • Information would be lost. • To do this, the code will have to tell Java that it is OK to lose this information - this is called a “narrowing” cast. • Your code has to carry out a “narrowing” cast explicitly, it will not be done automatically: int area = (int)(4 * 5.2); CISC101 - Prof. McLeod
Casting • The code: “(int)” is called a casting operator. • Whatever follows the (int) will be cast to an int value. • Note that casting truncates, it does not round a value. So, (int)10.9 is 10, not 11. • Casting takes precedence over the arithmetic operators. • (The “unary” operators take precedence over casting - but we have not discussed unary operators, yet.) CISC101 - Prof. McLeod
Casting - Cont. • “Implicit” casting is automatic, and will always go in the direction: byte > short > int > long > float > double • Anytime you want to cast in the opposite direction, you must use an “explicit” cast, using the appropriate casting operator. CISC101 - Prof. McLeod
Aside - Integer Arithmetic • Integer arithmetic gets interesting for division. • What is the value in aVal for: int aVal = 5 / 2; • 2 • Not 2.5, which would be a double! • 5 / 2 yields an int, not a double since both 5 and 2 are int literals. CISC101 - Prof. McLeod
Integer Arithmetic, Cont. • What is the value in aVal for: int aVal = 20 / 3; • 6 • Not 7! • Truncates, not rounds! CISC101 - Prof. McLeod
Integer Arithmetic, Cont. • Similarly, what is: int aVal = 1 / 5; • How about: double aNum = 7 / 2; aVal is 0 aNum is 3.0 CISC101 - Prof. McLeod
Unary Operators • Binary operators required values on both sides of the operator: * / - + % < > <= >= == != && || = • Unary operators operate on just one value, or variable: • (casting) • - (negation) • ++ -- (increment and decrement) • ! (logical “NOT”) CISC101 - Prof. McLeod
Unary Arithmetic Operators • Unary operators include “-”, where “-aNum” negates the value produced by aNum, for example. • They also include the increment (++) and decrement (--) operators which increase or decrease an integer value by 1. • Preincrement and predecrement operators appear before a variable. They increment or decrement the value of the variable before it is used in the expression. • Example:int i = 4, j = 2, k;k = ++i - j; // i = 5, j = 2, k = 3 CISC101 - Prof. McLeod
Unary Arithmetic Operators - Cont. • Postincrement and postdecrement operators appear after a variable. They increment or decrement the value of the variable after it is used in the expression. • Example: int i = 4, j = 2, k; k = i++ - j; // i = 5, j = 2, k = 2 • Keep expressions involving increment and decrement operators simple! CISC101 - Prof. McLeod
Unary Logical Operator • The one “unary” logical operator is “!”. • Called the “Not” operator. • It reverses the logical value of a boolean. • For example: !(5 > 3) evaluates tofalse CISC101 - Prof. McLeod
The Other Assignment Operators Syntax:variableName = expression; = set equal to (we’ve seen this one!) *= multiply and set equal to /= divide and set equal to -= subtract and set equal to += add and set equal to CISC101 - Prof. McLeod
Assignment Operators - Cont. • For example, variableName += expression; is equivalent to variableName = variableName + expression; CISC101 - Prof. McLeod
Screen I/O • Your program would not be much use if it could not communicate with the user! • Screen input is your program obtaining information - “values” - from the user. • Screen output is your program sending information to the screen for the user to read. • Screen input in Java is not as simple as screen output. CISC101 - Prof. McLeod
Screen Output • Three methods in the System.out class for Console window output: • println() • print() • printf() (only in Java 5.0) CISC101 - Prof. McLeod
Screen Output – Cont. • (Also called “Text Window”…) • Easy: System.out.print( Stuff_to_Print ); System.out.println( Stuff_to_Print ); • “Stuff_to_Print” can be anything - not just a String - these two methods are heavily overloaded. CISC101 - Prof. McLeod
Screen Output - Cont. • Note that: System.out.print(“\n”); is the same as: System.out.println(); • So, println() appends a carriage return/linefeed character sequence to the end of the output, where print() does not. CISC101 - Prof. McLeod
Screen Output - Cont. • “Escape sequences” can be used to control the appearance of the output: \” a double quote \’ a single quote \\ a backslash \n a linefeed \r a carriage return \t a tab character • These can be embedded anywhere in a String. CISC101 - Prof. McLeod
Screen Output - Cont. • For example the following code: System.out.println("\"Tabbed\" output:\t1\t2\t3\t4"); Prints the following to the screen: "Tabbed" output: 1 2 3 4 CISC101 - Prof. McLeod
printf Method • Which statement provides the most sensible output:? double aNum = 17.0 / 3.0; System.out.println("Using println: " + aNum); System.out.printf("Using printf: %5.2f", aNum); Using println: 5.666666666666667 Using printf: 5.67 CISC101 - Prof. McLeod
printf Method, Cont. • For more information follow the link: “Format String Syntax” in the API listing for the printf method. • Basically use %width.decimalsf for float and double numbers, and %d for int’s. • You can have multiple numbers listed by using multiple format placeholders. CISC101 - Prof. McLeod
Aside - Methods and Classes • I’ve been talking about “methods” and “classes” without really explaining them. • For example, printf() is a method in the System.out class. • Methods cannot exist on their own - they must “belong” to a class. • In order for Java to find the method, you must tell Java the name of the class that “owns” the method. CISC101 - Prof. McLeod
Aside - Methods and Classes - Cont. • Telling the Java compiler who owns the method is done by using the “dot operator” - a fancy name for a period. • The period is used to separate the class name from the method name: • For example: System.out.println() Class name Method name CISC101 - Prof. McLeod
Aside - Methods and Classes - Cont. • (If you are calling a method that exists within the same class as your main method, you do not need a class name or a period. We will see more about this later!) CISC101 - Prof. McLeod
Console Input in Java 5.0 • Use the “Scanner” class. It must be imported using: import java.util.Scanner; • In your program: Scanner console = new Scanner(System.in); CISC101 - Prof. McLeod
Console Input in Java 5.0, Cont. • Then, you can use the Object “console”, as many times as you want calling the appropriate method for whatever primitive type or String you want to get from the user. • For example: System.out.print("Please enter a number: "); double aNum = console.nextDouble(); CISC101 - Prof. McLeod
Exercise • Write a program that accepts a double value from the user and then displays the volume of a cube with sides of the length provided. • Hints: • above public class: import java.util.Scanner; • inside main: • Scanner console = new Scanner(System.in); • prompt the user • Accept the input using console.nextDouble() • Calculate and display the volume. CISC101 - Prof. McLeod
import java.util.Scanner; public class VolumeCalculation { public static void main (String[] args) { double sideLength; double volume; Scanner console = new Scanner(System.in); System.out.print("Enter side length: "); sideLength = console.nextDouble(); volume = sideLength * sideLength * sideLength; System.out.println("Volume is " + volume); } // end main } // end VolumeCalculation CISC101 - Prof. McLeod
Exercise, Cont. • Once your program works OK, try entering something that is not a number, to see what happens. CISC101 - Prof. McLeod
Other Scanner Class Input Methods • Has an input method for each primitive type. (See the API) • Use .nextLine() to get the entire line as a String. CISC101 - Prof. McLeod
Aside – “GUI” • GUI (“Graphical User Interface”) is all about the use of frames, laying out passive and interactive components (text boxes, command buttons, labels, etc.), and then attaching methods to listener events, for user interaction. • This might be fun?… But, we will not get sidetracked in this course into what really is design and not so much programming. • Besides, an application with a nice GUI interface can still be a lousy program if the underlying code does not work well! CISC101 - Prof. McLeod
Aside, GUI – Cont. • For screen output, you can use the JOptionPane class, and invoke the showMessageDialog() method. JOptionPane.showMessageDialog(null, “Volume is " + volume); • The JOptionPane class is part of the javax.swing package, so you must have the following line at the top of your program: import javax.swing.JOptionPane; CISC101 - Prof. McLeod
Aside, GUI – Cont. • Produces the cute little window: CISC101 - Prof. McLeod
GUI Input • Use the showInputDialog() method from the JOptionPane class: String message; message = JOptionPane.showInputDialog("Enter side length:"); • OK, but we have a String and we want a number… CISC101 - Prof. McLeod
GUI Input - Cont. • Use Scanner class again: Scanner getNumber = new Scanner(message); sideLength = getNumber.nextDouble(); • If message does not contain a double number, then an exception will be thrown. CISC101 - Prof. McLeod
GUI Input, Cont. • So, to prevent crashing our program, we need to catch an Exception, specifically a “java.lang.NumberFormatException”. • Once we catch it we need to do something sensible to prevent the problem from crashing the rest of our program. Our program would be more robust! • (Except we do not know how to catch exceptions – yet…) CISC101 - Prof. McLeod
import java.util.Scanner; import javax.swing.JOptionPane; public class VolumeCalculationGUI { public static void main (String[] args) { double sideLength; double volume; String message; message = JOptionPane.showInputDialog("Enter side length:"); Scanner getNumber = new Scanner(message); sideLength = getNumber.nextDouble(); volume = sideLength * sideLength * sideLength; JOptionPane.showMessageDialog(null, "Volume is " + volume); } // end main } // end VolumeCalculationGUI CISC101 - Prof. McLeod
Screen I/O, Summary • For this course, you can user either console I/O or JOptionPane I/O. • Don’t use both in a single program! • For now, assume that the user will supply the type requested. Later you can make more robust programs using exceptions. • We will not spend the time require to learn how to write full GUI programs in this course. CISC101 - Prof. McLeod
Variable Scope • Variables are only “known” within the block in which they are declared. • If a block is inside another block, then a variable declared in the outer block is known to all blocks inside the outer one. • “known” means that outside the block in which they are declared, it is as if the variable does not exist. • For example: CISC101 - Prof. McLeod
public class ScopeTest { public static void main (String[] args) { // block 1 { int aVal = 6; } // block 2 { aVal = 10; } } // end main method } // end ScopeTest CISC101 - Prof. McLeod
Variable Scope – Cont. • Note that both block 1 and block 2 are contained within the main method’s block, which itself is contained within the block for the class definition. • This program will not even compile. • The “aVal = 10;” line will be highlighted and the following error message will be shown: Error: No entity named “aVal” was found in this environment. • Next example: CISC101 - Prof. McLeod
public class ScopeTest { public static void main (String[] args) { int aVal; // block 1 { aVal = 6; } // block 2 { aVal = 10; } } // end main method } // end ScopeTest CISC101 - Prof. McLeod
Variable Scope – Cont. • This program compiles and runs fine. • aVal is declared in the same block that contains block 1 and block 2, so aVal is known inside both blocks. • One more example: CISC101 - Prof. McLeod
public class ScopeTest { public static void main (String[] args) { // block 1 { int aVal = 6; } // block 2 { int aVal = 10; } } // end main method } // end ScopeTest CISC101 - Prof. McLeod
Variable Scope – Cont. • This program compiles and runs fine, but is considered Very Bad Form! • You should never re-declare a variable within a method! • These two variables are completely separate as far as the compiler knows, but any person reading your code will be confused! CISC101 - Prof. McLeod