Part 1:
Java as an Object-oriented
Programming Language
00. Introduction to Java
Java History
James Gosling and Sun Microsystems
Oak
Java, May 20, 1995, Sun World
HotJava
The first Java-enabled Web browser
JDK Evolutions
J2SE, J2ME, and J2EE
16/09/23 2
JDK Editions
Java Standard Edition (J2SE)
J2SE can be used to develop client-side standalone applications or applets.
Java Enterprise Edition (J2EE)
J2EE can be used to develop server-side applications such as Java servlets and Java
ServerPages.
Java Micro Edition (J2ME).
J2ME can be used to develop applications for mobile devices such as cell phones.
16/09/23 3
Java IDE Tools
Text Pad
Net Bean
Eclipse
InteliJ
16/09/23 4
Your first Java program!
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}
What does this code output (print to the user) when you
run (execute) it?
5
Compiling a program
Before you run a program, you must compile it.
compiler: Translates a computer program
written in one language (i.e., Java) to another
language (i.e., byte code)
Compile (javac) Execute (java)
source code byte code output
(Hello.java) (Hello.class)
6
The Java Virtual Machine
(JVM, or VM)
The Java Virtual Machine executes byte code
Use the “java” command to execute it
It only understands byte code (“.class” files)
The VM makes Java a bit different from older
programming languages (C, C++)
It’s an extra step; compilers for other languages directly
produce machine code
It’s slower
But it allows the same byte code to run on any machine
with a VM
System.out.println
System.out.println: A statement to print a line
of output to the console.
pronounced “print-linn”
Two ways to use System.out.println:
System.out.println("<message>");
Prints the given message as a line of text to the console.
System.out.println();
Prints a blank line to the console.
8
A Java Program
Class name
Main method
Statements
Statement terminator
Reserved words
Comments
Blocks
9
Class Name
Every Java program must have at least one class. Each class
has a name. By convention, class names start with an
uppercase letter. In this example, the class name is Welcome.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
10
Main Method
Line 2 defines the main method. In order to run a class, the
class must contain a method named main. The program is
executed from the main method.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
11
Statement
A statement represents an action or a sequence of
actions. The statement System.out.println("Welcome to
Java!") in the program in Listing 1.1 is a statement to
display the greeting "Welcome to Java!“.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
12
Statement Terminator
Every statement in Java ends with a semicolon (;).
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
13
Reserved words
Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other
purposes in the program. For example, when the compiler
sees the word class, it understands that the word after class
is the name for the class.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
14
Blocks
A pair of braces in a program forms a block that groups
components of a program.
public class Test {
Class block
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Method block
}
}
15
Special Symbols
Character Name Description
{} Opening and closing Denotes a block to enclose statements.
braces
() Opening and closing Used with methods.
parentheses
[] Opening and closing Denotes an array.
brackets
// Double slashes Precedes a comment line.
" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.
16
{ …}
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
17
( … )
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
18
;
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
19
// …
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
20
"…"
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
21
Programming Style and Documentation
Appropriate Comments
Naming Conventions
Proper Indentation and Spacing
Lines
Block Styles
22
Appropriate Comments
Include a summary at the beginning of the program to explain
what the program does, its key features, its supporting data
structures, and any unique techniques it uses.
Include your name, class section, instructor, date, and a brief
description at the beginning of the program.
23
Naming Conventions
Choose meaningful and descriptive names.
Class names:
Capitalize the first letter of each word in the name.
For example, the class name
ComputeExpression.
24
Block Styles
Use end-of-line style for braces.
Next-line public class Test
style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}
End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}
25
Programming Errors
Syntax Errors
Detected by the compiler
Runtime Errors
Causes the program to abort
Logic Errors
Produces incorrect result
26
Syntax Errors
public class ShowSyntaxErrors {
public static main(String[] args) {
System.out.println("Welcome to Java);
}
}
27
Runtime Errors
public class ShowRuntimeErrors {
public static void main(String[] args) {
System.out.println(1 / 0);
}
}
28
Logic Errors
public class ShowLogicErrors {
public static void main(String[] args) {
System.out.print("Celsius 35 is ");
System.out.print("Fahrenheit ");
System.out.println((9 / 5) * 35 + 32);
}
}
29
Primitive data types,
expressions, and
variables
30
Primitive types
Java has eight primitive types. Here are two examples:
Name Description Examples
int integers 42, -3, 0, 926394
double real numbers 3.4, -2.53, 91.4e3
Numbers with a decimal point are treated as real numbers.
Question: Isn’t every integer a real number? Why bother?
31
Other Primitive Data Types
Discrete Types
byte
Continuous Types
short float
int double
long
Non-numeric Types
boolean
char
32
Data Type Representations
Type Representation Bits Bytes #Values
boolean true or false 1 N/A 2
char ‘a’ or ‘7’ or ‘\n’ 16 2 216 = 65,536
byte …,-2,-1,0,1,2,… 8 1 28 = 256
short …,-2,-1,0,1,2,… 16 2 216 = 65,536
int …,-2,-1,0,1,2,… 4 > 4.29 million
long …,-2,-1,0,1,2,… 8 > 18 quintillion
float 0.0, 10.5, -100.7 32
double 0.0, 10.5, -100.7 64
Precision in real numbers
The computer internally represents real numbers in an
imprecise way.
Example:
System.out.println(0.1 + 0.2);
The output is 0.30000000000000004!
34
Concatenation: Operating on strings
string concatenation: Using the + operator between a string
and another value to make a longer string.
Examples:
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc“ is "3abc"
"abc" + 9 * 3 is "abc27" (what happened here?)
"1" + 1 is "11"
4 - 1 + "abc“ is "3abc"
"abc" + 4 - 1 causes a compiler error. Why?
35
Overflow example
int n = 2000000000;
System.out.println(n * n);
// output: -1651507200
the result of n*n is 4,000,000,000,000,000,000 which needs 64-bits:
---------- high-order bytes -------
00110111 10000010 11011010 11001110
---------- low order bytes --------
10011101 10010000 00000000 00000000
In the case of overflow, Java discards the high-order bytes, retaining only
the low-order ones
In this case, the low order bytes represent 1651507200, and since the right
most bit is a 1 the sign value is negative.
Declaring variables
To create a variable, it must be declared.
Variable declaration syntax:
<type> <name>;
Convention: Variable identifiers follow the same
rules as method names.
Examples:
int x;
double myGPA;
int varName;
37
Boolean Arithmetic
38
The boolean Type
The boolean type has two possible values:
true and false
boolean variables are declared and initialized
just like other primitive data types:
boolean iAmSoSmrt = false; //just like int i =
2;
boolean minor = (age < 21); //just like int x =
y*2;
39
Relational expressions
Relational expressions have
numeric arguments and
boolean values.
They use one of the following six relational operators:
Operator Meaning Example Value
== equals 1 + 1 == 2 true
!= does not equal 3.2 != 2.5 true
< less than 10 < 5 false
> greater than 10 > 5 true
<= less than or equal to 126 <= 100 false
>= greater than or equal to 5.0 >= 5.0 true
40
Class Constants
A class constant is a variable
whose scope is the entire class, and
whose value can never change after it has been initialized.
To give it the right scope, simply declare it right inside the class:
public class MyClass {
public static final int myConstant = 4;
}
The final keyword means its value can’t be changed.
Scanner objects
42
Interactive programs
We have written programs that print console output.
It is also possible to read input from the console.
The user types the input into the console.
The program uses the input to do something.
Such a program is called an interactive program.
43
Scanner
Constructing a Scanner object to read the console:
Scanner <name> = new Scanner(System.in);
Example:
Scanner console = new Scanner(System.in);
44
Scanner methods
Some methods of Scanner:
Method Description
nextInt() reads and returns user input as an int
nextDouble() reads and returns user input as a double
next() reads and returns user input as a String
Each of these methods pauses your program until
the user types input and presses Enter.
Then the value typed is returned to your program.
45
Using a Scanner object
Example:
System.out.print("How old are you? "); // prompt
int age = console.nextInt();
System.out.println("You'll be 40 in " + (40 -
age)
+ " years.");
prompt: A message printed to the user, telling them
what input to type.
46
Input tokens
token: A unit of user input, as read by the Scanner.
Tokens are separated by whitespace (spaces, tabs, new lines).
How many tokens appear on the following line of input?
23 John Smith 42.0 "Hello world"
When the token doesn't match the type the Scanner tries to read,
the program crashes.
Example:
System.out.print("What is your age? ");
int age = console.nextInt();
Sample Run:
What is your age? Timmy
InputMismatchException:
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
...
47
Importing classes
Java class libraries: A large set of Java classes available
for you to use.
Classes are grouped into packages.
To use the classes from a package, you must include an
import declaration at the top of your program.
Scanner is in a package named java.util
Import declaration, general syntax:
import <package name>.*;
To use Scanner, put this at the start of your program:
import java.util.*;
48
code.ptit.edu.vn
49