0% found this document useful (0 votes)
16 views36 pages

Chapter 1_Module 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
16 views36 pages

Chapter 1_Module 1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 36

Introduction

 Main characteristics of Java


 Features of object oriented programming languages
 Phases to execute a java program

Introduction

Java is an object oriented language, which was generated by Sun Microsystems in 1995.
Objects, or more precisely, the classes objects come from, are reusable software components.
There are date objects, time objects, audio objects, video objects, automobile objects, people
objects and so on. In fact, almost any noun can be represented as a software object in terms of
attributes (e.g. name, color and size) and behaviors (e.g. calculating, moving and
communicating).

 A modular, object oriented design and implementation make software development more
productive than was possible with earlier techniques like structured programming.

 Object oriented programs are often easier to understand, correct and modify.

 Java is the world’s most widely used object oriented programming language.

 Java evolved from C++. C++ is a hybrid language – it is possible to program in either a
C-like style, an object oriented style or both. However, java is a pure object oriented
language, i.e. Java programs always consist of classes.

Main characteristics of Java:

1. Platform independence and portability

The Java complier translates Java source code into bytecodes. Bytecodes are executed by
the Java Virtual Machine (JVM) – a part of the JDK and the foundation of the Java
platform.

A virtual machine (VM) is a software application that simulates a computer but hides the
underlying operating system and hardware from the programs that interact with it. If the
same VM is implemented on many computer platforms,
applications that it executes can be used on all those platforms. The JVM is oneof the
most widely used virtual machines.

Machine code (binary code): is dependent on a specific computer hardware.

Bytecodes: are platform independent instructions, so Java’s bytecodes areportable.

The same bytecodes can execute on any platform containing a JVM thatunderstands the
version of Java in which the bytecodes were compiled.

2. Networking: Communication with other applications through the internet and the www.

3. Multithreading: which enables programmer to specify that activities should occur in


parallel.

4. Richer file processing than is provided by C or C++.

5. Builds applications with GUI.

6. Uses multimedia capabilities (image, animation, video and audio)

7. Object-oriented programming language: in Java, the unit of programming is a class from


which objects are instantiated (created). An object is an instance of a class.

Features of OOP:

1. Encapsulation (information hiding): attributes and operations are encapsulated (wrapped)


into objects. Objects communicate with other objects but they are not allowed to know
how other objects are implemented.

2. Inheritance relationships: a form of SW reuse, in which a new class is created by


absorbing characteristics of existing class and adding to them new characteristics of their
own.

Java doesn’t support multiple inheritance, it only supports single inheritance.

3. Abstraction: which provides an appropriate superclass from which other classes can
inherit and thus share a common design.
4. Polymorphism: which enables us to “program in the general” rather than “program in the
specific”. In particular, polymorphism enables us to write programs that process objects
that share the same superclass (either directly or indirectly) as if they’re all objects of the
superclass.

Phases to execute a java program:

Phase 1: creating a program

This phase consists of editing a file with an editor program. You type a source code using the
editor, make any necessary corrections and save the program on a secondary storage device. A
file name ending with .java extension indicates that the file contains java source code.

Many freeware and shareware editors are available online, including EditPlus, TextPad, jEdit. For
organizations that develop substantial information systems, integrated development environments
(IDEs) are available. Popular IDEs include Eclipse, NetBeans,JBuilder, JCreator, BlueJ, jGRASP.

Phase 2: compiling a java program into bytecodes

Compile the java program into Bytecodes using the command javac

The compiler creates the bytecodes and store them in a file ending with .class

Bytecodes are executed by JVM, JVM is invoked by the command java

Phase 3: loading a program into memory

The JVM’s class loader takes the .class files containing the program’s bytecodes andtransfers
then to primary memory.

Phase 4: bytecode verification

As classes are loaded, the bytecode verifier examines the bytecodes to ensure that theyare valid
and don’t violate java’s security restrictions.

Phase 5: Execution

JVM executes the program’s bytecodes.


Introduction to Java Application

Our first program in Java: printing a line of text


Modifying our first Java program
Displaying text with printf
Another application: adding integers
Memory concepts
Arithmetic
Decision making
Equality and relational operators

Our first program in Java: printing a line of text

A java application is a computer program that executes when you use the javacommand to
launch the JVM.

// Fig. 2.1: Welcome1.java


// Text-printing program.

public class Welcome1


{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.println( "Welcome to Java Programming!" );
} // end method main
} // end class Welcome1

/*******************************************************************
* (C) Copyright 1992-2010 by Deitel & Associates, Inc. and
* Pearson Education, Inc. All Rights Reserved.
********************************************************************/
Comment statements:
Output:
Welcome to Java Programming!
Used to document programs and improve their readability. Java compiler ignorescomments.
A comment begins with:
// end of line (single-line) comment, or
/* (and ends with */ ) traditional multiple-line comments.

17
White space
A white space can be black line, space character or tab, ignored by the compiler. Itmakes
programs easier to read.

The basic unit to write a program in Java is a class.There are


2 types of classes:
1. Java class libraries (API)
2. Programmer defined (user defined) classes.
Every program in Java consists of at least one class declaration defined by theprogrammer.

A class contains:
a- Variables (attributes)
b- One or more methods that manipulate the attributes that belong to a certainobject of
the class.

public class Welcome1

public and class are keywords (always lowercase letters)

public is an access modifier:


An access modifier can be public, private or protected. If not specified it is consideredas
package.
A public class can be accessed from anywhere. When you save the public classdeclaration in a
file, the file name must be: ClassName.java
In our example the file must be saved as Welcome1.java

So, Welcome1 is the class name:


Java is case sensitive – a1 is different than A1
By convention, all class names in Java begin with a capital letter (each subsequentword
begins with a capital letter).
The class name is an identifier (series of characters consisting of letters, digits,underscores and
$ that doesn’t begin with a digit and doesn’t contain spaces.)
◦ Examples of valid identifiers:
hello, valid_$1, $23, _Name
◦ Examples of invalid identifiers:
123Here, exam-1, student ID, not@valid, class

public static void main (String args[])

In a java application, JVM will not execute the application if the main method does notexist, i.e.
for a java application, exactly one of the methods must be called main, otherwise the JVM will
not execute the application. A method is a function that performs tasks and returns information.

17
static: a static method can be called without first creating an object of the class inwhich the
method is declared.

void: keyword that indicates that this method will perform a task but will not returnany
information when it completes its task.
System.out.println (“Welcome to Java Programming!”);System
is a class that is part of java.lang package.
A package is a collection of predefined classes that programmers can reuse (examples:
java.lang, java.util, javax.swing,…)
When you need to reuse a class that is defined in a java package, you can import it first.
All import declarations must appear before the first class declaration in the file.
Exceptions are classes defined in the package java.lang, where java.lang is imported into
all programs by the compiler so the programmer needs not to do so.
out is a class variable (attribute).

System.out is the standard output object that allows Java application to display sets ofcharacters.

println is a method – after printing, it moves the cursor to the next line.

“Welcome to Java Programming!” is an argument of the method println, thisargument is


the string to be printed (without quotation marks).

Modifying our first Java program

// Fig. 2.3: Welcome2.java


// Printing a line of text with multiple statements.
Output:
Welcome
public classtoWelcome2
Java Programming!
{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
} // end method main
} // end class Welcome2

17
Another example:
// Fig. 2.4: Welcome3.java
// Printing multiple lines with a single statement.

public class Welcome3


{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.println( "Welcome\nto\nJava\nProgramming!" );
} // end method main
} // end class Welcome3

Output:
Welcome
to
Java
Programming!
Note:
\character : two characters called escape sequence (\ is called escape character)
Escape sequence description
\n Newline. Position screen cursor at the beginning of the next line
\t Horizontal tab. Move screen cursor to the next tab stop
\r Carriage return. Position screen curser at the beginning of thecurrent
line. Any characters output after the carriage return
overrides the characters previously output on that line.
\\ Backslash. Used to print a backslash character
\” Double quote. Used to print double-quote character
\’ Single quote. Used to print single-quote character

Displaying text with printf

// Fig. 2.6: Welcome4.java


// Displaying multiple lines with method System.out.printf.

public class Welcome4


{
// main method begins execution of Java application
public static void main( String[] args )
{
System.out.printf( "%s\n%s\n",
"Welcome to", "Java Programming!" );
} // end method main
} // end class Welcome4
output

17
Welcome to
Java Programming!

System.out.printf: a method for displaying formatted data, this method takes multiplearguments
separated by commas.

Format string may consist of:


1. Fixed text
2. Format specifiers: place holders for the values and it specifies the type of datato ouput.

% character (the character represents the data type) for example:

%s : place holder for a String


%d : place holder for integer value
%f : place holder for floating-point numbers
%b : place holder for boolean

Variables:
A variable is a location in the computer's memory where a value can be stored for use later in a
program.

We have two kinds of variables:


1- Local variables
Syntax: dataType variableName [= value];
2- Field variables
Syntax: [AccessModifier] [static] dataType variableName [= value];

Variables must be declared with a name and a type:

A variable name can be any valid identifier. By convention, variable-name identifiers


begin with a lowercase letter, and every word in the name after the first begins with a
capital letter. E.g. firstNumber
Variable's type specifies the kind of information stored at that location in memory.
Data Types can be:
1- Primitive types
2- Reference types (Example: String)

17
Primitive Data Types
Category Description JAVA Size Values
8 bits -128 to 127 (i.e. -27 to 27-
byte 1)
whole numbers
(without decimal short 2 bytes -32768 to 32767
points) -2147483648 to
numbers int 4 bytes
2147483647

long 8 bytes -263 to 263-1


float 4 bytes e.g. 17.345f
real numbers
double e.g. 12452.212 (more
8 bytes accurate)
characters single characters char 2 bytes e.g. 'a', '1' and '?'
booleans boolean values boolean 1 byte true or false

Note: All keywords must appear in lowercase letters


Declaration statements end with a semicolon (;)
Variables of the same type may be declared in one declaration or in multiple declarations. For
examples, if you want to declare n1 and n2 as integer variables you can use any of the
following:

int n1;
int n2; or int n1, n2;
Local variables (those declared in the body of a particular method) must be initialized before
being used. For example:

int n1;
n1=15; or int n1=15;
(or their values can be obtained from the user)

char examples:

char a = 'z'; // the letter z (a actually stores the integer value of the letter z)
char b = '\n'; // new line
Strings

A string is a sequence of characters that are treated as a single unit.


A string may be assigned to a String reference, the declaration:

17
String color="blue";

Initializes string variable color to refer to a string object that contains the string "blue".

The class String is used to represent strings in Java. This class provides constructors for
initializing String objects in different ways. For example:

String s = new String ("hello");

Instantiates a new string object using class String's constructor using the sequence of
characters "hello" as its argument and assigns its reference to s.
Addition Example:

// Fig. 2.7: Addition.java


// Addition program that displays the sum of two numbers. The
import java.util.Scanner; // program uses class Scanner

public class Addition


{
// main method begins execution of Java application
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner( System.in );

int number1; // first number to add


int number2; // second number to add
int sum; // sum of number1 and number2

System.out.print( "Enter first integer: " ); // prompt


number1 = input.nextInt(); // read first number from user

System.out.print( "Enter second integer: " ); // prompt


number2 = input.nextInt(); // read second number from user

sum = number1 + number2; // add numbers

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

} // end method main


} // end class Addition
/********************************************************************************************************(
C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved.*/
statement:

import java.util.Scanner;

is an import declaration that helps the compiler locate a class that is used in this program. The
17
above declaration indicates that the program uses java's predefined Scanner class from package
(java.util).

Notes:

All import declarations must appear before the first class declaration in the file.

By default, the package java.lang is imported in every java program. So, classes
in java.lang don’t require an import declaration (e.g. class System).
The statement:

Scanner input = new Scanner (System.in);

is a variable declaration statement: variable name is input, type is Scanner. [A Scanner


enables a program to read data (e.g numbers) for use in a program, the data can come from a
file or the keyboard].

The above statement creates an object of class Scanner (using the keyword new) and the source
of data is specified by System.in (standard input object), which is the keyboard.

The statement:

number1 = input.nextInt();

uses the method nextInt to obtain an integer from the user.


Other Scanner methods:
 next(): read individual words, until a white space character
 nextDouble(): read double value
 nextLine(): read characters typed by the user until the new line character is encountered.
 nextByte()
 nextFloat()
 nextLong()
 nextShort()
 hasNext(): determine whether there's more data to input (returns Boolean value)

Operators:

Arithmetic operators

Java operation Arithmetic operator Algebraic expression Java expression

Addition + f+7 f +7

Subtraction - p-c p–c

Multiplication * bm b*m

Division / x/y or x÷y x/y


(integer or real division)
Remainder % r mod s r%s

Integer division yields integer quotient (provided that both operands are integers). Fractions in
17
the result are truncated (no rounding occurs). Examples:

int x = 7/4; //x= 1


int y= 17/5; //y= 3
In case at least one of the operands was a floating point number, the division will be a real
division (result should be stored in a variable of type double). For example:

double x = 5/2.0; //x= 2.5


Remainder operator yields the remainder after division. For example:
7%4 = 3
17%5 = 2
2%5=2
12%2=0
(note: the sign of the result is the sign of the first operand)

Equality and Relational operators

Standard algebraic Java equality or Sample java condition Meaning of java


equality or relational relational operator condition
operator

Equality operators

= == x == y x is equal to y

≠ != x != y x is not equal to y

Relational operators

> > x>y x is greater than y

< < x<y x is less than y

≥ >= x>=y x is greater than or


equal to y

≤ <= X<=y x is less than or


equal to y

Assignment operator (=)

Used to assign values to variables. Everything to the right of the assignment operator is always
evaluated before the assignment is performed.

17
Compound assignment operator

Any statement of the form: variable = variable operator expression;

Where operator is one of the binary operators +, -, *, / or % can be written in the form:
Variable operator= expression;
e.g. c=c+3 can be written as c+=3;

Assignment operator Sample expression Explanation assigns

Assume: int c=3, d=5, e=4, f=6, g=12;

+= c+=7 c=c+7 10 to c

-= d-=4 d=d-4 1 to d

*= e*=5 e=e*5 20 to e

/= f/=3 F=f/3 2 to f

%= g%=9 g=g%9 3 to g

Increment and decrement operators

Java provides two unary operators for adding 1 to or subtracting 1 from the value of a numeric
variable. The unary increment operator, ++, and the unary decrement operator, --

Operator Operator name Sample Explanation


expression
++ Prefix increment ++a Increment a by 1, then use
the new value of a in the
expression in which a resides.
++ Postfix increment a++ Use the current value of a in
the expression in which a
resides, then increment a by
1.
-- Prefix decrement --b Decrement b by 1, then use
the new value of b in the
expression in which b resides.
-- Postfix decrement b-- Use the current value of b in
the expression in which b
resides, then decrement b by
1.

17
Increment operator example

// Fig. 4.16: Increment.java


// Prefix increment and postfix increment operators.

public class Increment


{
public static void main( String args[] )
{
int c;

// demonstrate postfix increment operator


c = 5; // assign 5 to c
System.out.println( c ); // prints 5
System.out.println( c++ ); // prints 5 then postincrements
System.out.println( c ); // prints 6

System.out.println(); // skip a line

// demonstrate prefix increment operator


c = 5; // assign 5 to c
System.out.println( c ); // prints 5
System.out.println( ++c ); // preincrements then prints 6
System.out.println( c ); // prints 6

} // end main

} // end class Increment

/**************************************************************************
(C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved. */
Parentheses for grouping subexpressions

To multiply a times the quantity b+c, we write:

a*(b+c) if an expression contains nested parentheses, such


as ((a+b)*c)
The expression in the innermost set of parentheses is evaluated first.

17
Rules of operator precedence:

Operators Associativity Type

++ -- Left to right Increment and


decrement operators

* / % Left to right Multiplicative

+ - Left to right Additive

< <= > >= Left to right Relational

== != Left to right Equality

Right to left Conditional


?: (will be explained later)

= += -= *= /= %= Right to left assignment

Examples:

Algebra java

m=(a+b+c+d+e)/5;

m=a+b+c+d+e/5;

y = mx +b y= m*x+b;

z = pr mod q+ w/y z = p * r % q + w / x - y;

y = ax2+bx+c y = a * x * x + b * x + c;

z= p * r % q + w / x - y;
6 1 2 4 3 5
y = a * x * x + b * x + c;
6 1 2 4 3 5

suppose a=2, b=3, c=7, x=5, then y=72

17
Comparison example:

// Fig. 2.15: Comparison.java


// Compare integers using if statements, relational operators and equality operators.
import java.util.Scanner; // program uses class Scanner

public class Comparison


{
// main method begins execution of Java
application public static void main( String args[] )
{
// create Scanner to obtain input from command
window Scanner input = new Scanner( System.in );

int number1; // first number to compare


int number2; // second number to compare

System.out.print( "Enter first integer: " ); // prompt


number1 = input.nextInt(); // read first number from
user

System.out.print( "Enter second integer: " ); // prompt


number2 = input.nextInt(); // read second number from user

if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );

if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );

if ( number1 < number2 )


System.out.printf( "%d < %d\n", number1, number2 );

if ( number1 > number2 )


System.out.printf( "%d > %d\n", number1, number2 );

if ( number1 <= number2 )


System.out.printf( "%d <= %d\n", number1, number2 );

if ( number1 >= number2 )


System.out.printf( "%d >= %d\n", number1, number2 );

} // end method main


} // end class Comparison
/******************************************************************************************
**************( C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson
Education, Inc. All Rights Reserved.*/

17
Conversion between primitive types

Promotion: implicit conversion, conversion without losing data. Promotions allowed for
primitive types:
Type Valid promotions
double None
float double
long float or double
int long, float or double
char int, long, float or double
short int, long, float or double (but not char)
byte short, int, long, float or double (but not char)
Boolean None (Boolean values are not considered to be numbers in java.

For example, the following statements are correct:


int y = 4; char c = 'A';
double x = y; //x=4.0 int d = c; // d=65

but:
double a = 4.5; int m=65;
int b = a; //ERROR char c=m; //Error
Casting: explicit conversion, conversion may cause loss of data. For
example: int a = (int) 3.5; //a=3
long b = 5;
int a = (int) b; //a=5 (note that the value of b is not changed)

Note: when you declare a float variable and initialize it to some value, you should cast this
value because it is considered as double. For example:

float x=4.5; //Error


float x=(float) 4.5; //correct
float x=4.5f; //correct

float c=5.6f;
long b=c; //Error

float c =5.6f;
long b=(long) c; //b=5

17
Control Structures

• Java has three kinds of control structures:

– Sequence statement

– Selection statements (three types)

– Repetition statements (three types)

• Sequential statements

– Statements are normally executed one after the other in the order in which they are
written.

• Selection Statements

– Java has three types of selection statements:

– if statement

• Single-selection statement

– if…else statement

• Double-selection statement

– switch statement

• Multiple-selection statement

• if statement

– Execute an action if the specified condition is true

– For example, the statement:

if ( studentGrade >= 60 ) System.out.println( "Passed"


);
If the condition is true, “Passed” is printed, and the next statement in order is performed.
If the condition is false, the Print statement is ignored, and the next statement in order is
performed. The indentation of the second line of this selection statement is optional, but
recommended.

24
• if…else statement

– Executes one action if the specified condition is true or a different action if the specified
condition is false

– For example, the statement:

if ( grade >= 60 )

System.out.println( "Passed" );

else

System.out.println( "Failed" );

prints “Passed” if the student’s grade is greater than or equal to 60, but prints “Failed” if it
is less than 60. In either case, after printing occurs, the next statement in sequence is
performed.

• Conditional Operator ( ? : )

– Java provides the conditional operator (?:) that can be used in place of an if…else
statement.

– ?: is a ternary operator (takes three operands)

– ? : and its three operands form a conditional expression

• The first operand (to the left of the ?) is a boolean expression.

• The second operand (between the ? and :) is the value of the conditional
expression if the boolean expression is true

• The third operand (to the right of the :) is the value of the conditional
expression if the boolean expression evaluates to false.

– For example,

System.out.println( studentGrade >= 60 ? "Passed" : "Failed" );

The conditional expression in this statement evaluates to the string "Passed" if the
boolean expression studentGrade >= 60 is true and evaluates to the string "Failed" if the
boolean expression is false.

24
• Nested if…else statements

– if…else statements can be put inside other if…else statements

– For example, the following java code represents a nested if…else that prints A for exam
grades greater than or equal to 90, B for grades in the range 80 to 89, C for grades in the
range 70 to 79, D for grades in the range 60 to 69 and F for all other grades:

if ( studentGrade >= 90 ) System.out.println(


"A" );
else
if ( studentGrade >= 80 ) System.out.println(
"B" );
else
if ( studentGrade >= 70 ) System.out.println(
"C" );
else

24
if ( studentGrade
>= 60 )
System.out
.println(
"D" );
else
System.out.println( "F" );
- Most Java programmers prefer to write the preceding if…else statement as

if ( studentGrade >= 90 ) System.out.println(


"A" );
else if ( studentGrade >= 80 )
System.out.println( "B" );
else if ( studentGrade >= 70 )
System.out.println( "C" );
else if ( studentGrade >= 60 )
System.out.println( "D" );
else
System.out.println( "F" );
The two forms are identical except for the spacing and indentation, which the compiler
ignores.

24
• Dangling-else problem

– The Java compiler always associates an else with the immediately preceding if unless told
to do otherwise by the placement of braces ({ and }). This behavior can lead to what is
referred to as the dangling-else problem. For example:

if ( x > 5 )
if ( y > 5 )
System.out.println( "x and y are > 5" );
else
System.out.println( "x is <= 5" );
appears to indicate that if x is greater than 5, the nested if statement determines whether y
is also greater than 5. If so, the string "x and y are > 5" is output. Otherwise, it appears
that if x is not greater than 5, the else part of the if…else outputs the string "x is
<= 5".

Beware! This nested if…else statement does not execute as it appears. The compiler
actually interprets the statement as:

if ( x > 5 )
if ( y > 5 )
System.out.println( "x and y are > 5" );
else
System.out.println( "x is <= 5" );
To force the nested if…else statement to execute as it was originally intended, we must
write it as follows:

if ( x > 5 )
{
if ( y > 5 )
System.out.println( "x and y are > 5" );

}
else
System.out.println( "x is <= 5" );
The braces ({}) indicate to the compiler that the second if statement is in the body of the
first if and that the else is associated with the first if.

24
• Blocks

– Braces { } associate statements into blocks

– To include several statements in the body of an if , enclose the statements in braces ({


and }).

– The following example includes a block in the else-part of an if…else statement:

if ( grade >= 60 )

System.out.println( "Passed" );

else

{
System.out.println( "Failed" ); System.out.println("You must take this course
again");

In this case, if grade is less than 60, the program executes both statements in the body of
the else and prints

Failed

You must take this course again

• Logical operators

- Allows for forming more complex conditions (Combines simple conditions)

- Some Java logical operators are:

o && (conditional AND)

o || (conditional OR)

o & (boolean logical AND)

o | (boolean logical inclusive OR)

o ! (logical NOT)

24
• Conditional AND (&&) Operator

expression1 expression2 expression1 & expression2


&
false false False
false true False
true false False
true true True

– Consider the following if statement

if ( gender == “FEMALE” && age >= 65 )


++count;
• Conditional OR (||) Operator

expression1 expression2 expression1 || expression2


false false false
false true true
true false true
true true true

– Consider the following if statement

if ( ( semesterAverage >= 90 ) || ( finalExam >= 90 System.out.println(


)
“Student grade is A” );
• Short-Circuit Evaluation of Complex Conditions

– Parts of an expression containing && or || operators are evaluated only until it is known
whether the condition is true or false

– E.g., ( gender == “FEMALE” ) && ( age >= 65 )

• Stops immediately if gender is not equal to FEMALE

• Boolean Logical AND (&) Operator

– Works identically to && BUT & always evaluates both operands

• Boolean Logical OR (|) Operator

– Works identically to || BUT | always evaluate both operands

• Logical Negation (!) Operator

– Unary operator

24
• The precedence of the Java operators. The operators are shown from top to bottom in decreasing
order of precedence.

Operators Associativity Type


++ -- Left to right Increment and decrement operators
* / % Left to right Multiplicative
+ - Left to right Additive
< <= > >= Left to right Relational
== != Left to right Equality
& Left to right Boolean logical AND
| Left to right Boolean logical inclusive OR
&& Left to right Conditional AND
|| Left to right Conditional OR
?: Right to left Conditional
= += -= *= /= %= Right to left Assignment

- switch statement

- Used for multiple selections

- The switch statement performs one of many different actions depending on the value of an
expression.

- The general format of the switch statement is:

switch(Expression){case value1:
Statement;
break;
case value1:
Statement;
break;
.
.
default:
Statement;
}

24
- Although each case and the default case in a switch can occur in any order, place the default
case last. When the default case is listed last, the break for that case is not required. Some
programmers include this break for clarity and symmetry with other cases

- Expression in each case can be:

– Constant integral expression

• Combination of integer constants that evaluates to a constant integer value


(byte, short, int or char, but not long)

– Character constant

• E.g., ‘A’, ‘7’ or ‘$’

– Constant variable

• Declared with keyword final

- The switch statement differs from other control statements in that it does not require braces
around multiple statements in a case.

- Without break statements, each time a match occurs in the switch, the statements for that case
and subsequent cases execute until a break statement or the end of the switch is encountered.

- If no match occurs between the controlling expression’s value and a case label, the default
case executes. If no match occurs and the switch does not contain a default case, program
control simply continues with the first statement after the switch.

- Example:
The Output is:
int i=1;
switch (i) {
one
two case 0:
28 System.out.println("zero");
default
break;
case 1:
System.out.println("one");
case 2:
System.out.println("two");
default:
System.out.println("default");
}
• break/continue statements

– Alter flow of control

• break statement

– Causes immediate exit from control structure

• Used in while, for, do…while or switch statements

– Example:

1 // Fig. 5.12: BreakTest.java


2 // break statement exiting a for statement.public class BreakTest
3 {
4
public static void main( String args[] )
5
{
6
int count; // control variable also used after loop terminates
7
8
9 for ( count = 1; count <= 10; count++ ) // loop 10 times
10 {
11 if ( count == 5 ) // if count is 5,break; //
12
terminate loop
13
14
15 System.out.printf( "%d ", count );
16 } // end for
17
18 System.out.printf( "\nBroke out of loop at count = %d\n", count );
19 } // end class BreakTest

1234
Broke out of loop at count = 5

37
• continue statement

– Skips remaining statements in loop body

– Proceeds to next iteration

• Used in while, for or do…while statements


11 2 //3 Fig.
4 6 5.13:
7 8 9 ContinueTest.java
10
2Used continuestatement
// continue to skip printing 5
terminating an iteration of a for statement.public class ContinueTest
3
{
4
• Repetition
public static voidstatements ( looping
main( String args[] ) statements)
5
{
6
for–( int Repeatedly
count = 1; countperforms an action
<= 10; count++ ) // loopwhile its
10 times loop-continuation condition remains true
7
8 {
9
– if ( Java provides
count == three
5 ) // if count repetition statements:
is 5,
10 continue; // skip remaining code in loop
11
• while statement
12 System.out.printf( "%d ", count );
13 • Performs the actions in its body zero or more times
} // end for
14
15 • do…while statement
System.out.println( "\nUsed continue to skip printing 5" );
16
} // d i • Performs the actions in its body one or more times
17 } // end class ContinueTest

• for statement

• Performs the actions in its body zero or more times

37
• while statement

– Repeats an action while its loop-continuation condition remains true

– The general form of while statement is:

initialization;
while ( loopContinuationCondition )

{
statement;
increment;
}

– Not providing, in the body of a while statement, an action that eventually causes the
condition in the while to become false normally results in a logic error called an infinite
loop, in which the loop never terminates

– Counter-controlled repetition requires:

• Control variable (loop counter)

• Initial value of the control variable

• Increment/decrement of control variable through each loop

• Loop-continuation condition that tests for the final value of the control variable

– Example 1:
11 2// Fig.
3 5.1:
4 5WhileCounter.java
6 7 8 9 10
2 // Counter-controlled repetition with the while repetition statement.
3
4 public class WhileCounter
5 {
6 public static void main( String args[] )
7
{
8
int counter = 1; // declare and initialize control variable
9
10
11 while ( counter <= 10 ) // loop-continuation condition

12 {
13 System.out.printf( "%d ", counter );
14 ++counter; // increment control variable by 1
15 } // end while
16
17
System out println(); // output a newline
18 } // end class WhileCounter

37
- Note that the program performs the body of this while even when the control variable is
10. The loop terminates when the control variable exceeds 10 (i.e., counter becomes 11)

- The program in Fig. 5.1 can be made more concise by initializing counter to 0 in line 8
and preincrementing counter in the while condition as follows:

while ( ++counter <= 10 ) // loop-continuation conditionSystem.out.printf( "%d ",


counter );
- This code saves a statement (and eliminates the need for braces around the loop’s
body), because the while condition performs the increment before testing the condition.

- Example 2:

37
The output:

Example 3: int x = 0,y=0;


while (x <= 0) {
if (x < 0){
y = x;
x =x+4;
}
else{
y = -x;
x = x-3;
}
} Output: y= -3
• do…while RepetitionSystem.out.printf("y=%d",y);
Statement

– Similar to while structure

– The do…while statement tests the loop-continuation condition after executing the loop’s
body; therefore, the body always executes at least once.

– The general format of the do/while statement is:

do

statements

} while ( condition );

37
– Example1:
1 // Fig. 5.7: DoWhileTest.java
2
- Example2:
// do...while repetition statement.
3
4 int
public class x=1;
DoWhileTest
The output is:
5 { do{
6 public static voidxmain( String args[] )
= x*2;
2 4 6 8 16
7
8
• for{ System.out.print(" " +x); Repetition Statement
int counter = 1; // initialize counter
9 } while(x<=8);
10 - Java provides the for repetition
do
11 statement, which specifies the counter-
{
12 controlled- repetition details in a single line of code.
13 System.out.printf( "%d ", counter );
14 - The general format of the for statement is:
++counter;
15 } while ( counter <= 10 ); // end do...while
16 for (initialization ; loopContinuationCondition ; increment )
17
Systemstatement;
out println(); // outputs a newline
18 } // end class DoWhileTest

1 2 3 4 5 - 6 7where
8 9 : 10

37
- the initialization expression names the loop’s control variable and optionally provides
its initial value, loopContinuationCondition is the condition that determines whether
the loop should continue executing and increment modifies the control variable’s
value (possibly an increment or decrement), so that the loop-continuation condition
eventually becomes false.

- The two semicolons in the for header are required

- The for statement can be represented with an equivalent while statement as follows:

initialization;
while ( loopContinuationCondition ) {
statement;
increment;
}

- Example:

1 // Fig. 5.2: ForCounter.java


2 // Counter-controlled repetition with the for repetition statement.
3
4 public class ForCounter
5 {
6 public static void main( String args[] )
7 {
8 // for statement header includes initialization,
9 // loop-continuation condition and increment
10 for ( int counter = 1; counter <= 10; counter++ )
11 System.out.printf( "%d ", counter );
12
13 System.out.println(); // output a newline
14 } // end main
15 } // end class ForCounter

1 2 3 4 5 6 7 8 9 10

- Note: When a for statement’s control variable is declared in the initialization section of the for’s
header, using the control variable after the for’s body is a compilation error.

- Placing a semicolon immediately to the right of the right parenthesis of a for header makes that
for’s body an empty statement. This is normally a logic error.

- Infinite loops occur when the loop-continuation condition in a repetition statement never becomes
false. To prevent this situation in a counter-controlled loop, ensure that the control variable is
incremented (or decremented) during each iteration of the loop. In a sentinel- controlled loop,
37
ensure that the sentinel value is eventually input.

37
- Examples Using the for Statement

• Varying control variable in for statement

– Vary control variable from 1 to 100 in increments of 1

• for ( int i = 1; i <= 100; i++ )

– Vary control variable from 100 to 1 in increments of –1

• for ( int i = 100; i >= 1; i-- )

– Vary control variable from 7 to 77 in increments of 7

• for ( int i = 7; i <= 77; i += 7 )

– Vary control variable from 20 to 2 in decrements of 2

• for ( int i = 20; i >= 2; i -= 2 )

– Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20

• for ( int i = 2; i <= 20; i += 3 )

– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0

• for ( int i = 99; i >= 0; i -= 11 )

– Example: Summing the Even Integers from 2 to 20


1Sum is–110
// Fi g. 5.5: Sum.java
2 // Summing integers with the for statement.
3
4 public class Sum
5 {
6 public static void main( String args[] )
7
{
8
int total = 0; // initialize total
9
10
11 // total even integers from 2 through 20
12 for ( int number = 2; number <= 20; number += 2 )total += number;
13
14 System.out.printf( "Sum is %d\n", total ); // display results
15 } // end main
16 } // end class Sum

37
- All three expressions in a for header are optional. If the loopContinuationCondition is
omitted, Java assumes that the loop-continuation condition is always true, thus creating
an infinite loop.

- You might omit the initialization expression if the program initializes the control
variable before the loop. You might omit the increment expression if the program
calculates the increment with statements in the loop’s body or if no increment is
needed.

- The initialization, loop-continuation condition and increment portions of a for statement


can contain arithmetic expressions. For example, assume that x = 2 and y = 10. If x and
y are not modified in the body of the loop, the statement

for ( int j = x; j <= 4 * x *


y; j += y / x ) is equivalent
to the statement
for ( int j = 2; j <= 80; j += 5 )

- If the loop-continuation condition is initially false, the program does not execute the for
statement’s body.

- Example:
The output is:
int a =0; 1
int b = 4;
3
for (a =1; a<b;a++)
• System.out.println(a++); Nested Loops:

- The body of a loop can contain itself a loop, called a nested loop. It is possible to
nest an arbitrary number of loops. If a loop is nested the inner loop will execute all of
its iterations for each time the outer loop executes once.
- Example:
The for (int i =1 ; i<=3;i++){ output is:
for (int j =4; j<=5; j++)
System.out.print(i+" "+j+" " );
System.out.println();
}

1 4 1 5
2 4 2 5
3 4 3 5

37

You might also like