Title: Introduction to Java Programming
1Introduction to Java Programming
- Today we start off with basics of Java
programming - Java programs are written as classes
- This will be important later on when we want to
build large programs or ones that use built-in
routines for graphics - For now, we will write single, stand-alone
classes - The syntax will be a bit weird, just get used to
it - All classes start with a class definition of the
form - public class name
- name must match the file name, for instance if we
name a class HelloWorld, then the file must be
named HelloWorld.java (or HelloWorld.jav, etc) - Our class will comprise one piece of code, a main
method - The main method must always appear as
- public static void main(String args)
- where the are the instructions that we want to
execute
2Example Hello World
class name defined
public class HelloWorld public static void
main(String args) System.out.println("Hell
o World!")
the main method
one executable statement, it outputs a message to
System.out (a window)
used to delimit (start and stop) blocks of
code
Running the program produces this output
3Statements
- Inside the of our main method, we list our
statements - These will include variable and constant
declarations (we had none in this program) - And executable statements
- Input statements, output statements
- Assignment statements
- Loops and selection statements
- For the hello world program, the only executable
statement is println - This is an output statement
- It outupts whatever is placed inside of the ( )
- In this case, it outputs the literal message
Hello World!
4Variables, Values, Literals
- We want to store information for our program to
use - values are either
- placed directly in the program by the programmer,
called literals - or input or computed by the program and stored in
variables - Hello World is a literal, it will always appear
this way - Variables are memory locations where values can
be stored and retrieved - The advantage of a variable is that the value can
change, that is, the variable can hold multiple
values - Values have types, in Java the types are
- int, short, long
- char
- boolean
- float, double
- objects
We declare variables using the form type
variable name As in int x or char a, b, c
5Example 2 Revised Hello World
public class HelloWorld2 public static void
main(String args) String name name
"Frank Zappa" System.out.println("Hello "
name)
declaring a variable, name is a String Set name
to store Frank Zappa
output now contains a literal (Hello ) and a
variable notice the blank space after o
The output
6Another Way to Output
- System.out represents a window on your monitor
- often known as the console window or the system
window - Java has numerous GUI classes, one of which is
JOptionPane, which creates pop-up windows of
different types - To use this class (or others), you must import it
- import javax.swing.JOptionPane or
- import javax.swing.
- Replace the System.out.println statement with an
appropriate message to JOptionPane - JOptionPane.showMessageDialog(null, Hello
World, title", JOptionPane.INFORMATION_MESSAGE)
A JOptionPane window created by the program on
the next slide
7Example 3 New Hello World
import all classes from this library (these are
all GUI classes)
import javax.swing. public class
HelloWorld3 public static void main(String
args) String name name "Frank
Zappa" String title title "output
GUI" JOptionPane.showMessageDialog(null,
"Hello " name, title, JOptionPane.INFORMATION_
MESSAGE) System.exit(0)
add a title variable and store our title there
output message sent to pop-up window of type
INFORMATION_MESSAGE
System.exit(0) makes sure that the program
ends once our pop-up window is closed
8String Concatenation
- Notice in our previous programs, we used a in
our output statements - Hello name
- The is used to concatenate (join together)
Strings - So this results in the word Hello followed by a
blank followed by whatever is stored in name - Imagine that the int variable age stores a
persons age, then we could output a message
like - JOptionPane.showMessageDialog(null, "Hello "
name ", you are " age " years old "
,title, JOptionPane.INFORMATION_MESSAGE) - Notice that
- we separate the literal parts of the message and
the variables using signs - we enclose all literals in quote marks
- we include blank spaces inside of quote marks to
enforce blanks
9More on Variables
- We divide variables between
- primitive types (int, double, char, boolean, etc)
- and objects (Strings and others)
- Primitive types are handled through assignment
statements using arithmetic operators (, -, ,
/, ) - Objects are handled through message passing
- variable_name.message(parameters)
- Examples name is a String, to get its length
- name.length( )
- To get name as all upper or lower case
characters - name.toUpperCase( ) name.toLowerCase( )
- NOTE to name a variable, use characters, digits
and _ as in name1 or last_name or lastName
(variables cannot start with a number and cannot
be any of Javas reserved words like public,
void, int)
10Assignment Statements
- To assign a variable to a value
- The form of an assignment statement is
- variable expression
- expression is some arithmetic expression using
variables, literals, and arithmetic operators ,
-, , /, (mod) - For an assignment statement to properly work, the
expression must compute the same (or a
compatible) type as the variable - x 5 y z // x must be a compatible type
with y and z - for instance, if y and z are ints, x can be an
int, long, float or double, if y is a double,
then x must be a double - We can also have expressions that work on Strings
using the String concatenation operator () or
logical expressions that work on true and false
values
11More on Assignments
- Expressions may also contain messages to various
objects as long as the messages invoke operations
that return the proper type of value - for instance, the Math class has a number of such
operations such as sqrt, whereas
JOptionPane.showMessageDialog does not return any
value - x z Math.sqrt(y) // what if y is negative?
- x z Math.sqrt(Math.abs(y))
- To compute the average of 5 test scores
- average (t1 t2 t3 t4 t5) / 5
- Note that if t1, t2, t3, t4 and t5 are int
values, the expression computes an int value even
if average is a float or double
12Numeric Conversions
- Two types of conversion processes in Java
- Implicit conversions (called coercions) occur
automatically if the left-hand side variable is a
different type as to the right-hand side
expression - x y // y is an int, x is a double
- Casts occur because you force a value to change
types - casts are performed by placing the new type in (
) as in (int) - average ((double) t1 t2 t3 t4 t5) / 5
- changes t1 to a double, then the rest of the
expression computes a double value not an int
value - we could force a coercion instead by doing
average (t1 t2 t3 t4 t5) / 5.0 // 5.0
is a double, so the entire thing becomes a double
13Getting Input
- The easiest way to get input from the user is to
use JOptionPane again - In this case, the message to JOptionPane is
showInputDialog - Example name JOptionPane.showInputDialog(Ente
r your name) - This opens a pop-up window (see below) with the
question Enter your name and a box for the user
to enter something, plus two buttons, OK and
Cancel - When the user clicks on the OK button or presses
the enter key, whatever was typed in is returned
and stored in the String name
14Example Input and Output
import javax.swing.JOptionPane public class
HelloWorld4 public static void
main(String args) String firstName
JOptionPane.showInputDialog("Enter your first
name") String lastName JOptionPane.showInputDi
alog("Enter your last name") JOptionPane.show
MessageDialog(null, "Hello " firstName " "
lastName, "Greeting", JOptionPane.INFORMATION_M
ESSAGE) int many firstName.length( )
lastName.length( ) JOptionPane.showMessageDialog
(null, "Your name has " many " characters
in it", "Length", JOptionPane.INFORMATION_MESSAGE)
System.exit(0)
15More on Input
- showInputDialog is only one way to obtain input
- we will use it for now and study other approaches
later - one restriction on using showInputDialog is that
it can only input and return a String - If you want to input some other type (int,
double, char) you have to convert it - To convert input into integer
- Integer.parseInt(JOptionPane.showInputDialog())
- int age Integer.parseInt(JOptionPane.showInputDi
alog(Enter your age)) - To convert an input into double
- Double.parseDouble(JOptionPane.showInputDialog())
- double gpa double.parseDouble(JOptionPane.showIn
putDialog(Enter your GPA)) - To convert an input into char
- JOptionPane.showInputDialog().charAt(0)
- char sex JOptionPane.showInputDialog(Enter
your sex).charAt(0)
16Using charAt
- charAt returns a single character from a String
at the position of the value indicated in the
parens (this will be an int value or a variable
storing an int) - charAt is a message passed to a String object
- Example firstName.charAt(0) returns the first
letter - The integer value passed to charAt must be an int
between 0 and the length of the String 1 - For instance, to get someones initials, you
might use - initials firstName.charAt(0)
middleName.charAt(0) lastName.charAt(0) - or more appropriately
- initials firstName.charAt(0) .
middleName.charAt(0) . lastName.charAt(0)
. - To get the last character in a String, use length
but remember that the last character is at length
1 - lastLetters firstName.charAt(firstName.leng
th( ) 1) middleName.charAt(middleName.length(
) 1) lastName.charAt(lastName.length( ) 1)
Notice the use of which casts the expression
into a String
17More String Messages
- replace(oldchar, newchar)
- return a String with all of the chars that match
oldchar replaced by newchar - substring(startingpoint, endingpoint)
- return a String that consists of all of the
characters of this String that start at the index
startingpoint and end at endingpoint - 1 - toUpperCase( ), toLowerCase( )
- return new Strings that replace all letters in
the old String with their uppercase (or
lowercase) equivalents but leave all other
characters (digits, punctuation marks) unchanged - length( )
- already seen, returns an int value
- concat(str)
- takes the String str and concatenates it to this
String, so that str1.concat(str2) does the same
as str1 str2
18String Using Example
import javax.swing. public class
StringUsingExample public static void
main(String args) // get
the user's full name in 3 inputs String
firstName JOptionPane.showInputDialog("Enter
your first name") String middleName
JOptionPane.showInputDialog("Enter your middle
name") String lastName JOptionPane.showInputD
ialog("Enter your last name") String name
firstName " " middleName " "
lastName name name.replace('e', '3') //
store in name the new String once we name
name.replace('E', '3') // replace each of 'e',
'i', 'g', also name name.replace('i',
'1') // replacing the upper case
versions name name.replace('I', '1') name
name.replace('g', '6') name
name.replace('G', '6') // output a
response JOptionPane.showMessageDialog(null,
"Hello " name ".\nI do not like the
letters 'e', 'i' or 'g'\n" "so I have
replaced them with '3', '1' and '6'",
"Response", JOptionPane.INFORMATION_MESSAGE)
System.exit(0) // end the program once the
dialog window is closed
19The if Statement
- A common form of selection statement is the if
statement - In the if statement, a condition is tested, and
if it evaluates to true - then the statement which follows is executed,
otherwise the - statement which follows is skipped
20Why Use an if?
- We use the if statement so that our program can
make decisions and carry out actions - consider computing the users age as the current
year their birth year - age currentYear birthYear
- this is accurate as long as they have already had
a birthday, but if not, it is 1 year too many - consider that you were born in December of 1989,
this would make you 16 but our code above would
compute your age as 17 - input whether the user has had their birthday yet
(use the charAt(0) to take whatever they entered
and only store the first letter as a char) - if(birthday n) age age 1 // no
birthday yet then deduct 1
21Examples
if (total gt amount) total total (amount
1) if (sex m) pay pay 500 if
(age gt 21) System.out.println("Ok, you can
drink") if (sunny) System.out.println("Wear
your sunglasses!") if (rainy)
System.out.println("Take an umbrella") if (x gt
y) x x 5 y
sex is a character sunny and rainy
are boolean variables
Warning Do not confuse and
22if-else statement
- Used if there are two possibilities
- For instance, if you want to calculate someones
pay, there are two formulas, one for normal pay
and another for overtime pay - Example below to the right
- Note that the if-else statement has two separate
statements, one following the condition, one
following the word else - Neither the condition nor else have a after
it, the follows the statement - We refer to the statements as they if clause
and the else clause
if (hours lt 40) pay hours wages else
pay 40 wages (hours 40)
wages 1.5
23More Examples
if (score gt 60) grade P else grade
F if (number gt 0) sqt
Math.sqrt(number) else System.out.println("Ca
nt take the square root of a negative
number!") if (number 0)
System.out.println("Cant take reciprocal of
0") else rec 1.0 / (float) number if
(age gt 21) canGamble true else
canGamble false
Use if-else to decide what value should be
assigned a variable Use if-else to decide if an
operation could/should be performed
24Block Statements
- All of our examples so far have had a single
statement as the if clause and the else clause - What if we needed to accomplish more than one
instruction in an if or else clause? - We use block statements by wrapping all of the
instructions inside of - Blocks will be used often in our Java programs
If (temperature gt 80)
System.out.print("Wear shorts and t-shirt ")
effectiveTemp temperature HEATINDEX
humidity System.out.println("because it
is " effectiveTemp " degrees today")
Else System.out.println("It is not hot
today, the temperature is " temperature) The
if-clause has 3 instructions, so we place them in
a block