Big Java - Colorado School of Mines

Download Report

Transcript Big Java - Colorado School of Mines

Java Introduction
Getting Started – including
Eclipse
Java History
• 1991: use in consumer devices
• 1994: use in browsers
• programmers embraced because:
–
–
–
–
simpler than C++
rich library
portable programs
micro edition and enterprise edition provide support for
wide range of apps, from cell phones to large Internet
servers
– safe (must trust applets when you download!)
– Java virtual machine (JVM) catches many mistakes,
makes it easier to use
Java Versions
Version
Year
Features
1.0
1996
JAVA
1.1
1997
Inner classes
1.2
1998
Swing, collections
1.3
2000
Performance
1.4
2002
Assertions, XML
5
2004
Generics, enhanced for, auto-box, enumeration
6
2006
Library improvements
7
2011
Multi-core api, etc.
8
2014
Lambda expressions, safety
Learning Java
• Very similar to C++in most respects
• All programs are class definitions
• All objects are created dynamically (using
new)
• Extensive library – you must read Java
documentation!
Variables
Rules for identifiers:
• Can include letters, digits, _, $, can’t start with
digits
• Spaces and other characters not permitted
• Cannot use reserved words (e.g., public)
• Case sensitive
Conventions you must follow for CSCI306:
• variable and method names should start with
lower case, may include uppercase within (camel
case). e.g., luckyNumber
• Class names should begin with uppercase
• Constants should be in ALL_CAPS
• Variable and class names should be meaningful!!
Assignment and Initialization
• As in C++, variables have a type
• Unlike C++, variables MUST be assigned a
value before being used
int luckyNumber;
System.out.println(luckyNumber); // ERROR
if (tot = 5) // Compiler ERROR – must be
boolean
In C++ what would happen? tot would be
assigned 5. Any integer that is not 0 would be
considered “true”
Extra safety built into Java
HINT: In Eclipse, type Syso + ctrl-space to get System.out.println
Unicode
• C++ and other languages used ASCII to
encode characters
• Java uses a 16-bit encoding known as
Unicode
• First 128 characters (i.e., English
alphabet) are the same as ASCII
• Also includes German umlauts, about
21000 Chinese ideographs and others
• Can encode as escape sequence, e.g.
\u00E9 is e’
Numeric Data Types
• Integer values can be represented exactly, but
numeric operations may result in overflow
• Floating point values may not be exact, so
rounding errors may occur (shouldn’t use ==
with floating point values, use tolerance)
• double is therefore not appropriate for financial
calculations
• java.math has BigInteger and BigDecimal classes
which are slow but have better size/precision.
Must use add, subtract and multiply (no operator
overloading in Java)
Constant values
• preceded by keyword final (vs const in
C++)
• naming convention is all uppercase
• e.g.,
final double QUARTER_VALUE = 0.25;
• if used in a class, often make public (since
can’t change anyway) and often use
keyword static, meaning constant belongs
to the class:
public static final double DIME_VALUE =0.1;
• Math class has some useful constants, e.g.,
double circumference = Math.PI * diameter;
(vs Math::PI in C++)
Numeric Operations
• +, -, *, /, % - same precedence as C++
• Math class has a number of static functions (sqrt,
pow, sin, cos, exp, log, round, max, min, etc.)
• / of two integers yields an integer result (same as
C++)
Quality Tips:
– put space after every Java keyword, but not between a
method name and parentheses
– put space around all binary operators
– factor out common code
– example:
x1=(-b+Math.sqrt (b*b-4*a*c))/(2*a);
x2=(-b-Math.sqrt (b*b-4*a*c))/(2*a);
becomes:
double root = Math.sqrt(b * b - 4 * a * c);
x1 = (-b + root) / (2 * a);
x2 = (-b - root) / (2 * a);
Numeric Operations, continued
• Remember that you may need to round
floating point values
double f = 4.35;
int n = (int) (100 * f);
System.out.println(n); // prints 434!
Replace with:
int n = (int) Math.round(100 * f);
Decisions
• if, if-else and nested if-else just like C++
• use of braces for compound statements
just like C++
• Relational operators (> >= < <= == !=)
just like C++
• switch is just like C++ (remember break!)
• dangling else is a problem in Java, just as
in C++
• logical operators (&&, ||, !) just like C++
• short-circuit evaluation applies
Loops in Java
• while loops – same as C++
• same common errors: infinite loops, offby-one
• do loops – same as C++
• for loops – same as C++ (but with
another useful syntax for collections)
• same common errors: forget semicolon if
need empty body, or include semicolon on
for statement
• Quality tip: for loops are best for counting
loops. Use a while loop for other types
Loops in Java (continued)
• nested Loops – same as in C++
• Quality tip: don’t use != to test the end of
a range, better to use <, <= etc.
• sentinel loops – same as in C++
Getting Started with Eclipse
• Eclipse Distilled
– David Carlson, Addison Wesley
– ISBN 0-321-2885-7
• Download Eclipse
– http://www.eclipse.org
– get the Eclipse SDK download, latest release
– be sure to install Java first
• No installer, just unzip it and create a
shortcut for eclipse.exe
Java IDE
Java Perspective – views laid out for a particular task
Toolbar
Perspective
Switcher
Editor
Views
Using the IDE
New Java Project
New Java Class
New Java Package
Buttons on toolbar will bring up wizards that walk you through
creating a new project, package or class.
Create Project Options
Using a fully
qualified name
would be better,
such as
edu.mines.MyProject
Creates src and
bin directories
Create Class Options
warning wouldn’t
appear if we
used a package
you’ll need to
select a src if
one isn’t highlighted
click to create
main method
New Class
Default comments for a new class
Update HelloPrinter
If this is slow, modify your heap parameter.
Error in HelloPrinter
Errors
identified
in red
immediately
Listed
under
Problems
after
save
Execution in Eclipse
Simplest way is to select RunAs from toolbar
Be sure the program with main is selected!
Output will appear in the Console view/window.
First Program Explained
Unlike C++, ALL code is encapsulated in a class
Like C++, program starts at main
program can take array of Strings
end statement with ;
System.out is the console (monitor) object
println is a method that displays its parameters,
followed by a newline (can do print, no newline)
Each method has a public/private access declaration (vs C++, with
public: and private: sections)
static indicates that main does not operate on an object
More output options
Some String Methods
Strings are Immutable! what effect will this have?
A few more String methods
• + is string concatenation
String message = “Hello ” + name;
• To extract numbers from strings, use
parseInt or parseDouble:
int count = Integer.parseInt(input);
Useful in GUI programming
double price =
Double.parseDouble(input2);
• Use substring to extract parts of a string
String sub = greeting.substring(0, 5);
String tail = greeting.substring(7);
// copies from 7 to end of string
Objects
import rather than #include for libraries (called packages
in java). Could use * if multiple classes.
Always use new
for objects!! The
variable box is
a reference.
Determining the expected result in advance is an important
part of testing. This class relies on the user to compare the
expected and achieved result. Is that optimal?
NOTE: We’ll come back to this later…
Object comparison
What will be displayed when this is executed?
Comparing Strings
• To compare contents of strings, use equals:
if (string1.equals(string2)) . . .
• May prefer to ignore case:
if (string1.equalsIgnoreCase(string2)) . . .
• Can use compareTo to find out the relationship
(<0 if first is less, ==0 if same, >0 if first is
greater):
if (string1.compareTo(string2)) < 0) . . .
Order: numbers < uppercase < lowercase
shorter strings < longer strings (e.g., “car” <
“cargo”
String subtlety
String nickname = “Rob”;
// Creates a literal string “Rob”
if (nickname == “Rob”) // succeeds
But:
String name = “Robert”;
String nickname = name.substring(0, 3);
if (nickname == “Rob”) // fails
Working from home
•
•
•
•
•
•
•
Install Java
Install Eclipse
Save your work on the Z: drive
Copy your work to your computer
Do not put the files in your workspace
Open Eclipse
Choose File->Import->General->Java
project
• Check the “Copy project” box
• Browse to select your project
Time to Explore
• Do EclipsePlay exercise