SlideShare a Scribd company logo
Java™ How to Program, 9/e
© Copyright 1992-2012 by Pearson Education, Inc. All Rights
Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Java application programming
 Use tools from the JDK to compile and run programs.
 Videos at www.deitel.com/books/jhtp9/
 Help you get started with Eclipse and NetBeans integrated
development environments.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Java application
 A computer program that executes when you use the java
command to launch the Java Virtual Machine (JVM).
 Sample program in Fig. 2.1 displays a line of text.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Comments
// Fig. 2.1: Welcome1.java
 // indicates that the line is a comment.
 Used to document programs and improve their readability.
 Compiler ignores comments.
 A comment that begins with // is an end-of-line comment—it
terminates at the end of the line on which it appears.
 Traditional comment, can be spread over several lines as in
/* This is a traditional comment. It
can be split over multiple lines */
 This type of comment begins with /* and ends with */.
 All text between the delimiters is ignored by the compiler.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Javadoc comments
 Delimited by /** and */.
 All text between the Javadoc comment delimiters is ignored by
the compiler.
 Enable you to embed program documentation directly in your
programs.
 The javadoc utility program (Appendix M) reads Javadoc
comments and uses them to prepare your program’s
documentation in HTML format.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Blank lines and space characters
 Make programs easier to read.
 Blank lines, spaces and tabs are known as white space (or
whitespace).
 White space is ignored by the compiler.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Class declaration
public class Welcome1
 Every Java program consists of at least one class that you
define.
 class keyword introduces a class declaration and is
immediately followed by the class name.
 Keywords (Appendix C) are reserved for use by Java and are
always spelled with all lowercase letters.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Class names
 By convention, begin with a capital letter and capitalize the
first letter of each word they include (e.g.,
SampleClassName).
 A class name is an identifier—a series of characters consisting
of letters, digits, underscores (_) and dollar signs ($) that does
not begin with a digit and does not contain spaces.
 Java is case sensitive—uppercase and lowercase letters are
distinct—so a1 and A1 are different (but both valid) identifiers.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Braces
 A left brace, {, begins the body of every class declaration.
 A corresponding right brace, }, must end each class
declaration.
 Code between braces should be indented.
 This indentation is one of the spacing conventions mentioned
earlier.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Declaring the main Method
public static void main( String[] args )
 Starting point of every Java application.
 Parentheses after the identifier main indicate that it’s a
program building block called a method.
 Java class declarations normally contain one or more methods.
 main must be defined as shown; otherwise, the JVM will not
execute the application.
 Methods perform tasks and can return information when they
complete their tasks.
 Keyword void indicates that this method will not return any
information.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Body of the method declaration
 Enclosed in left and right braces.
 Statement
System.out.println("Welcome to Java Programming!");
 Instructs the computer to perform an action
 Print the string of characters contained between the double
quotation marks.
 A string is sometimes called a character string or a string literal.
 White-space characters in strings are not ignored by the
compiler.
 Strings cannot span multiple lines of code.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 System.out object
 Standard output object.
 Allows Java applications to display strings in the command
window from which the Java application executes.
 System.out.println method
 Displays (or prints) a line of text in the command window.
 The string in the parentheses the argument to the method.
 Positions the output cursor at the beginning of the next line in
the command window.
 Most statements end with a semicolon.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Compiling and Executing Your First Java Application
 Open a command window and change to the directory where the
program is stored.
 Many operating systems use the command cd to change directories.
 To compile the program, type
javac Welcome1.java
 If the program contains no syntax errors, preceding command creates
a.class file (known as the class file) containing the platform-
independent Java bytecodes that represent the application.
 When we use the java command to execute the application on a
given platform, these bytecodes will be translated by the JVM into
instructions that are understood by the underlying operating system.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 To execute the program, type java Welcome1.
 Launches the JVM, which loads the .class file for
class Welcome1.
 Note that the .class file-name extension is omitted
from the preceding command; otherwise, the JVM will
not execute the program.
 The JVM calls method main to execute the program.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Class Welcome2, shown in Fig. 2.3, uses two
statements to produce the same output as that shown in
Fig. 2.1.
 New and key features in each code listing are
highlighted.
 System.out’s method print displays a string.
 Unlike println, print does not position the output
cursor at the beginning of the next line in the command
window.
 The next character the program displays will appear
immediately after the last character that print displays.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Newline characters indicate to System.out’s print and
println methods when to position the output cursor at
the beginning of the next line in the command window.
 Newline characters are white-space characters.
 The backslash () is called an escape character.
 Indicates a “special character”
 Backslash is combined with the next character to form an
escape sequence.
 The escape sequence n represents the newline character.
 Complete list of escape sequences
java.sun.com/docs/books/jls/third_edition/html/
lexical.html#3.10.6.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 System.out.printf method
 f means “formatted”
 displays formatted data
 Multiple method arguments are placed in a comma-separated list.
 Java allows large statements to be split over many lines.
 Cannot split a statement in the middle of an identifier or string.
 Method printf’s first argument is a format string
 May consist of fixed text and format specifiers.
 Fixed text is output as it would be by print or println.
 Each format specifier is a placeholder for a value and specifies the type
of data to output.
 Format specifiers begin with a percent sign (%) and are followed
by a character that represents the data type.
 Format specifier %s is a placeholder for a string.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Integers
 Whole numbers, like –22, 7, 0 and 1024)
 Programs remember numbers and other data in the
computer’s memory and access that data through
program elements called variables.
 The program of Fig. 2.7 demonstrates these concepts.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 import declaration
 Helps the compiler locate a class that is used in this program.
 Rich set of predefined classes that you can reuse rather than
“reinventing the wheel.”
 Classes are grouped into packages—named groups of related
classes—and are collectively referred to as the Java class
library, or the Java Application Programming Interface (Java
API).
 You use import declarations to identify the predefined
classes used in a Java program.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Variable declaration statement
Scanner input = new Scanner( System.in );
 Specifies the name (input) and type (Scanner) of a variable that
is used in this program.
 Variable
 A location in the computer’s memory where a value can be stored for
use later in a program.
 Must be declared with a name and a type before they can be used.
 A variable’s name enables the program to access the value of the
variable in memory.
 The name can be any valid identifier.
 A variable’s type specifies what kind of information is stored at that
location in memory.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Scanner
 Enables a program to read data for use in a program.
 Data can come from many sources, such as the user at the keyboard or a
file on disk.
 Before using a Scanner, you must create it and specify the source of
the data.
 The equals sign (=) in a declaration indicates that the variable
should be initialized (i.e., prepared for use in the program) with
the result of the expression to the right of the equals sign.
 The new keyword creates an object.
 Standard input object, System.in, enables applications to read
bytes of information typed by the user.
 Scanner object translates these bytes into types that can be
used in a program.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Variable declaration statements
int number1; // first number to add
int number2; // second number to add
int sum; // sum of number1 and number2
declare that variables number1, number2 and sum hold
data of type int
 They can hold integer.
 Range of values for an int is –2,147,483,648 to +2,147,483,647.
 Actual int values may not contain commas.
 Several variables of the same type may be declared in one
declaration with the variable names separated by commas.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Prompt
 Output statement that directs the user to take a specific action.
 System is a class.
 Part of package java.lang.
 Class System is not imported with an import declaration at
the beginning of the program.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Scanner method nextInt
number1 = input.nextInt(); // read first number from
user
 Obtains an integer from the user at the keyboard.
 Program waits for the user to type the number and press the
Enter key to submit the number to the program.
 The result of the call to method nextInt is placed in
variable number1 by using the assignment operator, =.
 “number1 gets the value of input.nextInt().”
 Operator = is called a binary operator—it has two operands.
 Everything to the right of the assignment operator, =, is always
evaluated before the assignment is performed.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Arithmetic
sum = number1 + number2; // add numbers
 Assignment statement that calculates the sum of the variables
number1 and number2 then assigns the result to variable sum
by using the assignment operator, =.
 “sum gets the value of number1 + number2.”
 In general, calculations are performed in assignment statements.
 Portions of statements that contain calculations are called
expressions.
 An expression is any portion of a statement that has a value
associated with it.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Integer formatted output
System.out.printf( "Sum is %dn", sum );
 Format specifier %d is a placeholder for an int value
 The letter d stands for “decimal integer.”
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Variables
 Every variable has a name, a type, a size (in bytes) and a value.
 When a new value is placed into a variable, the new value
replaces the previous value (if any)
 The previous value is lost.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Arithmetic operators are summarized in Fig. 2.11.
 The asterisk (*) indicates multiplication
 The percent sign (%) is the remainder operator
 The arithmetic operators are binary operators because
they each operate on two operands.
 Integer division yields an integer quotient.
 Any fractional part in integer division is simply discarded (i.e.,
truncated)—no rounding occurs.
 The remainder operator, %, yields the remainder after
division.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Arithmetic expressions in Java must be written in
straight-line form to facilitate entering programs into
the computer.
 Expressions such as “a divided by b” must be written
as a / b, so that all constants, variables and operators
appear in a straight line.
 Parentheses are used to group terms in expressions in
the same manner as in algebraic expressions.
 If an expression contains nested parentheses, the
expression in the innermost set of parentheses is
evaluated first.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Rules of operator precedence
 Multiplication, division and remainder operations are applied first.
 If an expression contains several such operations, they are applied from
left to right.
 Multiplication, division and remainder operators have the same level of
precedence.
 Addition and subtraction operations are applied next.
 If an expression contains several such operations, the operators are
applied from left to right.
 Addition and subtraction operators have the same level of precedence.
 When we say that operators are applied from left to right, we are
referring to their associativity.
 Some operators associate from right to left.
 Complete precedence chart is included in Appendix A.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 As in algebra, it’s acceptable to place redundant
parentheses (unnecessary parentheses) in an ex-
pression to make the expression clearer.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 Condition
 An expression that can be true or false.
 if selection statement
 Allows a program to make a decision based on a condition’s value.
 Equality operators (== and !=)
 Relational operators (>, <, >= and <=)
 Both equality operators have the same level of precedence,
which is lower than that of the relational operators.
 The equality operators associate from left to right.
 The relational operators all have the same level of
precedence and also associate from left to right.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
 An if statement always begins with keyword if,
followed by a condition in parentheses.
 Expects one statement in its body, but may contain multiple
statements if they are enclosed in a set of braces ({}).
 The indentation of the body statement is not required, but it
improves the program’s readability by emphasizing that
statements are part of the body.
 Note that there is no semicolon (;) at the end of the
first line of each if statement.
 Such a semicolon would result in a logic error at execution
time.
 Treated as the empty statement—semicolon by itself.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.
© Copyright 1992-2012 by Pearson
Education, Inc. All Rights Reserved.

More Related Content

What's hot (15)

DOCX
Bca 4020 java programming
smumbahelp
 
DOC
CIS 406 Life of the Mind/newtonhelp.com   
bellflower5
 
DOCX
Cis 406 Enthusiastic Study - snaptutorial.com
Stephenson01
 
PDF
Introduction of C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
PPT
Overview of c#
Prasanna Kumar SM
 
PPT
Eo gaddis java_chapter_02_5e
Gina Bullock
 
PPT
Eo gaddis java_chapter_01_5e
Gina Bullock
 
PDF
An introduction to programming
rprajat007
 
PDF
C# c# for beginners crash course master c# programming fast and easy today
Afonso Macedo
 
PDF
Abc c program
Dayakar Siddula
 
PDF
3350703
Vipul Chauhan
 
PDF
JPT : A SIMPLE JAVA-PYTHON TRANSLATOR
caijjournal
 
PDF
Am4201257261
IJERA Editor
 
DOCX
_var_www_moodledata_temp_turnitintooltwo_1014058337._Ioan_Tuns-HNDCSD-PJ-19-1...
Ioan Tuns
 
PDF
OOP Comparative Study
Darren Tan
 
Bca 4020 java programming
smumbahelp
 
CIS 406 Life of the Mind/newtonhelp.com   
bellflower5
 
Cis 406 Enthusiastic Study - snaptutorial.com
Stephenson01
 
Introduction of C++ By Pawan Thakur
Govt. P.G. College Dharamshala
 
Overview of c#
Prasanna Kumar SM
 
Eo gaddis java_chapter_02_5e
Gina Bullock
 
Eo gaddis java_chapter_01_5e
Gina Bullock
 
An introduction to programming
rprajat007
 
C# c# for beginners crash course master c# programming fast and easy today
Afonso Macedo
 
Abc c program
Dayakar Siddula
 
3350703
Vipul Chauhan
 
JPT : A SIMPLE JAVA-PYTHON TRANSLATOR
caijjournal
 
Am4201257261
IJERA Editor
 
_var_www_moodledata_temp_turnitintooltwo_1014058337._Ioan_Tuns-HNDCSD-PJ-19-1...
Ioan Tuns
 
OOP Comparative Study
Darren Tan
 

Similar to 02장 Introduction to Java Applications (20)

PPT
jhtp10_ch02_Intro to java Applications: Input/Output and Operators
WaqasUlHassan10
 
PPTX
AndroidHTP3_AppA.pptx
MattMarino13
 
PPT
Ch.02.ppt[27/11, 11:00 am] Sumaya👸🏻✨️: Mida kale waqtiga wuba kudhamaadaye [2...
xaydari03
 
PDF
ch02-Java Fundamentals-Java Fundamentals.pdf
ayeshazaveri4
 
PPT
CSO_Gaddis_Java_Chapter02.ppt java book.
resoj26651
 
PPT
Java
tintinsan
 
PPT
01-ch01-1-println.ppt java introduction one
ssuser656672
 
PPTX
Chapter 2.4
sotlsoc
 
PPTX
OOP Using Java Ch2 all about oop .pptx
doopagamer
 
PPT
JAVA Programming notes.ppt
AravindSiva19
 
PPT
Java PPt.ppt
NavneetSheoran3
 
PPT
Cso gaddis java_chapter2
mlrbrown
 
PPT
Introduction to Java Applications
Andy Juan Sarango Veliz
 
PPTX
Java tutorial for beginners-tibacademy.in
TIB Academy
 
PDF
Java Basics.pdf
EdFeranil
 
PDF
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
PPTX
Multi Threading- in Java WPS Office.pptx
ManasaMR2
 
PPT
Java Primitive Type from Long Nguyen's lecture
ssusere8fc511
 
PPT
Introduction to objects and inputoutput
Ahmad Idrees
 
PPTX
Intro to programing with java-lecture 1
Mohamed Essam
 
jhtp10_ch02_Intro to java Applications: Input/Output and Operators
WaqasUlHassan10
 
AndroidHTP3_AppA.pptx
MattMarino13
 
Ch.02.ppt[27/11, 11:00 am] Sumaya👸🏻✨️: Mida kale waqtiga wuba kudhamaadaye [2...
xaydari03
 
ch02-Java Fundamentals-Java Fundamentals.pdf
ayeshazaveri4
 
CSO_Gaddis_Java_Chapter02.ppt java book.
resoj26651
 
Java
tintinsan
 
01-ch01-1-println.ppt java introduction one
ssuser656672
 
Chapter 2.4
sotlsoc
 
OOP Using Java Ch2 all about oop .pptx
doopagamer
 
JAVA Programming notes.ppt
AravindSiva19
 
Java PPt.ppt
NavneetSheoran3
 
Cso gaddis java_chapter2
mlrbrown
 
Introduction to Java Applications
Andy Juan Sarango Veliz
 
Java tutorial for beginners-tibacademy.in
TIB Academy
 
Java Basics.pdf
EdFeranil
 
Lec 5 13_aug [compatibility mode]
Palak Sanghani
 
Multi Threading- in Java WPS Office.pptx
ManasaMR2
 
Java Primitive Type from Long Nguyen's lecture
ssusere8fc511
 
Introduction to objects and inputoutput
Ahmad Idrees
 
Intro to programing with java-lecture 1
Mohamed Essam
 
Ad

More from 유석 남 (14)

PDF
01장 Introduction to Computers and Java
유석 남
 
PDF
14장 - 15장 예외처리, 템플릿
유석 남
 
PPTX
13장 연산자 오버로딩
유석 남
 
PDF
12장 상속 (고급)
유석 남
 
PPTX
11장 상속
유석 남
 
PDF
10장 문자열 클래스와 파일 클래스
유석 남
 
PPTX
09장 객체와 클래스 (고급)
유석 남
 
PDF
08장 객체와 클래스 (기본)
유석 남
 
PDF
06장 함수
유석 남
 
PDF
05장 논리적 자료표현: 구조체
유석 남
 
PDF
04장 고급변수 사용
유석 남
 
PPTX
03장 조건문, 반복문, 네임스페이스
유석 남
 
PDF
[20140624]소개자료
유석 남
 
PDF
Example
유석 남
 
01장 Introduction to Computers and Java
유석 남
 
14장 - 15장 예외처리, 템플릿
유석 남
 
13장 연산자 오버로딩
유석 남
 
12장 상속 (고급)
유석 남
 
11장 상속
유석 남
 
10장 문자열 클래스와 파일 클래스
유석 남
 
09장 객체와 클래스 (고급)
유석 남
 
08장 객체와 클래스 (기본)
유석 남
 
06장 함수
유석 남
 
05장 논리적 자료표현: 구조체
유석 남
 
04장 고급변수 사용
유석 남
 
03장 조건문, 반복문, 네임스페이스
유석 남
 
[20140624]소개자료
유석 남
 
Example
유석 남
 
Ad

Recently uploaded (20)

PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
DOCX
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PDF
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
PPTX
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPTX
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
PPTX
Thermal runway and thermal stability.pptx
godow93766
 
PPTX
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
Day2 B2 Best.pptx
helenjenefa1
 
Ethics and Trustworthy AI in Healthcare – Governing Sensitive Data, Profiling...
AlqualsaDIResearchGr
 
Design Thinking basics for Engineers.pdf
CMR University
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
MAD Unit - 2 Activity and Fragment Management in Android (Diploma IT)
JappanMavani
 
Heart Bleed Bug - A case study (Course: Cryptography and Network Security)
Adri Jovin
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Mechanical Design of shell and tube heat exchangers as per ASME Sec VIII Divi...
shahveer210504
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
Damage of stability of a ship and how its change .pptx
ehamadulhaque
 
Thermal runway and thermal stability.pptx
godow93766
 
Depth First Search Algorithm in 🧠 DFS in Artificial Intelligence (AI)
rafeeqshaik212002
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
MRRS Strength and Durability of Concrete
CivilMythili
 

02장 Introduction to Java Applications

  • 1. Java™ How to Program, 9/e © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 2. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 3. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 4.  Java application programming  Use tools from the JDK to compile and run programs.  Videos at www.deitel.com/books/jhtp9/  Help you get started with Eclipse and NetBeans integrated development environments. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 5.  Java application  A computer program that executes when you use the java command to launch the Java Virtual Machine (JVM).  Sample program in Fig. 2.1 displays a line of text. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 6. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 7.  Comments // Fig. 2.1: Welcome1.java  // indicates that the line is a comment.  Used to document programs and improve their readability.  Compiler ignores comments.  A comment that begins with // is an end-of-line comment—it terminates at the end of the line on which it appears.  Traditional comment, can be spread over several lines as in /* This is a traditional comment. It can be split over multiple lines */  This type of comment begins with /* and ends with */.  All text between the delimiters is ignored by the compiler. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 8.  Javadoc comments  Delimited by /** and */.  All text between the Javadoc comment delimiters is ignored by the compiler.  Enable you to embed program documentation directly in your programs.  The javadoc utility program (Appendix M) reads Javadoc comments and uses them to prepare your program’s documentation in HTML format. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 9. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 10. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 11.  Blank lines and space characters  Make programs easier to read.  Blank lines, spaces and tabs are known as white space (or whitespace).  White space is ignored by the compiler. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 12. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 13.  Class declaration public class Welcome1  Every Java program consists of at least one class that you define.  class keyword introduces a class declaration and is immediately followed by the class name.  Keywords (Appendix C) are reserved for use by Java and are always spelled with all lowercase letters. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 14.  Class names  By convention, begin with a capital letter and capitalize the first letter of each word they include (e.g., SampleClassName).  A class name is an identifier—a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not begin with a digit and does not contain spaces.  Java is case sensitive—uppercase and lowercase letters are distinct—so a1 and A1 are different (but both valid) identifiers. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 15. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 16.  Braces  A left brace, {, begins the body of every class declaration.  A corresponding right brace, }, must end each class declaration.  Code between braces should be indented.  This indentation is one of the spacing conventions mentioned earlier. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 17. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 18. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 19. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 20. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 21.  Declaring the main Method public static void main( String[] args )  Starting point of every Java application.  Parentheses after the identifier main indicate that it’s a program building block called a method.  Java class declarations normally contain one or more methods.  main must be defined as shown; otherwise, the JVM will not execute the application.  Methods perform tasks and can return information when they complete their tasks.  Keyword void indicates that this method will not return any information. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 22.  Body of the method declaration  Enclosed in left and right braces.  Statement System.out.println("Welcome to Java Programming!");  Instructs the computer to perform an action  Print the string of characters contained between the double quotation marks.  A string is sometimes called a character string or a string literal.  White-space characters in strings are not ignored by the compiler.  Strings cannot span multiple lines of code. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 23. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 24.  System.out object  Standard output object.  Allows Java applications to display strings in the command window from which the Java application executes.  System.out.println method  Displays (or prints) a line of text in the command window.  The string in the parentheses the argument to the method.  Positions the output cursor at the beginning of the next line in the command window.  Most statements end with a semicolon. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 25. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 26. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 27.  Compiling and Executing Your First Java Application  Open a command window and change to the directory where the program is stored.  Many operating systems use the command cd to change directories.  To compile the program, type javac Welcome1.java  If the program contains no syntax errors, preceding command creates a.class file (known as the class file) containing the platform- independent Java bytecodes that represent the application.  When we use the java command to execute the application on a given platform, these bytecodes will be translated by the JVM into instructions that are understood by the underlying operating system. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 28. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 29. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 30. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 31.  To execute the program, type java Welcome1.  Launches the JVM, which loads the .class file for class Welcome1.  Note that the .class file-name extension is omitted from the preceding command; otherwise, the JVM will not execute the program.  The JVM calls method main to execute the program. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 32. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 33. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 34.  Class Welcome2, shown in Fig. 2.3, uses two statements to produce the same output as that shown in Fig. 2.1.  New and key features in each code listing are highlighted.  System.out’s method print displays a string.  Unlike println, print does not position the output cursor at the beginning of the next line in the command window.  The next character the program displays will appear immediately after the last character that print displays. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 35. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 36.  Newline characters indicate to System.out’s print and println methods when to position the output cursor at the beginning of the next line in the command window.  Newline characters are white-space characters.  The backslash () is called an escape character.  Indicates a “special character”  Backslash is combined with the next character to form an escape sequence.  The escape sequence n represents the newline character.  Complete list of escape sequences java.sun.com/docs/books/jls/third_edition/html/ lexical.html#3.10.6. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 37. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 38. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 39.  System.out.printf method  f means “formatted”  displays formatted data  Multiple method arguments are placed in a comma-separated list.  Java allows large statements to be split over many lines.  Cannot split a statement in the middle of an identifier or string.  Method printf’s first argument is a format string  May consist of fixed text and format specifiers.  Fixed text is output as it would be by print or println.  Each format specifier is a placeholder for a value and specifies the type of data to output.  Format specifiers begin with a percent sign (%) and are followed by a character that represents the data type.  Format specifier %s is a placeholder for a string. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 40. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 41. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 42. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 43.  Integers  Whole numbers, like –22, 7, 0 and 1024)  Programs remember numbers and other data in the computer’s memory and access that data through program elements called variables.  The program of Fig. 2.7 demonstrates these concepts. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 44. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 45. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 46.  import declaration  Helps the compiler locate a class that is used in this program.  Rich set of predefined classes that you can reuse rather than “reinventing the wheel.”  Classes are grouped into packages—named groups of related classes—and are collectively referred to as the Java class library, or the Java Application Programming Interface (Java API).  You use import declarations to identify the predefined classes used in a Java program. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 47. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 48. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 49.  Variable declaration statement Scanner input = new Scanner( System.in );  Specifies the name (input) and type (Scanner) of a variable that is used in this program.  Variable  A location in the computer’s memory where a value can be stored for use later in a program.  Must be declared with a name and a type before they can be used.  A variable’s name enables the program to access the value of the variable in memory.  The name can be any valid identifier.  A variable’s type specifies what kind of information is stored at that location in memory. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 50.  Scanner  Enables a program to read data for use in a program.  Data can come from many sources, such as the user at the keyboard or a file on disk.  Before using a Scanner, you must create it and specify the source of the data.  The equals sign (=) in a declaration indicates that the variable should be initialized (i.e., prepared for use in the program) with the result of the expression to the right of the equals sign.  The new keyword creates an object.  Standard input object, System.in, enables applications to read bytes of information typed by the user.  Scanner object translates these bytes into types that can be used in a program. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 51.  Variable declaration statements int number1; // first number to add int number2; // second number to add int sum; // sum of number1 and number2 declare that variables number1, number2 and sum hold data of type int  They can hold integer.  Range of values for an int is –2,147,483,648 to +2,147,483,647.  Actual int values may not contain commas.  Several variables of the same type may be declared in one declaration with the variable names separated by commas. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 52. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 53. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 54. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 55.  Prompt  Output statement that directs the user to take a specific action.  System is a class.  Part of package java.lang.  Class System is not imported with an import declaration at the beginning of the program. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 56. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 57.  Scanner method nextInt number1 = input.nextInt(); // read first number from user  Obtains an integer from the user at the keyboard.  Program waits for the user to type the number and press the Enter key to submit the number to the program.  The result of the call to method nextInt is placed in variable number1 by using the assignment operator, =.  “number1 gets the value of input.nextInt().”  Operator = is called a binary operator—it has two operands.  Everything to the right of the assignment operator, =, is always evaluated before the assignment is performed. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 58. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 59.  Arithmetic sum = number1 + number2; // add numbers  Assignment statement that calculates the sum of the variables number1 and number2 then assigns the result to variable sum by using the assignment operator, =.  “sum gets the value of number1 + number2.”  In general, calculations are performed in assignment statements.  Portions of statements that contain calculations are called expressions.  An expression is any portion of a statement that has a value associated with it. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 60.  Integer formatted output System.out.printf( "Sum is %dn", sum );  Format specifier %d is a placeholder for an int value  The letter d stands for “decimal integer.” © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 61.  Variables  Every variable has a name, a type, a size (in bytes) and a value.  When a new value is placed into a variable, the new value replaces the previous value (if any)  The previous value is lost. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 62. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 63.  Arithmetic operators are summarized in Fig. 2.11.  The asterisk (*) indicates multiplication  The percent sign (%) is the remainder operator  The arithmetic operators are binary operators because they each operate on two operands.  Integer division yields an integer quotient.  Any fractional part in integer division is simply discarded (i.e., truncated)—no rounding occurs.  The remainder operator, %, yields the remainder after division. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 64. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 65.  Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer.  Expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line.  Parentheses are used to group terms in expressions in the same manner as in algebraic expressions.  If an expression contains nested parentheses, the expression in the innermost set of parentheses is evaluated first. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 66.  Rules of operator precedence  Multiplication, division and remainder operations are applied first.  If an expression contains several such operations, they are applied from left to right.  Multiplication, division and remainder operators have the same level of precedence.  Addition and subtraction operations are applied next.  If an expression contains several such operations, the operators are applied from left to right.  Addition and subtraction operators have the same level of precedence.  When we say that operators are applied from left to right, we are referring to their associativity.  Some operators associate from right to left.  Complete precedence chart is included in Appendix A. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 67. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 68. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 69.  As in algebra, it’s acceptable to place redundant parentheses (unnecessary parentheses) in an ex- pression to make the expression clearer. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 70.  Condition  An expression that can be true or false.  if selection statement  Allows a program to make a decision based on a condition’s value.  Equality operators (== and !=)  Relational operators (>, <, >= and <=)  Both equality operators have the same level of precedence, which is lower than that of the relational operators.  The equality operators associate from left to right.  The relational operators all have the same level of precedence and also associate from left to right. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 71. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 72. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 73. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 74. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 75.  An if statement always begins with keyword if, followed by a condition in parentheses.  Expects one statement in its body, but may contain multiple statements if they are enclosed in a set of braces ({}).  The indentation of the body statement is not required, but it improves the program’s readability by emphasizing that statements are part of the body.  Note that there is no semicolon (;) at the end of the first line of each if statement.  Such a semicolon would result in a logic error at execution time.  Treated as the empty statement—semicolon by itself. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 76. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 77. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 78. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 79. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 80. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
  • 81. © Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.