Title: Introduction to Java and DrJava
1Introduction to Java and DrJava
Notes adapted from Introduction to Computing and
Programming with Java A Multimedia Approach by
M. Guzdial and B. Ericson, andinstructor
materials prepared by B. Ericson.
2Learning Goals
- Understand at a conceptual level
- What is Java again?
- What is object-oriented about Java?
- What is DrJava?
- What are Java primitive types and how do they
work? - What are strings?
- What are Java math and relational operators?
- What are variables?
3What is Java Again?
- Java is a programming language developed by Sun
Microsystems - It was made to overcome problems and limitations
with other languages - It was also targeted to allow dynamic content and
applications to execute in browsers surfing the
Internet, something unheard of at the time - This meant that it had to be cross platform to
run on all the different types of computers out
there - To make this all easier, it was decided that Java
should be an object-oriented language
4What is Object-Oriented About Java?
- In Java, the focus is on objects
- Objects are persons, places, or things that can
do actions or be acted upon in a Java program - All objects have
- Properties (aka characteristics)
- Behaviours (aka actions)
- Every object belongs to a specific class
- Objects that belong to the same class share
properties and behaviours
5An Objects Example
- Consider the following restaurant example
- When customers enter the restaurant, a greeter
welcomes and seats them at a table - A waiter takes their order and one or morechefs
prepare the order - The waiter brings the drinks and food, and when
the customers are done, the waiter creates and
brings them their bill - On their way out, the customers pay the bill
6An Objects Example
- What people were involved in this scenario?
- Customers, a greeter, a waiter, and chefs
- What other things were doing actions or were
being acted upon? - Table, order, drink, food, and bill
- Each of the entities involvedin this scenario is
an object - The objects in this scenario worked together to
get the job done, which in this case was
feeding the customers
7An Objects Example
- What types of objects are they?
- Suppose, for example that there were two chefs
working on the order, Alice and Bob - In this case, we could call chefs a class,with
both Alice andBob being instancesor objects
that belongto the class chefs
8An Objects Example
- Like all chefs, Alice and Bob would have common
properties and behaviours. - They would both have a name, a set of dishes they
knew how to prepare, a number of years of
experience, and so on as properties. - They would both be able totalk, prepare
ingredients,cook dishes, and so on as
behaviours. - Even though they areboth chefs, they arealso
still individuals.
9An Objects Example
- Objects and classes in an object-oriented
programming language like Java work similarly to
this example - In a Java program, all of the objects work
together to get the task at hand done, even
though each object plays a different role - Each object belongs to a class, and all objects
in the same class share properties and
behaviours, but are still distinct entities - We will be seeing a lot more on objects very
soon
10What is DrJava?
- DrJava is a free integrated development
environment for doing Java programming - From Rice University
- It is written in Java
- It has several window panes in it
- For creating programs (definitions pane)
- For trying out Java code (interactions pane)
- Listing of open files (files pane)
- To try out DrJava, we will begin with doing some
fairly simple math in Java ...
11Math Operators in Java ( / - )
- Addition
- 3 4
- Multiplication
- 3 4
- Division
- 3 / 4
- Subtraction
- 3 4
- Negation
- -4
- Modulo (Remainder)
- 10 2 and 11 2
12Math Operators Exercise
- Lets open DrJava and do the following in the
interactions pane - Subtract 7 from 9
- Add 7 to 3
- Divide 3 by 2
- Divide 4.6 by 2
- Multiply 5 by 10
- Find the remainder when 10 is divided by 3
13Why is the Result of 3 / 2 1?
- Java is what is called a strongly typed
language - Each value has a type associated with it
- This tells the computer how to interpret the
number - It is an integer, floating point, letter, and so
on - The compiler determines the type if it isnt
specified (as in the case of literals) - 3 is an integer
- 3.0 is a floating point number (has a fractional
part) - The result of an operation is in the same type as
the operands - 3 and 2 are integers so the answer is an integer 1
14Casting in Java
- There are ways to solve the problem of 3 / 2
having a result of 1 - You can make one of the values floating point by
adding .0 to the number, as in - 3.0 / 2
- 3 / 2.0
- The result type will then be floating point
- Or you can cast one of the values to the
primitive types float or double - (double) 3 / 2
- 3 / (float) 2
15Casting Exercise
- Use casting to get the values right for a
temperature conversion from Fahrenheit to Celsius - Celsius is 5/9 (Fahrenheit 32)
- Try it first with a calculator
- Try it in DrJava without casting
- Try it in DrJava with casting
16Data Types in Java
- As mentioned earlier, Java is a strongly typed
language, so it wants everything to have a type - In Java, there are two kinds of data types
- Primitive data types
- Used to store very simple data valuesin main
memory these are not treatedas objects, mainly
for efficiency reasons - Reference data types
- Used to refer to objects (more on this soon)
17Java Primitive Data Types
- Integers (numbers without fractional parts) are
represented by - The types int or byte or short or long
- 235, -2, 33992093, etc.
- Floating point numbers (numbers with fractional
parts) are represented by - The types double or float
- 3.233038983 -423.9, etc.
- A single character is represented by
- The type char
- a b A etc.
- True and false values are represented by
- The type boolean
- true or false
18Why so Many Different Types?
- They take up different amounts of space
- They have different precisions
- Usually use int, double, and boolean
- byte uses 8 bits (1 byte) 2s compliment
- short uses 16 bits (2 bytes) 2s compliment
- int uses 32 bits (4 bytes) 2s compliment
- long uses 64 bits (8 bytes) 2s compliment
- float uses 32 bits (4 bytes) IEEE 754
- double uses 64 bits (8 bytes) IEEE 754
- char uses 16 bits (2 bytes) Unicode format
19Sizes of Primitive Types
byte
short
int
long
float
double
char
20Floating Point Numbers
- Numbers with a fractional part
- 6170.20389
- Stored as binary numbers in a scientific notation
-52.202 is -.52202 x 102 - The sign (1 bit)
- The digits in the number (mantissa)
- The exponent (8 bits)
- Two types
- float 6-7 significant digits accuracy
- double 14-15 significant digits accuracy
21Operator Order
- The default evaluation order is
- Parentheses
- Negation
- Multiplication, division, and modulo (remainder)
from left to right - Addition and subtraction from left to right
- The default order can be changed
- By using parentheses
- (3 4) 2 versus 3 4 2
- It is also sometimes useful for parentheses to
emphasize the default operator precedence
22Math Operator Order Exercise
- Try 2 3 4 5
- Add parentheses to make it clear what is
happening first, and emphasize the
defaultoperator precedence - How do you change it so that 2 3 happens
first? - How do you change it so that it multiplies the
result of 2 3 and the result of 4 5?
23Printing Output to the Console
- One of the things you often want to do in a
program is output the value of something - In Java the way to print to the console is to use
- System.out.println()
- Will print out the value of the thing in the
parentheses and a new line - System.out.print()
- To print just the thing in the parentheses
without a new line
24Console Output Exercise
- Use System.out.println() to print the results of
an expression to the console - System.out.println(3 28)
- System.out.println(14 7)
- System.out.println(10 / 2)
- System.out.println(128 234)
- Try using System.out.print() instead
- What is the difference?
25Comparison (Relational) Operators
- Greater than gt
- 4 gt 3 is true
- 3 gt 3 is false
- 3 gt 4 is false
- Less than lt
- 2 lt 3 is true
- 3 lt 2 is false
- Equal
- 3 3 is true
- 3 4 is false
- Not equal !
- 3 ! 4 is true
- 3 ! 3 is false
- Greater than or equal gt
- 4 gt 3 is true
- 3 gt 3 is true
- 2 gt 4 is false
- Less than or equal lt
- 2 lt 3 is true
- 2 lt 2 is true
- 4 lt 2 is false
26Comparison Operators Exercise
- In DrJava
- Try out the comparison operators in the
interactions pane - with numbers
- 3 lt 4
- 4 lt 4
- 5 lt 4
- 6 6.0
- with characters (single alphabet letter)
- Put single quote around a character
- a lt b
- b lt a
- a a
27Strings
- Java has a type called String
- A string is an object that has a sequence of
characters in Unicode, used to represent text - Java recognizes strings as beginning and ending
with " (a double quote) - They can have no characters (the null string "")
- They can have many characters
- "This is one long string with spaces in it."
28Strings
- Everything in a string is printed out as it was
entered in the first place - Even math operations "128 234"
- Try doing a System.out.println("128 234")
- One exception to this is the \ character, which
is used to embed special charactersinto a string
in Java. Examples include - \" Used to put a " in a string
- \\ Used to put a \ in a string
- \t Used to put a tab in a string
- \n Used to force a new line in a string
29Strings
- Java also knows how to add (or concatenate)
strings to other strings - It returns a new string with the characters of
the second string after the characters of the
first - Try System.out.println("Java is" "great")
versusSystem.out.println ("Java is" " "
"great") - Java also can add numbers and strings, by first
converting the number to a string, and then doing
the traditional concatenation - Try System.out.println("The total is " 10)
- Compare to System.out.println("The total is "
5 5 )
30Variables
- Weve used Java to do calculations and
concatenate strings, but we havent stored the
results - The results are in memory somewhere, but we dont
know where they are, and we dont know how to
get them back - To solve this problem, we use variables
31Variables
- Variables are named locations in memory used for
storing values - Variables are created and named by declaring
them - To declare a variable in Java you specify a type
for the variable, and give it a name - Remember that Java is strongly typed and wants to
have a known type for everything - Providing a type lets Java know how much memory
to set aside for the variable and whatit can do
with that variable in the future
32Variable Declarations
- In general, variables are declared like this
- type name
- A simple and more complex example
- int numPeople
- double bill, tip
- In this case, we have declared three variables
one integer variable (numPeople) and two double
precision floating point variables (bill and tip) - Java allows multiple variables to be declaredat
the same time
33Storing Values in Variables
- Values are stored to variables in Java using
assignment statements - In general, assignment statements look like
- name expression
- We do not read as equals, but rather we assign
the value from the expression on the right side
to the variable named on the left - As an example
- numPeople 2
- Here, we assign the value 2 to the integer
variable numPeople that we declared earlier
34Storing Values in Variables
- Java also allows us to declare variables and
assign initial values to them at the same time - For example, we can combine the declaration of
our integer variable numPeople with the
assignment we didon the previous slide - int numPeople 2
35Using Variables
- In essence, a variable can be used wherever a
literal value of the same type could be used - The variable must be declared first though
- And, in most cases, the variable must appear on
the left side of an assignment statement first
too, to ensure that it has a valid value stored
in it - This gives us a lot of flexibility in
usingvariables in our Java programs - Consider the example Java code on the following
slide
36Using Variables Example
- int numPeople 2
- System.out.println(numPeople)
- double bill 32.45
- System.out.println(bill)
- double tip bill 0.2
- System.out.println(tip)
- double total bill tip
- System.out.println(total)
- double totalPerPerson total / numPeople
- System.out.println(totalPerPerson)
37Tracing Through Code
- Quite often, you will find it useful to trace
through code to see what it does when you do not
have access to a computer - On midterm and final exams, for example
- A good way to do this is to draw and label boxes
for each variable in the code and follow through
with changes to them
2
6.49
32.45
38.94
38Named Constants
- In our using variables example two slides ago, we
used three literal constant values - 2, 32.45, and 0.2
- Sometimes you will hear this kind of constant
called a magic number - This term denotes a literal constant which may
mean something to the programmer, but means
nothing to someone else who is reading the code - Using magic numbers in programming is typically
considered to be a poor practice because it can
make code difficult to read and change
39Named Constants
- Instead, we used named constants that have
meaningful names to them - To create a named constant, we declare a variable
and assign a value to it at the same time, but
add the keyword final to signify that this
variable is a named constant - As an example
- final double TIP_RATE 0.2
- It can then be used like
- double tip bill TIP_RATE
40Common Errors with Variables and Constants
- Simple typos
- The most common error is to simply mistype
something Java could get quite confused over
something like that - Example duble total bill tip
- Example double total bil tip
- Case sensitivity
- Java is case sensitive and will generally treat
issues with case as it would typos - Example doublE total bill tip
- Example double total Bill tip
41Common Errors with Variables and Constants
- Redeclaring a variable
- Once a variable has been declared, attempting to
declare another variable with the same name can
cause issues, depending on where you do it - Example int numPeople 2 int
numPeople - Reassigning a constant
- A constants value cannot be changed.
- Example final double TIP_RATE 0.2 TIP_RATE
0.1
42Common Errors with Variables and Constants
- Loss of precision
- Java will automatically convert integer values to
floating point values as necessary - Java will not automatically convert floating
point values to integers, however, as this could
result in a loss of precision you must cast
instead - Example int age 5.6
- Uninitialized variables
- In most cases, Java wants variables to be
initialized before they are used - Example int bill, tip tip bill 0.2
43Reference Variables
- All of the variables we have discussed so far
have been for primitive types - These variables are used to store values of the
various primitive types - Reference variables (or object variables) are
variables that are used to refer to objects - They do not store the objects themselves
- Instead, they store the location of the
objectsso that they can be found when necessary - Thats why we say they refer to objects, andcall
them reference variables
44Using Reference Variables
- Reference variables are declared in much the same
way other variables are declared - For example, as mentioned earlier, strings are
objects. To declare a reference variable to
refer to a string, we can use the following
declaration - String test
- Note that this does not actually create a String
object, but declares a variable named test that
can later be used to refer to a String object - By default, however, it does not refer to
anything, and is said to be a null reference
45Using Reference Variables
- To have a reference variable refer to an object,
we use an assignment statement - For example
- test "Hi"
- Java will create a String object containing the
text Hi and has the variable test refer to it - Another example
- test new String("Bye")
- The new operator is the traditional method used
in Java to create new objects, so this statement
will create a String object containing the text
Bye and have test refer to it instead - We will see more about Strings and new later on
46Reference Variables Example
- String test
- System.out.println(test)
- test "Hi"
- System.out.println(test)
- test new String("Bye")
- System.out.println(test)
47Multiple References to Objects
- In Java, it is possible to have multiple
references to the same object. Consider this - String name1 new String("Suzanne Clark")
- String name2 name1
-
- In this case, name1 and name2 refer to the same
object in memory - We would call this identity equality
48Multiple References to Objects
- It is important to note that the two references
are independent what you do to one does not
affect the other - Following the example on the previous slide, now
consider this - name1 null
- This change only affects the reference variable
name1, and not name2
null
name1
Suzanne Clark
name2
49Multiple References to Objects
- Suppose we did things a little differently in the
first place and created two objects as in - String name1 new String("Suzanne Clark")
- String name2 new String("Suzanne Clark")
-
- In this case, name1 and name2 refer to two
different objects with the same contents - We would call this state equality
Suzanne Clark
name1
Suzanne Clark
name2
50Java Naming Conventions
- In Java, Class names start with an uppercase
letter - System, String, Picture
- Named constants are in all uppercase letters,
with underscores separating words - TIP_RATE
- All other names start with lowercase letters but
uppercase the first letter of each additional
word - picture, fileName, thisIsALongName
51Java Naming Conventions
- Java code will compile if you dont follow these
conventions, but it may be hard for other
programmers to understand your code - So, it is a good idea to follow these
conventions! - As an example, can you identify which of these
are primitive types, and which are the names of
classes, just by following conventions? - char
- Double
- Math
- double
- Integer
- String
52A Semicolon () ends a Statement
- Java programs are made up of statements
- Like sentences in English
- As you may have already noticed, Java statements
end in a semicolon not a period - Missing semicolons in a Java program could lead
to a lot of syntax errors in your code - DrJavas interaction pane, however, prints the
result of statements without a semicolon - But not the result of statements with a semicolon
- Use System.out.println() to force output
53Comments
- To make code readable, Java allows you to embed
comments in your code that describewhat your
code does - Comments are ignored by Java, but can be ofgreat
use to other people reading your code - Commenting your code is considered to be a very
good programming practice! - Java allows commenting in a couple of ways
- / Everything between these symbols is a comment
/ - // Everything on the line following this is a
comment
54Summary
- Java is object-oriented
- Java has both primitive and reference types
- Java has typical math and relational operators
- Java uses variable to store primitive values and
references to objects - You can print out things using System.out.println(
value)