JavaApplications

Download as pdf or txt
Download as pdf or txt
You are on page 1of 42

Introduction to Java Applications

APT 3040 – FALL 2020


Prof. Audrey Mbogho
USIU-Africa
Our First Java Program

A Java application is a computer program that
executes when you use the java command to launch
the Java Virtual Machine (JVM).

Later in this lecture we’ll discuss how to compile and
run a Java application.

First we consider a simple application that displays
a line of text.

These notes are taken from Java How to Program


by Paul & Harvey Deitel (10th or 11th Edition)

2
A Text Printing Program

3
Comments

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.

Lines 1, 2, 6, 10 and 11 have comments. This type
of comment, which begins with // is called an-end-
of line comment.

Java also allows block comments which are
delimited by /* and */

4
Javadoc Comments

Java provides comments of a third type—Javadoc
comments.

These are delimited by /** and */ . The compiler
ignores all text between the delimiters.

Javadoc comments enable you to embed
program documentation directly in your programs.

The javadoc utility program (part of the JDK)
reads Javadoc comments and uses them to
prepare program documentation in HTML format.

5
A Java Class

Every Java program consists of at least one
class that you (the programmer) define. In the
example it is declared on line 4.

The class keyword introduces a class
declaration and is immediately followed by the
class name ( Welcome1 ).

Keywords (sometimes called reserved words)
are reserved for use by Java and are always
spelled with all lowercase letters.

6
Filename for a public Class

A public class must be placed in a file that has a
filename of the form ClassName .java

So class Welcome1 is stored in the file
Welcome1.java

Both the spelling and capitalisation must be the
same.

A different name will cause a compiler error.

7
Identifiers

By convention, class names begin with a capital letter and capitalize
the first letter of each word they include (e.g., SampleClassName).

Identifiers for other program components start with a lower case letter.

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 it begins with a digit,
and the name input field is not a valid identifier because it contains a
space.

Java is case sensitive—uppercase and lowercase letters are distinct—
so value and Value are different identifiers.

8
Class Body

A left brace (as in line 5), { , begins the body of
every class declaration.

A corresponding right brace (at line 11), } , must
end each class declaration.

Lines 6–10 are indented. This makes your
program easy to read and is good programming
style. IDEs will indent for you automatically.

9
The main() method

The starting or entry point of a Java program is:
public static void main(String[ ] args)

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 7; 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. Later, we’ll see how a method can return information.

10
Performing Output

Line 9 shows how to send output to the screen:
System.out.println("Welcome to Java Programming!");

This instructs the computer to perform an action—
namely, to display the characters contained
between the double quotation marks (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.

Strings cannot span multiple lines of code.

11
The System.out Object

The System.out 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.

The string in the parentheses in line 9 is the
argument to the method.

When System.out.println completes its task, it
positions the output cursor at the beginning of the
next line in the command window.

12
A Java Statement

The entire line 9, including System.out.println,
the argument "Welcome to Java Programming!"
in the parentheses and the semicolon ( ; ), is
called a statement.

A method typically contains one or more
statements that perform its task.

Remove the semicolon and try to compile the
program. Pay attention to the error messages
generated.

13
Compiling and Running the Program

To compile the program on the command line
(or terminal), type
javac Welcome1.java

If there are no error messages, the command
was successful. If you look at the directory
listing, you will see the file Welcome1.class has
been created. Run it by typing
Java Welcome1

Do not include the .class extension

14
Modifying the Program

15
The print and println methods

The first statement uses System.out ’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.

16
The Newline Character

A single statement can display multiple lines by using
the newline character \n , which indicates 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.

Like blank lines, space characters and tab
characters, newline characters are whitespace
characters.

The program shown next outputs four lines of text,
using newline characters to determine when to begin
each new line.

17
Newline Characters

18
The Escape Character

Normally, the characters in a string are displayed exactly as
they appear in the double quotes. Note, however, that the
paired characters \ and n do not appear on the screen.

The backslash ( \ ) is an escape character, which has special
meaning to System.out ’s print and println methods.

When a backslash appears in a string, Java combines it with
the next character to form an escape sequence.

The escape sequence \n represents the newline character.

When a newline character appears in a string being output
with System.out, the newline character causes the screen’s
output cursor to move to the beginning of the next line in the
command window.

19
Some Common Escape Sequences

20
Displaying Text with printf

21
Displaying Text with printf

The System.out.printf method displays
formatted data.

The method call specifies three arguments
placed in a comma-separated list.

The printf method can have any number of
arguments depending on how many pieces of
information need to be displayed.

22
The format String

Method printf ’s first argument is a format string
that may consist of fixed text and format
specifiers.

Fixed text is output by printf just 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 also may include optional
formatting information.

23
Format Specifiers

Format specifiers begin with a percent sign ( % )
followed by a character that represents the data type.
The format specifier %s is a placeholder for a string.

The format string in line 9 specifies that printf should
output two strings, each followed by a newline
character.

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.

24
Format String

So this example substitutes "Welcome to" for
the first %s and "Java Programming!" for the
second %s .

The output shows that two lines of text are
displayed on two lines.

Notice that instead of using the escape
sequence \n , we used the %n format specifier.

You cannot use %n with System.out.print or
System.out.println

25
Adding Two Integers

Our next application reads (or inputs) two
integers (whole numbers, such as –22, 7, 0 and
1024) typed by a user at the keyboard,
computes their sum and displays it.

This program must keep track of the numbers
supplied by the user for the calculation later in
the program.

Programs remember numbers and other data in
the computer’s memory and access that data
through program elements called variables.

26
Adding Two Integers

27
Import Declarations

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).

28
Import Declarations

Line 3 states:
import java.util.Scanner

This is an import declaration that helps the
compiler locate a class used in this program.

It indicates that this example uses Java’s
predefined Scanner class (discussed shortly)
from the package that is named java.util .

This enables the compiler to ensure that you
use the class correctly.

29
Variable Declaration

Line 11 is a variable declaration:
Scanner input = new Scanner(System.in)

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.

A variable’s name can be any valid identifier.

A variable’s type specifies what kind of information is stored
at that location in memory.

30
The Scanner Type

Line 11 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.

31
The Scanner Type

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(System.in).

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, System.in , enables
applications to read bytes of data typed by the user.

The Scanner translates these bytes into types (like int s)
that can be used in a program.

32
Declaring int variables

Lines 13-15 declare variables of type int

This type holds integers (or whole numbers)

The amount of memory set aside for an int is 4
bytes

The range of values for an int is –2,147,483,648
to +2,147,483,647.

33
Other Data Types

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

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.

34
Prompting for Input

We use System.out.print to display the message "Enter first integer: "

This message is called a prompt because it directs the user to take a
specific action.

We use method print here rather than println so that the user’s input
appears on the same line as the prompt.

Recall that identifiers starting with capital letters typically represent
class names.

Class System is part of package java.lang. Notice that class System
is not imported with an import declaration at the beginning of the
program.

By default, package java.lang is imported in every Java program;
thus, classes in java.lang are the only ones in the Java API that do
not require an import declaration.

35
Reading Input

In line 18 gets input from the user
number1 = input.nextInt();

The Scanner object’s nextInt method is used 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. Later in the course, we will learn how
to handle errors (or exceptions as they are known).

36
The Assignment Operator

In line 18, we place the result of the call to method nextInt (an int
value) in variable number1 by using the assignment operator, = .
number1 = input.nextInt();

The statement is read as “ number1 gets the value of
input.nextInt() .”

Operator = is called a binary operator, because it has two
operands— number1 and the result of the method call
input.nextInt() .

This statement is called an assignment statement, because it
assigns a value to a variable.

Everything to the right of the assignment operator, = , is always
evaluated before the assignment is performed.

37
Using Variables in Calculation

Line 23
sum = number1 + number2;

is an assignment statement that calculates the sum of the
variables number1 and number2 then assigns the result to
variable sum by using the assignment operator, = .

The statement is read as “ sum gets the value of number1 +
number2.”

When the program encounters the addition operation, it
performs the calculation using the values stored in the
variables number1 and number2 . In the preceding
statement, the addition operator is a binary operator—its two
operands are the variables number1 and number2.

38
Expressions

Portions of statements that contain calculations
are called expressions. 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
input.nextInt() is the integer typed by the user.

39
Arithmetic Operators

40
Integer Division and the Modulus
Operator

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.

Java provides the remainder operator, % ,
which yields the remainder after division. Thus,
7 % 4 yields 3 , and 17 % 5 yields 2 .

41
Arithmetic Operator Precedence

42

You might also like