Introduction
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
What is java?
 Developed by Sun Microsystems
 General-purpose and Object-oriented language
 Widespread acceptance
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
Java Features
 Simple
• no pointers
• automatic garbage collection
• rich pre-defined class library
 Object oriented
• all functions are associated with objects
• potentially better code organization and reuse
 Platform independent
• Same application runs on all platforms
• Java bytecode can run on any JVM, on any platform
• …including mobile phones and other hand-held devices
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
Java Virtual Machine (JVM)
 Steps:
1. Write all source code is in plain text files ending with
the .java extension.
2. Compile those source files into .class files by
the javac compiler.
• A .class file contains bytecodes — the machine language of
the Java Virtual Machine(Java VM).
3. Run the bytecode/.class file using JVM
Copyright © 2014 by John Wiley & Sons. All rights reserved.
4
Java Virtual Machine (JVM)
 Because the Java VM is available on many different
operating systems, the same .class files are capable
of running on any platform.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
Java Versions
Copyright © 2014 by John Wiley & Sons. All rights reserved.
6
Writing first application
 You need:
• The Java SE Development Kit 7 (JDK 7)
• A text editor:
• Simple text editors:
– Notepad, Notepad++ , …..
• Integrated Development Environment (IDE):
– Eclipse, Netbeans, DrJava , …..
Copyright © 2014 by John Wiley & Sons. All rights reserved.
7
QUESTION
 What is the difference between JDK and JRE?
• Java Download page has both!
•
http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-1880261.html
 ANSWER:
• You need to answer the question: Do you want to run Java
programs or do you want to develop Java programs?
• JRE:
• If you want to run Java programs, but not develop them,
download the JRE.
• JDK:
• If you want to develop Java applications, download the Java
Development Kit, or JDK.
• The JDK includes the JRE, so you do not have to download both
separately.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
8
Installing Java JDK
 On Windows:
• http://docs.oracle.com/javase/7/docs/webnotes/install/windo
ws/jdk-installation-windows.html
 On Linux:
• http://docs.oracle.com/javase/7/docs/webnotes/install/linux/
linux-jdk.html
 On Mac OS X:
• http://docs.oracle.com/javase/7/docs/webnotes/install/mac/
mac-jdk.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
9
Your first Program: HelloPrinter.java
 Choice 1: Using simple text editor
• STEP1: Write and save your program in text editor as
HelloPrinter.java
• STEP2: Compile the source file into a .class file
• STEP3: Run the program
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
Programming Question
 In your home directory create a folder cs160. Inside it create a
folder ch01.
 Write HelloPrinter program using gedit editor
 Save program in cs160/ch01 as HelloPrinter.java
 Open a terminal and navigate (cd) to cs160/ch01
 Compile program (if no errors, verify .class file is generated)
 Run program
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
Your first Program: HelloPrinter.java

1.
2.
3.
4.
Choice 2: Using IDE
Start the Java development environment (We use DrJava).
Write a simple program.
Run the program.
Organize your work.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
12
Becoming Familiar with Your
Programming Environment
2. Compile
1. Write and save program (File->save)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3. Run
13
Comments
 Java supports three types of comments:
1. single-line comment:
2. multiline comment
3. document comment
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Identifiers
 Names chosen by the programmer
 E.g. variable names, method names, class names etc.
 Identifiers are subject to the following rules:
• Identifiers may contain letters (both uppercase and lowercase),
digits, and underscores (_).
• Identifiers begin with a letter or underscore.
• There’s no limit on the length of an identifier.
• Lowercase letters are not equivalent to uppercase letters. (A
language in which the case of letters matters is said to be
case-sensitive.)
• Cannot be reserved words (keywords)
Copyright © 2014 by John Wiley & Sons. All rights reserved.
15
Reserved Words
 Here is a list of keywords in the Java programming
language. You cannot use any of the following as
identifiers in your programs.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Multiword Identifiers
 When an identifier consists of multiple words, it’s
important to mark the boundaries between words.
 One way to break up long identifiers is to use
underscores between words:
last_index_of
 Another technique is to capitalize the first letter of
each word after the first:
lastIndexOf
This technique is the one commonly used in Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
Java Conventions
 A rule that we agree to follow, even though it’s not required by
the language
1. Begin a class name with an uppercase letter:
Student
Employee
String
2. Names of variables and methods, never start with an uppercase
letter.
age
 variable name
print()
 method name
3. Identifier names follow camel casing (For subsequent words in name,
first word capitalizd)
totalSalary
getName()
SalariedEmployee
Copyright © 2014 by John Wiley & Sons. All rights reserved.
 variable name
 method name
 class name
18
Variables
 Stores values/state
 Must be declared before they can be used
• static typing
Copyright © 2014 by John Wiley & Sons. All rights reserved.
19
Primitive Data Types
 Java supports eight basic data types known
as primitive types.
integer
floating
point
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
Declaring Variables
 Syntax: <variable type> <variable name> ;
 Example:
int i;
// Declares i to be an int variable
 Several variables can be declared at a time:
int i, j, k;
 It’s often better to declare variables individually.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
21
Initializing Variables
 Assign a value to the variable for the first time.
 us =, the assignment operator:
i = 0;
byte z = 22;
double h = 3.1l3;
char x = ‘x’;
 Variables always need to be initialized before the first time
their value is used.
 You can initialize variables at the time of declaration too:
boolean found=true, contains;
int a, b=20, c;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
22
Changing the Value of a Variable
 The assignment operator can be used both to initialize
a variable and to change the value of the variable later
in the program:
i = 1;
…
i = 2;
// Value of i is now 1
// Value of i is now 2
Copyright © 2014 by John Wiley & Sons. All rights reserved.
23
Literals
 A token that represents a particular number or other
value.
 Examples of int literals:
0
437
30343
 Examples of double literals:
37.0
37.
3.7e1
3.7e+1
.37e2
370e-1
 The only boolean literals are true and false.
 char literals are enclosed within single quotes:
'a'
'z'
'A'
'Z'
Copyright © 2014 by John Wiley & Sons. All rights reserved.
'0'
'9'
'%'
'.'
' '
24
Copyright © 2014 by John Wiley & Sons. All rights reserved.
25
Constants: final
 Represents values that do not change.
 Use keyword final when declaring a variable as a
constant
 Convention:
• use all-uppercase names for constants
• Words separated by underscore(“_”)
final double PENNY_VALUE = 0.01;
final double NICKEL_VALUE = 0.05;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
Class Declaration
 Classes:
• are the fundamental building blocks of Java programs:
• The name of the public class MUST match the name of the file
containing the class:
• Class HelloPrinter must be contained in a file named
HelloPrinter.java
1
2
3
4
5
6
7
8
9
public class HelloPrinter
Class declaration
{
public static void main(String[] args)
{
// Display a greeting in the console window
System.out.println("Hello, World!");
}
}
Class body
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
Methods
 Each class contains declarations of methods.
 Each method contains a sequence of instructions
describing how to carry out a particular task.
 A method is called by specifying the method and its
arguments.
 Every Java application contains a class with a main
method
• When the application starts, the instructions in the main method
are executed
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
1
2
3
4
5
6
7
8
9
public class HelloPrinter
Method
{
declaration
public static void main(String[] args)
{
// Display a greeting in the console window
System.out.println("Hello, World!");
}
}
Method body
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29
Statements
 The body of the main method contains statements.
 Every statement ends with a semicolon (“;”)
 Our method has a single statement:
System.out.println("Hello, World!");
 It prints a line of text:
Hello, World!
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
1
2
3
4
5
6
7
8
9
public class HelloPrinter
{
public static void main(String[] args)
{
// Display a greeting in the console window
System.out.println("Hello, World!");
}
}
Statement 1
Copyright © 2014 by John Wiley & Sons. All rights reserved.
31
Print statement
 System.out.print
• Prints in the same line
 System.out.println
• Prints in a new line
• System.out.println();//Prints in an empty line
 Printing Multiple Items
• The + operator can be used to combine multiple items into a
single string for printing purposes:
int I = 10;
System.out.println(“The value of i is: " + i);
• At least one of the two operands for the + operator must be a
string.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
32
Syntax 1.1 Java Program
Copyright © 2014 by John Wiley & Sons. All rights reserved.
33
Indentation
 Programmers use indentation to indicate nesting.
 An increase in the amount of indentation indicates
an additional level of nesting.
 The HelloPrinter program consists of a statement
nested inside a method nested inside a class:
public class HelloPrinter
{
public static void main(String[] args)
{
// Display a greeting in the console window
System.out.println("Hello, World!");
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
Brace Placement
 Brace placement is another important issue.
 Option1:
• Put each left curly brace at the end of a line.
• The matching right curly brace is lined up with the first character on
that line:
public class HelloPrinter{
public static void main(String[] args) {
// Display a greeting in the console window
System.out.println("Hello, World!");
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
Brace Placement
 Option2:
• Some programmers prefer to put left curly braces on separate
lines:
public class HelloPrinter
{
public static void main(String[] args)
{
// Display a greeting in the console window
System.out.println("Hello, World!");
}
}
• This makes it easier to verify that left and right braces match
up properly. However, program files become longer because
of the additional lines.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
36
Programming Question
 Write a tester class IdentifierDemo that does the
following:
• Create seven variables, one for each of the primitive number
types in Java
• Initialize each variable with any appropriate value.
• Print out the name of each variable and its value.
• Modify the value of each variable with an assignment
statement
• Print out the names of the variables and their new values.
• Next, create a double constants pi with value
3.141592653589793.
• Print the name of the constant and its value.
 What happens if you try to a assign a value to a
constant?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
Answer
public class IdentifierDemo
{
public static void main(String[] args)
{
boolean bln = true; // booleans can only be 'true' or 'false'
byte b = 20;
short s = 500;
char c = '%';
// must use single quotes to denote characters
int i = 1000000;
// decimal notation
float f = 1.5f;
// trailing 'f' distinguishes from double
long l = 2000000L; // trailing 'L' distinguishes from int
IdentifierDemo.java
System.out.println("bln="+bln);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("i="+i);
System.out.println("f="+f);
System.out.println("bln="+bln);
System.out.println("l="+l);
bln
b =
s =
c =
i =
f =
l =
= false; // booleans can only be 'true' or 'false'
70;
800;
't';
// must use single quotes to denote characters
23;
// decimal notation
3.0f;
// trailing 'f' distinguishes from double
5600000L; // trailing 'L' distinguishes from int
System.out.println();
System.out.println("bln="+bln);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("i="+i);
System.out.println("f="+f);
System.out.println("bln="+bln);
System.out.println("l="+l);
final double
pi = 3.141592653589793;
// doubles are higher precision
System.out.println("pi="+pi);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Java Language Basics: Operators
 Java provides a rich set of operators to manipulate
variables.
•
•
•
•
•
•
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
Java Language Basics: Operators
 Arithmetic Operators:
• Assume variables A=10 , B=20
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
QUESTION
 What is the output of following java expressions?
1) 1 / 2
2) 5 / 3
3) 6.1 + 2
4) 7 % 3
5) 1.0/0.0
6) -1.0/0.0
7) 0.0/0.0
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Answer
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Operator Precedence
 What’s the value of 6 + 2 * 3?
• (6 + 2) * 3, which yields 24?
• 6 + (2 * 3), which yields 12?
 Operator precedence resolves issues such as this.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
 *, /, and % take precedence over + and -.
 Examples:
5
8
6
9
6
+
*
/
+
2
3
1
4
2
/
*
+
%
2
5
7
6
3





5 + (2 / 2)
(8 * 3) - 5
6 - (1 * 7)
(9 / 4) + 6
6 + (2 % 3)
Copyright © 2014 by John Wiley & Sons. All rights reserved.





6
19
–1
8
8
45
Associativity
 Precedence rules are of no help when it comes to
determining the value of 1 - 2 - 3.
 Associatively rules come into play when precedence
rules alone aren’t enough.
 The binary +, -, *, /, and % operators are all left
associative:
2 + 3 - 4  (2 + 3) - 4  1
2 * 3 / 4  (2 * 3) / 4  1
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
Parentheses in Expressions
 Parentheses can be used to override normal
precedence and associativity rules.
 Parentheses in the expression (6 + 2) * 3 force the
addition to occur before the multiplication.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
Question
 What is the default parenthesis used in java for
following expression:
 2+3*4+1+4/2
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
Answer
 (((2+(3*4))+1)+(4/2))
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
Compound Assignment Operators
 The compound assignment operators make it easier
to modify the value of a variable.
 A partial list of compound assignment operators:
+= Combines addition and assignment
-= Combines subtraction and assignment
*= Combines multiplication and assignment
/= Combines division and assignment
%= Combines remainder and assignment
Copyright © 2014 by John Wiley & Sons. All rights reserved.
50
Compound Assignment Operators
 Examples:
i += 2;
i -= 2;
i *= 2;
i /= 2;
i %= 2;
//
//
//
//
//
Same
Same
Same
Same
Same
as
as
as
as
as
Copyright © 2014 by John Wiley & Sons. All rights reserved.
i
i
i
i
i
=
=
=
=
=
i
i
i
i
i
+
*
/
%
2;
2;
2;
2;
2;
51
Programming Question
 Write a tester class FtoC that convert a Fahrenheit
temperature to Celsius.
• In the main method declare two variables fahrenheit and celsius.
• Initialize fahrenheit to 98.6.
• Calculate value of celcius using following equation:
• Expected output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
Answer
FtoC.java
// Converts a Fahrenheit temperature to Celsius
public class FtoC {
public static void main(String[] args) {
double fahrenheit = 98.6;
double celsius = (fahrenheit - 32.0) * (5.0 / 9.0);
System.out.println("Celsius equivalent: “ + celsius);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
53
Programming Question
 Note that the ratio 5.0/9.0 and value 32.0 is a
constant in FtoC program. Modify your program so
that you define a constant DEGREE_RATIO (5.0/9.0)
and FREEZING_POINT(32.0) and adjust your equation
accordingly.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
54
Answer
FtoC.java
// Converts a Fahrenheit temperature to Celsius
public class FtoC {
public static void main(String[] args) {
final double FREEZING_POINT = 32.0;
final double DEGREE_RATIO = 5.0 / 9.0;
double fahrenheit = 98.6;
double celsius = (fahrenheit - FREEZING_POINT) * DEGREE_RATIO;
System.out.println("Celsius equivalent: “+celsius);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
Converting Floating-Point Numbers to Integers - Cast
 The compiler disallows the assignment of a double to an
int because it is potentially dangerous
 This is an error:
double balance = total + tax;
int dollars = balance; // Error: Cannot assign double to int
 Use the cast operator (int) to convert a floating-point
value to an integer.
double balance = total + tax;
int dollars = (int) balance;
 Cast discards fractional part
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Syntax 4.2 Cast
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
Packages
 Java classes are grouped into packages.
• java.net package  classes for networking
• java.io package  input/output functions
• javax.swing package  graphical user interface development
• Refere javadoc API
 To use a class in a package, you must import the package
• E.g. to use Rectangle class in java.awt package:
import java.awt.Rectangle;
 Put the line at the top of your program.
 You DON’T need to import classes in the java.lang package
such as String and System.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
58
Syntax 2.4 Importing a Class from a
Package
Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
Read user input
 Use a class called Scanner to read keyboard input.
 To use the Scanner class, import it by placing the
following at the top of your program file (before class
definition):
import java.util.Scanner
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
2. Obtain a Scanner object:
Scanner in = new Scanner(System.in);
1. Prompt user a message asking to input data:
System.out.println(“Enter the Fahrenheit temperature : ”);
By default, a scanner uses white space to separate tokens.
White space characters include blanks, tabs, and line terminators.
2. Read the user input:
•
•
Read int: use nextInt() method
Read double: nextDouble() method
•
Read string: next() method
Refer Scanner page in Oracle JavaAPI
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
 nextInt() example:
System.out.print("Please enter the number of bottles: ");
int bottles = in.nextInt();
• When the nextInt method is called,
• The program waits until the user types a number and
presses the Enter key;
• After the user supplies the input, the number is placed into
the bottles variable;
• The program continues.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
 To read different and multiple inputs from user,
creating one scanner object is enough.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
63
Programming Question
 Write a tester class ScannerDemo.java that accepts two
numbers from user and prints the sum.
 Sample output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
64
Answer
ScannerDemo.java
import java.util.Scanner;
public class ScannerDemo
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter number 1: ");
int n1 = in.nextInt();
System.out.print("Enter number 2: ");
int n2 = in.nextInt();
int total = n1 + n2;
System.out.println(n1+ " + "+n2+ " = "+total);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
65
Formatted Output
 Use the printf method to specify how values should be formatted.
 Suppose you have a variable price with value 1.215962441314554
 If you use
System.out.println(price)
Will print :
1.215962441314554
 If you want a formatted output(e.g. only 2 decimal points displayed):
System.out.printf("%.2f", price);
Will print:
1.22
Copyright © 2014 by John Wiley & Sons. All rights reserved.
66
Formatted Output
 You can also specify a field width:
System.out.printf("%10.2f", price);
This prints 10 characters, six spaces followed by the four characters
1.22
 This command
System.out.printf("Price per liter:%10.2f", price);
Prints
Price per liter: 1.22
Copyright © 2014 by John Wiley & Sons. All rights reserved.
67
Formatted Output
Copyright © 2014 by John Wiley & Sons. All rights reserved.
68
Formatted Output
 You can print multiple values with a single call to the
printf method.
 Example
System.out.printf("Quantity: %d Total: %10.2f",quantity, total);
 Output explained:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
69