0% found this document useful (0 votes)
6 views59 pages

Running Your First Java Application

The document provides a comprehensive guide on running a Java application, starting with a simple program that displays a welcome message. It covers key concepts such as class declaration, comments, method definitions, and the use of the Java Virtual Machine (JVM) for execution. Additionally, it explains the importance of variable declarations and the use of the Scanner class for user input.

Uploaded by

gexyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views59 pages

Running Your First Java Application

The document provides a comprehensive guide on running a Java application, starting with a simple program that displays a welcome message. It covers key concepts such as class declaration, comments, method definitions, and the use of the Java Virtual Machine (JVM) for execution. Additionally, it explains the importance of variable declarations and the use of the Scanner class for user input.

Uploaded by

gexyu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Running the first Java Application

•A Java application is a computer program


that executes when you use the java
command to launch the Java Virtual
Machine (JVM).
1. //The first java program
2. //Displays line of text
3. public class EthP
4. {
5. // main method begins execution of Java
application
6. public static void main(String[] args)
7. {
8. [Link]("Welcome to Ethio
Programming Youtube Channel!!!");
9. } // end method main
10. } // end class EthP
Running the first Java Application
Commenting Your Programs
 We insert comments to document

programs and improve their readability.


 The Java compiler ignores comments, so

they do not cause the computer to


perform any action when the program is
run.
 The comment inprogram
1. //The first java line 1

 begins with //, indicating that it’s an end-


of-line comment—it terminates at the end
of the line on which the // appears.
Running the first Java Application
 An end-of-line comment need not begin
a line; it also can begin in the middle of
a line and continue until the end (as in
lines 4, 8 and 9).
 Java also has traditional comments,
which can be spread over several lines
as in
/* This is a traditional comment.
It
can be split over multiple lines
*/
Running the first Java Application
 Java provides comments of a third type
—Javadoc comments.
 These are delimited by /** and */.
 The compiler ignores all text between
the delimiters.
Running the first Java Application
Declaring a Class
Line 4
3. public class EthP

 begins a class declaration for class EthP .


 Every Java program consists of at least one class
that you (the programmer) define.
 The class keyword introduces a class declaration
and is immediately followed by the class name
(EthP ).
 Keywords (sometimes called reserved words) are
reserved for use by Java and are always spelled
with all lowercase letters.
 The complete list of keywords is shown in
Appendix C of Java How to Program 10 th Edition.
Running the first Java Application
 public is access specifier which makes
the class to be visible inside and outside
the class.
 A public class must be placed in a file
that has a filename of the form
[Link], so class EthP is stored
in the file EthP .java.
 compilation error occurs if a public
class’s filename is not exactly same
name as the class (in terms of both
spelling and capitalization) followed by
the .java extension.
Running the first Java Application
Class Names and Identifiers
 By convention, class names 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.
 Some valid identifiers are Welcome1, $value,

_value, m_inputField1 and button7.


 The name 7button is not a valid identifier

because
Running the first Java Application
 it begins with a digit, and the name input
field is not a valid identifier because it
contains a space.
 Normally, an identifier that does not begin

with a capital letter is not a class name.


 Java is case sensitive—uppercase and

lowercase letters are distinct—so value


and Value are different (but both valid)
identifiers.
Class Body
 A left brace (as in line 4), {, begins the

body of every class declaration.


Running the first Java Application
 A corresponding right brace (at line 10), },
must end each class declaration. Lines 5–9
are indented.
 Indent the entire body of each class
declaration one “level” between the left
brace and the right brace that delimit the
body of the class.
 This format emphasizes the class
declaration’s structure and makes it easier
to read.
 We use three spaces to form a level of
indent—many programmers prefer two or
four spaces. Whatever you choose, use it
consistently.
Running the first Java Application
 Declaring a Method
Line 6
6. public static void main(String[] args)
 is the starting point of every Java
application.
 The 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.
 For a Java application, one of the methods
must be called main and must be defined as
shown in line 6;
Running the first Java Application
 otherwise, the Java Virtual Machine
(JVM) will not execute the application.
 Static keyword tells the compiler that
the main method is belongs to only to
the class not to the object.
 Keyword void indicates that this
method will not return any
information.
 The String[] args in parentheses is a
required part of the method main’s
declaration in order to declare a valid
java main function.
Running the first Java Application
 The left brace in line 7 begins the body of
the method declaration.
 A corresponding right brace must end it

(line 9).
 Performing Output with

[Link]
Line 8
[Link]("Welcome to Ethio Programming Youtube
Channel!!!");

 instructs the computer to perform an


action to display the characters contained
between the double quotation marks.
Running the first Java Application
 However, the quotation marks
themselves are not displayed
 Together, the quotation marks and the
characters between them are a string—
also known as 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.
Running the first Java Application
 The [Link] object—which is predefined
for you—is known as the standard output
object.
 It allows a Java application to display
information in the command window from
which it executes.
 In recent versions of Microsoft Windows, the
command window is the Command Prompt.
 In UNIX/Linux/Mac OS X, the command
window is called a terminal window or a shell.
 Many programmers call it simply the
command line.
Running the first Java Application
 Method [Link] displays (or
prints) a line of text in the command
window.
 The string in the parentheses in line 8 is
the argument to the method.
[Link]("Welcome to Ethio Programming Youtube
Channel!!!");
Running the first Java Application
 When [Link] completes its
task, it positions the output cursor (the
location where the next character will
be displayed) at the beginning of the
next line in the command window.
 This is similar to what happens when
you press the Enter key while typing in
a text editor—the cursor appears at the
beginning of the next line in the
document.
[Link]("Welcome to Ethio Programming Youtube
Channel!!!");
Running the first Java Application
 The entire line 8, including
[Link], the argument
"Welcome to Ethio Programming Youtube
Channel!!!" in the parentheses and the
semicolon (;), is called a statement.
 A method typically contains one or
more statements that perform its task.
 Most statements end with a semicolon.
 When the statement in line 8 executes, it
displays Welcome to Ethio Programming
Youtube Channel!!!
in the command window.
Running the first Java Application
 When you encounter an error, it will give
you an idea of what caused it.
 Try removing a semicolon or brace from
the program.
 then recompile the program to see the
error messages generated by the
omission.
 When the compiler reports a syntax error,
it may not be on the line that the error
message indicates.
 First, check the line for which the error
was reported.
 If you don’t find an error on that line,
Running the first Java Application
 Compiling Your First Java Application
 We’re now ready to compile and
execute our program.
 We assume you’re using the Java
Development Kit’s command-line tools,
not an IDE.
 To prepare to compile the program,
open a command window and change
to the directory where the program is
stored. Many operating systems use
the command cd to change directories.
Running the first Java Application
 To compile the program, type
javac [Link]
 If the program contains no compilation
errors, this command creates a new file
called
 [Link] (known as the class file for EthP)
containing the platform-independent Java
bytecodes that represent our application.
 When we use the java command to execute
the application on a given platform, the JVM
will translate these bytecodes into
instructions that are understood by the
underlying operating system and hardware.
Running the first Java Application
Executing the EthP Application
 The following instructions assume that

you are in the directory where


[Link] or [Link] file exists.
 To execute this program in a

command window, type :


java EthP and press Enter.
 This command launches the JVM,

which loads the [Link] file.


 The command omits the .class file-

name extension;
 otherwise, the JVM will not execute the

program.
Running the first Java Application
 The JVM calls class EthP’s main
method.
 Next, the statement at line 8 of main
displays "Welcome to Ethio
Programming Youtube
Welcome Channel!!!".
to Ethio Programming Youtube
Channel!!!
Revising the first Java Application

[Link]("Welcome to ");
[Link]("Java Programming!");

 The first statement uses [Link]’s


method print to display a string.
 Each print or println statement resumes
displaying characters from where the last
print or println statement stopped displaying
characters.
 Unlike println, after displaying its argument,
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.
Revising the first Java Application

Displaying Multiple Lines of Text with a


Single Statement.
[Link]("Welcome to Java Programming!");

 Like blank lines, space characters


and tab characters, newline
characters are whitespace
characters.
 The backslash (\) is an escape
character,
Revising the first Java Application
Displaying Text with printf
 The [Link] method (f
means “formatted”) displays
formatted data.
 The program below uses this method

to output on two lines: the strings


"Welcome to" and “Ethio
Programming!!!".
1. // Displaying multiple lines with method [Link].
2. public class Welcome4
3. {
4. // main method begins execution of Java application
5. public static void main(String[] args)
6. {
7. [Link]("%s%n%s%n", "Welcome to", " Ethio
Programming!!!");
8. } // end method main
9. } // end class Welcome4
Displaying Text with printf
[Link]("%s%n%s%n", "Welcome to", " Ethio
 Line 7 Programming!!!");
 call method [Link] to display
the program’s output.
 The method call specifies three arguments.
 When a method requires multiple
arguments, they’re placed in a comma-
separated list.
 Calling a method is also referred to as
invoking a method.
 Place a space after each comma (,) in an
argument list to make programs more
readable.
Displaying Text with printf
 Format specifiers begin with a percent
sign (%) followed by a character that
represents the data type.
 For example, the format specifier %s is
a placeholder for a string.
Displaying Text with printf
 At the first format specifier’s position,

printf substitutes the value of the first


argument after the format string.
 At each subsequent format specifier’s

position, printf substitutes the value of


the next argument.
 So this example substitutes "Welcome

to" for
 the first %s and “Ethio Programming

Youtube Channel!!!" for the second %s.


 The output shows that two lines of text

are
Welcome displayed
to on two lines.
Ethio Programming Youtube Channel
Exercise
 Display type with many exercises
Adding Two numbers
import Declarations
import [Link];
 A great strength of Java is its rich set of

predefined classes that you can reuse


rather than “reinventing the wheel.”
 These 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).
Adding Two numbers
import Declarations
import [Link];
 is an import declaration that helps the

compiler locate a class that’s used in this


program.
 It indicates that the program uses the

predefined Scanner class .


 The compiler then ensures that you use

the class correctly.


 All import declarations must appear before

the first class declaration in the file.


 Placing an import declaration inside or

after a class declaration is a syntax error.


Adding Two numbers
import Declarations
import [Link];
 Forgetting to include an import

declaration for a class that must be


imported results in a compilation
error containing a message such as
“cannot find symbol.”
 When this occurs, check that you

provided the proper import


declarations and that the names in
them are correct, including proper
capitalization.
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
 A variable is a location in the
computer’s memory where a value can
be stored for use later in a program.
 All Java variables 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.
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
 A variable’s name can be any valid
identifier—again, a series of characters
consisting of letters, digits, underscores (_)
and dollar signs ($) .
 It does not begin with a digit and does not
contain spaces.
 A variable’s type specifies what kind of
information is stored at that location in
memory.
 Like other statements, declaration
statements end with a semicolon (;).
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
Scanner input = new Scanner([Link]);
 is a variable declaration statement that
specifies the name (input) and type (Scanner)
of a variable that’s used in this program.
 A Scanner enables a program to read data
(e.g., numbers and strings) for use in a
program.
 The 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.
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
Scanner input = new Scanner([Link]);

 The = in line 11 indicates that Scanner


variable input should be initialized (i.e.,
prepared for use in the program) in its
declaration with the result of the
expression to the right of the equals
sign—new Scanner([Link]).
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
 This expression uses the new keyword
to create a Scanner object that reads
characters typed by the user at the
keyboard.
 The standard input object, [Link],
enables applications to read bytes of
data typed by the user.
 The Scanner translates these bytes into
types (like ints) that can be used in a
program.
Scanner input = new Scanner([Link]);
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
int number1; // first
number to add
int number2; // second number to add
int sum; // sum of number1 and
 declare that variables
number2number1,
number2 and sum hold data of type int
—they can hold integer values
(whole numbers such as 72, –1127 and
0).
 These variables are not yet initialized.
Declaring and Creating a
Scanner to Obtain User Input
from the Keyboard
 The range of values for an int is –
2,147,483,648 to +2,147,483,647.
 Note: The int values you use in a
program should not contain commas.
 Some other types of data are float
and double, for holding real numbers,
and char, for holding character data.
Real numbers contain decimal points,
such as in 3.4, 0.0 and 11.19.
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard
 Variables of type char represent individual
characters, such as an uppercase letter (e.g.,
A), a digit (e.g., 7), a special character (e.g., *
or %) or an escape sequence (e.g., the tab
character, \t).
 The types int, float, double and char are called
primitive types.
 Primitive-type names are keywords and must
appear in all lowercase letters.
 Appendix D of how to program java 10th edition
summarizes the characteristics of the eight
primitive types (boolean, byte, char, short, int,
long, float and double).
Declaring and Creating a Scanner to
Obtain User Input from the
Keyboard

 Several variables of the same type may


be declared in a single declaration with
the variable
 names separated by commas (i.e., a
comma-separated list of variable
names). For
int number1, // first number to add
 For example, it can
number2, // secondbenumber
written
to add as:
sum; // sum of number1 and number2

int number1, number2, sum;


Prompting the User for Input
 Class System is part of package
[Link].
 Notice that class System is not
imported with an import declaration at
the beginning of the program.
 By default, package [Link] is
imported in every Java program; thus,
classes in [Link] are the only ones in
the Java API that do not require an
import declaration.
Obtaining an int as Input from the
User
number1 = [Link](); // read first number
from user
 uses Scanner object input’s nextInt
method to obtain an integer from the
user at the keyboard.
 At this point the program waits for the
user to type the number and press the
Enter key to submit the number to the
program.
 Our program assumes that the user
enters a valid integer value.
 If not, a runtime logic error will occur and
the program will terminate.
Obtaining an int as Input from the
User
number1 = [Link](); // read first number
from user
 we place the result of the call to
method nextInt (an int value) in
variable number1 by using the
assignment operator, =.
 The statement is read as “number1
gets the value of [Link]().”
 Operator = is called a binary operator,
because it has two operands—number1
and the result of the method call
[Link]().
Obtaining an int as Input from the
User
 Portions of statements that contain
calculations are called expressions.
sum = number1 + number2; // add numbers then store
total in sum
 In fact, an expression is any portion of a
statement that has a value associated
with it.
 For example, the value of the expression
number1 + number2 is the sum of the
numbers.
 Similarly, the value of the expression:
[Link]() is the integer typed by the
user.
Obtaining an int as Input from the
User
 After the calculation has been performed,
[Link]("Sum is %d%n", sum); //
 display sum to display the
uses method [Link]
sum. The format specifier %d is a placeholder
for an int value (in this case the value of sum)—
the letter d stands for “decimal integer.”
 The remaining characters in the format string
are all fixed text. So, method printf displays
"Sum is ", followed by the value of sum (in the
position of the %d format specifier) and a
newline.
 Calculations can also be performed inside printf
statements. We could have combined the
[Link]("Sum
statements like: is %d%n", (number1
+ number2));
Memory Concepts
 Variable names such as number1,
number2 and sum actually
correspond to locations in the
computer’s memory. // read first number
number1 = [Link]();
from user
 Every variable has a name, a type, a
size (in bytes) and a value.
 the number typed by the user is
placed into a memory location
corresponding to the name number1.
 Suppose that the user enters 95.
Memory Concepts
 The computer places that integer
value into location
 number1, replacing the previous
value (if any) in that location.
 The previous value is lost, so this
process is said to be destructive.
 When a value is read from a memory
location, the process is
nondestructive. Because it just read
not cut.
number1 = [Link](); // read first number
from user
Arithmetic
 Most programs perform arithmetic
calculations.
 The arithmetic operators are
summarized in the figure below.
 Note the use of various special symbols
not used in algebra.
Arithmetic
 The asterisk (*) indicates
multiplication, and the percent sign
(%) is the remainder operator.
 The arithmetic operators are binary
operators, because each operates
on two operands.
 For example, the expression f + 7
contains the binary operator + and
the two operands f and 7.
Arithmetic
 Integer division yields an integer
quotient.
 For example, the expression 7 / 4
evaluates to 1, and the expression
17 / 5 evaluates to 3.
 Any fractional part in integer
division is simply truncated (i.e.,
discarded)—no rounding occurs.
Arithmetic
 Java provides the remainder
operator, %, which yields the
remainder after division.
 The expression x % y yields the
remainder after x is divided by y.
 Thus, 7 % 4 yields 3, and 17 % 5
yields 2.
 This operator is most commonly
used with integer operands but it
can also be used with other
arithmetic types.
Rules of Operator Precedence
 Java applies the operators in arithmetic
expressions in a precise sequence
determined by the rules of operator
precedence, which are generally the same
as those followed in algebra:
1. Multiplication, division and remainder
operations are applied first.
 If an expression contains several such

operations, they’re applied from left to


right. Multiplication, division and remainder
operators have the same level of
precedence.
Rules of Operator Precedence
2. 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.


Rules of Operator Precedence
 These rules enable Java to apply operators in
the correct order.
 Figure below summarizes these rules of
operator precedence.
 A complete precedence chart is included in
Appendix A of java how to program 10 th
edition.
Decision Making: Equality and
Relational Operators
 A condition is an expression that can be true
or false.
 Conditions can be formed by using the
equality operators (== and !=) 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
import [Link]; // program uses class Scanner
public class Comparison
{
// main method begins execution of Java application
public static void main(String[] args)
{
Scanner input = new Scanner([Link]);
int number1, number2;
[Link]("Enter first integer: "); // prompt
number1 = [Link](); // read first number from
user
[Link]("Enter second integer: "); // prompt
number2 = [Link](); // read second number from
user

[Link] (number1 == number2);


[Link] ((number1 != number2));
[Link] ((number1 < number2));
[Link] ((number1 > number2));
[Link] ( (number1 <= number2));
[Link] ((number1 >= number2));
} // end method main
} // end class Comparison

You might also like