Title: CS2
1CS2
- Category Java Basics
- Topic Creating basic programs
- Objectives
- Basic Program
- Comments and Conventions
- Data Types, Expressions, Operators
- Creating Objects
- Packages and the import statement
2CS 2
- Introduction to
- Object Oriented Programming
- Java Basics
3Basic Java Program
- Application execution begins at a main method
- Executes each statement one after the other and
until reaches the end. - Statements end with a semicolon.
- All Java programs have to have at least one class
- Usually there will be several
4Basic Class Definition
- public class Hello
- public static void main(String args)
// display a greeting in the console
window System.out.println("Hello,
World!!")
5Documentation Comments
- Three ways to do it
- // Double slashes comment out everything until
the - // end of the line
- / This syntax comments out everything between
- the / and the /.
- / (There are no nested comments as in C.) /
- /
- This is syntax for Javadoc comments (similar
to - the second style of commenting. It has tags
which - allow for HTML formatting features.
- /
1
2
3
6Documentation and Commenting
- 70-80 of the cost of software is maintenance
- Program code is written for two audiences
- The compiler
- The programmer and his colleagues who will need
to understand the code after it is written EVEN
IF IT WORKS - Comment to make your code clear!
7Javadoc
- Once commenting is complete the Javadoc program
is run from the OS prompt. - If for example a group of class files for a given
project are located in the same directory then
Javadoc may be run by typing - javadoc .java
- When the program runs it will report any problems
and will produce a series of HTML files
documenting all classes, methods and fields. - A Javadoc template is on the next slide followed
by a sample
8- / A class called Template. Used to make
template objects! / - public class Template
- / Serial. The objects serial number. /
- public int serial
- / Pressure. The objects pressure in psi. /
- public double press
- / Temperature. The objects temperature in
degrees C / - public float temp
- / Time variables. Hours and minutes--the
objects time. / - int hours, minutes
- / Invisible. Why doesn't this one appear???
/ - long hidden
- / Descriptive phrase. Longer statement of
purpose. - _at_param p1 A description of this parameter
- _at_param p2 A description of this parameter
- _at_ return A description of the return value
- /
- public int someMethod(double p1, String p2)
9Running javadoc
- Cgtjavadoc .java
- Loading source file Template.java...
- Constructing Javadoc information...
- Building tree for all the packages and classes...
- Building index for all the packages and
classes... - Generating overview-tree.html...
- Generating index-all.html...
- Generating deprecated-list.html...
- Building index for all classes...
- Generating allclasses-frame.html...
- Generating index.html...
- Generating packages.html...
- Generating Template.html...
- Generating serialized-form.html...
- Generating package-list...
- Generating help-doc.html...
- Generating stylesheet.css...
10Results
11Results
12Results
13Java Conventions
- No spaces between words for names
- Each word in a class name starts with an
uppercase letter - BankAccount
- All other names start with a lowercase letter
- aCheckingAccount
- balance
14Variable Declarations
- Simple form
- ltdatatypegt ltidentifiergt
- Example
- int total
- Optional initialization at declaration
- ltdata typegt ltidentifiergt ltinit valuegt
- Example
- int total 0
15Data Types
- Two main types of data in Java
- Primitive
- Numbers, Characters, Boolean
- Object
- Strings, Arrays, System.out (in standard package)
- Objects from libraries (other packages)
- Objects you define
16Primitive Type Facts
Type
Size
Min
Default
Max
boolean
false
1
false
true
char
'\u0000' (null)
16
byte
(byte) 0
8
-128
127
short
(short) 0
16
-32,768
32,767
int
0
32
-2,147,483,648
2,147,483,647
long
0L
64
-9,223,372,036,854,775,808
9,223,372,036,854,775,807
float
0.0F
32
Approx 3.4E38 with 7 significant digits
double
0.0D
64
Approx 1.7E308 with 15 significant digits
void
Not truly min and max.
17Examples
- Local Variables
- int counter 0
- double batAvg 20d // notice this
- char gender f
- boolean isEmpty true
- Field Declarations
- private boolean flag
- public static final int
- MAX_STUDENTS200
18Specifying Numbers
- Note that whole integers appearing in your source
code are taken to be ints. So, you might wish
to flag them when assigning to non-ints - float fMaxGrade 100f // now holds 100.0
- double dTemp 583d // holds double
- // precision 583
- float fTemp 5.5 // ERROR! Java thinks
- // 5.5 is a double
- Upper and lower case letters can be used for
float (F or f), double (D or d), and long
(l or L, but we should prefer L) - float fMaxGrade 100F // now holds 100.0
- long x 583l // holds 583, but looks
- // like 5,381
- long y 583L // Ah, much better!
19Space Time
- Why so many data types?
- Performance
- Smaller data items (byte, short, float) take up
less space - Integer calculations are faster than floating
point calculations - Nevertheless, sometimes we need to convert data
from one type into another
20Type Checking
- What happens when data is changed from one
representation to another? - Some languages (such as Java) enforce a strict
set of rules to try and catch problems early - It is a complier error to move data from a larger
type to a smaller type without an explicit cast
to the new type.
21Explicit Casting Intentional Loss of Precision
int x 45 byte b b (byte) x // cast
needed
Symbol Picture of
Memory
x
b
cast needed!
22But wait...
- int i 42
- byte b
- b i
- Surely 42 will fit in a byte???
- Yes, we just need to tell Java we know what we're
doing!!! How? Casting
23Precise Rules
- Consider
- float f
- int i 5
- int j 2
- f i/j
- Result?
- f 2.0
But what if we wanted 2.5 as a result?
24One way
- Consider
- float f
- int i 5
- int j 2
- float temp1 i
- float temp2 j
- f temp1/temp2
- Result?
- f 2.5
25Better (Easier?) Way
- Consider
- float f
- int i 5
- int j 2
- f (float)i/(float)j
- Result?
- f 2.5
26Casting
- We say "cast i to a float"
- (float)i
- Are we actually changing i???
- No, we are telling Java to convert the value of i
to a float before making the calculation. - We are not actually changing the contents of
variable i.
27We can even...
- Consider
- float f
- int i 5
- int j 2
- f (float)i/j
- Result?
- f 2.5
- When dividing two different types Java will
automatically cast the j for us
28Expressions
- Formed by combining
- Variables
- Selected reserved words
- Methods (Java/OO speak for procedures and
functions) - Literal values
- Operators
- Syntax mostly borrowed from C/C
29Reserved Words(Keywords)
- abstract default if private throw
- boolean do implements protected
throws - break double import public transient
- byte else instanceof return try
- case extends int short void
- catch final interface static
volatile - char finally long super
while - class float native switch
- const for new synchronized
- continue goto package this
-
Don't worry about what all these words mean or
do, but be aware that you cannot use them for
other purposes like variable names.
30Operators
- Assignment (, , -, , /, etc.)
- Arithmetic , -, , /, (modulo) and unary
minus - String concatenation (overloaded)
- Increment and Decrement Operators
- Comparison , !, lt. lt. gt, gt
- Boolean (and), (or), ! (not) plus others
(, , ) - Others which we will introduce as appropriate
- instanceof, . , , (), new, etc.
- Not used in CS1322
- Bitwise Not used in CS2 (, , , , ltlt, gtgt,
gtgtgt) - Conditional operator ?
31Operator Issues
- Are applied to operands (one or more)
- Different type operands may change meaning of
operator () - Operators always return a value
- Operators may also have side effects
- Pay attention to the order of evaluation
32Assignment
- Basic assignment
- Compute value of expression on right hand side
of operator - Store result in variable on left hand side
- Combination assignment operators
- - / etc.
- Calculate value of expression on right hand side
- Perform operation (first part of symbol (, -, ,
/) using variable on left hand side and value of
expression on right hand side - Store result in variable on left hand side
- a 1 is equivalent to a a 1
- Note The format of these operators is
- "operation then "equals sign
- x 2
- Not x 2 which just means assign to x the
value positive 2
33Arithmetic
- , -, , /, (modulo), unary minus
- Precedence
- Unary minus (negation)
- , /,
- , -
34High precedence postfix operators .
(params) expr expr-- unary operators
expr --expr expr -expr ! creation or cast
new (type)expr multiplicative /
additive - shift
ltlt gtgt gtgtgt relational lt gt lt gt
instanceof equality ! bitwise
AND bitwise exclusive OR bitwise
inclusive OR logical AND
logical OR conditional
? assignment - /
ltlt gtgt gtgtgt Low
precedence
When operators of equal precedence appear in the
same expression, a rule must govern which is
evaluated first. All binary operators except for
the assignment operators are evaluated in
left-to-right order. Assignment operators are
evaluated right to left.
35String Concatenation
- Strings are objects in Java that hold textual
data like "abc" - Use \ to put a double quote in a string
- Strings separated by a plus () sign indicate
concatenation of the Strings - String temp abc def // abcdef
36Pre and Post Increment and Decrement Operators
- counter // same as counter counter 1
- counter-- // same as counter counter - 1
- counter // same as counter counter 1
- --counter // same as counter counter - 1
- What's the difference?
- counter counter increments after the
statement containing it is evaluated. - counter counter increments before the
statement containing it is evaluated. - counter 7
- a counter
- b counter
- What's the value of a, b and counter?
37Increment and Decrement Operators
- These operators are more than just a way to save
typing. - Be careful when using them.
- Misuse can introduce bugs!
38Declaring Variables
- When you declare a primitive you get space
allocated for that primitive - int x 0 32 bits allocated and set to 0
- When you declare an object you get an object
reference (not an object!) - String name
- name new String(Fred)
null
name
FredString
name
39Creating Objects
- Create objects use the new keyword
- Address myAddress new Address(123 Main, Apt
2, Bedrock, GA, 30219) - The Address class will create an address object
and call a constructor that takes 5 String
objects - Constructors initialize the fields of an object
Address
myAddress
40String Objects
- Strings can be created with the new keyword
- String name new String(Fred)
- Strings can also be set to literals
- String name Fred
- Strings are immutable (cant change)
- Changes result in a new string
41Some String Methods
- How do I get the number of characters in a
String? - How do I create a substring?
- How do I change a string to all uppercase
letters? - How do I change a string to all lowercase
letters? - How do I find a replace a character in a string?
42Java Packages
- Java organizes groups of related classes into
packages - java.lang (String and System are in here)
- java.io
- java.sql
- java.net
-
43Import Statement
- If you wish to use a class that isnt in
java.lang you can - Use the full name of the class everywhere
- java.util.Random randomGen
- new java.util.Random()
- Or use an import statement giving the full name
or (giving access to all in package) - import java.util.Random // allow Random
- import java.util. // allow all in
package - Import statements go before the class definition
in a file
44Useful Classes
- Random
- In java.util
- Pseudorandom number generator
- NumberFormat
- In java.text
- Format numbers for currency and percentages
- DecimalFormat
- In java.text
- Format decimal numbers for output
45Class Methods
- All java code must belong to a class
- How to provide general math functions?
- Like absolute value (abs)
- Calculate the square root (sqrt)
- Class methods on the Math class
- Invoked by ClassName.function()
- Math.abs(-7)
- Math.sqrt(4)
46Questions
47(No Transcript)