Intro to Java
Stoney Jackson
[email protected]
wwwcsif.cs.ucdavis.edu/~jacksoni
What’s the first question you’ve got to ask about a language named Java?
Computer Programming
computer science discipline dealing
with the creation and maintenance
of computer programs
computer programming is just one
activity in the more complex field
of software engineering
Programming Language – a set of rules, symbols, and special
words used to construct programs.
2
Java Programming Language
developed in early 1990s by James Gosling et.
al. as the programming language component of
the Green Project at Sun Microsystems
originally named Oak and intended for
programming networked “smart” consumer
electronics
launched in 1995 as a “programming language
for the Internet”; quickly gained popularity with
the success of the World Wide Web
3
Java Programming Language
currently used by around 5 million software
developers and powers more than 2.5 billion
devices worldwide, from computers to mobile
phones
design goals
simple: derived from C/C++, but easier to learn
secure: built-in support for compile-time and run-time
security
distributed: built to run over networks
object-oriented: built with OO features from the start
4
Java Programming Language
robust: featured memory management, exception
handling, etc.
portable: “write once, run anywhere''
interpreted: “bytecodes” executed by the Java Virtual
Machine
multithreaded, dynamic, high-performance,
architecture-neutral
Bytecodes are the machine language of
the Java virtual machine
5
Java Platform
Java Virtual Machine, or JVM: a virtual
machine, usually implemented as a program,
which interprets the bytecodes produced by the
Java compiler; the JVM converts the bytecode
instructions to equivalent machine language
code of the underlying hardware; compiled Java
programs can be executed on any device that
has a JVM.
6
Can you make coffee with it?
7
It was meant to!!
A programming language for appliances!
8
Must Run on Any Architecture
debug
“WRITE ONCE, RUN ANYWHERE!”
pretty portable
Program Java Java
in Java Compiler Bytecode
Java Virtual Machine Java Virtual Machine
9
Doesn’t Make Coffee Yet
10
How it works…!
Compile-time Environment Compile-time Environment
Class
Loader Java
Class
Bytecode Libraries
Java Verifier
Source
(.java)
Just in
Java Java
Time
Bytecodes Interpreter Java
Compiler
move locally Virtual
or through machine
Java network
Compiler
Runtime System
Operating System
Java
Bytecode
(.class ) Hardware
So What’s Java Good For?
Web applications!
Java Applet
Java Applet
Server
12
Java on the Web: Java Applets
Clients download applets via Web browser
Browser runs applet in a Java Virtual Machine
(JVM)
Applet
Client
Server
Interactive web, security, and client consistency
Slow to download, inconsistent VMs (besides,
flash won this war)
13
Java on the Web: J2EE
Thin clients (minimize download)
Java all “server side”
JSPs
Servlets
Client
Server
EJB
THIS IS WHAT YOU’LL BE DOING!! JDBC
14
Java Features
Well defined primitive data types: int, float, double, char,
etc.
int 4 bytes [–2,147,648, 2,147,483,647]
Control statements similar to C++: if-then-else, switch,
while, for
Interfaces
Exceptions
Concurrency
Packages
Name spaces
Reflection
Applet model
15
The Java programming environment
Java programming language specification
Syntax of Java programs
Defines different constructs and their semantics
Java byte code: Intermediate representation for Java
programs
Java compiler: Transform Java programs into Java byte
code
Java interpreter: Read programs written in Java byte code
and execute them
Java virtual machine: Runtime system that provides
various services to running programs
Java programming environment: Set of libraries that
provide services such as GUI, data structures,etc.
Java enabled browsers: Browsers that include a JVM +
ability to load programs from remote hosts
16
Java: A tiny intro
How are Java programs written?
How are variables declared?
How are expressions specified?
How are control structures defined?
How to define simple methods?
What are classes and objects?
What about exceptions?
17
How are Java programs written?
/* This program displays the message "Hello, World!" on the
standard output device (usually the screen)...This code must be
saved in a file named HelloWorld.java...
*/
// this is the declaration of the HelloWorld class...
public class HelloWorld {
// the main method defines the "starting point" of the execution
// of this program...
public static void main(String[] args) {
// this statement displays the program’s output...
System.out.println("Hello, World!");
} // end of method main...
} // end of class HelloWorld...
18
Fundamental Concepts
Java programs are made up of one or more classes.
A Java class is defined through a class declaration,
which, aside from assigning a name for the class,
also serves to define the structure and behavior
associated with the class.
By convention, Java class names start with an
uppercase letter. Java programs are case-sensitive.
A Java source code file usually contains one class
declaration, but two or more classes can be declared
in one source code file. The file is named after the
class it declares, and uses a .java filename extension.
19
Fundamental Concepts
For a class to be executable, it must be declared
public, and must provide a public static method
called main, with an array argument of type String.
If a file contains more than one class declaration,
only one of the classes can be declared public, and
the file must be named after the sole public class.
The Java compiler (javac) is used to compile a Java
source code file into a class file in bytecode format.
The resulting class file has the same name as the
source code file, but with a .class filename
extension.
The Java Virtual Machine (java) is used to execute
the class file.
20
Variables, Constants, and Data
Types
Primitive Data Types
Variables, Initialization, and Assignment
Constants
Characters
Strings
21
Primitive Data
There are eight primitive data types in Java
Four of them represent integers:
byte, short, int, long
Two of them represent floating point numbers:
float, double
One of them represents characters:
char
And one of them represents boolean values:
boolean
22
Numeric Primitive Data
The difference between the various numeric
primitive types is their size, and therefore
the values they can store:
Type Storage Min Value Max Value
byte 8 bits -128 127
short 16 bits -32,768 32,767
int 32 bits -2,147,483,648 2,147,483,647
long 64 bits < -9 x 1018 > 9 x 1018
float 32 bits +/- 3.4 x 1038 with 7 significant digits
double 64 bits +/- 1.7 x 10308 with 15 significant digits
23
Boolean Primitive Data
A boolean value represents a true or false condition
The reserved words true and false are the only
valid values for a boolean type
boolean done = false;
A boolean variable can represent any two states such
as a light bulb being on or off
boolean isOn = true;
24
Variables
A variable is a name for a location in memory
A variable must be declared by specifying the
variable's name and the type of information that it
will hold
data type variable name
int total;
Multiple variables can be created in one
declaration:
int count, temp, result;
25
Variable Initialization
A variable can be given an initial value in
the declaration with an equals sign
int sum = 0;
int base = 32, max = 149;
When a variable is referenced in a program,
its current value is used
int keys = 88;
System.out.println(“A piano has ” + keys + “ keys.”);
Prints as:
A piano has 88 keys.
26
Assignment
An assignment statement changes the value of a
variable
The equals sign is also the assignment operator
total = 55;
The expression on the right is evaluated and the
result is stored as the value of the variable on the
left
The value previously stored in total is overwritten
You can only assign a value to a variable that is
consistent with the variable's declared type
27
Constants
A constant is an identifier that is similar to a
variable except that it holds the same value
during its entire existence
As the name implies, it is constant, not variable
In Java, we use the reserved word final in the
declaration of a constant
final int MIN_HEIGHT = 69;
Any subsequent assignment statement with
MIN_HEIGHT on the left of the = operator will be
flagged as an error
28
Constants
Constants are useful for three important reasons
First, they give meaning to otherwise unclear literal
values
For example, NUM_STATES means more than the literal 50
Second, they facilitate program maintenance
If a constant is used in multiple places and you need to
change its value later, its value needs to be updated in only
one place
Third, they formally show that a value should not
change, avoiding inadvertent errors by other
programmers
29
Characters
A char variable stores a single character
Character literals are delimited by single
quotes:
'a' 'X' '7' '$' ',' '\n'
Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
30
Character Sets
A character set is an ordered list of
characters, with each character
corresponding to a unique number
A char variable in Java can store any
character from the Unicode character set
The Unicode character set uses sixteen bits
per character, allowing for 65,536 unique
characters
It is an international character set,
containing symbols and characters from
many world languages
31
Characters
The ASCII character set is older and smaller
than Unicode, but is still quite popular (in C
programs)
The ASCII characters are a subset of the
Unicode character set, including:
uppercase letters A, B, C, …
lowercase letters a, b, c, …
punctuation period, semi-colon, …
digits 0, 1, 2, …
special symbols &, |, \, …
control characters carriage return, tab, ...
32
Character Strings
A string of characters can be represented as a
string literal by putting double quotes around
the text:
Examples:
"This is a string literal."
"123 Main Street"
"X"
Note the distinction between a primitive
character ‘X’, which holds only one character,
and a String object, which can hold a sequence
of one or more characters
Every character string is an object in Java,
defined by the String class
33
The println Method
The System.out object represents a destination
(the monitor screen) to which we can send output
System.out.println ("Whatever you are, be a good one.");
object method information provided to the method
name (parameters)
34
The print Method
The System.out object provides another
method
The print method is similar to the println
method, except that it does not start the next
line
Therefore any parameter passed in a call to
the print method will appear on the same
line
System.out.print (“Three… ”);
System.out.print (“Two… ”);
Prints as:
Three… Two…
35
String Concatenation
The string concatenation operator (+) is used
to append one string to the end of another
"Peanut butter " + "and jelly"
It can also be used to append a number to a
string
A string literal cannot be broken across two
lines in a program so we must use
concatenation
System.out.println(“We present the following facts for
your ” + “extracurricular edification”);
36
String Concatenation
The + operator is also used for arithmetic
addition
The function that it performs depends on the
type of the information on which it operates
If both operands are strings, or if one is a string
and one is a number, it performs string
concatenation
If both operands are numeric, it adds them
The + operator is evaluated left to right, but
parentheses can be used to force the order
System.out.println(“24 and 45 concatenated: ” + 24 + 45);
Prints as:
24 and 45 concatenated: 2445
37
String Concatenation
The + operator is evaluated left to right, but
parentheses can be used to force the order
Addition is
Done first
System.out.println(“24 and 45 added: ” + (24 + 45));
Prints as:
Then concatenation is done
24 and 45 added: 69
38
Escape Sequences
What if we want to include the quote character
itself?
The following line would confuse the compiler
because it would interpret the two pairs of
quotes as two strings and the text between the
strings as a syntax error:
System.out.println ("I said "Hello" to you.");
Syntax
A String A String
Error
An escape sequence is a series of characters that
represents a special character
Escape sequences begin with a backslash
character (\)
System.out.println ("I said \"Hello\" to you.");
A String 39
Escape Sequences
• Some Java Escape Sequences
Escape Sequence Meaning
\b backspace
\t tab
\n newline
\r carriage return
\" double quote
\' single quote
\\ backslash
System.out.println(“Roses are red,\n\tViolets are blue,\n” +
• Prints as:
Roses are red,
Violets are blue,
40
Escape Sequences
To put a specified Unicode character into a string
using its code value, use the escape sequence: \uhhhh
where hhhh are the hexadecimal digits for the Unicode
value
Example: Create a string with a temperature value and
the degree symbol:
double temp = 98.6;
System.out.println(
“Body temperature is ” + temp + “ \u00b0F.”);
Prints as:
Body temperature is 98.6 ºF.
41