SlideShare a Scribd company logo
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
Java Vs. Java Script
Java (this is what you need to know for this course)
• A complete programming language developed by Sun
• Can be used to develop either web based or stand-alone software
• Many pre-created code libraries available
• For more complex and powerful programs
Java Script (not covered in this course)
• A small language that’s mostly used for web-based applications
(run through a web browser like Internet Explorer, Firefox, Safari,
Chrome)
• Good for programming simple special effects for your web page
e.g., roll-overs
• e.g.,
http://pages.cpsc.ucalgary.ca/~tamj/2005/231P/assignments/assi
gnment4/index.html
2
Java: History (1)
• The invention of the microprocessor revolutionized computers
Intel microprocessor
Commodore Pet microcomputer
Java: History (2)
• It was believed that the logical next step for microprocessors
was to have them run intelligent consumer electronics
4
Java History (3)
•Sun Microsystems funded an internal research project “Green”
to investigate this opportunity.
• Result: A programming language called “Oak”
Blatant advertisement: James Gosling was
a graduate of the U of C Computer Science
program.
Wav file from “The Simpsons” © Fox, Image
from the website of Sun Microsystems
5
Java History (4)
• Problem: There was already a programming language called Oak.
• The “Green” team met at a local coffee shop to come up with
another name...
•Java!
Java: History (5)
•The popularity of the Internet resulted in Sun’s re-focusing of Java
on computers.
•Prior to the advent of Java, web pages allowed you to download
only text and images.
Your computer at home running a web browser
User clicks on a link
Images and text get
downloaded
Server containing a web page
7
Your computer at
home running a
web browser
Server containing
a web page
Java: History (6)
• Java enabled web browsers allowed for the downloading of
programs (Applets).
• Java is still used in this context today:
• Facebook (older version)
• Hotmail (older version)
User clicks on a link
Java Applet downloaded
Java version of the Game of Life: http://www.bitstorm.org/gameoflife/
Online checkers: http://www.darkfish.com/checkers/index.html
8
Java: Write Once, Run Anywhere
• Consequence of Java’s history:
platform-independence
Mac user running Safari
Windows user running Internet Explorer
Web page stored on Unix server
Click on link to Applet
Byte code is downloaded
Virtual machine translates byte code to
native Mac code and the Applet is run
Byte code
(part of web
page)
Java: Write Once, Run Anywhere
• Consequence of Java’s history:
platform-independent
Mac user running Safari
Windows user running Internet Explorer
Web page stored on Unix server
Click on link to Applet
Byte code is downloaded
Virtual machine translates byte code to
native Windows code and the Applet is run
Java: Write Once, Run
Anywhere (2)
• But Java can also create standard (non-web based) programs
Dungeon Master (Java version)
http://homepage.mac.com/aberfield/dmj/
Examples of mobile Java games: http://www.mobilegamesarena.net
Kung Fu Panda 2: THQ 11
Java: Write Once, Run
Anywhere (3)
• Java has been used by large and reputable companies to
create serious stand-alone applications.
• Example:
• Eclipse1: started as a programming environment created by IBM for
developing Java programs. The program Eclipse was itself written in Java.
1 For more information: http://www.eclipse.org/downloads/
12
Compiled Programs With Different
OperatingSystems
Windows
compiler
Executable (Windows)
UNIX
compiler
Executable (UNIX)
Mac OS
compiler
Executable (Mac)
Computer
program
13
A High Level View Of
Translating/Executing Java Programs
Java compiler
(javac)
Java program
Filename.java
Java
bytecode
(generic
binary)
Filename.class
Stage 1: Compilation
14
A High Level View Of Translating/Executing
JavaPrograms(2)
Java interpreter
(java)
Java
bytecode
(generic
binary)
Filename.class
Machine language
instruction (UNIX)
Machine language
instruction (Windows)
Machine language
instruction (Apple)
Stage 2: Interpreting and executing the byte code
15
Which Java?
•Java 6+ JDK (Java Development Kit), Standard Edition includes:
• JDK (Java development kit) – for developing Java software
(creating Java programs.
• JRE (Java Runtime environment) – only good for running pre-
created Java programs.
•Java Plug-in – a special version of the JRE designed to run through
web browsers.
http://java.sun.com/javase/downloads/index.jsp
16
Smallest CompitibleAnd ExecutableJava
Program
The name of the online example is: Smallest.java (Important note: file name
matches the word after the keyword ‘class’)
public class Smallest
{
public static void main (String[] args)
{
System.out.println(“Hello World!”);
}
}
17
Compiling The Smallest Java Program
public class Smallest
{
public static void main (String[] args)
{
}
}
Smallest.java
javac
(Java byte code)
10000100000001000
00100100000001001
: :
Smallest.class
Type “javac
Smallest.java”
18
Running The Smallest Java Program
(Java byte code)
10000100000001000
00100100000001001
: :
Smallest.class
java
Type “java Smallest” (Platform/Operating specific binary
10100111000001000
00100111001111001
: :
19
Running The Java Compiler At Home
• After installing Java you will need to indicate to the operating
system where the java compiler has been installed (‘setting
the path’).
• For details of how to set your path variable for your particular
operating system try the Sun or Java website.
• Example of how to set the path in Windows:
• http://java.sun.com/j2se/1.4.2/install-windows.html (see step 5)
20
Multi-line documentation
/* Start of documentation
*/ End of documentation
Documentation for a single line
//Everything until the end of the line is a comment
Java Output
•Format:
System.out.print(<string or variable name one> + <string or variable
name two>..);
OR
System.out.println(<string or variable name one> + <string or variable
name two>..);
•Examples (online program called “OutputExample1.java”)
public class OutputExample1
{
public static void main (String [] args)
{
int num = 123; // More on this shortly
System.out.println("Good-night gracie!");
System.out.print(num);
System.out.println("num="+num);
}
}
21
Output : Some Escape Sequences
For Formatting
Escape sequence Description
t Horizontal tab
r Carriage return
n New line
” Double quote
 Backslash
Example Formatting Codes
• Name of the online example: FormattingExample.java
public class FormattingExample
{
public static void main (String [] args)
{
System.out.print("loltzn");
System.out.println("hellorworld");
System.out.println(""Geek" talk slash () com");
}
}
23
Variables
• Unlike Python variables must be declared before they can be
used.
• Variable declaration:
• Creates a variable in memory.
• Specify the name of the variable as well as the type of
information that it will store.
• E.g. int num;
• Using variables
• Only after a variable has been declared can it be used.
• E.g., num = 12;
24
Declaring Variables: Syntax
• Format:
<type of information> <name of variable>;
• Example:
char myFirstInitial;
• Variables can be initialized (set to a starting value) as they’re
declared:
char myFirstInitial = „j‟;
int age = 30;
25
Some Built-In Types Of Variables In Java
Type Description
byte 8 bit signed integer
short 16 but signed integer
int 32 bit signed integer
long 64 bit signed integer
float 32 bit signed real number
double 64 bit signed real number
char 16 bit Unicode character (ASCII and
beyond)
boolean 1 bit true or false value
String A sequence of characters between double
quotes ("")
26
Location Of Variable
Declarations
public class <name of class>
{
public static void main (String[] args)
{
// Local variable declarations occur here
<< Program statements >>
: :
}
}
27
Style Hint: Initializing Variables
• Always initialize your variables prior to using them!
• Do this whether it is syntactically required or not.
• Example how not to approach:
public class OutputExample1
{
public static void main (String [] args)
{
int num;
System.out.print(num);
}
} OutputExample1.java:7: error: variable
num might not have been initialized
System.out.print(num);
^
28
Java Constants
Reminder: constants are like variables in that they have a name
and store a certain type of information but unlike variables they
CANNOT change. (Unlike Python this is syntactically
enforced…hurrah!).
Format:
final <constant type> <CONSTANT NAME> = <value>;
Example:
final int SIZE = 100;
29
Location Of Constant
Declarations
public class <name of class>
{
public static void main (String[] args)
{
// Local constant declarations occur here (more later)
// Local variable declarations
< Program statements >>
: :
}
}
30
Why Use Constants?
1. They make your program easier to read and understand
populationChange = (0.1758 – 0.1257) * currentPopulation;
Vs.
final float BIRTH_RATE = 17.58;
final float MORTALITY_RATE = 0.1257;
int currentPopulation = 1000000;
populationChange = (BIRTH_RATE - MORTALITY_RATE) *
currentPopulation;
31
Why Use Constants? (2)
2. It can make your program easier to maintain (update with
changes).
• If the constant is referred to several times throughout the
program, changing the value of the constant once will change it
throughout the program.
32
Why Use Constants? (3)
final float BIRTH_RATE = 0.1758;
final float MORTALITY_RATE = 0.1257;
float populationChange = 0;
float currentPopulation = 1000000;
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;
if (populationChange > 0)
System.out.println("Increase“)
System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ +
MORTALITY_RATE, " + Population change:“ + populationChange);
else if (populationChange < 0)
System.out.println("Decrease“);
System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+
MORTALITY_RATE
+"Population change:“+populationChange);
else
System.out.print("No change“);
System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+
MORTALITY_RATE+
"Population change:“+populationChange);
33
Why Use Constants? (4)
final float BIRTH_RATE = 0.5;
final float MORTALITY_RATE = 0.1257;
float populationChange = 0;
float currentPopulation = 1000000;
populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation;
if (populationChange > 0)
System.out.println("Increase“)
System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ +
MORTALITY_RATE, " + Population change:“ + populationChange);
else if (populationChange < 0)
System.out.println("Decrease“);
System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+
MORTALITY_RATE
+"Population change:“+populationChange);
else
System.out.print("No change“);
System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+
MORTALITY_RATE+
"Population change:“+populationChange);
One change in the
initialization of the
constant changes all
references to that
constant.
34
Variable Naming Conventions
In Java
• Compiler requirements
• Can’t be a keyword nor can the names of the special constants:
true, false or null be used
• Can be any combination of letters, numbers, underscore or dollar
sign (first character must be a letter or underscore)
• Common stylistic conventions
• The name should describe the purpose of the variable
• Avoid using the dollar sign
• With single word variable names, all characters are lower case
•e.g., double grades;
• Multiple words are separated by capitalizing the first letter of
each word except for the first word
•e.g., String firstName = “James”; 35
Java Keywords
abstract boolean break byte case catch char
class const continue default do double else
extends final finally float for goto if
implement
s
import instanceof int
interfac
e
long native
new package private protected public return short
static super switch
synchronize
d
this throw throws
transient try void volatile while
CommonJava Operators/ OperatorPrecedence
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

More Related Content

What's hot (16)

Great cup of java
Great  cup of javaGreat  cup of java
Great cup of java
CIB Egypt
 
Java Programming - 01 intro to java
Java Programming - 01 intro to javaJava Programming - 01 intro to java
Java Programming - 01 intro to java
Danairat Thanabodithammachari
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
Ajay Sharma
 
1 java programming- introduction
1  java programming- introduction1  java programming- introduction
1 java programming- introduction
jyoti_lakhani
 
Letest
LetestLetest
Letest
Prakash Poudel
 
Java basic introduction
Java basic introductionJava basic introduction
Java basic introduction
Ideal Eyes Business College
 
History of Java 1/2
History of Java 1/2History of Java 1/2
History of Java 1/2
Eberhard Wolff
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
What is-java
What is-javaWhat is-java
What is-java
Shahid Rasheed
 
Java introduction
Java introductionJava introduction
Java introduction
The icfai university jaipur
 
Java programming course for beginners
Java programming course for beginnersJava programming course for beginners
Java programming course for beginners
Eduonix Learning Solutions
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
Java introduction
Java introductionJava introduction
Java introduction
logeswarisaravanan
 
History of java
History of javaHistory of java
History of java
Mani Sarkar
 
Learn Java Part 1
Learn Java Part 1Learn Java Part 1
Learn Java Part 1
Gurpreet singh
 

Similar to Introduction to java programming part 1 (20)

Introduction to java programming part 1
Introduction to java programming part 1Introduction to java programming part 1
Introduction to java programming part 1
university of education,Lahore
 
Mpl 1
Mpl 1Mpl 1
Mpl 1
AHHAAH
 
Java-Unit-I.ppt
Java-Unit-I.pptJava-Unit-I.ppt
Java-Unit-I.ppt
RameswarGprec
 
JAVA Module 1______________________.pptx
JAVA Module 1______________________.pptxJAVA Module 1______________________.pptx
JAVA Module 1______________________.pptx
Radhika Venkatesh
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
SmitaBorkar9
 
LECTURE 2 -Object oriented Java Basics.pptx
LECTURE 2 -Object oriented  Java Basics.pptxLECTURE 2 -Object oriented  Java Basics.pptx
LECTURE 2 -Object oriented Java Basics.pptx
AOmaAli
 
What is Java, JDK, JVM, Introduction to Java.pptx
What is Java, JDK, JVM, Introduction to Java.pptxWhat is Java, JDK, JVM, Introduction to Java.pptx
What is Java, JDK, JVM, Introduction to Java.pptx
kumarsuneel3997
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
Fraz Bakhsh
 
Java Programming
Java ProgrammingJava Programming
Java Programming
Anjan Mahanta
 
Java Basics.pptx from nit patna ece department
Java Basics.pptx from nit patna ece departmentJava Basics.pptx from nit patna ece department
Java Basics.pptx from nit patna ece department
om2348023vats
 
Programming in java ppt
Programming in java  pptProgramming in java  ppt
Programming in java ppt
MrsRLakshmiIT
 
Programming in java ppt
Programming in java  pptProgramming in java  ppt
Programming in java ppt
MrsRBoomadeviIT
 
Synapse India Reviews
Synapse India ReviewsSynapse India Reviews
Synapse India Reviews
Synapseindiappsdevelopment
 
1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming
amitraj53904
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)
hossamghareb681
 
Modern_2.pptx for java
Modern_2.pptx for java Modern_2.pptx for java
Modern_2.pptx for java
MayaTofik
 
Java
JavaJava
Java
Zeeshan Khan
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Skillwise Elementary Java Programming
Skillwise Elementary Java ProgrammingSkillwise Elementary Java Programming
Skillwise Elementary Java Programming
Skillwise Group
 
JAVA Module 1______________________.pptx
JAVA Module 1______________________.pptxJAVA Module 1______________________.pptx
JAVA Module 1______________________.pptx
Radhika Venkatesh
 
j-chap1-Basics.ppt
j-chap1-Basics.pptj-chap1-Basics.ppt
j-chap1-Basics.ppt
SmitaBorkar9
 
LECTURE 2 -Object oriented Java Basics.pptx
LECTURE 2 -Object oriented  Java Basics.pptxLECTURE 2 -Object oriented  Java Basics.pptx
LECTURE 2 -Object oriented Java Basics.pptx
AOmaAli
 
What is Java, JDK, JVM, Introduction to Java.pptx
What is Java, JDK, JVM, Introduction to Java.pptxWhat is Java, JDK, JVM, Introduction to Java.pptx
What is Java, JDK, JVM, Introduction to Java.pptx
kumarsuneel3997
 
Java Basics.pptx from nit patna ece department
Java Basics.pptx from nit patna ece departmentJava Basics.pptx from nit patna ece department
Java Basics.pptx from nit patna ece department
om2348023vats
 
Programming in java ppt
Programming in java  pptProgramming in java  ppt
Programming in java ppt
MrsRLakshmiIT
 
1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming1_Introduction to Java.pptx java programming
1_Introduction to Java.pptx java programming
amitraj53904
 
JAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.pptJAVA_BASICS_Data_abstraction_encapsulation.ppt
JAVA_BASICS_Data_abstraction_encapsulation.ppt
VGaneshKarthikeyan
 
M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)M251_Meeting 1(M251_Meeting 1_updated.pdf)
M251_Meeting 1(M251_Meeting 1_updated.pdf)
hossamghareb681
 
Modern_2.pptx for java
Modern_2.pptx for java Modern_2.pptx for java
Modern_2.pptx for java
MayaTofik
 
Java for Mainframers
Java for MainframersJava for Mainframers
Java for Mainframers
Rich Helton
 
Skillwise Elementary Java Programming
Skillwise Elementary Java ProgrammingSkillwise Elementary Java Programming
Skillwise Elementary Java Programming
Skillwise Group
 
Ad

More from university of education,Lahore (20)

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

Recently uploaded (20)

Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptxChalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdfGEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdfIntroduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptxROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
What is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptxWhat is FIle and explanation of text files.pptx
What is FIle and explanation of text files.pptx
Ramakrishna Reddy Bijjam
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdfGEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke WarnerPublishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
Introduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdfIntroduction to Generative AI and Copilot.pdf
Introduction to Generative AI and Copilot.pdf
TechSoup
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student NewsLDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptxROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Ray Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big CycleRay Dalio How Countries go Broke the Big Cycle
Ray Dalio How Countries go Broke the Big Cycle
Dadang Solihin
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 SlidesHow to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
Overview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo SlidesOverview of Employee in Odoo 18 - Odoo Slides
Overview of Employee in Odoo 18 - Odoo Slides
Celine George
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptxUnit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 

Introduction to java programming part 1

  • 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 [email protected], [email protected] [email protected], [email protected] , [email protected]
  • 2. Java Vs. Java Script Java (this is what you need to know for this course) • A complete programming language developed by Sun • Can be used to develop either web based or stand-alone software • Many pre-created code libraries available • For more complex and powerful programs Java Script (not covered in this course) • A small language that’s mostly used for web-based applications (run through a web browser like Internet Explorer, Firefox, Safari, Chrome) • Good for programming simple special effects for your web page e.g., roll-overs • e.g., http://pages.cpsc.ucalgary.ca/~tamj/2005/231P/assignments/assi gnment4/index.html 2
  • 3. Java: History (1) • The invention of the microprocessor revolutionized computers Intel microprocessor Commodore Pet microcomputer
  • 4. Java: History (2) • It was believed that the logical next step for microprocessors was to have them run intelligent consumer electronics 4
  • 5. Java History (3) •Sun Microsystems funded an internal research project “Green” to investigate this opportunity. • Result: A programming language called “Oak” Blatant advertisement: James Gosling was a graduate of the U of C Computer Science program. Wav file from “The Simpsons” © Fox, Image from the website of Sun Microsystems 5
  • 6. Java History (4) • Problem: There was already a programming language called Oak. • The “Green” team met at a local coffee shop to come up with another name... •Java!
  • 7. Java: History (5) •The popularity of the Internet resulted in Sun’s re-focusing of Java on computers. •Prior to the advent of Java, web pages allowed you to download only text and images. Your computer at home running a web browser User clicks on a link Images and text get downloaded Server containing a web page 7
  • 8. Your computer at home running a web browser Server containing a web page Java: History (6) • Java enabled web browsers allowed for the downloading of programs (Applets). • Java is still used in this context today: • Facebook (older version) • Hotmail (older version) User clicks on a link Java Applet downloaded Java version of the Game of Life: http://www.bitstorm.org/gameoflife/ Online checkers: http://www.darkfish.com/checkers/index.html 8
  • 9. Java: Write Once, Run Anywhere • Consequence of Java’s history: platform-independence Mac user running Safari Windows user running Internet Explorer Web page stored on Unix server Click on link to Applet Byte code is downloaded Virtual machine translates byte code to native Mac code and the Applet is run Byte code (part of web page)
  • 10. Java: Write Once, Run Anywhere • Consequence of Java’s history: platform-independent Mac user running Safari Windows user running Internet Explorer Web page stored on Unix server Click on link to Applet Byte code is downloaded Virtual machine translates byte code to native Windows code and the Applet is run
  • 11. Java: Write Once, Run Anywhere (2) • But Java can also create standard (non-web based) programs Dungeon Master (Java version) http://homepage.mac.com/aberfield/dmj/ Examples of mobile Java games: http://www.mobilegamesarena.net Kung Fu Panda 2: THQ 11
  • 12. Java: Write Once, Run Anywhere (3) • Java has been used by large and reputable companies to create serious stand-alone applications. • Example: • Eclipse1: started as a programming environment created by IBM for developing Java programs. The program Eclipse was itself written in Java. 1 For more information: http://www.eclipse.org/downloads/ 12
  • 13. Compiled Programs With Different OperatingSystems Windows compiler Executable (Windows) UNIX compiler Executable (UNIX) Mac OS compiler Executable (Mac) Computer program 13
  • 14. A High Level View Of Translating/Executing Java Programs Java compiler (javac) Java program Filename.java Java bytecode (generic binary) Filename.class Stage 1: Compilation 14
  • 15. A High Level View Of Translating/Executing JavaPrograms(2) Java interpreter (java) Java bytecode (generic binary) Filename.class Machine language instruction (UNIX) Machine language instruction (Windows) Machine language instruction (Apple) Stage 2: Interpreting and executing the byte code 15
  • 16. Which Java? •Java 6+ JDK (Java Development Kit), Standard Edition includes: • JDK (Java development kit) – for developing Java software (creating Java programs. • JRE (Java Runtime environment) – only good for running pre- created Java programs. •Java Plug-in – a special version of the JRE designed to run through web browsers. http://java.sun.com/javase/downloads/index.jsp 16
  • 17. Smallest CompitibleAnd ExecutableJava Program The name of the online example is: Smallest.java (Important note: file name matches the word after the keyword ‘class’) public class Smallest { public static void main (String[] args) { System.out.println(“Hello World!”); } } 17
  • 18. Compiling The Smallest Java Program public class Smallest { public static void main (String[] args) { } } Smallest.java javac (Java byte code) 10000100000001000 00100100000001001 : : Smallest.class Type “javac Smallest.java” 18
  • 19. Running The Smallest Java Program (Java byte code) 10000100000001000 00100100000001001 : : Smallest.class java Type “java Smallest” (Platform/Operating specific binary 10100111000001000 00100111001111001 : : 19
  • 20. Running The Java Compiler At Home • After installing Java you will need to indicate to the operating system where the java compiler has been installed (‘setting the path’). • For details of how to set your path variable for your particular operating system try the Sun or Java website. • Example of how to set the path in Windows: • http://java.sun.com/j2se/1.4.2/install-windows.html (see step 5) 20 Multi-line documentation /* Start of documentation */ End of documentation Documentation for a single line //Everything until the end of the line is a comment
  • 21. Java Output •Format: System.out.print(<string or variable name one> + <string or variable name two>..); OR System.out.println(<string or variable name one> + <string or variable name two>..); •Examples (online program called “OutputExample1.java”) public class OutputExample1 { public static void main (String [] args) { int num = 123; // More on this shortly System.out.println("Good-night gracie!"); System.out.print(num); System.out.println("num="+num); } } 21
  • 22. Output : Some Escape Sequences For Formatting Escape sequence Description t Horizontal tab r Carriage return n New line ” Double quote Backslash
  • 23. Example Formatting Codes • Name of the online example: FormattingExample.java public class FormattingExample { public static void main (String [] args) { System.out.print("loltzn"); System.out.println("hellorworld"); System.out.println(""Geek" talk slash () com"); } } 23
  • 24. Variables • Unlike Python variables must be declared before they can be used. • Variable declaration: • Creates a variable in memory. • Specify the name of the variable as well as the type of information that it will store. • E.g. int num; • Using variables • Only after a variable has been declared can it be used. • E.g., num = 12; 24
  • 25. Declaring Variables: Syntax • Format: <type of information> <name of variable>; • Example: char myFirstInitial; • Variables can be initialized (set to a starting value) as they’re declared: char myFirstInitial = „j‟; int age = 30; 25
  • 26. Some Built-In Types Of Variables In Java Type Description byte 8 bit signed integer short 16 but signed integer int 32 bit signed integer long 64 bit signed integer float 32 bit signed real number double 64 bit signed real number char 16 bit Unicode character (ASCII and beyond) boolean 1 bit true or false value String A sequence of characters between double quotes ("") 26
  • 27. Location Of Variable Declarations public class <name of class> { public static void main (String[] args) { // Local variable declarations occur here << Program statements >> : : } } 27
  • 28. Style Hint: Initializing Variables • Always initialize your variables prior to using them! • Do this whether it is syntactically required or not. • Example how not to approach: public class OutputExample1 { public static void main (String [] args) { int num; System.out.print(num); } } OutputExample1.java:7: error: variable num might not have been initialized System.out.print(num); ^ 28
  • 29. Java Constants Reminder: constants are like variables in that they have a name and store a certain type of information but unlike variables they CANNOT change. (Unlike Python this is syntactically enforced…hurrah!). Format: final <constant type> <CONSTANT NAME> = <value>; Example: final int SIZE = 100; 29
  • 30. Location Of Constant Declarations public class <name of class> { public static void main (String[] args) { // Local constant declarations occur here (more later) // Local variable declarations < Program statements >> : : } } 30
  • 31. Why Use Constants? 1. They make your program easier to read and understand populationChange = (0.1758 – 0.1257) * currentPopulation; Vs. final float BIRTH_RATE = 17.58; final float MORTALITY_RATE = 0.1257; int currentPopulation = 1000000; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation; 31
  • 32. Why Use Constants? (2) 2. It can make your program easier to maintain (update with changes). • If the constant is referred to several times throughout the program, changing the value of the constant once will change it throughout the program. 32
  • 33. Why Use Constants? (3) final float BIRTH_RATE = 0.1758; final float MORTALITY_RATE = 0.1257; float populationChange = 0; float currentPopulation = 1000000; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation; if (populationChange > 0) System.out.println("Increase“) System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ + MORTALITY_RATE, " + Population change:“ + populationChange); else if (populationChange < 0) System.out.println("Decrease“); System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE +"Population change:“+populationChange); else System.out.print("No change“); System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE+ "Population change:“+populationChange); 33
  • 34. Why Use Constants? (4) final float BIRTH_RATE = 0.5; final float MORTALITY_RATE = 0.1257; float populationChange = 0; float currentPopulation = 1000000; populationChange = (BIRTH_RATE - MORTALITY_RATE) * currentPopulation; if (populationChange > 0) System.out.println("Increase“) System.out.println("Birth rate:“+ BIRTH_RATE + " Mortality rate:“ + MORTALITY_RATE, " + Population change:“ + populationChange); else if (populationChange < 0) System.out.println("Decrease“); System.out.println("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE +"Population change:“+populationChange); else System.out.print("No change“); System.out.print("Birth rate:“+BIRTH_RATE, “+Mortality rate:“+ MORTALITY_RATE+ "Population change:“+populationChange); One change in the initialization of the constant changes all references to that constant. 34
  • 35. Variable Naming Conventions In Java • Compiler requirements • Can’t be a keyword nor can the names of the special constants: true, false or null be used • Can be any combination of letters, numbers, underscore or dollar sign (first character must be a letter or underscore) • Common stylistic conventions • The name should describe the purpose of the variable • Avoid using the dollar sign • With single word variable names, all characters are lower case •e.g., double grades; • Multiple words are separated by capitalizing the first letter of each word except for the first word •e.g., String firstName = “James”; 35
  • 36. Java Keywords abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implement s import instanceof int interfac e long native new package private protected public return short static super switch synchronize d this throw throws transient try void volatile while
  • 37. CommonJava Operators/ OperatorPrecedence 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