Introduction to Java

advertisement
Introduction to Java
ISYS 350
A Brief History
• Sun Microsystems released this language in 1996
– Versions: 1.0 – 1.6
• Java Development Kit, JDK
– Standard Edition, SE and Enterprise Edition, EE
– With versions 1.2 through 1.5, SE and EE were known
as Java 2 Platform, J2SE and J2EE.
– Latest version is called Java SE 6 and Java EE 6
• Syntax is similar to C++
– Both languages are case-sensitive
• Web-based applications
Portability
Java: Write Once Run Anywhere
Java Byte Code
Java Source Code
Java Virtual Machine
(JVM)
Java Byte Code
(Intermediate Code)
Executable Code
How Java compiles and interprets code
Java virtual machine (JVM)
Text editor
Java compiler
source code
(*.java files)
bytecodes
(*.class files)
Java interpreter
Operating system
Download Java SE Development Kit,
SDK
• http://java.sun.com/javase/downloads/index.j
sp
• JDK 6 Update 14 with JavaFX SDK
• Select or Create a folder for downloaded file:
– For example. C:\JavaDownload
Directories of the JDK
• Typical JDK directory:
– C:\Program Files\Java\jdk1.6.0_14
• Sub Directories:
– bin: Java development tools including the Java
compiler (javac)
– Jre: Java Runtime Environment needed to run
compiled Java programs
– lib: Additional libraries used by the development tools
– Note:
http://java.sun.com/javase/6/docs/technotes/tools/w
indows/jdkfiles.html
Testing Java Installation
Demo: Use NotePad to create a Java program:
public class TestApp
{
public static void main(String[] args)
{
System.out.println("Java has been successfully installed. ");
}
}
Save this program
1.The name of this program must mach the name
of the public class.
2. It must have an extension “java” in lower case.
3. In the Save As box, enclose the name in
quotation marks like this:
“TestApp.java”
Start the Command Prompt and Change Path
• Start the command prompt:
– Start/Run/
– Then, run this program:
• C:\WINDOWS\system32\cmd.exe
• Set the path to the bin folder in order to run java compiler:
– Right click MyComputer icon and choose Properties
– Select the Advanced tab and click on the Environment Variables
button
– Use the Enviroment Variables dialog box to edit the variable named
Path
– Type a semicolon and the path C:\Program Files\Java\jdk1.6.0_14\bin
to the far right of the list of paths.
• From the Command prompt, change the directory to the program’s
folder:
– C: > CD C:\Java\Examples
Run a Java Program from Command Prompt
• Compile the program: javac TestApp.java
– If no syntax error, a class with the same name will be
created in the same folder
• Run the program: java TestApp
Common compile-time error message
C:\java\examples\ch01\TestApp.java:1: class testapp is
public, should be declared in a file named testapp.java
public class testapp
^
What it means
The *.java file name doesn’t match the name of the public class. You
must save the file with the same name as the name that’s coded after
the words “public class”. In addition, you must add the java extension
to the file name.
Solution
Edit the class name so it matches the file name (including
capitalization), or change the file name so it matches the class name.
Then, compile again.
Slide 12
A common runtime error message
Exception in thread "main" java.lang.NoSuchMethodError: main
What it means
The class doesn’t contain a main method.
Solution
Run a different class that does have a main method, or enter a main
method for the current class.
Slide 13
Integrated Development
Environment, IDE
• An integrated development environment (IDE)
also known as integrated design environment is a
software application that provides
comprehensive facilities to computer
programmers for software development. An IDE
normally consists of:
–
–
–
–
a source code editor
a compiler and/or an interpreter
build automation tools
a debugger
• Examples: NetBeans, Eclipse
NetBeans IDE
• A free, open-source Integrated Development
Environment for software developers. You get
all the tools you need to create professional
desktop, enterprise, web, and mobile
applications.
• Support many languages:
– Java, PHP, C++, Ruby
• Support many platforms:
– Windows, Linux, Mac OS X and Solaris
Download NetBeans IDE
• Before you install the IDE, the Java SE
Development Kit must be installed on your
system.
• Website:
http://www.netbeans.org/downloads/index.html
• Choose All that includes Java, PHP with bundled
servers.
• NetBeans IDE 6.7.1 Installation Instructions
– http://www.netbeans.org/community/releases/67/ins
tall.html
NetBeans’ Tutorials
• From NetBeans home page:
– http://www.netbeans.org/
– click Tutorials link
• Quick Start Guide
Using NetBeans to Create the TestApp
Java Program
•
•
•
•
1. Start NetBeans
2. Click File/New Project and select Java
3. Name project and specify project folder
4. Copy and paste the TestApp program’s
statements to the generated Main method.
• 5. Click Run/Run Main project to test.
Class and Method
• Class: When develop a Java application, you code one
or more classes for it.
– Access modifier: Control the scope of a class
• public: Other classes can access it.
• private: Used only in a project.
• Method: A class may contain one or more methods
which are pieces of code that perform tasks.
• The “main” method:
– A special method that is automatically executed when the
class that holds it is run. It is always declared to be public.
The Syntax for Declaring a Class
public!|or private class ClassName
{
statements
}
public class TestApp
{
public static void main(String[] args)
{
System.out.println("Java has been successfully installed. ");
}
}
main Method Syntax
• public static void main(String[] args)
– public: Other classes can access it.
– static: Other classes can call this method directly
without first creating an object.
– void: The method won’t return any values.
– The code in the parenthesis lists the arguments
that the method uses. Every main method has an
argument named args which is defined as an array
of strings.
Package and Project
• Package: Related classes are organized into
package.
• A project may contain one or more packages.
Java Language Tutorials
• http://java.sun.com/docs/books/tutorial/java/
TOC.html
• Questions and Exercises section at the end of
each topic.
Java Application Program Interface, API
API is an interface that defines the ways by
which an application program may request
services from libraries.
API, provides all the classes that are
included as part of the JDK.
You can view the API documentation from
the Java web site, or you can download and
install it on your system.
Java API page: http://java.sun.com/javase/7/docs/api/
Murach’s Java SE 6, C1
© 2007, Mike Murach & Associates, Inc.
Slide 24
Basic Coding Skills
• Statements: Direct the operation of the program.
–
–
–
–
Can continue from one line to next line
Spaces
Block of code: { }
Indentation for easy reading
• Comments:
– Single-line comment: //comment
– Block comment:
• /* comment
comment */
Naming an Identifier
Valid identifiers
InvoiceApp
Invoice
InvoiceApp2
subtotal
discountPercent
$orderTotal
_orderTotal
input_string
_get_total
$_64_Valid
i
x
TITLE
MONTHS_PER_YEAR
The rules for naming an identifier
 An identifier is any name that you create in a Java program. These
can be the names of classes, methods, variables, and so on.
 Start each identifier with a letter, underscore, or dollar sign. Use
letters, dollar signs, underscores, or digits for subsequent
characters.
 Use up to 255 characters.
 Don’t use Java keywords.
 Remember that Java is a case-sensitive language.
Slide 26
Keywords
boolean
char
byte
float
void
short
double
int
long
abstract
if
else
final
private
protected
public
static
new
this
super
interface
package
switch
case
break
default
for
continue
do
extends
class
volatile
while
return
throw
try
catch
finally
transient
instanceof
true
false
throws
native
implements
import
synchronized
const
goto
null
Definition
 A keyword is a word that’s reserved by the Java language. As a
result, you can’t use keywords as identifiers.
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 27
Write a Program that asks user to enter two
numbers and displays the larger number
• Inputs:
– two numbers entered via keyboard
– Must be able to read the numbers
– Must be able to save the numbers in the program
• Declare two variables
• Process: Compare the two numbers
• Output:
– Must be able to display the result.
Two of the eight primitive data types
Type Bytes Description
int
4
Integers from -2,147,483,648 to 2,147,483,647.
double 8
Numbers with decimal places that range from
-1.7E308 to 1.7E308 with up to 16 significant digits.
Variables and data types
 A variable stores a value that can change as a program executes.
 Java provides for eight primitive data types that you can use for
storing values in memory.
 The int data type is used for storing integers (whole numbers).
 The double data type is used for storing numbers that can have one
or more decimal places.
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 29
How to declare and initialize variables
 To initialize a variable, you declare a data type and assign an
initial value to the variable.
 An assignment statement assigns a value to a variable. This value
can be a literal value, another variable, or an expression.
 If a variable has already been declared, the assignment statement
doesn’t include the data type of the variable.
Naming recommendations for variables
 Start variable names with a lowercase letter and capitalize the first
letter in all words after the first word.
 Each variable name should be a noun or a noun preceded by one
or more adjectives.
 Try to use meaningful names that are easy to remember.
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 30
How to declare and initialize a variable in one
statement
Syntax
type variableName = value;
Examples
int scoreCounter = 1;
double unitPrice = 14.95;
// initialize an integer variable
// initialize a double variable
How to code assignment statements
int quantity = 0;
int maxQuantity = 100;
// initialize an integer variable
// initialize another integer variable
// two assignment statements
quantity = 10;
// quantity is now 10
quantity = maxQuantity;
// quantity is now 100
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 31
The basic operators for arithmetic expressions
Operator Name
+
Addition
Subtraction
*
Multiplication
/
Division
Description
Adds two operands.
Subtracts the right operand from the left.
Multiplies the right and left operands.
Divides the right operand into the left. If both
are integers, the result is an integer.
How to code arithmetic expressions
 An arithmetic expression consists of one or more operands and
arithmetic operators.
 When an expression mixes int and double variables, Java
automatically casts the int types to double types. To keep the
decimal places, the variable that receives the result must be a
double.
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 32
Statements that use simple arithmetic expressions
// integer arithmetic
int x = 14;
int y = 8;
int result1 = x + y;
int result2 = x - y;
int result3 = x * y;
int result4 = x / y;
//
//
//
//
result1
result2
result3
result4
// double arithmetic
double a = 8.5;
double b = 3.4;
double result5 = a + b;
double result6 = a - b;
double result7= a * b;
double result8 = a / b;
//
//
//
//
result5 = 11.9
result6 = 5.1
result7 = 28.9
result8 = 2.5
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
=
=
=
=
22
6
112
1
Slide 33
Using Java Classes
• To develop Java applications, we need to use
many different Java classes.
• Groups of related Java classes are organized
into packages.
• To use a class from a package we use the
“import” statement to import the class.
Common Java packages
Package name
java.lang
java.text
java.util
java.io
java.sql
java.applet
Murach’s Java SE 6, C2
Description
Provides classes fundamental to Java, including
classes that work with primitive data types,
strings, and math functions.
Provides classes to handle text, dates, and
numbers.
Provides various utility classes including those for
working with collections.
Provides classes to read data from files and to
write data to files.
Provides classes to read data from databases and
to write data to databases.
An older package that provides classes to create
an applet.
© 2007, Mike Murach & Associates, Inc.
Slide 35
Common Java packages (continued)
Package name
java.awt
java.awt.event
javax.swing
Murach’s Java SE 6, C2
Description
An older package called the Abstract Window
Toolkit (AWT) that provides classes to create
graphical user interfaces.
A package that provides classes necessary to
handle events.
A newer package called Swing that provides
classes to create graphical user interfaces and
applets.
© 2007, Mike Murach & Associates, Inc.
Slide 36
How to import Java classes
 All classes stored in the java.lang package are automatically
available to all Java programs.
 To use classes that aren’t in the java.lang package, you can code
an import statement.
 To import one class from a package, specify the package name
followed by the class name. To import all classes in a package,
specify the package name followed by an asterisk (*).
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 37
Reading Data Entered from Keyboard
• Need utilities:
– Class Scanner: A simple text scanner which can parse
primitive types and strings
• java.util.Scanner
• Methods: nextDouble, nextInt
– Must import the Scanner class to program.
• import java.util.Scanner;
– System.in
• The "standard" input stream. This stream is already open
and ready to supply input data. Typically this stream
corresponds to keyboard input.
• Example:
– Scanner sc = new Scanner(System.in) ;
– double num1 = sc.nextDouble();
How to use Java classes
1. Create an object from a class
Syntax
ClassName objectName = new ClassName(arguments);
Examples
Scanner sc = new Scanner(System.in);
// creates a Scanner object named sc
2. Call a method from an object
Syntax
objectName.methodName(arguments)
Examples
double subtotal = sc.nextDouble();
// get a double entry from the console
String currentDate = now.toString();
// convert the date to a string
A static method of a class can be called
directly without first creating an object from
the class.
How to call a static method from a class
Syntax
ClassName.methodName(arguments)
Examples
String sPrice = Double.toString(price);
// convert a double to a string
double total = Double.parseDouble(userEntry);
// convert a string to a double
Murach’s Java SE 6, C2
© 2007, Mike Murach & Associates, Inc.
Slide 40
The larger of two numbers
max method of the Math Class
• The max method is declared as static (see Java
API)
– public static float max(float a, float b)
– Example:
• Math.max(num1,num2)
• Other methods:
– public static double pow(double a, double b)
• a raises to the power of b
• Math.pow(a, b);
Display Result
• System.out Class
– System.out.println(data)
– System.out.print(data)
• System.out.println("The larger number is: " +
Math.max(num1,num2));
Code Example
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in) ;
System.out.println("enter the first number: ");
double num1 = sc.nextDouble();
System.out.println("enter the second number: ");
double num2 = sc.nextDouble();
System.out.println("The larger number is: " + Math.max(num1,num2));
}
}
Formula to Expression
B
A
A  2 AB
2
A B
CD
AB
CD
B
A
CD
X
 
Y 
X
X
A
B
A B
CD
AB
CD
Date Class
java.util.Date
• The class Date represents a specific instant in
time, with millisecond precision.
– Date myDate = new Date();
– System.out.println("Today is: " + myDate.toString());
• Note: import java.util.Date;
• Note: import java.util.*;
Download