Lecture Three - Operators
IDEs The String variable Read Chapter 2, Square Two program p. 36-38 of Chapter 3 Operators program Logical operators Comparison operators Increment/Decrement operators ShowOdd program If statement Drill
1
IDEs
Currently we have been writing programs in simple text editors (like Notepad or Wordpad) and compiling them in a command window Because this can be a pain, IDEs (integrated development environments) were created to ease the process of writing code There are many Java IDEs out there (some free), but for the purposes of this class we will continue to assume we are compiling through the command line However, if you wish to use your favorite IDE for this class feel free!
2
IDEs (continued)
Benefits:
speeds development eliminates the need to run commands in the command window syntax highlighting for easier readability of code built in debuggers (tools that help programmers find errors in program code)
Draw backs
May cost to buy them (JPadPro after 30days) May be difficult to learn (JBuilder)
3
IDEs (continued)
Here is a list of some popular Java IDEs
Borland JBuilder (http://www.borland.com/jbuilder) JCreator (http://www.jcreator.com) JPadPro (http://www.modelworks.com) Eclipse (http://www.eclipse.org) NetBeans (http://www.netbeans.org)
A teacher we know is preparing some information on JCreator (a common favorite that has a totally free version) – We’ll post it soon.
4
The String variable
We have already talked about the primitive (built in) variables in Java – char, int, double, boolean, etc. – which are typically denoted by lowercase letters String is a class (more on this later) in the Java API that can be used as a variable, similar to the primitive types. Note that classes begin with a capital letter (String) while primitive types begin with a lower case letter (int) A String is defined as a sequence characters (denoted in double quotes “”)
5
The String variable (continued)
Important things to remember about Strings:
Even if a String contains a numerical value like “254” this does mean you are able to treat it as a number. Remember this simply means the String contains the character ‘2’, the character ‘5’, and the character ‘4’ They can be concatenated with the ‘+’ symbol
Example:
String first = “John”; String last = “Doe”; String name = first + “ ” + last; // name is “John Doe”
6
The String variable (continued)
Pop Quiz! Suppose we have the following code segment:
String a = “34”; String b = “11”; String result = a + b; System.out.println(result);
Question: What is the output?
7
The String variable (continued)
Pop Quiz! Suppose we have the following code segment:
String a = “34”; String b = “11”; String result = a + b; System.out.println(result);
Question: What is the output? Answer: 3411 (not 45)
8
Square Two
We will now revisit our Square program from Lesson 2 This time, however, we will use JOptionPane to get input from the user and to output our results The next slide contains the code for our updated Square program
9
Square Two – The code
// Square 2 import javax.swing.JOptionPane; public class Square2 { public static void main (String args[]) { double side; // length of a side of a square double perimeter; // variable to hold perimeter double area; // variable to hold area String input; // variable to hold input // input input = JOptionPane.showInputDialog(null, “Please enter a side length”, “Input Side”, JOptionPane.QUESTION_MESSAGE); // process side = Double.parseDouble(input); // convert input into a double perimeter = side * 4; // calculate perimeter area = side * side; // calculate area // output JOptionPane.showMessageDialog(null, "A square which is " + side + " in. on each side has a perimeter of " + perimeter + " in. and an area of " + area + " sq in.", "Perimeter and Area Output", JOptionPane.INFORMATION_MESSAGE); } }
10
Square Two – The code
public static void main (String args[]) { double side; // length of a side of a square double perimeter; // variable to hold perimeter double area; // variable to hold area String input; // variable to hold input ... }
1.
2.
Here we declare our variables just as we did in Square1. However, unlike Square1, we will not initialize them In addition to the variables from Square1 we also add a String variable named input. This variable will be used to hold the input from the JOptionPane. It has to be a String, because String is the only data type that JOptionPane can accept.
11
Square Two – The code
public static void main (String args[]) { ... // input input = JOptionPane.showInputDialog(null, “Please enter a side length”, “Input Side”, JOptionPane.QUESTION_MESSAGE); ... } We have already used the showMessageDialog method of JOptionPane in order to output a message to the user. To receive input from the user we call the showInputDialog method showInputDialog takes the same 4 arguments as showMessageDialog The difference between the two is that showInputDialog has a return value (it will send a value back to your program that can be assigned to a variable.) showInputDialog will return a String that contains the input entered by the user. We will store that String in our input String variable using the assignment operator ‘= ’
3.
4. 5.
6.
12
Square Two – The code
public static void main (String args[]) { ... // process }
7.
...
side = Double.parseDouble(input);
// convert input into a double
8.
9.
10.
This part of the code may seem a bit confusing at first. Remember, the input to JOptionPane from the user is not a number, like 54, it is a String like “54”. And recall, just because a String may contain a numerical value does not mean that it can be used as number. Therefore, we must convert the String to a primitive type so we can perform some computation with it. Luckily for us, Java has classes in its API (library) that can perform this kind of operation for us. In this case, we use the class Double and call the parseDouble method which converts a String that contains numerical characters to a double. Similar operations are available for ints and booleans (Integer.parseInt and Boolean.parseBoolean)
13
Square Two – The code
The rest of the code from Square2 should be familiar to you Type and run Square2 on your own to get a feel of how showInputDialog works Next we will take a look at a program that uses logical operators (operators that return true or false). Try to predict what the output will be!
14
The Operators Program
Sometimes we need to use boolean variables (return only true and false) and comparison operators (Operators that tell us if A is larger than B or if C is equal to D) We will also have to test logical combinations like AND (are A and B both true?) and OR (is at least one of E and F true?) Type in the code for Operators (on the next slide), get it to run, and then we will discuss it.
15
Operators – The code
// Operators program public class Operators { public static void main (String args[]) { boolean trueFlag = true; // declare variables boolean falseFlag = false; int five = 5; int six = 6; boolean result; result = trueFlag && falseFlag; // logical AND System.out.println(trueFlag + " AND " + falseFlag + " equals " + result); result = trueFlag || falseFlag; // logical OR System.out.println(trueFlag + " OR " + falseFlag + " equals " + result); result = !trueFlag; // logical NOT System.out.println("NOT " + trueFlag + " equals " + result); result = five < six; // comparison (less than) System.out.println(five + " < " + six + " equals " + result); five++; // increment five to six
}
}
result = five == six; // comparison (equals) System.out.println(five + " == " + six + " equals " + result);
16
Operators – Output
Executing the code on the previous page would give the following output:
true AND false equals false true OR false equals true NOT true equals false 5 < 6 equals true 6 == 6 equals true
This program demonstrates the use of logical and comparison operators These operators are important in Java because they allow for conditional branching (tests that determine which direction a program should go) The next two slides list the meaning of the logical and comparative operators in Java 17
Logical Operators
The three basic logical operators are:
NOT (!) – unary (takes a single operand); returns the inverse value of the operand AND (&&) – takes two operands and returns true if both operands are true; otherwise it returns false OR (||) – takes two operands and returns true if either or both operands are true; only returns false when both operands are false
Logical operators can only be used with boolean operands and always return boolean values (true or false) 18
Comparison Operators
Six common comparison operators
== - equality operator; if the two operands have the same value then true is returned; otherwise false is returned != - inequality; returns true if two operands do not have the same value > - greater than; returns true if the first operand is greater than the second operand < - less than; returns true if the first operand is less than the second operand >= - greater than or equal; returns true if the first operand is greater than or equal to the second <= - less than or equal; returns true if the first operand is less than or equal to the second
Comparison operators can take any primitive types as operands and return a boolean value. Strings can also be used as operands, but only in the case of equality and inequality
19
Increment/Decrement operators
Another operator that we used in the Operators program was the increment operator. The increment operator (++) is used to add 1 to a value. Likewise, the decrement operator (--) can be used to subtract 1 from a value. These are just shortcut notations to save you typing time – if you write x = x + 1; you get the same result as x++; Like the logical NOT operator, these operators are unary and are typically used for counting iterations in loops (which we will talk about in our next lesson). These operators can occur before the operand (prefix) or after the operand (postfix). Both essentially perform the same function. The only difference occurs when they are used inside expressions (which we will not get in to right now). Example:
int a = 5; a++; ++a; a--; // a now becomes 6 (postfix) // a now becomes 7 (prefix) // a goes back to 6
20
ShowOdd program
Now that we know about logical and comparison operators we may want to see their relevance in a program Let’s suppose we want to write a simple program that takes a number from the user and then displays a message ONLY if the number is an odd number The following slide shows the code for our ShowOdd program Type it and run it
21
ShowOdd program - code
import javax.swing.JOptionPane; public class ShowOdd { public static void main(String[] args) { String input; // to hold input from JOptionPane int number; // to hold the number // input input = JOptionPane.showInputDialog(null, "Please enter a number", "Enter number", JOptionPane.QUESTION_MESSAGE); // process number = Integer.parseInt(input); // convert to int // output if (number % 2 != 0) JOptionPane.showMessageDialog(null, number + " is odd!", "Number isodd", JOptionPane.INFORMATION_MESSAGE);
22
}
}
If statement
Most of what you see in the ShowOdd program should be familiar to you with the exception of the if statement at the end of the code The if statement is an example of a selection (conditional) statement if (test) do something; The test expression is enclosed with parentheses next to the if keyword. If the test expression is true then the code following the if statement will be executed, otherwise it will be skipped
In the ShowOdd program our test expression was number % 2 != 0 which essentially takes the remainder of our number divided by two and checks to see if it is not equal to zero (i.e. if our number is odd)
23
If statement (continued)
In some cases we may want to execute more than one line of code if a condition is true. In this case we would specify a block of code (contained in braces { }) after our statement For example, suppose we want to modify the ShowOdd program so that, if we encounter an even number our program will increment it by one and then display it as an odd number. The code is shown in the next slide You guessed it – type and run the code ☺
24
If statement (continued)
public static void main (String args[]) { ... // if odd if (number % 2 != 0) JOptionPane.showMessageDialog(null, number + " is odd!", "Number is odd", JOptionPane.INFORMATION_MESSAGE); // if even if (number % 2 == 0) { number++; JOptionPane.showMessageDialog(null, number + " is odd!”, "Number is odd", JOptionPane.INFORMATION_MESSAGE); }
25
}
One more variation – the if else
It may seem redundant to have two if statements in the previous example, (and it is). Obviously if a number is not odd then it must be even! We can eliminate this redundancy with an if/else construct. When we use this construct the code after the if statement will be executed when the test expression is true. Otherwise the code after the else statement will be executed when the test expression is false.
26
The if – else code
public static void main (String args[]) { ... // if the number odd if (number % 2 != 0) JOptionPane.showMessageDialog(null, number + " is odd!", "Number is odd", JOptionPane.INFORMATION_MESSAGE); // but if the number is not odd, do this else { number++; JOptionPane.showMessageDialog(null, number + " is odd!", "Number is odd", JOptionPane.INFORMATION_MESSAGE); } 27 }
Drill 3
Write a program that outputs the truth tables for the logical operators !, &&, and ||. That is, output the results of every combination of operands with each logical operator (like true && true, true && false, false && true, false && false, etc.) Write a program that uses JOptionPane to get input from the user. Ask the user to enter two numbers (hint: you will need to call showInputDialog twice). Use comparison operators along when a series of conditional statements (i.e. if/else constructs) to determine which of the two numbers is larger. Then use JOptionPane to output the largest number. Be sure to tell the user if the numbers are the same as well! As always – HAVE FUN!
28