Chapter 1_Module 1
Chapter 1_Module 1
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.
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.
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.
Features of OOP:
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.
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.
Compile the java program into Bytecodes using the command javac
The compiler creates the bytecodes and store them in a file ending with .class
The JVM’s class loader takes the .class files containing the program’s bytecodes andtransfers
then to primary memory.
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
A java application is a computer program that executes when you use the javacommand to
launch the JVM.
/*******************************************************************
* (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.
A class contains:
a- Variables (attributes)
b- One or more methods that manipulate the attributes that belong to a certainobject of
the class.
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.
17
Another example:
// Fig. 2.4: Welcome3.java
// Printing multiple lines with a single statement.
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
17
Welcome to
Java Programming!
System.out.printf: a method for displaying formatted data, this method takes multiplearguments
separated by commas.
Variables:
A variable is a location in the computer's memory where a value can be stored for use later in a
program.
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
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
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:
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:
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:
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();
Operators:
Arithmetic operators
Addition + f+7 f +7
Multiplication * bm b*m
Integer division yields integer quotient (provided that both operands are integers). Fractions in
17
the result are truncated (no rounding occurs). Examples:
Equality operators
= == x == y x is equal to y
≠ != x != y x is not equal to y
Relational operators
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
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;
+= 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
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, --
17
Increment operator example
} // end main
/**************************************************************************
(C) Copyright 1992-2007 by Deitel & Associates, Inc. and Pearson Education, Inc. All Rights Reserved. */
Parentheses for grouping subexpressions
17
Rules of operator precedence:
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
17
Comparison example:
if ( number1 == number2 )
System.out.printf( "%d == %d\n", number1, number2 );
if ( number1 != number2 )
System.out.printf( "%d != %d\n", number1, number2 );
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.
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 c=5.6f;
long b=c; //Error
float c =5.6f;
long b=(long) c; //b=5
17
Control Structures
– Sequence statement
• Sequential statements
– Statements are normally executed one after the other in the order in which they are
written.
• Selection Statements
– if statement
• Single-selection statement
– if…else statement
• Double-selection statement
– switch statement
• Multiple-selection statement
• if statement
24
• if…else statement
– Executes one action if the specified condition is true or a different action if the specified
condition is false
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.
• 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,
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
– 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:
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
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
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
• Logical operators
o || (conditional OR)
o ! (logical NOT)
24
• Conditional AND (&&) Operator
– Parts of an expression containing && or || operators are evaluated only until it is known
whether the condition is true or false
– Unary operator
24
• The precedence of the Java operators. The operators are shown from top to bottom in decreasing
order of precedence.
- switch statement
- The switch statement performs one of many different actions depending on the value of an
expression.
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
– Character constant
– Constant variable
- 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
• break statement
– Example:
1234
Broke out of loop at count = 5
37
• continue statement
• for statement
37
• while statement
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
• 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:
- Example 2:
37
The output:
– The do…while statement tests the loop-continuation condition after executing the loop’s
body; therefore, the body always executes at least once.
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 for statement can be represented with an equivalent while statement as follows:
initialization;
while ( loopContinuationCondition ) {
statement;
increment;
}
- Example:
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
– Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33, 22, 11, 0
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.
- 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