Sei sulla pagina 1di 157

7/3/2018 1

Java

Java SE Java EE Java ME

Java SE used for Desktop Applications

Java EE used for Web Applications

Java ME used for Embedded Applications

7/3/2018 2
A programming language
 Fully buzzword-compliant:

A simple, object oriented, distributed, interpreted, robust,


secure, architecture neutral, portable, high performance,
multithreaded, dynamic language.

From: Java: An Overview


James Gosling, Sun Microsystems,
February 1995.
According to Gosling:
 “An environment”
 “A platform”
 “A way of thinking”
 …ok, whatever

Java is a phenomenon
 Took the world by storm in 1995 when
introduced with the HotJava web Browser
 Quickly integrated with Netscape browser
 1993 Oak project at Sun
 small, robust, architecture independent, Object-Oriented, language to
control interactive TV.
 didn’t go anywhere
 1995 Oak becomes Java
 Focus on the web
 1996 Java 1.0 available
 1997 (March) Java 1.1 - some language changes, much larger library, new
event handling model
 1997 (September) Java 1.2 beta – huge increase in libraries including Swing,
new collection classes, J2EE
 1998 (October) Java 1.2 final (Java2!)
 2000 (April) Java 1.3 final
 2001 Java 1.4 final (assert)
 2004 Java 1.5 (parameterized types, enum, …) (Java5!)
 2005 J2EE 1.5
 Java is a general-purpose, high-level
programming language.
 The features of Java
 Java program is both compiled and interpreted.
 Write once, run anywhere

 Java is a software-only platform running on top


of other, hardware-based platforms.
 Java Virtual Machine (Java VM)
 The Java Application Programming Interface
(JAVA API)
 Simple  Portable
 Architecture-neutral  High-Performance
 Object-Oriented  Robust
 Distributed  Secure
 Compiled  Extensible
 Interpreted  Well-Understood
 Statically Typed
 Multi-Threaded
 Garbage Collected
Get started quickly
Write less code
Write better code
Develop programs faster
Avoid platform dependencies with 100% pure
Java
Write once, run anywhere
Distribute software more easily
 Stand-alone Applications
 Just like any programming language
 Applet
 Run under a Java-Enabled Browser
 Midlet
 Run in a Java-Enabled Mobile Phone
 Servlet
 Run on a Java-Enabled Web Server
 Switchlet
…
Java's programming environment
 Core Java API
 compiler
 interpreter
 debugger
 dis-assembler
 profiler
 more...
Java Java
Compiler Interpreter

Java Source Java Bytecode

<file>.java <file>.class
Java
Dis-assembler
Source Computer

Java Program Compilation Java ByteCode

Internet

Verification
Your computer

Java ByteCode Execution Restricted Env.


For most languages, compilation produces
machine code
Java compilation produces “bytecode”
 Intermediate code readable by the VM
 Transferable across the Internet as applets
VM interprets BC into instructions
 Partly responsible for performance lag
ByteCode produced on any platform may
be executed on any other platform which
supports a VM
source bytecode
(text) compiler (aka. class file)
JVML
dynamic
loading

verifier
virtual machine

JIT compiled
bytecode code
compiler
interpreter

CPU
Just-In-Time compiler
Translates bytecode into machine code at
runtime
 1-time overhead when run initiated
 Performance increase 10-30 times
Now the default for most JVM’s
 Can be turned off if desired
 JIT can apply statistical optimizations based on
runtime usage profile
 JVM (J2EE & J2SE)
 Well-known Java Virtual Machine.
 CVM, KVM (J2ME)
 Small devices.
 Reduces some VM features to fit resource-
constrained devices.
 JCVM (Java Card)
 Smart cards.
 It has least VM features.

 And there are also lots of other JVMs


 Java API and Virtual
Machine insulate the
Java program from
hardware dependencies.
 Java API
 Collection of ready-  Core API
made software  Essentials: Object, String,
components that Input and Output...
provide many useful  Applets
 Networking
capabilities.
 Internationalization
 Grouped into libraries  Security
(packages) of related  Software Components
components.  Object Serialization
 Java Database
Connectivity (JDBC)
 Primary Goals

There were five primary goals in the creation of the Java


language:

 It should use the object-oriented programming methodology.


 It should allow the same program to be executed on multiple
operating systems.
 It should contain built-in support for using computer
networks.
 It should be designed to execute code from remote sources
securely.
 It should be easy to use by selecting what were considered
the good parts of other object-oriented languages.

7/3/2018 21
 Prerequisites
Required
 Substantial Programming Experience
 Know how to write, edit, and compile a program
 Know how to design algorithms and data structures to solve a problem
 Know how to write clean, legible, maintainable code
 Know how to debug a program
 Reading knowledge of C
 You should know what a for loop looks like.
 You should know what ints, floats, and doubles are.
 You should be able to recognize a function call and its arguments
 You do not need to know pointer arithmetic.
 You do not need to understand the preprocessor.
 You do not need to understand arcana like enums, unions, structs,
bitwise operators, or typedef.
 Some basic computer skills
 Know how to use the Web, email, and ftp
 Know how to take screenshots on your platform of choice
 Know how to manipulate directories
 Know how to add a program to your path
 Know how to set environment variables
7/3/2018 22
 Compiled and Interpreted
Usually a computer language is either compiled or interpreted. Java
combines both these approaches thus making Java a two-stage
system. First, Java compiler translates source code into what is
known as bytecode instructions. Bytecodes are not machine
instructions and therefore, in the second stage, Java interpreter
generates machine code that can be directly executed by the
machine that is running the Java program. We can thus say that
Java is both a compiled and an interpreted language.

7/3/2018 23
 Platform-Independent and Portable
The most significant features of Java over other languages is its
portability. Java Programs can be easily moved from one computer
to another, anywhere and anytime. Changes and upgrades in
operation systems, processors and system resources will not force
any changes in Java programs. This is the reason why Java has
become a popular language for programming on internet which
interconnects different kinds of systems worldwide. We can
download a Java applet from a remote computer onto our local
system via internet and execute it locally. This makes the internet
an extension of the user`s basic system proving practically
unlimited number of accessible applets and applications.
Java ensures portability in two ways. First, Java compiler
generates bytecode instructions that can be implemented on any
machine. Secondly, the size of the primitive data types are machine
independent.

7/3/2018 24
 Object -Oriented
Java is a true object-oriented language. Almost everything in Java is
object. All the program code and data reside within objects and
classes. Java comes with an extensive set of classes, arranged in
packages, that we can use in our programs by inheritance. The
object model in Java is simple and easy to extend.

method
method

data

method method

Object= Data+method
7/3/2018 25
 Robust and Secure
Java is a robust language. It provides many safeguards to ensure
reliable code. It has strict compile time and run time checking for
data types. It is designed as a garbage-collected language relieving
the programmers virtually all memory management problems. Java
also incorporates the concept of exception handling which captures
series errors and eliminates any risk of crashing the system.
Security becomes an important issue for a language that is used
for programming on internet. Threat of issues and abuse of
resources is everywhere. Java systems are not only verify all
memory access but also that no viruses are communicated with an
applet. The absence of pointers in Java ensures that programs
cannot gain access to memory locations without proper
authorization.

7/3/2018 26
 Distributed
Java is designed for the distribution environment of the internet,
because it handles TCP/IP protocols. In fact, accessing a resource
using a URL is not much different from accessing a file. Java also
supports Remote Method Invocation(RMI). This feature enables a
program to invoke methods across a network.

7/3/2018 27
 Simple, Small and Familiar

Java was designed to be easy for the professional programmer to


learn and use effectively. Assuming that you have some programming
experience, you will not find Java hard to master. If you already
understand the basic concepts of Object-Oriented programming,
learning Java will be even easier. Best of all, if you are an
experienced C++ programmer, moving to Java will require very little
effort. Because Java inherits the C/C++ syntax and many of the
object oriented features of C++.
Familiarity is another striking features of Java. To make the
language look familiar to the existing programmers, it was modeled
on C and C++ languages. Java uses many constructs of C and C++ and
therefore, Java code “looks like a C++” code. In fact, Java is a
simplified version of C++.

7/3/2018 28
 Multithreaded and Interactive
Java is inherently multi-threaded. A single Java program can have
many different threads executing independently and continuously.
Three Java applets on the same page can run together with each
getting equal time from the CPU with very little extra effort on the
part of the programmer. This makes Java very responsive to user
input. It also helps to contribute to Java's robustness and provides
a mechanism whereby the Java environment can ensure that a
malicious applet doesn't steal all of the host's CPU cycles.
Unfortunately multithreading is so tightly integrated with Java,
that it makes Java rather difficult to port to architectures like
Windows 3.1 or the PowerMac that don't natively support
preemptive multi-threading. There is a cost associated with multi-
threading. Multi-threading is to Java what pointer arithmetic is to
C, that is, a source of devilishly hard to find bugs. Nonetheless, in
simple programs it's possible to leave multi-threading alone and
normally be OK. The Java runtime comes with tools that support
multi process synchronization and construct smoothly running
interactive systems.
7/3/2018 29
 High Performance
Java performance is impressive for an interpreted language, mainly
due to the use of intermediate bytecode. According to Sun, Java
speed is comparable to the native C/C++. Java architecture is also
designed to reduce overheads during runtime. Further, the
incorporation of multithreading enhances the overall execution
speed of Java programs.

7/3/2018 30
 Dynamic
Java programs carry with them substantial amounts of run-time
type information that is used to verify and resolve accesses to
objects at run time. This makes it possible to dynamically link code
in a safe and expedient manner. This is crucial to the robustness of
the applet environment, in which small fragments of bytecode may
be dynamically updated on a running system.

7/3/2018 31
How Java differs from C & C++ ?

To learn Java we need to


know the following in C
C++ language-

JAVA  Control Structures


C  Arrays
 Functions

As we know that C++ is a


superset nor a subset of C or
C++. Java may be considered
as a first cousin of C++ and a
second cousin of C as
Overlapping of C, C++ and Java illustrated in the figure.

7/3/2018 32
 Java`s interaction with the web

User`s Computer Remote Computer

Applet Source
Bytecode Code

Java Web HTML


browser Document Bytecode

request Applet Tag

HTML Document
Output

Web Server

User
7/3/2018 33
 Data types in Java

Data Types in JAVA

Primitive Non-Primitive
(Intrinsic) (Derived)

Classes
Numeric Non-numeric
Interface

Integer Character
Arrays
Boolean
Floating-point

7/3/2018 34
 byte, short, int, and long
 for integer values of various sizes
 float and double
 for real (rational) values of differing accuracy
 boolean
 for logical (true/false) values
 char
 for individual characters
 Variables & Data types

There are eight primitive data types in Java:


boolean , byte , short , int , long, float, double, char
However there are only seven kinds of literals, and one of those is
not a primitive data type:
boolean: true or false
int: 89, -945, 37865
long: 89L, -945L, 5123567876L
float: 89.5f, -32.5f,
double: 89.5, -32.5, 87.6E45
char: 'c', '9', 't'

7/3/2018 36
String: "This is a string literal"
There are no short or byte literals.
Strings are a reference or object type, not a primitive type. However
the Java compiler has special support for strings so this sometimes
appears not to be the case.

class Variables
{
public static void main (String args[]) {
boolean b = true;
int low = 1;
long high = 76L;
long middle = 74;
float pi = 3.1415292f;
double e = 2.71828; String s = "Hello World!";
}
}

7/3/2018 37
 Simple Java program

class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}

Hello World is very close to the simplest program imaginable. When you
successfully compile and run it, it prints the words "Hello World!" on
your display. Although it doesn't teach very much programming, it gives
you a chance to learn the mechanics of typing and compiling code. The
goal of this program is not to learn how to print words to the terminal.
It's to learn how to type, save and compile a program. This is often a
non-trivial procedure, and there are a lot of things that can go wrong
even if your source code is correct.

7/3/2018 38
 To write the code you need a text editor. You can use any text editor
like Notepad, Brief, emacs or vi, Text pad.
 You should not use a word processor like Microsoft Word or
WordPerfect since these save their files in a proprietary format and
not in pure ASCII text. If you absolutely must use one of these, be
sure to tell it to save your files as pure text. Generally this will require
using Save As... rather than Save. If you have an integrated
development environment like Borland JBuilder that will include a text
editor you can use to edit Java source code. It will probably change your
words various colors and styles for no apparent reason. Don't worry
about this yet. As long as the text is correct you'll be fine.
 When you've chosen your text editor, type or copy the above program
into a new file. For now type it exactly as it appears here. Like C and
unlike Fortran, Java is case sensitive so system.out.println is not the
same as System.out.println. CLASS is not the same as class, and so on.
 However, white space is not significant except inside string literals. The
exact number of spaces or tabs you use doesn't matter.
 Save this code in a file called HelloWorld.java. Use exactly that name
including case. Congratulations! You've written your first Java program.
7/3/2018 39
 Compiling and Running HelloWorld

 To make sure your Java environment is correctly configured, bring


up a command-line prompt and type
javac nofile.java
If your computer responds with
error: Can't read: nofile.java
you're ready to begin. If, on the other hand, it responds
javac: Command not found
or something similar, then you need make sure you have the Java
environment properly installed and your PATH configured.
 Assuming that Java is properly installed on your system there are
three steps to creating a Java program:
 writing the code
 compiling the code
 running the code
7/3/2018 40
 Under Unix, compiling and running the code looks like this:
$ javac HelloWorld.java
$ java HelloWorld
Hello World
$
 Under Windows, it's similar. You just do this in a DOS shell.
C:> javac HelloWorld.java
C:> java HelloWorld
Hello World
C:>

Notice that you use the .java extension when compiling a file, but
you do not use the .class extension when running a file.

For IDEs, consult your product documentation.


7/3/2018 41
 Typical Java program consists of
 User written classes
 Java Application Programming Interface (API)
classes
 Java application
 Has one class with a main method
 Java program basic elements:
 Packages
 Classes
 Data fields
 Methods

7/3/2018 42
Provide a mechanism for grouping related
classes
package statement
 Indicates a class is part of a package
Java assumes all classes in a particular
package are contained in same directory
Java API consists of many predefined packages

7/3/2018 43
import statement
 Allows you to use classes contained in other
packages
Package java.lang is implicitly imported to
all Java code

7/3/2018 44
Figure 1-1
A simple Java Program 31
 Data type that specifies data and methods
available for instances of the class
 An object in Java is an instance of a class
 Class definition includes
 Optional subclassing modifier
 Optional access modifier
 Keyword class
 Optional extends clause
 Optional implements clause
 Class body

7/3/2018 46
Every Java class is a subclass of either
 Another Java class
 Object class
new operator
 Creates an object or instance of a class

33
7/3/2018
Figure 1-2
Components of a class 48
Class members that are either variables or
constants
Data field declarations can contain
 Access modifiers
 Use modifiers
 Modules

7/3/2018 35
Figure 1-3
Modifiers used in data field declarations 36
Used to implement operations
Should perform one well-defined task
Method modifiers
 Access modifiers and use modifiers
Valued method
 Returns a value
 Body must contain return expression;

37
7/3/2018
Figure 1-4
Modifiers used in a method declaration 1-52
Syntax of a method declaration
access-modifier use-modifiers return-type
method-name (formal-parameter-list) {
method-body
}
Arguments are passed by value
 Except for objects and arrays
 A reference value is copied instead

Java 1.5 allows a method to have a variable


number of arguments of the same type
 Using the ellipses (three consecutive dots)
7/3/2018 1-53
Constructor
 Special kind of method
 Has the same name as the class and no return
type
 Executed only when an object is created
A class can contain multiple constructors

7/3/2018 1-54
Data fields and methods declared public
 Name the object, followed by a period, followed
by member name
Members declared static
 Use the class name, followed by a period,
followed by member name

7/3/2018 1-55
Java application
 Collection of classes
 One class contains the main method
Java programs can also be written as applets

7/3/2018 1-56
Comment line
 Begins with two slashes (//)
 Continues until the end of the line
Multiple-line comment
 Begins with /* and ends with */
 Useful for debugging
 Cannot contain another multiple-line comment
javadoc comments
 Begins with /** and ends with */

7/3/2018 1-57
Types of objects must be declared before
they are used

Declaration of variables requires a certain


syntax

In declaration, the name of a variable is


associated with a type
 Built of other types
 Example: String, Screen, Keyboard
 Also considered “class types”
 Reference types
 begin with uppercase letter
 not known to Java compiler, must be explained
 Contrast primitive types
 begin with lower case letter
 are known to Java compiler
 Integers
 4, 19, -5, 0, 1000
 Doubles
 3.14, 0.0, -16.123
 Strings
 “Hi Mom” “Enter the number : “
 Character
 'A' 'X' '9' '$' '\n'
 Boolean
 true, false
 Names given to variables, objects, methods
 Must not be a Java keyword
 See Appendix B for list of keywords
 May begin with a letter or the underline character _
 Followed by any number of characters, digits, or _
(note, no blanks)
 Identifiers should be well chosen
 use complete words (even phrases)
 this helps program documentation
 Classes
 Names given in lowercase except for first letter of each
word in the name
 Variables
 Same as classes, except first letter is lowercase
 Constants
 All caps with _ between words
 Methods
 like variable names but followed by parentheses
 Purpose is to provide compiler with meaning of an
identifier
 Accomplished in declaration statement
 Some declarations (classes and methods) are
provided and must be imported
import ann.easyio.*;
 Variables to store values must be declared
 they can be initialized at time of declaration
 initialized with a literal or even with keyboard input
 if not explicitly initialized, the default initial value is zero
Primitive-type variables
 store a value of the specified type (int, double)
Reference-type variables
 store an address of memory location where value
is stored
 thought of as a handle for the object that actually
stores the values
 Syntax:
type variable_name;
or
type variable_name = expression;
 Note
 type must be known to the compiler
 variable_name must be a valid identifier
 expression is evaluated and assigned to
variable_name location
 In the first form, a default value is given (0, false, or null,
depending on type)
Indicate particular values within a program
Used to initialize the value of a variable
Decimal integer constants
 Do not use commas, decimal points, or leading
zeros
 Default data type is either int or long
Floating constants
 Written using decimal points
 Default data type is double

7/3/2018 1-66
Character constants
 Enclosed in single quotes
 Default data type is char
 Literal character strings
 Sequence of characters enclosed in double quotes

7/3/2018 1-67
Have values that do not change
Declared as a variable but using the keyword
final

7/3/2018 1-68
Expressions
 Combination of variables, constants, operators,
and parentheses
Assignment statement
 Example: radius = r;
Arithmetic expression
 Combine variables and constants with arithmetic
operators and parentheses
 Arithmetic operators: *, /, %, +, -

7/3/2018 1-69
Relational expressions
 Combine variables and constants with relational,
or comparison, and equality operators and
parentheses
 Relational orcomparison operators: <, <=, >=. >
 Equality operators: ==, !=

 Evaluate to true or false

7/3/2018 1-70
Logical expressions
 Combine variables and constants of arithmetic
types, relational expressions with logical
operators
 Logical operators: &&, ||
 Evaluate to true or false
 Short-circuit evaluation
 Evaluates logical expressions from left to right
 Stops as soon as the value of expression is apparent

7/3/2018 1-71
Implicit type conversions
 Occur during assignment and during expression
evaluation
 Right-hand side of assignment operator is
converted to data type of item on left-hand side
 Floating-point values are truncated not rounded
 Integral promotion
 Values of type byte, char, or short are converted
to int
 Conversion hierarchy
 int → long → float → double

7/3/2018 1-72
 Explicit type conversions
 Possible by means of a cast
 Cast operator
 Unary operator
 Formed by enclosing the desired data type within
parentheses
 Multiple assignments
 Embed assignment expressions within assignment
expressions
 Example: a = 5 + (b = 4)
 Evaluates to 9 while b is assigned 4

7/3/2018 1-73
Other assignment operators
 -=
 *=
 /=
 %=
 ++
 --

7/3/2018 1-74
Operator Order of Operation
evaluation
() left - right parenthesis for
explicit grouping
* / % left - right multiplication,
division, modulus
+ - left - right addition,
subtraction
= right - left assignment
Operator Order of Operation
evaluation
++ -- right - left preincrement, predecrement
++ -- right - left postincrement, postdecrement
* / % left - right multiplication, division,
modulus
+ - left - right addition or String
concatenation, subtraction
= += -= right - left assignment
*= /= %=
 Numbers without fractional parts
3, 47, -12
 Variables can be used to store integers using an
assignment statement
int daysInWeek;
daysInWeek = 7;
 In general integer variables may be used any place
an integer literal can be
import CSLib.*;

Inputbox in;
int i;

in = newInputBox();
in.setPrompt(“Enter an integer: “);
i = in.readInt();
Symbol Operation Example
+ Addition 45 + 5 = 50
- Subtraction 657 – 57 = 600
* Multiplication 7000 * 3 = 2100
/ Division 10 / 3 = 3
% Remainder 10 % 3 = 1
1. Evaluate all subexpressions in parentheses
2. Evaluate nested parentheses from the inside out
3. In the absence of parentheses or within
parentheses
a. Evaluate *, /, or % before + or –
b. Evaluate sequences of *, /, and % operators from left to
right
c. Evaluate sequences of + and – operators from left to
right
Example 1
6 + 37 % 8 / 5 is the same as
6 + ((37 % 8) / 5) =
6 + ( 5 / 5) = 7
Example 2
6 + 37 % (8 / 5) =
6 + 37 % 1 =
6+0=6
 Self-assignment
temperature = temperature + 10;
 Increment
cent++;
equivalent to
cent = cent + 1;
 Decrement
cent--;
equivalent to
cent = cent - 1;
 May be used to give variables initial values
int x = 5;
int y = 6;
 Can be written more concisely
int x = 5,
y = 6;
 Can use expressions on the right hand side
int x = 5,
y = x + 1;
Useful when you want a variable whose value
never changes
Use the modifier final in its declaration
Example
final int US_Population = 278058881;
 Numbers with fractional parts
3.14159, 7.12, 9.0, 0.5e001, -16.3e+002
 Declared using the type double
double pricePerPound = 3.99;
taxRate = 0.05;
shippingCost = 5.55;
 The initialization part of the declaration is optional
Symbol Operation Example
+ Addition 4.50e01 + 5.30e00 =
5.03e01
- Subtraction 6.57e02 – 5.7oe01 =
6.00e02
* Multiplication 7e02 * 3.0e00 =
2.1e04
/ Division 9.6e01 / 2e01 =
4.8e00
import CSLib.*;

Inputbox in;
double temp;

in = newInputBox();
in.setPrompt(“Enter a real number: “);
temp = in.readDouble();
Type Size Minimum Value Maximum Value
in Bytes

short 2 -32,768 32,767


int 4 -2, 147, 483, 648 2, 147, 483, 647
long 8 -9,223,372,036,854,775,808 9,223,372,036,854,775,807

Example declarations:
int testGrade;
int numPlayers, highScore, diceRoll;
short xCoordinate, yCoordinate;
byte ageInYears;
long cityPopulation;
Numbers with fractional parts
Type Size Minimum Value Maximum Value
in Bytes
float 4 1.4E-45 3.4028235E38
double 8 4.9E-324 1.7976931348623157E308

Example declarations:
float salesTax;
double interestRate;
double paycheck, sumSalaries;
One Unicode character (16 bits - 2 bytes)
Type Size Minimum Value Maximum Value
in Bytes
char 2 character character
encoded as 0 encoded as FFFF

Example declarations:
char finalGrade;
char newline, tab, doubleQuotes;
Two values only:
true
false
Used for decision making or as "flag" variables
Example declarations:
boolean isEmpty;
boolean passed, failed;
 Assignment operator =
 Value on the right of the operator is assigned to the
variable on the left
 Value on the right can be a literal (text representing a
specific value), another variable, or an expression
(explained later)
 Syntax:
dataType variableName = initialValue;
Or
dataType variable1 = initialValue1,
variable2 = initialValue2, …;
int, short, byte
Optional initial sign (+ or -) followed by digits
0 – 9 in any combination.
long
Optional initial sign (+ or -) followed by digits
0–9 in any combination, terminated with
an L or l.
***Use the capital L because the lowercase l
can be confused with the number 1.
float
Optional initial sign (+ or -) followed by a
floating-point number in fixed or scientific
format, terminated by an F or f.
double
Optional initial sign (+ or -) followed by a
floating-point number in fixed or scientific
format.
Commas, dollar signs, and percent signs (%)
cannot be used in integer or floating-point
literals
char
 Any printable character enclosed in single quotes
 A decimal value from 0 – 65535
 '\m' , where \m is an escape sequence. For
example, '\n' represents a newline, and '\t'
represents a tab character.
boolean
true or false
See Example 2.2 Variables.java
Syntax:
dataType variable2 = variable1;
Rules:
1. variable1 needs to be defined before this
statement appears in the source code
2. variable1 and variable2 need to be compatible
data types; in other words, the precision of variable1
must be lower than or equal to that of variable2.
Any type in right column can be assigned to type in left column:

Data Type Compatible Data Types


byte byte
short byte, short
int byte, short, int, char
long byte, short, int, long, char
float float, byte, short, int, long, char
double float, double, byte, short, int, long, char
boolean boolean
char char
This is a valid assignment:
float salesTax = .05f;
double taxRate = salesTax;

This is invalid because the float data type is


lower in precision than the double data type:
double taxRate = .05;
float salesTax = taxRate;
 To include a special character in a String, use an escape
sequence
Character Escape Sequence
Newline \n
Tab \t
Double quotes \"
Single quote \'
Backslash \\
Backspace \b
Carriage return \r
Form feed \f
See Example 2.3 Literals.java
Once a variable is declared, its data type
cannot be changed.
These statements:
double cashInHand;
int cashInHand;
generate this compiler error:
cashInHand is already defined
 String is a class defined in the java.lang package
 Unlike other Java classes String has literals and a defined
operation
 Examples
String prompt = “Enter an integer:”;
String t1 = “To be “,
t2 = “or not to be”;
out.print(t1 + t2);
Out.print(“Mass is “ + x * 2.2 + “ Kg”);
OutputBox out = new OutputBox();
String s1 = “Here is a test string”;

out.println(s1.indexOf(“s”)); // prints 6
out.println(s1.indexOf(“x”)); // prints -1

out.println(s1.length()); // prints 22

out.println(s1.substring(8,14));
// prints ‘a test’
import CSLib.*;

Inputbox in;
String input;

in = newInputBox();
in.setPrompt(“Enter a real number: “);
input = in.readString();
 Any key you type on the keyboard generates a
character which may or may not be displayed on the
screen (e.g. nonprinting characters)
 Characters are a primitive type in Java and are not
equivalent to strings
 Examples
char vitamin = ‘’A’,
chromosome = ‘’y’,
middleInitial = ‘’N’;
‘A’, … ,‘Z’ Uppercase letters
‘a’, … ,‘z’ Lowercase letters
‘0’, … , ‘9’ Digits
‘.’,’,’,’!’,’”’,etc. Punctuation Marks
‘ ’ Blank
‘\n’ New line
‘\t’ Tab
‘\\’ Backslash
‘\’’ Single Right Quote
 Misleading compiler error messages
 Syntax errors indicated on one-line may actually reflect an
error made on an earlier line
 Capitalization errors
 Java is case sensitive, identifier names must use the same
capitalization rules each time
 Logic Errors
 Program appears to run correctly, but on closer inspection
the wrong output is displayed
 Unlike the integers mathematics the type int is
not infinitely large and it is possible to compute a
value incorrectly because the value is too large to be
stored in an int variable storage location
 Unlike the real numbers in mathematics the type
double is not dense, it is not always possible to test
double expressions for equality and obtain a
correct result due to rounding errors in
representations
 Java will automatically convert int expressions to double
values without loss of information
int i = 5;
double x = i + 10.5;
 To convert double expressions to int requires a
typecasting operation and truncation will occur
i = (int) (10.3 * x)
 To round-up instead of truncating add 0.5
i = (int) (10.3 * x + 0.5)
 It is important to remember that “13” and 13 are not
the same
 Examples
out.println(“4” + “5”) // prints 45
out.println(“4” + 5) // prints 45
out.println(4 + 5) // prints 9
 It is legal to assign a char to an int variable
int i = ‘a’; // assigns 97 to i
 It is legal to assign an int to an char variable
char c = 97; // assigns ‘a’ to c
 It is possible to perform arithmetic on char
variables
char ch = ‘a’;
ch = ch + 1; // assigns ‘b’ to ch
 Collection of elements with the same data type
 Array elements have an order
 Support direct and random access
 One-dimensional arrays
 Declaration example
final int DAYS_PER_WEEK = 7;
double [] maxTemps = new double[DAYS_PER_WEEK];
 Length of an array is accessible using data field
length
 Use an index or subscript to access an array element

7/3/2018 1-114
Figure 1-7
One-dimensional array of at most seven elements

1-115
 One-dimensional arrays (continued)
 Initializer list example
double [] weekDayTemps = {82.0, 71.5, 61.8, 75.0,
88.3};
 You can also declare array of object references
 Multidimensional arrays
 Use more than one index
 Declaration example
final int DAYS_PER_WEEK = 7;
final int WEEKS_PER_YEAR = 52;
double[][] minTemps = new
double[DAYS_PER_WEEK][WEEKS_PER_YEAR];

7/3/2018 1-116
Figure 1-8
A two-dimensional array
1-117
Passing an array to a method
 Declare the method as follows:
public double averageTemp(double[] temps, int n)
 Invoke the method by writing:
double avg = averageTemp(maxTemps, 6);
 Location of array is passed to the method
 Cannot return a new array through this value
 Method can modify content of the array

7/3/2018 1-118
 The if statement  Nested if
if (expression)
if (expression) {
statement1
statement1
or }
if (expression) else if (expression) {
statement1 statement2
else }
statement2 else {
statement3
} // end if

7/3/2018 1-119
The switch statement
switch (integral expression) {
case 1:
statement1;
break;
case 2, case 3:
statement2;
case 4:
statement3;
break;
default:
statement4;
} //end of switch

7/3/2018 1-120
The while statement
while (expression) {
statement
}
statement is executed as long as
expression is true
statement may not be executed at all
continue expression
 Stops the current iteration of the loop and begins
the next iteration at the top of the loop
7/3/2018 1-121
The for statement
for (initialize; test; update)
statement
statement is executed as long as test is
true
for statement is equivalent to a while
statement
The for loop and arrays
for (ArrayElementType variableName : arrayName)
statement

7/3/2018 1-122
The do statement
do {
statement
} while (expression);
statement is executed until
expression is false
do statement loops at least once

7/3/2018 1-123
The Object class
 Java supports a single class inheritance hierarchy
 With class Object as the root

 More useful methods


 public boolean equals(Object obj)
 protected void finalize()
 public int hashCode()
 public String toString()

7/3/2018 1-124
 String classes
 Class String
 Declaration examples:
 String title;
 String title = “Walls and Mirrors”;
 Assignment example:
 Title = “Walls and Mirrors”;
 String length example:
 title.length();
 Referencing a single character
 title.charAt(0);
 Comparing strings
 title.compareTo(string2);

7/3/2018 1-125
String classes (continued)
 Class String
 Concatenation example:
String monthName = "December";
int day = 31;
int year = 02;
String date = monthName + " " + day + ",
20" + year;

7/3/2018 1-126
 String classes (continued)
 Class StringBuffer
 Creates mutable strings
 Provides same functionality as class String
 More useful methods
 public StringBuffer append(String str)
 public StringBuffer insert(int offset,
String str)
 public StringBuffer delete(int start, int
end)
 public void setCharAt(int index, char ch)
 public StringBuffer replace(int start, int
end, String str)

7/3/2018 1-127
String classes (continued)
 Class StringTokenizer
 Allows a
program to break a string into pieces or tokens
 More useful methods
 public StringTokenizer(String str)
 public StringTokenizer(String str, String
delim)
 public StringTokenizer(String str, String
delim, boolean returnTokens)
 public String nextToken()
 public boolean hasMoreTokens()

7/3/2018 1-128
Exception
 Handles an error during execution
Throw an exception
 To indicate an error during a method execution
Catch an exception
 To deal with the error condition

7/3/2018 1-129
Java provides try-catch blocks
 To handle an exception
Place statement that might throw an
exception within the try block
 Must be followed by one or more catch blocks
 When an exception occurs, control is passed to
catch block
Catch block indicates type of exception you
want to handle

7/3/2018 1-130
try-catch blocks syntax
try {
statement(s);
}
catch (exceptionClass identifier) {
statement(s);
}

Some exceptions from the Java API cannot be


totally ignored
 You must provide a handler for that exception

7/3/2018 1-131
Figure 1-9
Flow of control in a simple Java application
1-132
Types of exception
 Checked exceptions
 Instances of classes that are subclasses of
java.lang.Exception
 Must be handled locally or thrown by the method
 Used when method encounters a serious problem
 Runtime exceptions
 Occur when the error is not considered serious
 Instances of classes that are subclasses of
java.lang.RuntimeException

7/3/2018 1-133
The finally block
 Executed whether or not an exception is thrown
 Can be used even if no catch block is used
 Syntax
finally {
statement(s);
}

7/3/2018 1-134
 throws clause
 Indicates a method may throw an exception
 If an error occurs during its execution
 Syntax
public methodName throws
ExceptionClassName
 throw statement
 Used to throw an exception at any time
 Syntax
throw new exceptionClass(stringArgument);
 You can define your own exception class

7/3/2018 1-135
 Input and output consist of streams
 Streams
 Sequence of characters that either come from or go
to an I/O device
 InputStream - Input stream class
 PrintStream - Output stream class
 java.lang.System provides three stream variables
 System.in – standard input stream
 System.out – standard output stream
 System.err – standard error stream

7/3/2018 1-136
Prior to Java 1.5
BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));

String nextLine = stdin.readLine();

StringTokenizer input = new


StringTokenizer(nextLine);
x = Integer.parseInt(input.nextToken());
y = Integer.parseInt(input.nextToken());

7/3/2018 1-137
Java 1.5 – The Scanner class
int nextValue;
int sum=0;
Scanner kbInput = new Scanner(System.in);
nextValue = kbInput.nextInt();
while (nextValue > 0) {
sum += nextValue;
nextValue = kbInput.nextInt();
} // end while
kbInput.close();

7/3/2018 1-138
Java 1.5 – The Scanner class (continued)
 More useful next methods
 String next();
 boolean nextBoolean();
 double nextDouble();
 float nextFloat();
 int nextInt();
 String nextLine();
 long nextLong();
 short nextShort();

7/3/2018 1-139
Methods print and println
 Write character strings, primitive types, and
objects to System.out
 println terminates a line of output so next one
starts on the next line
 When an object is used with these methods
 Return value of object’s toString method is
displayed
 You usually override this method with your own
implementation
 Problem
 Lack of formatting abilities

7/3/2018 1-140
 Method printf
 C-style formatted output method
 Syntax
printf(String format, Object... args)
 Example:
String name = "Jamie";
int x = 5, y = 6;
int sum = x + y;
System.out.printf("%s, %d + %d = %d",
name, x, y, sum);
//produces output Jamie, 5 + 6 = 11

7/3/2018 1-141
Figure 1-10
Formatting example with printf
1-142
 File
 Sequence of components of the same type that
resides in auxiliary storage
 Can be large and exists after program execution
terminates
 Files vs. arrays
 Files grow in size as needed; arrays have a fixed size
 Files provides both sequential and random access;
arrays provide random access
 File types
 Text and binary (general or nontext) files

7/3/2018 1-143
Designed for easy communication with people
 Flexible and easy to use
 Not efficient with respect to computer time and
storage
End-of-line symbol
 Creates the illusion that a text file contains lines
End-of-file symbol
 Follows the last component in a file
Scanner class can be used to process text files
7/3/2018 1-144
Figure 1-11
A text file with end-of-line and end-of-file symbols
1-145
Example
String fname, lname;
int age;
Scanner fileInput;
File inFile = new File("Ages.dat");
try {
fileInput = new Scanner(inFile);
while (fileInput.hasNext()) {
fname = fileInput.next();
lname = fileInput.next();
age = fileInput.nextInt();
age = fileInput.nextInt();
System.out.printf("%s %s is %d years old.\n",
fname, lname, age);
} // end while
fileInput.close();
} // end try
catch (FileNotFoundException e) {
System.out.println(e);
} // end catch

7/3/2018 1-146
Open a stream to a file
 Before you can read from or write to a file
 Use class FileReader
 Constructor throws a FileNotFoundException

 Stream is usually embedded within an instance of


class BufferedReader
 That provides text processing capabilities
 StringTokenizer
 Used to break up the string returned by readLine
into tokens for easier processing

7/3/2018 1-147
Example
BufferedReader input;
StringTokenizer line;
String inputLine;
try {
input = new BufferedReader(new FileReader("Ages.dat"));
while ((inputLine = input.readLine()) != null) {
line = new StringTokenizer(inputLine);
// process line of data
...
}
} // end try
catch (IOException e) {
System.out.println(e);
System.exit(1); // I/O error, exit the program
} // end catch

7/3/2018 1-148
File output
 You need to open an output stream to the file
 Use class FileWriter
 Stream is usually embedded within an instance of
class PrintWriter
 That provides methods print and println

7/3/2018 1-149
Example
try {
PrintWriter output = new PrintWriter(new
FileWriter("Results.dat"));
output.println("Results of the survey");
output.println("Number of males: " + numMales);
output.println("Number of females: " +
numFemales);
// other code and output appears here...
} // end try
catch (IOException e) {
System.out.println(e);
System.exit(1); // I/O error, exit the program
} // end catch

7/3/2018 1-150
Closing a file
 Syntax
myStream.close();
Adding to a text file
 When opening a file, you can specify if file should
be replaced or appended
 Syntax
PrintWriter ofStream = new
PrintWriter(new
FileOutputStream("Results.dat",
true));
7/3/2018 1-151
Data persistence
 Data stored in a file for later use
Object serialization
 Java mechanism to create persistent objects
Serialization
 Transforming an object into a sequence of bytes
that represents the object
 Serialized objects can be stored to files for later
use
7/3/2018 1-152
Deserialization
 Reverse process
Interface java.io.Serializable
 Needed to save an object using object
serialization
 Contains no methods
Objects referenced by a serialized object are
also serialized
 As long as these objects also implement the
Serializable interface
7/3/2018 1-153
 Java packages
 Provide a mechanism for grouping related classes
 import statement
 Required to use classes contained in other packages
 Object in Java is an instance of a class
 Class
 Data type that specifies data and methods available
 Data fields are either variables or constants
 Methods implement object behavior
 Method parameters are passed by value

7/3/2018 1-154
Comments in Java
 Comment lines
 Multiple-line comments
Java identifier
 Sequence of letters, digits, underscores, and
dollar signs
Primitive data types categories
 Integer, character, floating point, and boolean
Java reference
 Used to locate an object

7/3/2018 1-155
Define named constant with final keyword
Java uses short-circuit evaluation for logical
and relational expressions
Array
 Collection of references that have the same data
type
Selection statements
 if and switch
Iteration statements
 while, for, and do

7/3/2018 1-156
String
 Sequence of characters
 String classes: String, StringBuffer,
StringTokenizer
Exceptions
 Used to handle errors during execution
Files are accessed using Scanner class or
streams
Data persistence and object serialization
7/3/2018 1-157

Potrebbero piacerti anche