First Program in JAVA: Printing a Line of Text Modifying our First Java Program Escape Sequences ...

48
Introduction to Java Applications

Transcript of First Program in JAVA: Printing a Line of Text Modifying our First Java Program Escape Sequences ...

Page 1: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Introduction to Java Applications

Page 2: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Topics First Program in JAVA: Printing a Line of Text

Modifying our First Java Program

Escape Sequences

Displaying Text with printf

Data types in JAVA

Another Application: Adding Integers

Programs

Memory Concepts

Arithmetic

Decision Making: Equality and Relational Operators

Precedence and Associativity of Operators

Exercises Questions

Programs

Page 3: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

Page 4: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

// Program Name: Welcome.java

// This Program prints line of text

// indicates that the line is a comment. Used to document programs and improve their

readability.

Compiler ignores comments. So they do not cause the computer to perform any action when

the program is run.

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.

Comments:

Page 5: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

public class Welcome

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.

Welcome is a java identifier that specifies the name of the class to be defined.

Keywords are reserved for use by Java and are always spelled with all lowercase letters.

By convention, class names begin with a capital letter and capitalize the first letter of each

word they include for example: AdditionTwoNos

Class declaration:

Opening brace:

Every class definition in Java begins with an opening brace { and ends with a matching

closing brace }, appearing in the last line in the above program.

Page 6: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

public static void main(String[] args) - is the starting point of every

Java application. All parameters are declared inside a pair of parentheses. Defines a method

named main. Conceptually, this is similar to the main() function in C.

A Java application can have any number of classes but only one of them must include a

main method to initiate the execution. otherwise, the JVM will not execute the application.

Methods perform tasks and can return information when they complete their tasks.

This line contains a number of keywords - public, static and void

Method defining:

public

The keyword public is an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes

static

Which declares this method as one that belongs to entire class and not a part of any objects of the class. The main must always be declared as static since the interpreter uses this method before any objects are created. More about the static variables and methods will be discussed later.

void Void is an modifier that states the main method does not return any value.

Page 7: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

Enclosed in left and right braces. All methods in java should be enclosed with open brace

{ and ending brace }.

Body of the method declaration:

System.out.println("Welcome to Java Programming!");

Instructs the computer to perform an action to print the string of characters contained

between the double quotation marks..

System.out: Standard output object.

Allows Java applications to display strings in the command window from which the Java

application executes.

System.out.println : 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.

The statements in java should end with semicolon (;).

Statement:

Page 8: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

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

The figure as shown

Compiling and Executing Your First Java Application :

Page 9: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

javac is the command which complies the java file. If program has the errors it displays the errors with lines numbers and error description. If there are no errors it will display the prompt.

Page 10: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

First Program in JAVA : Printing a Line of Text

To execute the program, type java Welcome.

Launches the JVM, which loads the .class file for class Welcome.

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.

Compiling and Executing Your First Java Application :

Output:

java with the class file name which executes the program displays the result.

Page 11: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Modifying Our First Java Program

Class Welcome1, uses two statements to produce the same output as that shown in above

program..

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.

Page 12: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Modifying Our First Java Program

Prints Welcome to and leaves cursor on same line

Prints Java Programming! starting where the cursor was positioned previously, then outputs a new lines character

Page 13: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Modifying Our First Java Program

Output:

Page 14: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Escape Sequences

The effect of these characters are felt at the time execution but not at the time of compilation.

The backslash (\) is called an escape character. Indicates a “special character”

Backslash is combined with the next character to form an escape sequence.

Some common escape sequences are listed. They are:

Page 15: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Escape Sequences

Program using “\n”

Each \n moves the output cursor to the next line. Where output continues

Page 16: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Escape Sequences

Output:

Page 17: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Displaying Text with printf

Feature added in Java SE 5.0

System.out.printf

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.

Page 18: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Displaying Text with printf

Each %s is a placeholder for a String that comes later in the argument

Statements can be split over multiple lines.

Output:

Page 19: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Data types in JAVA

Although complex data values are represented using objects, Java defines a set of

primitive types to represent simple data.

Java provides eight primitive data types, they are

boolean

char, byte, short, int, long

float, double

Primitive Data Types

Size in Bytes

Size in Bits

int 4 32

long 8 64

float 4 32

double 8 64

char 2 16

boolean (boolean in Java)

1 8

Page 20: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Data types in JAVA

A data type is defined by a set of values called the domain and a set of operations. The

following table shows the data domains and common operations for all eight of Java’s

primitive types:

Type

short

int

long

float

double

char

boolean

8-bit integers in the range –128 to 127

16-bit integers in the range –32768 to 32767

32-bit integers in the range–2146483648 to 2146483647

64-bit integers in the range–9223372036754775808 to 9223372036754775807

32-bit floating-point numbers in the range± 1.4 x 10-45 to ± 3.4028235 x 10-38

64-bit floating-point numbers in the range± 4.39 x 10-322 to ± 1.7976931348623157 x 10308

16-bit characters encoded using Unicode

the values true and false

The arithmetic operators:+-

*/%

addsubtract

remainderdividemultiply

= =<

!=<=>=

equal toless than

greater or equalless or equalnot equal

> greater than

The arithmetic operators except %

The relational operators:

The relational operators

The relational operators

The logical operators:&& add || or ! not

Domain Common operations

byte

Page 21: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Imports class scanner for use in this program

Creates Scanner object for reading data from the user

Page 22: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Varaibles that are declared but not initalized

Page 23: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Reads an int value from the user

Page 24: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Reads another int value from the user

Page 25: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Sums the values of num1 and num2

Page 26: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Output:

Page 27: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

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.

Scanner class :

For input we use methods of the class java.util.Scanner.

Scanner is not part of the fundamental Java Language but is part of a package, java.util, that

you can include in your program.

A Package is a collection of classes which may be used in your program. Think of a package

as a tool box and the classes within it as tools. Different programs need different tools and

include different packages.

Page 28: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Scanner statement :

Scanner input = new Scanner(System.in);

Specifies the name (input) and type (Scanner) of a variable that is used in this program.

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.

Page 29: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Getting Input from a Scanner :

Page 30: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

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.

Variable declaration statements :

int num1; // first number to addint num2; // second number to addint sum; // sum of num1 and num2

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

Page 31: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

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.

Scanner method nextInt

num1 = 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 num1 by using the assignment

operator, =.

“num1 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.

Page 32: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Another Application: Adding Integers

Arithmetic :

sum = num1 + num2;

Assignment statement that calculates the sum of the variables num1 and num2 then assigns

the result to variable sum by using the assignment operator, =.

“sum gets the value of num1 + num2.”

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.

Integer formatted output :

System.out.printf("Sum is %d\n", sum); // display sum

Format specifier %d is a placeholder for an int value

The letter d stands for “decimal integer.”

Page 33: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Programs

Write a java application to display the subtraction two given numbers?

Output:

Write a java application to read the radius of the circle from user and display area and

circumference of the circle? (area: and circumference r) = 3.14

Output:

Write a java application to read the radius of the circle from user and display area and

circumference of the circle? (area: and circumference r) = 3.14

Page 34: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Programs

Write a java application to swap two numbers and display the swapped numbers?

Output:

Page 35: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Memory Concepts

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.

num1 45 num2 72

Memory locations after storing values for num1 and num2

num1 45 num2 72

sum 117

Memory locations after storing sum of num1 and num2

Page 36: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Arithmetic

Arithmetic operators are summarized in given Fig

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

Page 37: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Arithmetic

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.

Page 38: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Arithmetic

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.

Page 39: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Arithmetic

Page 40: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Arithmetic

Write a java application to display the average of three numbers?

Output:

Page 41: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Decision Making: Equality and Relational Operators

Condition: An expression that can be true or false.

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.

Page 42: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Decision Making: Equality and Relational Operators

Page 43: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Decision Making: Equality and Relational Operators

Page 44: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Decision Making: Equality and Relational Operators

Output:

Page 45: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Precedence and Associativity of Operators

All these operators , with the exception of the assignment operator, =, associate from left to

right . Addition is left associate so an expression like x + y + z is evaluated as if had been

various as ( x + y ) + z.

The assignment operator = association is right to left so an expression like x = y = 0 is

evaluated as if it had been written as x = ( y = 0), which first assigns the value 0 to variable

y, then assigns the result of that assignment 0 to x.

The figure as shown

Page 46: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Exercises Questions

1. Assuming x = 2 and y = 3, what does each of the following statements display?

1. System.out.printf(“x = %d\n”, x)

2. System.out.printf(“value of %d + %d = %d”, x, y, (x + y * x ));

2. Assuming that float variable p = 5 and q = 7, what does each of the following statements

display?

1. System.out.printf( "p = %f\n", p );

2. System.out.printf( "%f = %f\n", ( p + q ), ( p + q ) );

Answers:

1.1 x = 2

1.2 2 + 3 = 8

2.1 p = 5.000000

2.2 12.000000 = 12.000000

Page 47: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

Programs

1. Write an application that reads an integer and determines and prints whether it’s even or

odd. [Hint: use the remainder operator. An even number is multiple of 2. Any multiple of 2

leaves remainder of 0 when divided by 2.]

Output:

2. Write an application that ask the user to enter two integers, and prints their sum, product,

difference and division.

Page 48: First Program in JAVA: Printing a Line of Text  Modifying our First Java Program  Escape Sequences  Displaying Text with printf  Data types in JAVA.

?