UniversityofEducationOkaraCampus
1
Introduction To Java
Programming
You will learn about the process of creating Java programs and
constructs for input, output, branching, looping, as well some of
the history behind Java’s development.
Inam Ul-Haq
Lecturer in Computer Science
MS Computer Science (Sweden)
University of Education, Okara Campus
Inam.bth@gmail.com, organizer@dfd-charity.com
inam@acm.org, inam@ue.edu.pk , inkh10@student.bth.se
Lecture 2, Part-2
Common Java Operators / Operator
Precedence
Precedence
level
Operator Description Associativity
1 i++
i--
Post-increment
Post-decrement
Right to left
2 ++i
--i
+
-
!
~
(type)
Pre-increment
Pre-decrement
Unary plus
Unary minus
Logical negation
Bitwise complement
Cast
Right to left
Common Java Operators / Operator
Precedence
Precedence
level
Operator Description Associativity
3 *
/
%
Multiplication
Division
Remainder/modulus
Left to right
4 +
-
Addition or String
concatenation
Subtraction
Left to right
5 <<
>>
Left bitwise shift
Right bitwise shift
Left to right
Common Java Operators / Operator
Precedence
Precedenc
e level
Operator Description Associativity
6 <
<=
>
>=
Less than
Less than, equal to
Greater than
Greater than, equal to
Left to right
7 = =
!=
Equal to
Not equal to
Left to right
8 & Bitwise AND Left to right
9 ^ Bitwise exclusive OR Left to right
Common Java Operators / Operator
Precedence
Precedence
level
Operator Description Associativity
10 | Bitwise OR Left to right
11 && Logical AND Left to right
12 || Logical OR Left to right
Common Java Operators / Operator
Precedence
Precedence
level
Operator Description Associativity
13 =
+=
-=
*=
/=
%=
&=
^=
|=
<<=
>>=
Assignment
Add, assignment
Subtract, assignment
Multiply, assignment
Division, assignment
Remainder, assignment
Bitwise AND, assignment
Bitwise XOR, assignment
Bitwise OR, assignment
Left shift, assignment
Right shift, assignment
Right to left
Post/Pre Operators
The name of the example is: Order1.java
public class Order1
{
public static void main (String [] args)
{
int num = 5;
System.out.println(num);
num++;
System.out.println(num);
++num;
System.out.println(num);
System.out.println(++num);
System.out.println(num++);
}
}
UniversityofEducationOkaraCampus
7
Pre=++num
Post=num++
Post/Pre Operators (2)
The name of the example is: Order2.java
public class Order2
{
public static void main (String [] args)
{
int num1;
int num2;
num1 = 5;
num2 = ++num1 * num1++;
System.out.println("num1=" + num1);
System.out.println("num2=" + num2);
}
}
UniversityofEducationOkaraCampus
8
Pre=++num
Post=num++
Unary Operator/Order/Associativity
The name of the example: Unary_Order3.java
public class Unary_Order3.java
{
public static void main (String [] args)
{
int num = 5;
float fl;
System.out.println(num);
num = num * -num;
System.out.println(num);
}
}
UniversityofEducationOkaraCampus
9
Pre=+num
Accessing Pre-Created Java
Libraries
• It’s accomplished by placing an ‘import’ of the appropriate
library at the top of your program.
• Syntax:
import <Full library name>;
• Example:
import java.util.Scanner;
UniversityofEducationOkaraCampus
10
Getting Text Input
• You can use the pre-written methods (functions) in the
Scanner class.
• General structure:
UniversityofEducationOkaraCampus
11
import java.util.Scanner;
main (String [] args)
{
Scanner <name of scanner> = new Scanner (System.in);
<variable> = <name of scanner> .<method> ();
}
Creating a
scanner object
(something
that can scan
user input)
Using the capability of
the scanner object
(actually getting user
input)
Getting Text Input (2)
The name of the online example: MyInput.java
import java.util.Scanner;
public class MyInput
{
public static void main (String [] args)
{
String str1;
int num1;
Scanner in = new Scanner (System.in);
System.out.print ("Type in an integer: ");
num1 = in.nextInt ();
System.out.print ("Type in a line: ");
in.nextLine ();
str1 = in.nextLine ();
System.out.println ("num1:" +num1 +"t str1:" + str1);
}
}
UniversityofEducationOkaraCampus
12
Useful Methods Of Class
Scanner1
• nextInt () //input for integer
• nextLong ()
• nextFloat ()
• nextDouble ()
• nextLine (); //input for string
UniversityofEducationOkaraCampus
13
1 Online documentation: http://java.sun.com/javase/6/docs/api/
Reading A Single Character
• Text menu driven programs may require this capability.
• Example:
GAME OPTIONS
(a)dd a new player
(l)oad a saved game
(s)ave game
(q)uit game
• There’s different ways of handling this problem but one
approach is to extract the first character from the string.
• Partial example:
String s = “foo“;
System.out.println(s.charAt(0));
UniversityofEducationOkaraCampus
14
Reading A Single Character
• Name of the (more complete example): MyInputChar.java
import java.util.Scanner;
public class MyInputChar
{
public static void main (String [] args)
{
final int FIRST = 0; //contant
String selection;
Scanner in = new Scanner (System.in);
System.out.println("GAME OPTIONS");
System.out.println("(a)dd a new player");
System.out.println("(l)oad a saved game");
System.out.println("(s)ave game");
System.out.println("(q)uit game");
System.out.print("Enter your selection: ");
UniversityofEducationOkaraCampus
15
selection = in.nextLine ();
System.out.println ("Selection: " + selection.charAt(FIRST));
}
}
Decision Making In Java
• Java decision making constructs
• if
• if, else
• if, else-if
• switch
UniversityofEducationOkaraCampus
16
Decision Making: Logical Operators
Logical Operation Python Java
AND and &&
OR or ||
NOT not, ! !
Decision Making: If
Format:
if (Boolean Expression)
Body
Example:
if (x != y)
System.out.println("X and Y are not equal");
if ((x > 0) && (y > 0))
{
System.out.println("X and Y are positive");
}
UniversityofEducationOkaraCampus
17
•Indenting the body of
the branch is an
important stylistic
requirement of Java
but unlike Python it is
not enforced by the
syntax of the
language.
•What distinguishes the
body is either:
1.A semi colon (single
statement branch)
2.Braces (a body that
consists of multiple
statements)
Decision Making: If, Else
Format:
if (Boolean expression)
Body of if
else
Body of else
Example:
if (x < 0)
System.out.println("X is negative");
else
System.out.println("X is non-negative");
UniversityofEducationOkaraCampus
18
Example Program: If-Else
• Name of the example: BranchingExample1.java
import java.util.Scanner;
public class BranchingExample1
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
final int WINNING_NUMBER = 131313;
int playerNumber = -1;
System.out.print("Enter ticket number: ");
playerNumber = in.nextInt();
if (playerNumber == WINNING_NUMBER)
System.out.println("You're a winner!");
else
System.out.println("Try again.");
}
}
UniversityofEducationOkaraCampus
19
If, Else-If (1)
Format:
if (Boolean expression)
Body of if
else if (Boolean expression)
Body of first else-if
: : :
else if (Boolean expression)
Body of last else-if
else
Body of else
UniversityofEducationOkaraCampus
20
If, Else-If (2)
Name of the online example: BranchingExample.java
import java.util.Scanner;
public class BranchingExample2
{
public static void main (String [] args)
{
Scanner in = new Scanner(System.in);
int gpa = -1;
System.out.print("Enter letter grade: ");
gpa = in.nextInt();
UniversityofEducationOkaraCampus
21
If, Else-If (3)
if (gpa == 4)
System.out.println("A");
else if (gpa == 3)
System.out.println("B");
else if (gpa == 2)
System.out.println("C");
else if (gpa == 1)
System.out.println("D");
else if (gpa == 0)
System.out.println("F");
else
System.out.println("Invalid letter grade");
}
}
UniversityofEducationOkaraCampus
22
Alternative To Multiple Else-If’s: Switch
(1)
Format (character-based switch):
switch (character variable name)
{
case '<character value>':
Body
break;
case '<character value>':
Body
break;
:
default:
Body
}
1Thetypeofvariableinthebracketscanbeabyte,char,short,intorlong
UniversityofEducationOkaraCampus
23
Important! The break is
mandatory to separate
Boolean expressions
(must be used in all but
the last)
Switch: When To Use/When Not To Use
(2)
• Name of the example: SwitchExample.java
import java.util.Scanner;
public class SwitchExample
{
public static void main (String [] args)
{
final int FIRST = 0;
String line;
char letter;
int gpa;
Scanner in = new Scanner (System.in);
System.out.print("Enter letter grade: ");
UniversityofEducationOkaraCampus
24
Switch: When To Use/When Not To Use
(3)
line = in.nextLine ();
letter = line.charAt(FIRST);
switch (letter)
{
case 'A':
case 'a':
gpa = 4;
break;
case 'B':
case 'b':
gpa = 3;
break;
case 'C':
case 'c':
gpa = 2;
break;
UniversityofEducationOkaraCampus
25
Switch: When To Use/When Not To Use
(4)
case 'D':
case 'd':
gpa = 1;
break;
case 'F':
case 'f':
gpa = 0;
break;
default:
gpa = -1;
}
System.out.println("Letter grade: " + letter);
System.out.println("Grade point: " + gpa);
}
}
UniversityofEducationOkaraCampus
26
Switch: When To Use/When Not To Use
(5)
• When a switch can’t be used:
• For data types other than characters or integers
• Boolean expressions that aren’t mutually exclusive:
• As shown a switch can replace an ‘if-elseif’ construct
• A switch cannot replace a series of ‘if’ branches).
• Example when not to use a switch:
if (x > 0)
System.out.print(“X coordinate right of the origin”);
If (y > 0)
System.out.print(“Y coordinate above the origin”);
• Example of when not to use a switch:
String name = in.readLine()
switch (name)
{
}
UniversityofEducationOkaraCampus
27
Loops
Java Pre-test loops
• For
• While
Java Post-test loop
• Do-while
UniversityofEducationOkaraCampus
28
While Loops
Format:
while (Boolean expression)
Body
Example:
int i = 1;
while (i <= 4)
{
// Call function
createNewPlayer();
i = i + 1;
}
For Loops
Format:
for (initialization; Boolean expression; update control)
Body
Example:
for (i = 1; i <= 4; i++)
{
// Call function
createNewPlayer();
i = i + 1;
}
Post-Test Loop: Do-While
• Recall: Post-test loops evaluate the Boolean expression after the
body of the loop has executed.
• This means that post test loops will execute one or more times.
• Pre-test loops generally execute zero or more times.
UniversityofEducationOkaraCampus
29
Format:
do
Body
while (Boolean expression);
Example:
char ch = 'A';
do
{
System.out.println(ch);
ch++;
}
while (ch <= 'K');
Contrasting Pre Vs. Post Test
Loops
• Although slightly more work to implement the while loop is
the most powerful type of loop.
• Program capabilities that are implemented with either a ‘for’
or ‘do-while’ loop can be implemented with a while loop.
• Implementing a post test loop requires that the loop control
be primed correctly (set to a value such that the Boolean
expression will evaluate to true the first it’s checked).
UniversityofEducationOkaraCampus
30
Example: Post-Test
Implementation
• Name of the online example: PostTestExample.java
public class PostTestExample
{
public static void main (String [] args)
{
final int FIRST = 0;
Scanner in = new Scanner(System.in);
char answer;
String temp;
do
{
System.out.println("JT's note: Pretend that we play our game");
System.out.print("Play again? Enter 'q' to quit: ");
temp = in.nextLine();
answer = temp.charAt(FIRST);
} while ((answer != 'q') && (answer != 'Q'));
}
}
UniversityofEducationOkaraCampus
31
Example: Pre-Test
Implementation
• Name of the online example: PreTestExample.java
public class PreTestExample
{
public static void main (String [] args)
{
final int FIRST = 0;
Scanner in = new Scanner(System.in);
char answer = ' ';
String temp;
while ((answer != 'q') && (answer != 'Q'))
{
System.out.println("JT's note: Pretend that we play our game");
System.out.print("Play again? Enter 'q' to quit: ");
temp = in.nextLine();
answer = temp.charAt(FIRST);
}
}
}
UniversityofEducationOkaraCampus
32
Now What Happens???
import java.util.Scanner;
public class PreTestExample
{
public static void main (String [] args)
{
final int FIRST = 0;
Scanner in = new Scanner(System.in);
char answer = ' ';
String temp;
while ((answer != 'q') && (answer != 'Q'))
System.out.println("JT's note: Pretend that we play our game");
System.out.print("Play again? Enter 'q' to quit: ");
temp = in.nextLine();
answer = temp.charAt(FIRST);
}
}
UniversityofEducationOkaraCampus
33
After This Section You Should Now Know
• How Java was developed and the impact of it's roots on the
language
• The basic structure required in creating a simple Java program as
well as how to compile and run programs
• How to document a Java program
• How to perform text based input and output in Java
• The declaration of constants and variables
• What are the common Java operators and how they work
• The structure and syntax of decision making and looping constructs
UniversityofEducationOkaraCampus
34
Special Thanks to James Tam
The End
let’s go for tea
UniversityofEducationOkaraCampus
35

More Related Content

PPT
Introduction to java programming part 1
PPTX
java: basics, user input, data type, constructor
PDF
C progrmming
PPT
Java tutorial PPT
PPT
Lecture 3 java basics
PPTX
Core java online training
PPTX
Object oriented programming-with_java
PDF
Basic Java Programming
Introduction to java programming part 1
java: basics, user input, data type, constructor
C progrmming
Java tutorial PPT
Lecture 3 java basics
Core java online training
Object oriented programming-with_java
Basic Java Programming

What's hot (20)

PPT
Java Basics
PPT
Java platform
PPTX
Core java
PPTX
Introduction to java 101
PDF
Java basics notes
PPTX
Chapter 2.1
PPTX
Java features
PPTX
Java 101 intro to programming with java
PPTX
Java basics
PPTX
Basics of Java
PPSX
Java &amp; advanced java
PPT
JAVA BASICS
PDF
Core Java Tutorial
PPSX
Short notes of oop with java
PDF
Java Presentation For Syntax
PPTX
Java Notes
PPTX
Core Java Tutorials by Mahika Tutorials
PPTX
Java programming language
PDF
Java chapter 1
DOCX
Notes of java first unit
Java Basics
Java platform
Core java
Introduction to java 101
Java basics notes
Chapter 2.1
Java features
Java 101 intro to programming with java
Java basics
Basics of Java
Java &amp; advanced java
JAVA BASICS
Core Java Tutorial
Short notes of oop with java
Java Presentation For Syntax
Java Notes
Core Java Tutorials by Mahika Tutorials
Java programming language
Java chapter 1
Notes of java first unit
Ad

Viewers also liked (20)

PPT
System Development Proecess
PPTX
Internet & Animal Sciences
PPTX
Itertaive process-development model
PPT
PPTX
How Information System is Implmanted in an Organization
PPTX
Zoology Related Software
PPT
Report Management System
PPT
Lecture 1 Information System
PPT
transaction processing system
PPT
Information System & Organizational System
PPTX
Protoytyping Model
PPT
Introduction to programming languages part 2
PPTX
Information System's Planning and Change Management
PPT
Introduction to programming languages part 1
PPTX
Lect 2 assessing the technology landscape
PPTX
PPTX
Human Computer Interface of an Information System
PPTX
Computer Sided Software Engineering
PPT
E Commerce and TPS
System Development Proecess
Internet & Animal Sciences
Itertaive process-development model
How Information System is Implmanted in an Organization
Zoology Related Software
Report Management System
Lecture 1 Information System
transaction processing system
Information System & Organizational System
Protoytyping Model
Introduction to programming languages part 2
Information System's Planning and Change Management
Introduction to programming languages part 1
Lect 2 assessing the technology landscape
Human Computer Interface of an Information System
Computer Sided Software Engineering
E Commerce and TPS
Ad

Similar to Introduction to java programming part 2 (20)

PPT
Introduction to Java Programming Part 2
PPT
Learning Java 1 – Introduction
PDF
4CS4-25-Java-Lab-Manual.pdf
PPTX
Unit-1 Data Types and Operators.pptx to computers
PPTX
Java Notes by C. Sreedhar, GPREC
PPT
Java API, Exceptions and IO
PPTX
JAVA(module1).pptx
PPTX
Programming in java basics
PDF
Exception handling
PPT
Java Fundamentals.pptJava Fundamentals.ppt
PDF
Java Interview Questions PDF By ScholarHat
PPTX
Java fundamentals
DOCX
Autoboxing and unboxing
PPTX
Java Programs
ODP
Synapseindia reviews.odp.
PPTX
Java Language fundamental
PDF
Beyond PITS, Functional Principles for Software Architecture
PPT
Java findamentals1
PPT
Java findamentals1
PPT
Java findamentals1
Introduction to Java Programming Part 2
Learning Java 1 – Introduction
4CS4-25-Java-Lab-Manual.pdf
Unit-1 Data Types and Operators.pptx to computers
Java Notes by C. Sreedhar, GPREC
Java API, Exceptions and IO
JAVA(module1).pptx
Programming in java basics
Exception handling
Java Fundamentals.pptJava Fundamentals.ppt
Java Interview Questions PDF By ScholarHat
Java fundamentals
Autoboxing and unboxing
Java Programs
Synapseindia reviews.odp.
Java Language fundamental
Beyond PITS, Functional Principles for Software Architecture
Java findamentals1
Java findamentals1
Java findamentals1

More from university of education,Lahore (20)

PPT
Activites and Time Planning
PPT
Classical Encryption Techniques
PPT
Activites and Time Planning
PPTX
OSI Security Architecture
PPTX
Network Security Terminologies
PPT
Project Scheduling, Planning and Risk Management
PPTX
Software Testing and Debugging
PPTX
PPT
Enterprise Application Integration
PPTX
PPTX
Itertaive Process Development
PPTX
Computer Aided Software Engineering Nayab Awan
PPTX
system level requirements gathering and analysis
Activites and Time Planning
Classical Encryption Techniques
Activites and Time Planning
OSI Security Architecture
Network Security Terminologies
Project Scheduling, Planning and Risk Management
Software Testing and Debugging
Enterprise Application Integration
Itertaive Process Development
Computer Aided Software Engineering Nayab Awan
system level requirements gathering and analysis

Recently uploaded (20)

PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
PDF
Empowerment Technology for Senior High School Guide
PDF
Journal of Dental Science - UDMY (2020).pdf
PDF
Race Reva University – Shaping Future Leaders in Artificial Intelligence
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
HVAC Specification 2024 according to central public works department
PDF
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
PDF
My India Quiz Book_20210205121199924.pdf
PDF
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PDF
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
PDF
Climate and Adaptation MCQs class 7 from chatgpt
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
PPTX
Module on health assessment of CHN. pptx
PDF
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
PDF
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
PDF
FORM 1 BIOLOGY MIND MAPS and their schemes
PPTX
Share_Module_2_Power_conflict_and_negotiation.pptx
PDF
Journal of Dental Science - UDMY (2021).pdf
B.Sc. DS Unit 2 Software Engineering.pptx
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 2).pdf
Empowerment Technology for Senior High School Guide
Journal of Dental Science - UDMY (2020).pdf
Race Reva University – Shaping Future Leaders in Artificial Intelligence
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
HVAC Specification 2024 according to central public works department
LIFE & LIVING TRILOGY - PART (3) REALITY & MYSTERY.pdf
My India Quiz Book_20210205121199924.pdf
BP 505 T. PHARMACEUTICAL JURISPRUDENCE (UNIT 1).pdf
A powerpoint presentation on the Revised K-10 Science Shaping Paper
CISA (Certified Information Systems Auditor) Domain-Wise Summary.pdf
Climate and Adaptation MCQs class 7 from chatgpt
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
Module on health assessment of CHN. pptx
BP 704 T. NOVEL DRUG DELIVERY SYSTEMS (UNIT 1)
LEARNERS WITH ADDITIONAL NEEDS ProfEd Topic
FORM 1 BIOLOGY MIND MAPS and their schemes
Share_Module_2_Power_conflict_and_negotiation.pptx
Journal of Dental Science - UDMY (2021).pdf

Introduction to java programming part 2

  • 1. UniversityofEducationOkaraCampus 1 Introduction To Java Programming You will learn about the process of creating Java programs and constructs for input, output, branching, looping, as well some of the history behind Java’s development. Inam Ul-Haq Lecturer in Computer Science MS Computer Science (Sweden) University of Education, Okara Campus [email protected], [email protected] [email protected], [email protected] , [email protected] Lecture 2, Part-2
  • 2. Common Java Operators / Operator Precedence Precedence level Operator Description Associativity 1 i++ i-- Post-increment Post-decrement Right to left 2 ++i --i + - ! ~ (type) Pre-increment Pre-decrement Unary plus Unary minus Logical negation Bitwise complement Cast Right to left
  • 3. Common Java Operators / Operator Precedence Precedence level Operator Description Associativity 3 * / % Multiplication Division Remainder/modulus Left to right 4 + - Addition or String concatenation Subtraction Left to right 5 << >> Left bitwise shift Right bitwise shift Left to right
  • 4. Common Java Operators / Operator Precedence Precedenc e level Operator Description Associativity 6 < <= > >= Less than Less than, equal to Greater than Greater than, equal to Left to right 7 = = != Equal to Not equal to Left to right 8 & Bitwise AND Left to right 9 ^ Bitwise exclusive OR Left to right
  • 5. Common Java Operators / Operator Precedence Precedence level Operator Description Associativity 10 | Bitwise OR Left to right 11 && Logical AND Left to right 12 || Logical OR Left to right
  • 6. Common Java Operators / Operator Precedence Precedence level Operator Description Associativity 13 = += -= *= /= %= &= ^= |= <<= >>= Assignment Add, assignment Subtract, assignment Multiply, assignment Division, assignment Remainder, assignment Bitwise AND, assignment Bitwise XOR, assignment Bitwise OR, assignment Left shift, assignment Right shift, assignment Right to left
  • 7. Post/Pre Operators The name of the example is: Order1.java public class Order1 { public static void main (String [] args) { int num = 5; System.out.println(num); num++; System.out.println(num); ++num; System.out.println(num); System.out.println(++num); System.out.println(num++); } } UniversityofEducationOkaraCampus 7 Pre=++num Post=num++
  • 8. Post/Pre Operators (2) The name of the example is: Order2.java public class Order2 { public static void main (String [] args) { int num1; int num2; num1 = 5; num2 = ++num1 * num1++; System.out.println("num1=" + num1); System.out.println("num2=" + num2); } } UniversityofEducationOkaraCampus 8 Pre=++num Post=num++
  • 9. Unary Operator/Order/Associativity The name of the example: Unary_Order3.java public class Unary_Order3.java { public static void main (String [] args) { int num = 5; float fl; System.out.println(num); num = num * -num; System.out.println(num); } } UniversityofEducationOkaraCampus 9 Pre=+num
  • 10. Accessing Pre-Created Java Libraries • It’s accomplished by placing an ‘import’ of the appropriate library at the top of your program. • Syntax: import <Full library name>; • Example: import java.util.Scanner; UniversityofEducationOkaraCampus 10
  • 11. Getting Text Input • You can use the pre-written methods (functions) in the Scanner class. • General structure: UniversityofEducationOkaraCampus 11 import java.util.Scanner; main (String [] args) { Scanner <name of scanner> = new Scanner (System.in); <variable> = <name of scanner> .<method> (); } Creating a scanner object (something that can scan user input) Using the capability of the scanner object (actually getting user input)
  • 12. Getting Text Input (2) The name of the online example: MyInput.java import java.util.Scanner; public class MyInput { public static void main (String [] args) { String str1; int num1; Scanner in = new Scanner (System.in); System.out.print ("Type in an integer: "); num1 = in.nextInt (); System.out.print ("Type in a line: "); in.nextLine (); str1 = in.nextLine (); System.out.println ("num1:" +num1 +"t str1:" + str1); } } UniversityofEducationOkaraCampus 12
  • 13. Useful Methods Of Class Scanner1 • nextInt () //input for integer • nextLong () • nextFloat () • nextDouble () • nextLine (); //input for string UniversityofEducationOkaraCampus 13 1 Online documentation: http://java.sun.com/javase/6/docs/api/
  • 14. Reading A Single Character • Text menu driven programs may require this capability. • Example: GAME OPTIONS (a)dd a new player (l)oad a saved game (s)ave game (q)uit game • There’s different ways of handling this problem but one approach is to extract the first character from the string. • Partial example: String s = “foo“; System.out.println(s.charAt(0)); UniversityofEducationOkaraCampus 14
  • 15. Reading A Single Character • Name of the (more complete example): MyInputChar.java import java.util.Scanner; public class MyInputChar { public static void main (String [] args) { final int FIRST = 0; //contant String selection; Scanner in = new Scanner (System.in); System.out.println("GAME OPTIONS"); System.out.println("(a)dd a new player"); System.out.println("(l)oad a saved game"); System.out.println("(s)ave game"); System.out.println("(q)uit game"); System.out.print("Enter your selection: "); UniversityofEducationOkaraCampus 15 selection = in.nextLine (); System.out.println ("Selection: " + selection.charAt(FIRST)); } }
  • 16. Decision Making In Java • Java decision making constructs • if • if, else • if, else-if • switch UniversityofEducationOkaraCampus 16 Decision Making: Logical Operators Logical Operation Python Java AND and && OR or || NOT not, ! !
  • 17. Decision Making: If Format: if (Boolean Expression) Body Example: if (x != y) System.out.println("X and Y are not equal"); if ((x > 0) && (y > 0)) { System.out.println("X and Y are positive"); } UniversityofEducationOkaraCampus 17 •Indenting the body of the branch is an important stylistic requirement of Java but unlike Python it is not enforced by the syntax of the language. •What distinguishes the body is either: 1.A semi colon (single statement branch) 2.Braces (a body that consists of multiple statements)
  • 18. Decision Making: If, Else Format: if (Boolean expression) Body of if else Body of else Example: if (x < 0) System.out.println("X is negative"); else System.out.println("X is non-negative"); UniversityofEducationOkaraCampus 18
  • 19. Example Program: If-Else • Name of the example: BranchingExample1.java import java.util.Scanner; public class BranchingExample1 { public static void main (String [] args) { Scanner in = new Scanner(System.in); final int WINNING_NUMBER = 131313; int playerNumber = -1; System.out.print("Enter ticket number: "); playerNumber = in.nextInt(); if (playerNumber == WINNING_NUMBER) System.out.println("You're a winner!"); else System.out.println("Try again."); } } UniversityofEducationOkaraCampus 19
  • 20. If, Else-If (1) Format: if (Boolean expression) Body of if else if (Boolean expression) Body of first else-if : : : else if (Boolean expression) Body of last else-if else Body of else UniversityofEducationOkaraCampus 20
  • 21. If, Else-If (2) Name of the online example: BranchingExample.java import java.util.Scanner; public class BranchingExample2 { public static void main (String [] args) { Scanner in = new Scanner(System.in); int gpa = -1; System.out.print("Enter letter grade: "); gpa = in.nextInt(); UniversityofEducationOkaraCampus 21
  • 22. If, Else-If (3) if (gpa == 4) System.out.println("A"); else if (gpa == 3) System.out.println("B"); else if (gpa == 2) System.out.println("C"); else if (gpa == 1) System.out.println("D"); else if (gpa == 0) System.out.println("F"); else System.out.println("Invalid letter grade"); } } UniversityofEducationOkaraCampus 22
  • 23. Alternative To Multiple Else-If’s: Switch (1) Format (character-based switch): switch (character variable name) { case '<character value>': Body break; case '<character value>': Body break; : default: Body } 1Thetypeofvariableinthebracketscanbeabyte,char,short,intorlong UniversityofEducationOkaraCampus 23 Important! The break is mandatory to separate Boolean expressions (must be used in all but the last)
  • 24. Switch: When To Use/When Not To Use (2) • Name of the example: SwitchExample.java import java.util.Scanner; public class SwitchExample { public static void main (String [] args) { final int FIRST = 0; String line; char letter; int gpa; Scanner in = new Scanner (System.in); System.out.print("Enter letter grade: "); UniversityofEducationOkaraCampus 24
  • 25. Switch: When To Use/When Not To Use (3) line = in.nextLine (); letter = line.charAt(FIRST); switch (letter) { case 'A': case 'a': gpa = 4; break; case 'B': case 'b': gpa = 3; break; case 'C': case 'c': gpa = 2; break; UniversityofEducationOkaraCampus 25
  • 26. Switch: When To Use/When Not To Use (4) case 'D': case 'd': gpa = 1; break; case 'F': case 'f': gpa = 0; break; default: gpa = -1; } System.out.println("Letter grade: " + letter); System.out.println("Grade point: " + gpa); } } UniversityofEducationOkaraCampus 26
  • 27. Switch: When To Use/When Not To Use (5) • When a switch can’t be used: • For data types other than characters or integers • Boolean expressions that aren’t mutually exclusive: • As shown a switch can replace an ‘if-elseif’ construct • A switch cannot replace a series of ‘if’ branches). • Example when not to use a switch: if (x > 0) System.out.print(“X coordinate right of the origin”); If (y > 0) System.out.print(“Y coordinate above the origin”); • Example of when not to use a switch: String name = in.readLine() switch (name) { } UniversityofEducationOkaraCampus 27
  • 28. Loops Java Pre-test loops • For • While Java Post-test loop • Do-while UniversityofEducationOkaraCampus 28 While Loops Format: while (Boolean expression) Body Example: int i = 1; while (i <= 4) { // Call function createNewPlayer(); i = i + 1; } For Loops Format: for (initialization; Boolean expression; update control) Body Example: for (i = 1; i <= 4; i++) { // Call function createNewPlayer(); i = i + 1; }
  • 29. Post-Test Loop: Do-While • Recall: Post-test loops evaluate the Boolean expression after the body of the loop has executed. • This means that post test loops will execute one or more times. • Pre-test loops generally execute zero or more times. UniversityofEducationOkaraCampus 29 Format: do Body while (Boolean expression); Example: char ch = 'A'; do { System.out.println(ch); ch++; } while (ch <= 'K');
  • 30. Contrasting Pre Vs. Post Test Loops • Although slightly more work to implement the while loop is the most powerful type of loop. • Program capabilities that are implemented with either a ‘for’ or ‘do-while’ loop can be implemented with a while loop. • Implementing a post test loop requires that the loop control be primed correctly (set to a value such that the Boolean expression will evaluate to true the first it’s checked). UniversityofEducationOkaraCampus 30
  • 31. Example: Post-Test Implementation • Name of the online example: PostTestExample.java public class PostTestExample { public static void main (String [] args) { final int FIRST = 0; Scanner in = new Scanner(System.in); char answer; String temp; do { System.out.println("JT's note: Pretend that we play our game"); System.out.print("Play again? Enter 'q' to quit: "); temp = in.nextLine(); answer = temp.charAt(FIRST); } while ((answer != 'q') && (answer != 'Q')); } } UniversityofEducationOkaraCampus 31
  • 32. Example: Pre-Test Implementation • Name of the online example: PreTestExample.java public class PreTestExample { public static void main (String [] args) { final int FIRST = 0; Scanner in = new Scanner(System.in); char answer = ' '; String temp; while ((answer != 'q') && (answer != 'Q')) { System.out.println("JT's note: Pretend that we play our game"); System.out.print("Play again? Enter 'q' to quit: "); temp = in.nextLine(); answer = temp.charAt(FIRST); } } } UniversityofEducationOkaraCampus 32
  • 33. Now What Happens??? import java.util.Scanner; public class PreTestExample { public static void main (String [] args) { final int FIRST = 0; Scanner in = new Scanner(System.in); char answer = ' '; String temp; while ((answer != 'q') && (answer != 'Q')) System.out.println("JT's note: Pretend that we play our game"); System.out.print("Play again? Enter 'q' to quit: "); temp = in.nextLine(); answer = temp.charAt(FIRST); } } UniversityofEducationOkaraCampus 33
  • 34. After This Section You Should Now Know • How Java was developed and the impact of it's roots on the language • The basic structure required in creating a simple Java program as well as how to compile and run programs • How to document a Java program • How to perform text based input and output in Java • The declaration of constants and variables • What are the common Java operators and how they work • The structure and syntax of decision making and looping constructs UniversityofEducationOkaraCampus 34 Special Thanks to James Tam
  • 35. The End let’s go for tea UniversityofEducationOkaraCampus 35