SlideShare une entreprise Scribd logo
1  sur  36
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.
1
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
Common Java Operators / Operator
Precedence
Precedence
level
Operator Description Associativity
1 expression++
expression--
Post-increment
Post-decrement
Right to left
2 ++expression
--expression
+
-
!
~
(type)
Pre-increment
Pre-decrement
Unary plus
Unary minus
Logical negation
Bitwise complement
Cast
Right to left
Common Java Operators / Operator
Precedence
Precedenc
e 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 online 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++);
}
} 7
Pre=++num
Post=num++
Post/Pre Operators (2)
The name of the online 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);
}
}
8
Pre=++num
Post=num++
Unary
Operator/Order/Associativit
yThe name of the online 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);
}
}
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;
10
Getting Text Input
• You can use the pre-written methods (functions) in the
Scanner class.
• General structure:
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)
11
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);
}
12
Useful Methods Of Class
Scanner1
• nextInt ()
• nextLong ()
• nextFloat ()
• nextDouble ()
• nextLine ();
1 Online documentation: http://java.sun.com/javase/6/docs/api/
13
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 = "boo“;
System.out.println(s.charAt(0));
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;
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: ");
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
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");
}
•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)
17
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");
18
Example Program: If-Else
• Name of the online 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.");
}
}
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
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();
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");
}
}
22
Branching: Common Mistakes
• Recall that for single bodies: what lies between the closing
bracket of the Boolean expression and the next semi-colon is
the body.
if (Boolean Expression)
instruction;
if (Boolean Expression) instruction;
if (Boolean Expression)
instruction1;
Instruction2;
body
body
body
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
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 online 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: ");
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;
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);
}
}
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)
{
28
Loops
Java Pre-test loops
• For
• While
Java Post-test loop
• Do-while
29
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.
30
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).
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'));
}
}
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);
}
}
}
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);
}
}
34
Many Pre-Created Classes
Have Been Created
• Rule of thumb: Before writing new program code to
implement the features of your program you should check to
see if a class has already been written with the features that
you need.
• The Java API is Sun Microsystems's collection of pre-built Java
classes:
• http://java.sun.com/javase/6/docs/api/
35
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
36
Special Thanks to James Tam

Contenu connexe

Tendances (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Type Casting Operator
Type Casting OperatorType Casting Operator
Type Casting Operator
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Variables and Data Types
Variables and Data TypesVariables and Data Types
Variables and Data Types
 
OCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertionsOCJP Samples Questions: Exceptions and assertions
OCJP Samples Questions: Exceptions and assertions
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Lazy java
Lazy javaLazy java
Lazy java
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Scala test
Scala testScala test
Scala test
 
Java programs
Java programsJava programs
Java programs
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
 

Similaire à Java Programming Introduction

Similaire à Java Programming Introduction (20)

Introduction to java programming part 2
Introduction to java programming  part 2Introduction to java programming  part 2
Introduction to java programming part 2
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Java programs
Java programsJava programs
Java programs
 
Chapter i(introduction to java)
Chapter i(introduction to java)Chapter i(introduction to java)
Chapter i(introduction to java)
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf3.Lesson Plan - Input.pdf.pdf
3.Lesson Plan - Input.pdf.pdf
 
Java introduction
Java introductionJava introduction
Java introduction
 
object oriented programming java lectures
object oriented programming java lecturesobject oriented programming java lectures
object oriented programming java lectures
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
02basics
02basics02basics
02basics
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
 
Core java day1
Core java day1Core java day1
Core java day1
 
Java Notes
Java Notes Java Notes
Java Notes
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java final lab
Java final labJava final lab
Java final lab
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 

Plus de university of education,Lahore

Plus de university of education,Lahore (20)

Activites and Time Planning
 Activites and Time Planning Activites and Time Planning
Activites and Time Planning
 
Steganography
SteganographySteganography
Steganography
 
Classical Encryption Techniques
Classical Encryption TechniquesClassical Encryption Techniques
Classical Encryption Techniques
 
Activites and Time Planning
Activites and Time PlanningActivites and Time Planning
Activites and Time Planning
 
OSI Security Architecture
OSI Security ArchitectureOSI Security Architecture
OSI Security Architecture
 
Network Security Terminologies
Network Security TerminologiesNetwork Security Terminologies
Network Security Terminologies
 
Project Scheduling, Planning and Risk Management
Project Scheduling, Planning and Risk ManagementProject Scheduling, Planning and Risk Management
Project Scheduling, Planning and Risk Management
 
Software Testing and Debugging
Software Testing and DebuggingSoftware Testing and Debugging
Software Testing and Debugging
 
ePayment Methods
ePayment MethodsePayment Methods
ePayment Methods
 
SEO
SEOSEO
SEO
 
A Star Search
A Star SearchA Star Search
A Star Search
 
Enterprise Application Integration
Enterprise Application IntegrationEnterprise Application Integration
Enterprise Application Integration
 
Uml Diagrams
Uml DiagramsUml Diagrams
Uml Diagrams
 
eDras Max
eDras MaxeDras Max
eDras Max
 
RAD Model
RAD ModelRAD Model
RAD Model
 
Microsoft Project
Microsoft ProjectMicrosoft Project
Microsoft Project
 
Itertaive Process Development
Itertaive Process DevelopmentItertaive Process Development
Itertaive Process Development
 
Computer Aided Software Engineering Nayab Awan
Computer Aided Software Engineering Nayab AwanComputer Aided Software Engineering Nayab Awan
Computer Aided Software Engineering Nayab Awan
 
Lect 2 assessing the technology landscape
Lect 2 assessing the technology landscapeLect 2 assessing the technology landscape
Lect 2 assessing the technology landscape
 
system level requirements gathering and analysis
system level requirements gathering and analysissystem level requirements gathering and analysis
system level requirements gathering and analysis
 

Dernier

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxMaryGraceBautista27
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 

Dernier (20)

Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Science 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptxScience 7 Quarter 4 Module 2: Natural Resources.pptx
Science 7 Quarter 4 Module 2: Natural Resources.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 

Java Programming Introduction

  • 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. 1 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
  • 2. Common Java Operators / Operator Precedence Precedence level Operator Description Associativity 1 expression++ expression-- Post-increment Post-decrement Right to left 2 ++expression --expression + - ! ~ (type) Pre-increment Pre-decrement Unary plus Unary minus Logical negation Bitwise complement Cast Right to left
  • 3. Common Java Operators / Operator Precedence Precedenc e 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 online 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++); } } 7 Pre=++num Post=num++
  • 8. Post/Pre Operators (2) The name of the online 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); } } 8 Pre=++num Post=num++
  • 9. Unary Operator/Order/Associativit yThe name of the online 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); } } 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; 10
  • 11. Getting Text Input • You can use the pre-written methods (functions) in the Scanner class. • General structure: 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) 11
  • 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); } 12
  • 13. Useful Methods Of Class Scanner1 • nextInt () • nextLong () • nextFloat () • nextDouble () • nextLine (); 1 Online documentation: http://java.sun.com/javase/6/docs/api/ 13
  • 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 = "boo“; System.out.println(s.charAt(0)); 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; 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: "); 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 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"); } •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) 17
  • 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"); 18
  • 19. Example Program: If-Else • Name of the online 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."); } } 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 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(); 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"); } } 22
  • 23. Branching: Common Mistakes • Recall that for single bodies: what lies between the closing bracket of the Boolean expression and the next semi-colon is the body. if (Boolean Expression) instruction; if (Boolean Expression) instruction; if (Boolean Expression) instruction1; Instruction2; body body body 23
  • 24. 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 Important! The break is mandatory to separate Boolean expressions (must be used in all but the last) 24
  • 25. Switch: When To Use/When Not To Use (2) • Name of the online 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: "); 25
  • 26. 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; 26
  • 27. 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); } } 27
  • 28. 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) { 28
  • 29. Loops Java Pre-test loops • For • While Java Post-test loop • Do-while 29 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; }
  • 30. 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. 30 Format: do Body while (Boolean expression); Example: char ch = 'A'; do { System.out.println(ch); ch++; } while (ch <= 'K');
  • 31. 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). 31
  • 32. 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')); } } 32
  • 33. 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); } } } 33
  • 34. 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); } } 34
  • 35. Many Pre-Created Classes Have Been Created • Rule of thumb: Before writing new program code to implement the features of your program you should check to see if a class has already been written with the features that you need. • The Java API is Sun Microsystems's collection of pre-built Java classes: • http://java.sun.com/javase/6/docs/api/ 35
  • 36. 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 36 Special Thanks to James Tam