SlideShare a Scribd company logo
musaabubakartm@gmail.com 08107072658 Page 1
COMPUTER SCIENCE DEPARTMENT
ABDUGUSAU POLYTECHNIC TALATA MAFARA ZAMFARA
STATE
LECTURE NOTE
ON
COMPUTER PROGRAMMING USING OBJECT
ORIENTED JAVA I
(COM 123)
FOR
NDI COMPUTER SCIENCE
COMPILED BY:
MUSA ABUBAKAR
musaabubakartm@gmail.com 08107072658
Using Java
Page 2
A Brief History of Java
Java is an Object Oriented Programming language developed by the team of James Gosling, Patrick
Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems in 1991. This
language was initially called “Oak” but was renamed “Java” in 1995. The name Java came about
when some Suns people went for a cup of coffee and the name Java was suggested and it struck.
Java was developed out of the rich experiences of the professionals who came together to design
the programming language thus, it is an excellent programming language. It has similar syntax to
C/C++ programming languages but without it complexities. Java is an elegant programming language.
Why Java?
Thousands of programmers are embracing Java as the programming language of choice and
several hundred more will be joining before the end of the decade. Why is this so? The
basic reasons for these are highlighted below:
a. Portability: Java is a highly portable programming language because it is not designed
for any specific hardware or software platform. Java programs once written are translated
into an intermediate form called byte code. The byte code is then translated by the Java
Virtual Machine (JVM) into the native object code of the processor that the program is
been executed on. JVMs exist for several computer platforms; hence the term Write Once
Run Anywhere (WORA).
b. Memory Management: Java is very conservative with memory; once a resource is no
longer referenced the garbage collector is called to reclaim the resource. This is one of
the elegant features that distinguish Java from C/C++ where the programmer has to
“manually” reclaim memory.
c. Extensibility: The basic unit of Java programs is the class. Every program written in
Java is a class that specifies the attributes and behaviors of objects of that class. Java
APIs (Application Programmers Interface) contains a rich set reusable classes that is
made available to the programmers. These classes are grouped together as packages from
which the programmer can build new enhanced classes. One of the key terms of object
oriented programming is reuse.
d. Secure: Java is a very secure programming language. Java codes (applets) may not
access the memory on the local computer that they are downloaded upon. Thus it
provides a secure means of developing internet applications.
e. Simple: Java’s feature makes it a concise programming language that is easy to learn and
understand. It is a serious programming language that easily depicts the skill of the
programmer.
f. Robustness: Java is a strongly typed programming language and encourages the
development of error free applications.
Types of Java Programs
Java programs may be developed in three ways. They will be mentioned briefly here:
a. Java Applications: These are stand-alone applications such word processors, inventory
control systems etc.
b. Java Applets: These programs that are executed within a browser. They are executed on
the client computer.
c. Java Serverlets: These are server side programs that are executed within a browser.
In this course we will limit ourselves to only the first one mentioned types of Java program
applications.
musaabubakartm@gmail.com 08107072658 Page 3
INTEGRATED DEVELOPMENT ENVIRONMENT (IDE)
programs called Integrated Development Environments (IDEs), have been created to support the
development of Java programs. IDEs combine an editor, compiler, and other Java support tools
into a single application. The specific tools you will use to develop your programs. Examples of
IDEs include NetBeans depend on your environment, Eclipse, BlueJ etc.
OBJECT ORIENTED PROGRAMMING: Is an approach to software development in
which the software is structured inform of class and object interacting with each other.
Object-oriented languages are outgrowths of functional languages. In object-oriented
languages, the code used to write the program and the data processed by the program are
grouped together into units called objects. Objects are further grouped into classes, which
define the attributes objects must have.
FEATURES OF OOP
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction
5. Interface
6. Class
7. Object
Inheritance: is the ability of a particular class (child class) to inherit the functionalities of
another class (parent class) and add its own.
Polymorphism: is the ability of an object to take different forms.
Encapsulation: is the ability of an object to hide its contents.
Class: is the description of an object.
Object: is an instance of a class.
Data Types in Java
A data type defines a set of values and the operations that can be defined on those values. The
data type of a value (or variable in some contexts) is an attribute that tells what kind of data that
value can have. It define a particular characteristics of data used in software programs and
inform the compilers about predefined attributes required by specific variables or associated
data objects.
Data types in Java can be divided into two groups:
a. Primitive Data Types
b. Reference Data Types (or Non-Primitives)
Primitive Data Types
The term primitive is used here to indicate that these types are not objects in an object-oriented
sense, but rather, normal binary values. All of Java’s other data types are constructed from
these primitive types.
There are eight primitive data types in Java: four subsets of integers, two subsets of floating
point numbers, a character data type, and a boolean data type.
Integers and Floating Points
Java has two basic kinds of numeric values: integers, which have no fractional part, and floating
points, which do. There are four integer data types (byte, short, int, and long) and two floating
point data types (float and double). All of the numeric types differ by the amount of memory
space used to store a value of that type, which determines the range of values that can be
represented. The size of each data type is the same for all hardware platforms. All numeric types
musaabubakartm@gmail.com 08107072658 Page 4
are signed, meaning that both positive and negative values can be stored in them. Below is the
summary of the numeric primitive types.
Type Storage Minimum Value Maximum Value
byte 8 bits -128 127
short 16 bits –32,768 32,767
int 32 bits –2,147,483,648 2,147,483,647
long 64 bits –9,223,372,036,854,775,808 9,223,372,036,854,775,807
float 32 bits Approximately –3.4E+38
with 7 significant digits
Approximately 3.4E+38
with 7 significant digits
double 64 bits Approximately –1.7E+308
with 15 significant digits
Approximately 1.7E+308
with 15 significant digits
Character Data Types
Character data types deal with printable and displayable characters.
a. Char Type
The Char data type is a single two-byte (16-bit) character. The value could be any single
character. For example: e.g “A”,”a”,”B” ,”b”or “C”,”c” e.t.c
b. String Type
The String data type is a sequence of zero or more two-byte (16-bit) characters. If a variable can
contain an indefinite number of characters, declare it as String. The value could be a collection
of characters e.g “musa”, “abdu gusau polytechnic” e.t.c
Boolean DataType
The Boolean DataType is an unsigned value that is interpreted as either True or False. If a
variable can contain only two-state values such as true/false, yes/no, or on/off, declare it as
Boolean.
Reference (Non-primitive Data Types)
Reference or non-primitive type data is used to represent objects. An object is defined by a
class, which can be thought of as the data type of the object. The operations that can be
performed on the object are defined by the methods in the class. The attributes or qualities of
the objects of a class are defined by the fields which in essence are primitive type data values.
Every object belongs to a class and can be referenced using identifiers. An identifier is a name
which is used to identify programming elements such as memory location, names of classes,
Java statements and so on. The names used for identifying memory locations are commonly
referred to as memory variables or variables for short.
Variables
A variable, in the context of programming, is a symbolic name given to an unknown quantity
that permits the name to be used independent of the information it represents. Variables are
associated with data storage locations, and values of a variable are normally changed during the
course of program execution. Variables represent all kinds of data, including booleans, names,
integers, arrays, pictures, sounds, scalars, strings, or any object or class of objects depending on
the programming language that supports them. The symbolic names of variables are replaced
with the actual data location by compilers and interpreters. Data in locations changes during
execution while locations and names are fixed.
In programming, a variable is a container (storage area) to hold data.
musaabubakartm@gmail.com 08107072658 Page 5
To indicate the storage area, each variable should be given a unique name (identifier). Variable
names are just the symbolic representation of a memory location.
Rules for naming variables
a. Variables names may start with and alphabet (a-z / A-Z) and the remaining characters may be,
an underscore (_) or a dollar sign, or a number for example sum, counter, firstName, bar2x
amount_Paid are all valid variable names. 9x, 0value are invalid.
b. Embedded blank spaces may not be included in variable names though an underscore may
be used to join variable names that comprises of compound words. Example x 10 is not
valid, it could be written as x_10 or x10.
c. Reserved words (words defined for specific use in Java) may not be employed as
variables names. Example loop, do, for, while, switch are reserved.
d. Special symbols such as arithmetic operators, comma (,), ?, /, ! are not allowed. e.
Variable name may be of any length.
Variable Declaration
When declaring variable names the scope (visibility) of variables from other part of the program
may be specified, the type of data that should be stored in the area of memory.
Variable names may also represent either primitive data or reference data. The general form for
creating or declaring variable is presented below.
accessModifierdataType variableList or variableNames
accessModifier determines the visibility of the variable to other part of the program e.g. public
or private.
dataType represents either primitive (int, char, float) or reference type data (array, String).
variableList is one or more valid variables separated using commas.
Examples:
a. private int x, y, z;
In this example the access modifier is private, the data type is int and the variables that are
permitted to hold integer values are the identifiers x, y and z.
b. private float balance, initTemperature;
c. private boolean alreadyPaid;
d. public long population;
Alternatively the initial values to be stored in the memory may be specified when declaring the
variables. The general form for declaring and initializing the variables is presented below:
AccessModifier dataType variable1= value1, variable=value2, variable..n=value..n;
examples.
private int x = 10;
private int a = 0, b= 0, c = 0;
public double amountLoaned = 100;
Note: when declaring variables in a method (e.g. main method) do not include the access
modifiers because all variables declared in methods are implicitly private hence localized to that
method. The examples given above can be used to create instance variables.
The following are examples of numeric variable declarations in Java:
int marks = 100;
int x1, x2;
short a = 5;
byte smallNo1, smallNo2;
long total_Balance = 83456.43;
musaabubakartm@gmail.com 08107072658 Page 6
float ratio = 0.2363;
double pi=3.142;
OPERATORS IN JAVA
Arithmetic Operators
Arithmetic operators are special symbols for carrying out calculations. These operators enable
programmers to write arithmetic expressions. An expression is an algebraic like term that
evaluates to a value; it comprises of one or more operands (values) joined together by one or
more operators. Below is a summary of Java arithmetic operators in their order of precedence,
that is, the order in which the arithmetic expression are evaluated.
Order of
Precedence Operator Symbol
Algebraic
Expression
Java
Expression Association
First
Multiplication * a x c a * c Left to Right
Division / x/y or x ÷ y or x/y Left to Right
Modulus or
Remainder
% w mod 3 w % 3 Left to Right
Second
Addition + d+ p d + p Right to Left
Subtraction - j – 2 j - 2 Right to Left
Precedence of Arithmetic Operators
The order in which arithmetic operators are applied on data values (operand) is termed rules of
operator precedence. These rules are similar to that of algebra. They enable Java to evaluate
arithmetic expressions consistently and correctly.
The rules are summarized below:
a. Multiplication, division and modulus are applied first. Arithmetic expressions with several
of these operators are evaluated from the left to the right.
b. Addition and subtraction are applied next. In the situation that an expression contains
several of these operators they are evaluated from right to left.
The order in which the expressions are evaluated is referred to as their association.
Algebra:
Java: (x + y + z)/3;
This expression calculates the average of three values. The parentheses is required so that the
values represented by x, y and z will be added and the result divided by three. If the parentheses
is omitted only z will be divided by three because division has a higher precedence over addition.
Algebra: y = mx + c
Java: y = m * x + c;
In this case the parentheses is not required because multiplication has higher precedence over
addition.
Algebra: z = pr % q + w/x – y
Java: z = p * r % q + w/x – y;
In this example, the expression contains the operators *, % followed by +, / and -. The order of
execution is listed below:
musaabubakartm@gmail.com 08107072658 Page 7
Note: the order of precedence may be overwritten by using parentheses. that is to say if we
desire addition before multiplication or division for example we can include the part of the
expression in parentheses. In the above expression, if x - y is written as (x – y), then the value
represented by the y will be subtracted from that of x then the result will be divided by w.
Exercises
Show the order of execution the following arithmetic expressions and write their Java
equivalents:
a. T= 4r + d mod 4
b. V= y - z x 6/2
c. X = p mod q + r/3
d. Z= (a-b)+cd/2
Relational operators
Relational operators are used to compare numeric values. Each operator takes as operands
two expressions that evaluate to numeric values. The following are examples of relational
operators.
>, <, >=,<=,<>,!=,==
Logical Operators
Logical operators compare Boolean expressions and return a Boolean result that true or false.
E.g &&, ||.
The && Operator performs logical conjunction on two Boolean expressions. If both expressions
evaluate to True, then && returns True. If at least one of the expressions
evaluates to False, then && returns False.
The || Operator performs logical disjunction or inclusion on two Boolean expressions. If
either expression evaluates to True, or both evaluate to True, then Or returns True. If neither
expression evaluates to True, || returns False.
The following example illustrates the && and || operators.
Boolean a, b, c, d, e, f, g;
a. 23 > 14 && 11 > 8
b. 14 > 23 && 11 > 8
The preceding statements set a to True and b to False.
c. 23 > 14 || 8 > 11
d. 23 > 67 || 8 > 11
The preceding statements set c to True and d to False.
Components of a Java Application Program
Every Java application program comprises of a class declaration header, fields (instance variables –
which is optional), the main method and several other methods as required for solving the
problem. The methods and fields are members of the class. In order to explore these components let
us write our first Java program.
musaabubakartm@gmail.com 08107072658 Page 8
/*
* HelloWorld.java
* Displays Hello world!!! to the output window
*/
public class HelloWorld // class definition header
{
public static void main( String[] args )
{
System.out.println( “Hello World!!! “ ); // print text
} // end method main
} // end class HelloWorld
The above program is a simple yet complete program containing the basic features of all Java
application programs. We will consider each of these features and explain them accordingly.
The first few lines of the program are comments.
/*
* HelloWorld.java
* Displays Hello world!!! to the output window
*
*/
The comments are enclosed between the /* */ symbols.
Comments are used for documenting a program, that is, for passing across vital information
concerning the program. Comments are not executed by the computer.
Comments may also be created by using the // symbols either at the beginning of a line:
// This is a comment
Or on the same line after with an executable statement.
System.out.println( “Hello World!!! “ ); // in-line comment.
The rest of the program is the class declaration, starting with the class definition header:
public class HelloWorld, followed by a pair of opening and closing curly brackets.
{
}
The class definition header starts with the access modifier public followed by the keyword class
then the name of the class HelloWorld. The access modifier tells the Java compiler that the class
can be accessed outside the program file that it is declared in.
The keyword class tells Java that we want to define a class using the name HelloWorld.
Note: The file containing this class must be saved using the name HelloWorld.java. The name of
the file and the class name must be the same both in capitalization and sequence. Java is very
case sensitive thus HelloWorld is different from helloworld and also different from HELLOWORLD.
The next part of the program is the declaration of the main method. Methods are used for
carrying out the desired tasks in a Java program, they are akin to functions used in C/C++
programming languages.
public static void main( String[] args )
{
}
is the main method definition header. It starts with the access modifier public, followed by the
musaabubakartm@gmail.com 08107072658 Page 9
keyword static which implies that the method main( ) may be called before an object of the class
has been created. The keyword void implies that the method will not return any value on completion
of its task. These keywords public, static, and void should always be placed in the sequenced
shown. Any information that you need to pass to a method is received by variables specified
within the set of parentheses that follow the name of the method. These variables are called
parameters. If no parameters are required for a given method, you still need to include theempty
parentheses. In main( ) there is only one parameter, String[] args, which declares a
parameter named args. This is an array of objects of type String. (Arrays are collections of
similar objects.) Objects of type String store sequences of characters. In this case, args receives
any command-line arguments present when the program is executed. Note that the parameters
could have been written as String args[]. This is perfectly correct.
The instructions (statements) enclosed within the curly braces will be executed once the main
method is run. The above program contains the instruction that tells Java to display the output
“Hello World!!!” followed by a carriage return. This instruction is:
System.out.println( “Hello World!!!” ); //print text
This line outputs the string followed by a new line on the screen.Output is actually accomplished
by the built-in println( ) method. In this case, println( ) displays the string which is
passed to it. As you will see, println( ) can be used to display other types of information,
too. The line begins with System.out. While too complicated to explain in detail at this time,
briefly, System is a predefined class that provides access to the system, and out is the
output stream that is connected to the console. Thus, System.out is an object that
encapsulates console output. The fact that Java uses an object to define console output is further
evidence of its object-oriented nature.
Notice that the println( ) statement ends with a semicolon. All statements in Java end with a
semicolon. The reason that the other lines in the program do not end in a semicolon is that they
are not, technically, statements.
The first closing brace -}- in the program ends main( ), and the last } ends the HelloWorld
class definition.
(1)program that will display hello word.
public class HelloWorld {
public static void main ( String [ ] args ) {
system.out.println(“Hello World”)
}
(2) program that will display strings in different lines.
public class Example {
public static void main ( String [ ] args ) {
System.out.print("Musa ");
System.out.println("Abubakar ");
System.out.print("Computer Science ");
System.out.println("Department ");
System.out.print("Abdu Gusau ");
System.out.println("Polytechnic ");
System.out.println("Talata Mafara ");
System.out.println("Zamfara State ");
}
}
musaabubakartm@gmail.com 08107072658
USING (Import.java.util.Scanner) TO ACCEPT INPUT FROM THE USER AND
(System.out.println) TO DISPLAY OUTPUT TO THE USER
(3) program that will ask the user to enter two numbers and
display the sum of the two numbers.
import java.util.Scanner;
public class sum {
public static void main ( String [ ] args) {
int Num1,Num2,Sum;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter the first number ");
Num1 = input.nextInt();
System.out.println( "Enter the second number ");
Num2 = input.nextInt();
Sum = Num1 + Num2;
System.out.println(" the sum is " + Sum);
}
}
(3) program that will ask the user to enter radius and display
the sum of the two numbers.
import java.util.Scanner;
public class Area {
public static void main ( String [ ] args) {
double pi,r,area;
pi=3.142;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter the radius ");
r = input.nextDouble();
area= pi*r*r;
System.out.println(" the area of a circle is " + area);
}
}
(4) program that will ask the user to enter base and height
of a triangle. The program will display the area of a triangle .
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
double b,h,area;
Scanner input = new Scanner (System.in);
System.out.print("Enter the base:-");
b = input.nextDouble();
System.out.print("Enter the height:-");
h = input.nextDouble();
area = 1/2*b*h;
System.out.print("The area= " + area);
}
}
Page 10
musaabubakartm@gmail.com 08107072658 Page 11
(4) program that will accept the value of x,y and z from the
user, calculate the expression v = (x*y)/z and display the
value of V.
import java.util.Scanner;
public class Example {
public static void main ( String [ ] args) {
double x,y,z,v;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter the value of x ");
x = input.nextInt();
System.out.println( "Enter the value of y ");
y = input.nextInt();
System.out.println( "Enter the value of z ");
z = input.nextInt();
v = (x*y)/z;
System.out.println("the answer is " + v);
}
}
(5) program that will allow the user to enter price and
quantity of the goods purchased, calculate the total amount
and display the result.
import java.util.Scanner;
public class Example {
public static void main ( String [ ] args) {
double price,quantity,total_amount;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter the unit price ");
price = input.nextDouble();
System.out.println( "Enter the quantity ");
quantity = input.nextDouble();
total_amount=quantity*price;
System.out.println(" Your Total Amount Is " + total_amount);
}
}
(6) program that will ask the user to enter his name, the program will
display WELCOM E TO AGP and his name.
import java.util.Scanner;
public class Example {
public static void main ( String [ ] args) {
String fullname;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter your fullname please ");
fullname = input.next();
System.out.println(" WELCOME TOAGP " + fullname);
}
}
musaabubakartm@gmail.com 08107072658 Page 12
CONTROL STRUCTURES
If Statement
Conditionally executes a group of statements when the given condition is true.
Syntax
Single-line syntax:
if ( condition ) {
statements
}
Multi-line syntax:
if (condition1) {
Statements1
}
else if (condition2) {
Statements2
}
else if (condition….n) {
Statements….n
}
else
{
statement
}
The if statement performs an action if a condition is true and performs a different action if the
condition is false.
The if statement is a single-selection statement because it selects or ignores a single action.
The if...else statement is called a double- selection statement because it selects between two
different actions (or groups of actions).
if Single-S election Statement
Programs use selection statements to choose among alternative courses of action. For example,
suppose that the passing grade on an exam is 40. The java statement
if ( studentGrade >= 40 )
System.out.println( "Passed" );
if...else Double-Selection Statement
The if...else double-selection statement allows the programmer to specify an action to perform
when the condition is true and a different action when the condition is false. For example, the
java statement
if ( grade >= 60 )
System.out.println( "Passed" );
else
System.out.println( "Failed" );
Note that the body of the else is also indented. Whatever indentation convention you choose
should be applied consistently throughout your programs. It is difficult to read programs that do
not obey uniform spacing conventions.
Conditio nal Operator (?:)
Java provides the conditional operator (?:) that can be used in place of an if...else statement.
This is Java's only ternary operator this means that it takes three operands. Together, the
operands and the ?: symbol form a conditional expression. The first operand (to the left of the
?) is a boolean expression (i.e., a condition that evaluates to a boolean value true or false), the
musaabubakartm@gmail.com 08107072658 Page 13
second operand (between the ? and :) is the value of the conditional expression if the boolean
expression is True and 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 statement
System.out.println( studentGrade >= 40 ? "Passed" : "Failed" );
prints the value of println's conditional-expression argument. The conditional expression in
this statement evaluates to the string "Passed" if the boolean expression studentGrade >= 40
is true and evaluates to the string "Failed" if the boolean expression is false. Thus, this
statement with the conditional operator performs essentially the same function as the if...else
statement shown earlier in this section. The precedence of the conditional operator is low, so the
entire conditional expression is normally placed in parentheses. We will see that conditional
expressions can be used in some situations where if...else statements cannot.
Nested if...else Statements
A program can test multiple cases by placing if...else statements inside other if...else
statements to create nested if...else statements. For example, the following java
statements 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 if ( studentGrade >= 60 )
System.out.println( "D" );
else
System.out.println( "F" );
If studentGrade is greater than or equal to 90, the first four conditions will be true, but only the
statement in the if-part of the first if...else statement will execute. After that statement
executes, the else-part of the "outermost" if...else statement is skipped.
(7) program that will ask the user to enter any number and determine
whether it is negative or positive.
import java.util.Scanner;
public class Decision {
public static void main ( String [ ] args) {
int n;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter any number ");
n = input.nextInt();
if (n>= 0) {
System.out.println(" the number you entered is positive");
}
else if (n<0) {
System.out.println(" the number you entered is negative");
}
}
(8) program that will ask the user to enter two numbers and
determine the maximum among the two numbers.
import java.util.Scanner;
public class Decision {
public static void main ( String [ ] args) {
double a,b;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter the value of a ");
a = input.nextInt();
System.out.println( "Enter the value of b ");
b = input.nextInt();
if (a > b) {
System.out.println(" a is greater than b");
}
else if (b > a) {
System.out.println(" b is greater than a");
}
else if (a == b) {
System.out.println(" a and b are equal");
}
}
}
(9) program that will ask the user to enter his score and display the
grade of the score entered by the user.
import java.util.Scanner;
public class Decision {
public static void main ( String [ ] args) {
int score;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Please Enter your score");
score = input.nextInt();
if (score > 100) {
System.out.println("Invalid Score");
}
else if ( score >= 70) {
System.out.println("Your Grade is A");
}
else if (score >=60 ) {
System.out.println("Your Grade is B");
}
else if (score >=50 ) {
System.out.println("Your Grade is C");
}
else if (score >=45 ) {
System.out.println("Your Grade is D");
}
else if (score >=40 ) {
System.out.println("Your Grade is E");
}
else if (score <40 ) {
System.out.println("Your Grade is F");
}
}
}
musaabubakartm@gmail.com 08107072658 Page 14
The while Repetition Statement
A repetition statement (also called a looping statement or a loop) allows the programmer to
specify that a program should repeat an action while some condition remains true.
As an example of Java's while repetition statement, consider a program segment designed to
find the first power of 3 larger than 100. Suppose that the int variable product is initialized to
3. When the following while statement finishes executing, product contains the result:
int product = 3;
while ( product <= 100 )
product = 3 * product;
When this while statement begins execution, the value of variable product is 3. Each iteration
of the while statement multiplies product by 3, so product takes on the values 9, 27, 81 and
243 successively. When variable product becomes 243, the while statement condition product
<= 100becomes false. This terminates the repetition, so the final value of product is 243. At this
point, program execution continues with the next statement after the while statement.
(10) increment program usingDo…While Loop.
import java.util.Scanner;
public class Loop {
public static void main ( String [ ] args) {
inti;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter a number ");
i = input.nextInt();
do
{
System.out.println(i);
i=i+1;
}
while (i<=20);
}
}
(11) decrement program using Do..While Loop.
import java.util.Scanner;
public class Loop {
public static void main ( String [ ] args) {
inti;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter any number ");
i = input.nextInt();
do
{
System.out.println(i);
i=i-1;
}
while (i>0);
}
}
musaabubakartm@gmail.com 08107072658 Page 15
musaabubakartm@gmail.com 08107072658 Page 16
For loop
The For loop is one of the oldest loop structures in programming languages. Unlike the
other two loops, the For loop requires that you know how many times the statements in the
loop will be executed. The For loop has the following syntax:
For (initialization,condition,increment)
{
Statement(s)
}
Example:
For (i=10;i>0;i--) {
System.out.println(i);
}
(12) increment program using For..Loop.
import java.util.Scanner;
public class Loop {
public static void main ( String [ ] args) {
inti;
Scanner input = new Scanner( System.in );
// Accept values from the user
System.out.println( "Enter a number ");
i=input.nextInt();
for (i=1;i<=20;i++)
{
System.out.println(i);
}
}
}
(13) program that will print the factorial of any number entered by user
import java.util.Scanner;
public class Loop {
public static void main ( String [ ] args) {
int i, fact, x;
Scanner input = new Scanner(System.in);
System.out.println("ENTER the number to get it factorial:-");
x = input.nextInt();
fact = 1;
for (i=1; i<=x; i++)
{
fact = fact * i;
}
System.out.println("The factorial of :-" + x + "= " + fact);
}
}
musaabubakartm@gmail.com 08107072658 Page 17
(1) program that will display Hello World to the user and allow him to
enter his name and display WELCOME TO AGP and his name USING
JOptionPane.
import javax.swing.JOptionP ane;
public class HelloGUI {
public static void main(String[] args) {
String msg = "Hello World";
String name;
JOptionPane.showMessageDialog(null, msg );
// accept the users name
name = JOptionPane.showInputDialog( null, "Enter your Name
Please");
// say hello to the user
JOptionPane.showMessageDialog(null, "Welcome To AGP " + name );
} // end method main
} // end of class HelloWorldGUI
(2) program that will allow the user enter two numbers and display the
sum of the two numbers USING JOptionPane.
import javax.swing.JOptionP ane;
public class AddTwoNo {
public static void main(String[] args) {
int FirstNumber, SecondNumber, Sum;
String input;
// accept the NUMBERS FROM THE USER
input = JOptionPane.showInputDialog( null,"EN TER THE FIRST NUMBER");
FirstNumber = Integer.parseInt(input);
input = JOptionPane.showInputDialog( null,"EN TER THE SECOND
NUMBER");
SecondNumber = Integer.parseInt(input);
Sum = FirstNumber + SecondNumber;
JOptionPane.showMessageDialog( null, "The Sum Is " + Sum);
} // end method main
} // end of class AddTwoNo
Using Graphical User Interfaces
The entire program we have written so far has inputted or displayed prompts to the user via the
output window. In most real world programs, this will not be the case. Most modern applications
display messages to the user using windows form, dialog boxes, and use same to accept data
from the user. In our next examples, we will improve on the programs that will be using dialog
boxes.
USING JOptionPane
The JOptionPane class (javax.swing package) enables the user to use its static methods
showInputDialog and showMessageDialog to accept data and display information graphically.
The HelloWorldGUI.java which implements JOptionPane static methods for displaying hello
world to the user is presented below
(3) program that will allow the user to enter principal, rate, and time, the program
will calculate simple interest and display the result USING JOptionPane.
import javax.swing.JOptionPane;
public class SimpleInterest {
public static void main(String[] args) {
double p,r,t,si;
String input;
input=JOptionPane.showInputDi alog(null,"EN TER THE PRINCIPAL AMOUNT");
p=Double.parseDouble(input);
input=JOptionPane.showInputDi alog(null,"EN TER THE RATE");
r=Double.parseDouble(input);
input=JOptionPane.showInputDi alog(null,"EN TER THE TIME");
t=Double.parseDouble(input);
si = (p*r*t)/100;
JOptionPane.showMessageDi alog(null,"THE SIMPLE INTEREST IS " + si);
}
}
(4) program that will allow the user enter two numbers and display the
maximum among the two numbers USING JOptionPane.
import javax.swing.JOptionPane;
public class DecisionGUI {
public static void main(String[] args) {
inta,b;
String input;
input=JOptionPane.showInputDialog(null,"ENTERTHE VALUE OF A");
a=Integer.parseInt(input);
input=JOptionPane.showInputDialog(null,"ENTERTHE VALUE OF B");
b=Integer.parseInt(input); if (a > b){
JOptionPane.showMessageDialog(null,"AISGREATER THAN B”);
}
else if (b > a){
JOptionPane.showMessageDialog(null,"B ISGREATER THAN A”);
}
else if (a==b){
JOptionPane.showMessageDialog(null,"Aand B are equal");
}
}
}
musaabubakartm@gmail.com 08107072658 Page 18
(5) program that will ask the user to enter his total marks and display
whether the user pass or failed USING JOptionPane.
import javax.swing.JOptionPane;
public class DecisionGUI {
public static void main(String[] args) {
intTotal_Marks; String input;
input=JOptionPane.showInputDialog(null,"ENTERYOUR TOTAL MARKS ");
Total_Marks=Integer.parseInt(input); if (Total_Marks > 40 ){
JOptionPane.showMessageDialog(null,"YOU PASS THIS COURSE");
}
else if ( Total_Marks < 40 ){
JOptionPane.showMessageDialog(null,"YOU FAILTHIS COURSE");
}
}
}
musaabubakartm@gmail.com 08107072658 Page 19
musaabubakartm@gmail.com 08107072658 Page 23
Ad

More Related Content

Similar to java handout.doc (20)

ICSE-JavaNotes class 10th -V4.7.2.pdf
ICSE-JavaNotes class 10th    -V4.7.2.pdfICSE-JavaNotes class 10th    -V4.7.2.pdf
ICSE-JavaNotes class 10th -V4.7.2.pdf
ssuser498fb21
 
Java_presesntation.ppt
Java_presesntation.pptJava_presesntation.ppt
Java_presesntation.ppt
VGaneshKarthikeyan
 
Chapter One Basics ofJava Programmming.pptx
Chapter One Basics ofJava Programmming.pptxChapter One Basics ofJava Programmming.pptx
Chapter One Basics ofJava Programmming.pptx
Prashant416351
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
Nuzhat Memon
 
C-sharping.docx
C-sharping.docxC-sharping.docx
C-sharping.docx
LenchoMamudeBaro
 
Java (1).ppt seminar topics engineering
Java (1).ppt  seminar topics engineeringJava (1).ppt  seminar topics engineering
Java (1).ppt seminar topics engineering
4MU21CS023
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
DevaKumari Vijay
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
ssuser2963071
 
A tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfA tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdf
ParasJain570452
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
Java1
Java1Java1
Java1
computertuitions
 
Java
Java Java
Java
computertuitions
 
Java Technologies notes of unit 1 and 2.
Java Technologies notes of unit 1 and 2.Java Technologies notes of unit 1 and 2.
Java Technologies notes of unit 1 and 2.
sumanyadavdpg
 
2.Lesson Plan - Java Variables and Data types.pdf.pdf
2.Lesson Plan - Java Variables and Data types.pdf.pdf2.Lesson Plan - Java Variables and Data types.pdf.pdf
2.Lesson Plan - Java Variables and Data types.pdf.pdf
AbhishekSingh757567
 
Java Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
Akshaj Vadakkath Joshy
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
vmadan89
 
Mit103 object oriented programming
Mit103  object oriented programmingMit103  object oriented programming
Mit103 object oriented programming
smumbahelp
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
ArthyR3
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
Madishetty Prathibha
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
Raveendra R
 
ICSE-JavaNotes class 10th -V4.7.2.pdf
ICSE-JavaNotes class 10th    -V4.7.2.pdfICSE-JavaNotes class 10th    -V4.7.2.pdf
ICSE-JavaNotes class 10th -V4.7.2.pdf
ssuser498fb21
 
Chapter One Basics ofJava Programmming.pptx
Chapter One Basics ofJava Programmming.pptxChapter One Basics ofJava Programmming.pptx
Chapter One Basics ofJava Programmming.pptx
Prashant416351
 
Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)Std 12 Computer Chapter 7 Java Basics (Part 1)
Std 12 Computer Chapter 7 Java Basics (Part 1)
Nuzhat Memon
 
Java (1).ppt seminar topics engineering
Java (1).ppt  seminar topics engineeringJava (1).ppt  seminar topics engineering
Java (1).ppt seminar topics engineering
4MU21CS023
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
DevaKumari Vijay
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
ssuser2963071
 
A tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdfA tour of C# - Overview _ Microsoft Learn.pdf
A tour of C# - Overview _ Microsoft Learn.pdf
ParasJain570452
 
Introduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologiesIntroduction to Java Object Oiented Concepts and Basic terminologies
Introduction to Java Object Oiented Concepts and Basic terminologies
TabassumMaktum
 
Java Technologies notes of unit 1 and 2.
Java Technologies notes of unit 1 and 2.Java Technologies notes of unit 1 and 2.
Java Technologies notes of unit 1 and 2.
sumanyadavdpg
 
2.Lesson Plan - Java Variables and Data types.pdf.pdf
2.Lesson Plan - Java Variables and Data types.pdf.pdf2.Lesson Plan - Java Variables and Data types.pdf.pdf
2.Lesson Plan - Java Variables and Data types.pdf.pdf
AbhishekSingh757567
 
Java Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming BasicsJava Simplified: Understanding Programming Basics
Java Simplified: Understanding Programming Basics
Akshaj Vadakkath Joshy
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
vmadan89
 
Mit103 object oriented programming
Mit103  object oriented programmingMit103  object oriented programming
Mit103 object oriented programming
smumbahelp
 
Qb it1301
Qb   it1301Qb   it1301
Qb it1301
ArthyR3
 
Introduction to Core Java Programming
Introduction to Core Java ProgrammingIntroduction to Core Java Programming
Introduction to Core Java Programming
Raveendra R
 

More from SOMOSCO1 (16)

MAC 426 Political Communication.docx
MAC 426 Political Communication.docxMAC 426 Political Communication.docx
MAC 426 Political Communication.docx
SOMOSCO1
 
project topic on Voice over internet protocol.docx
project topic on Voice over internet protocol.docxproject topic on Voice over internet protocol.docx
project topic on Voice over internet protocol.docx
SOMOSCO1
 
transistor.docx
transistor.docxtransistor.docx
transistor.docx
SOMOSCO1
 
Speech-Success-is.docx
Speech-Success-is.docxSpeech-Success-is.docx
Speech-Success-is.docx
SOMOSCO1
 
THE ROLE OF JUDICIARY IN SOCIETY.docx
THE ROLE OF JUDICIARY IN SOCIETY.docxTHE ROLE OF JUDICIARY IN SOCIETY.docx
THE ROLE OF JUDICIARY IN SOCIETY.docx
SOMOSCO1
 
ROLE OF NIGERIAN TELEVISION AUTHORITY.docx
ROLE OF NIGERIAN TELEVISION AUTHORITY.docxROLE OF NIGERIAN TELEVISION AUTHORITY.docx
ROLE OF NIGERIAN TELEVISION AUTHORITY.docx
SOMOSCO1
 
Types of probability sampling22.docx
Types of probability sampling22.docxTypes of probability sampling22.docx
Types of probability sampling22.docx
SOMOSCO1
 
Vroom suggested that the relationship between people.docx
Vroom suggested that the relationship between people.docxVroom suggested that the relationship between people.docx
Vroom suggested that the relationship between people.docx
SOMOSCO1
 
STP 211 PEST AND PEST CONTROL.docx
STP 211 PEST AND PEST CONTROL.docxSTP 211 PEST AND PEST CONTROL.docx
STP 211 PEST AND PEST CONTROL.docx
SOMOSCO1
 
ACCOUNTING 111.docx
ACCOUNTING  111.docxACCOUNTING  111.docx
ACCOUNTING 111.docx
SOMOSCO1
 
advertising.docx
advertising.docxadvertising.docx
advertising.docx
SOMOSCO1
 
Advertising brief.doc
Advertising brief.docAdvertising brief.doc
Advertising brief.doc
SOMOSCO1
 
ADMED AISHAT OYIZA.docx
ADMED AISHAT OYIZA.docxADMED AISHAT OYIZA.docx
ADMED AISHAT OYIZA.docx
SOMOSCO1
 
ABUBAKIR MUHAMMED.docx
ABUBAKIR MUHAMMED.docxABUBAKIR MUHAMMED.docx
ABUBAKIR MUHAMMED.docx
SOMOSCO1
 
ACKNOWLEDGEMEN pre.docx
ACKNOWLEDGEMEN pre.docxACKNOWLEDGEMEN pre.docx
ACKNOWLEDGEMEN pre.docx
SOMOSCO1
 
ABUBAKAR FATIMAT OHUNENE.docx
ABUBAKAR FATIMAT OHUNENE.docxABUBAKAR FATIMAT OHUNENE.docx
ABUBAKAR FATIMAT OHUNENE.docx
SOMOSCO1
 
MAC 426 Political Communication.docx
MAC 426 Political Communication.docxMAC 426 Political Communication.docx
MAC 426 Political Communication.docx
SOMOSCO1
 
project topic on Voice over internet protocol.docx
project topic on Voice over internet protocol.docxproject topic on Voice over internet protocol.docx
project topic on Voice over internet protocol.docx
SOMOSCO1
 
transistor.docx
transistor.docxtransistor.docx
transistor.docx
SOMOSCO1
 
Speech-Success-is.docx
Speech-Success-is.docxSpeech-Success-is.docx
Speech-Success-is.docx
SOMOSCO1
 
THE ROLE OF JUDICIARY IN SOCIETY.docx
THE ROLE OF JUDICIARY IN SOCIETY.docxTHE ROLE OF JUDICIARY IN SOCIETY.docx
THE ROLE OF JUDICIARY IN SOCIETY.docx
SOMOSCO1
 
ROLE OF NIGERIAN TELEVISION AUTHORITY.docx
ROLE OF NIGERIAN TELEVISION AUTHORITY.docxROLE OF NIGERIAN TELEVISION AUTHORITY.docx
ROLE OF NIGERIAN TELEVISION AUTHORITY.docx
SOMOSCO1
 
Types of probability sampling22.docx
Types of probability sampling22.docxTypes of probability sampling22.docx
Types of probability sampling22.docx
SOMOSCO1
 
Vroom suggested that the relationship between people.docx
Vroom suggested that the relationship between people.docxVroom suggested that the relationship between people.docx
Vroom suggested that the relationship between people.docx
SOMOSCO1
 
STP 211 PEST AND PEST CONTROL.docx
STP 211 PEST AND PEST CONTROL.docxSTP 211 PEST AND PEST CONTROL.docx
STP 211 PEST AND PEST CONTROL.docx
SOMOSCO1
 
ACCOUNTING 111.docx
ACCOUNTING  111.docxACCOUNTING  111.docx
ACCOUNTING 111.docx
SOMOSCO1
 
advertising.docx
advertising.docxadvertising.docx
advertising.docx
SOMOSCO1
 
Advertising brief.doc
Advertising brief.docAdvertising brief.doc
Advertising brief.doc
SOMOSCO1
 
ADMED AISHAT OYIZA.docx
ADMED AISHAT OYIZA.docxADMED AISHAT OYIZA.docx
ADMED AISHAT OYIZA.docx
SOMOSCO1
 
ABUBAKIR MUHAMMED.docx
ABUBAKIR MUHAMMED.docxABUBAKIR MUHAMMED.docx
ABUBAKIR MUHAMMED.docx
SOMOSCO1
 
ACKNOWLEDGEMEN pre.docx
ACKNOWLEDGEMEN pre.docxACKNOWLEDGEMEN pre.docx
ACKNOWLEDGEMEN pre.docx
SOMOSCO1
 
ABUBAKAR FATIMAT OHUNENE.docx
ABUBAKAR FATIMAT OHUNENE.docxABUBAKAR FATIMAT OHUNENE.docx
ABUBAKAR FATIMAT OHUNENE.docx
SOMOSCO1
 
Ad

Recently uploaded (20)

Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnTemplate_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
cegiver630
 
How iCode cybertech Helped Me Recover My Lost Funds
How iCode cybertech Helped Me Recover My Lost FundsHow iCode cybertech Helped Me Recover My Lost Funds
How iCode cybertech Helped Me Recover My Lost Funds
ireneschmid345
 
Digilocker under workingProcess Flow.pptx
Digilocker  under workingProcess Flow.pptxDigilocker  under workingProcess Flow.pptx
Digilocker under workingProcess Flow.pptx
satnamsadguru491
 
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
gmuir1066
 
Defense Against LLM Scheming 2025_04_28.pptx
Defense Against LLM Scheming 2025_04_28.pptxDefense Against LLM Scheming 2025_04_28.pptx
Defense Against LLM Scheming 2025_04_28.pptx
Greg Makowski
 
Medical Dataset including visualizations
Medical Dataset including visualizationsMedical Dataset including visualizations
Medical Dataset including visualizations
vishrut8750588758
 
GenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.aiGenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.ai
Inspirient
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Calories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptxCalories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptx
TijiLMAHESHWARI
 
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjksPpt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
panchariyasahil
 
Thingyan is now a global treasure! See how people around the world are search...
Thingyan is now a global treasure! See how people around the world are search...Thingyan is now a global treasure! See how people around the world are search...
Thingyan is now a global treasure! See how people around the world are search...
Pixellion
 
chapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptxchapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptx
justinebandajbn
 
C++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptxC++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptx
aquibnoor22079
 
Data Science Courses in India iim skills
Data Science Courses in India iim skillsData Science Courses in India iim skills
Data Science Courses in India iim skills
dharnathakur29
 
DPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdfDPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdf
inmishra17121973
 
04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story
ccctableauusergroup
 
Flip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptxFlip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptx
mubashirkhan45461
 
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Abodahab
 
EDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbb
EDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbbEDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbb
EDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbb
JessaMaeEvangelista2
 
Classification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptxClassification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptx
wencyjorda88
 
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnTemplate_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Template_A3nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
cegiver630
 
How iCode cybertech Helped Me Recover My Lost Funds
How iCode cybertech Helped Me Recover My Lost FundsHow iCode cybertech Helped Me Recover My Lost Funds
How iCode cybertech Helped Me Recover My Lost Funds
ireneschmid345
 
Digilocker under workingProcess Flow.pptx
Digilocker  under workingProcess Flow.pptxDigilocker  under workingProcess Flow.pptx
Digilocker under workingProcess Flow.pptx
satnamsadguru491
 
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
Adobe Analytics NOAM Central User Group April 2025 Agent AI: Uncovering the S...
gmuir1066
 
Defense Against LLM Scheming 2025_04_28.pptx
Defense Against LLM Scheming 2025_04_28.pptxDefense Against LLM Scheming 2025_04_28.pptx
Defense Against LLM Scheming 2025_04_28.pptx
Greg Makowski
 
Medical Dataset including visualizations
Medical Dataset including visualizationsMedical Dataset including visualizations
Medical Dataset including visualizations
vishrut8750588758
 
GenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.aiGenAI for Quant Analytics: survey-analytics.ai
GenAI for Quant Analytics: survey-analytics.ai
Inspirient
 
LLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bertLLM finetuning for multiple choice google bert
LLM finetuning for multiple choice google bert
ChadapornK
 
Calories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptxCalories_Prediction_using_Linear_Regression.pptx
Calories_Prediction_using_Linear_Regression.pptx
TijiLMAHESHWARI
 
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjksPpt. Nikhil.pptxnshwuudgcudisisshvehsjks
Ppt. Nikhil.pptxnshwuudgcudisisshvehsjks
panchariyasahil
 
Thingyan is now a global treasure! See how people around the world are search...
Thingyan is now a global treasure! See how people around the world are search...Thingyan is now a global treasure! See how people around the world are search...
Thingyan is now a global treasure! See how people around the world are search...
Pixellion
 
chapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptxchapter 4 Variability statistical research .pptx
chapter 4 Variability statistical research .pptx
justinebandajbn
 
C++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptxC++_OOPs_DSA1_Presentation_Template.pptx
C++_OOPs_DSA1_Presentation_Template.pptx
aquibnoor22079
 
Data Science Courses in India iim skills
Data Science Courses in India iim skillsData Science Courses in India iim skills
Data Science Courses in India iim skills
dharnathakur29
 
DPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdfDPR_Expert_Recruitment_notice_Revised.pdf
DPR_Expert_Recruitment_notice_Revised.pdf
inmishra17121973
 
04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story04302025_CCC TUG_DataVista: The Design Story
04302025_CCC TUG_DataVista: The Design Story
ccctableauusergroup
 
Flip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptxFlip flop presenation-Presented By Mubahir khan.pptx
Flip flop presenation-Presented By Mubahir khan.pptx
mubashirkhan45461
 
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Day 1 - Lab 1 Reconnaissance Scanning with NMAP, Vulnerability Assessment wit...
Abodahab
 
EDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbb
EDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbbEDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbb
EDU533 DEMO.pptxccccvbnjjkoo jhgggggbbbb
JessaMaeEvangelista2
 
Classification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptxClassification_in_Machinee_Learning.pptx
Classification_in_Machinee_Learning.pptx
wencyjorda88
 
Ad

java handout.doc

  • 1. [email protected] 08107072658 Page 1 COMPUTER SCIENCE DEPARTMENT ABDUGUSAU POLYTECHNIC TALATA MAFARA ZAMFARA STATE LECTURE NOTE ON COMPUTER PROGRAMMING USING OBJECT ORIENTED JAVA I (COM 123) FOR NDI COMPUTER SCIENCE COMPILED BY: MUSA ABUBAKAR
  • 2. [email protected] 08107072658 Using Java Page 2 A Brief History of Java Java is an Object Oriented Programming language developed by the team of James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems in 1991. This language was initially called “Oak” but was renamed “Java” in 1995. The name Java came about when some Suns people went for a cup of coffee and the name Java was suggested and it struck. Java was developed out of the rich experiences of the professionals who came together to design the programming language thus, it is an excellent programming language. It has similar syntax to C/C++ programming languages but without it complexities. Java is an elegant programming language. Why Java? Thousands of programmers are embracing Java as the programming language of choice and several hundred more will be joining before the end of the decade. Why is this so? The basic reasons for these are highlighted below: a. Portability: Java is a highly portable programming language because it is not designed for any specific hardware or software platform. Java programs once written are translated into an intermediate form called byte code. The byte code is then translated by the Java Virtual Machine (JVM) into the native object code of the processor that the program is been executed on. JVMs exist for several computer platforms; hence the term Write Once Run Anywhere (WORA). b. Memory Management: Java is very conservative with memory; once a resource is no longer referenced the garbage collector is called to reclaim the resource. This is one of the elegant features that distinguish Java from C/C++ where the programmer has to “manually” reclaim memory. c. Extensibility: The basic unit of Java programs is the class. Every program written in Java is a class that specifies the attributes and behaviors of objects of that class. Java APIs (Application Programmers Interface) contains a rich set reusable classes that is made available to the programmers. These classes are grouped together as packages from which the programmer can build new enhanced classes. One of the key terms of object oriented programming is reuse. d. Secure: Java is a very secure programming language. Java codes (applets) may not access the memory on the local computer that they are downloaded upon. Thus it provides a secure means of developing internet applications. e. Simple: Java’s feature makes it a concise programming language that is easy to learn and understand. It is a serious programming language that easily depicts the skill of the programmer. f. Robustness: Java is a strongly typed programming language and encourages the development of error free applications. Types of Java Programs Java programs may be developed in three ways. They will be mentioned briefly here: a. Java Applications: These are stand-alone applications such word processors, inventory control systems etc. b. Java Applets: These programs that are executed within a browser. They are executed on the client computer. c. Java Serverlets: These are server side programs that are executed within a browser. In this course we will limit ourselves to only the first one mentioned types of Java program applications.
  • 3. [email protected] 08107072658 Page 3 INTEGRATED DEVELOPMENT ENVIRONMENT (IDE) programs called Integrated Development Environments (IDEs), have been created to support the development of Java programs. IDEs combine an editor, compiler, and other Java support tools into a single application. The specific tools you will use to develop your programs. Examples of IDEs include NetBeans depend on your environment, Eclipse, BlueJ etc. OBJECT ORIENTED PROGRAMMING: Is an approach to software development in which the software is structured inform of class and object interacting with each other. Object-oriented languages are outgrowths of functional languages. In object-oriented languages, the code used to write the program and the data processed by the program are grouped together into units called objects. Objects are further grouped into classes, which define the attributes objects must have. FEATURES OF OOP 1. Inheritance 2. Polymorphism 3. Encapsulation 4. Abstraction 5. Interface 6. Class 7. Object Inheritance: is the ability of a particular class (child class) to inherit the functionalities of another class (parent class) and add its own. Polymorphism: is the ability of an object to take different forms. Encapsulation: is the ability of an object to hide its contents. Class: is the description of an object. Object: is an instance of a class. Data Types in Java A data type defines a set of values and the operations that can be defined on those values. The data type of a value (or variable in some contexts) is an attribute that tells what kind of data that value can have. It define a particular characteristics of data used in software programs and inform the compilers about predefined attributes required by specific variables or associated data objects. Data types in Java can be divided into two groups: a. Primitive Data Types b. Reference Data Types (or Non-Primitives) Primitive Data Types The term primitive is used here to indicate that these types are not objects in an object-oriented sense, but rather, normal binary values. All of Java’s other data types are constructed from these primitive types. There are eight primitive data types in Java: four subsets of integers, two subsets of floating point numbers, a character data type, and a boolean data type. Integers and Floating Points Java has two basic kinds of numeric values: integers, which have no fractional part, and floating points, which do. There are four integer data types (byte, short, int, and long) and two floating point data types (float and double). All of the numeric types differ by the amount of memory space used to store a value of that type, which determines the range of values that can be represented. The size of each data type is the same for all hardware platforms. All numeric types
  • 4. [email protected] 08107072658 Page 4 are signed, meaning that both positive and negative values can be stored in them. Below is the summary of the numeric primitive types. Type Storage Minimum Value Maximum Value byte 8 bits -128 127 short 16 bits –32,768 32,767 int 32 bits –2,147,483,648 2,147,483,647 long 64 bits –9,223,372,036,854,775,808 9,223,372,036,854,775,807 float 32 bits Approximately –3.4E+38 with 7 significant digits Approximately 3.4E+38 with 7 significant digits double 64 bits Approximately –1.7E+308 with 15 significant digits Approximately 1.7E+308 with 15 significant digits Character Data Types Character data types deal with printable and displayable characters. a. Char Type The Char data type is a single two-byte (16-bit) character. The value could be any single character. For example: e.g “A”,”a”,”B” ,”b”or “C”,”c” e.t.c b. String Type The String data type is a sequence of zero or more two-byte (16-bit) characters. If a variable can contain an indefinite number of characters, declare it as String. The value could be a collection of characters e.g “musa”, “abdu gusau polytechnic” e.t.c Boolean DataType The Boolean DataType is an unsigned value that is interpreted as either True or False. If a variable can contain only two-state values such as true/false, yes/no, or on/off, declare it as Boolean. Reference (Non-primitive Data Types) Reference or non-primitive type data is used to represent objects. An object is defined by a class, which can be thought of as the data type of the object. The operations that can be performed on the object are defined by the methods in the class. The attributes or qualities of the objects of a class are defined by the fields which in essence are primitive type data values. Every object belongs to a class and can be referenced using identifiers. An identifier is a name which is used to identify programming elements such as memory location, names of classes, Java statements and so on. The names used for identifying memory locations are commonly referred to as memory variables or variables for short. Variables A variable, in the context of programming, is a symbolic name given to an unknown quantity that permits the name to be used independent of the information it represents. Variables are associated with data storage locations, and values of a variable are normally changed during the course of program execution. Variables represent all kinds of data, including booleans, names, integers, arrays, pictures, sounds, scalars, strings, or any object or class of objects depending on the programming language that supports them. The symbolic names of variables are replaced with the actual data location by compilers and interpreters. Data in locations changes during execution while locations and names are fixed. In programming, a variable is a container (storage area) to hold data.
  • 5. [email protected] 08107072658 Page 5 To indicate the storage area, each variable should be given a unique name (identifier). Variable names are just the symbolic representation of a memory location. Rules for naming variables a. Variables names may start with and alphabet (a-z / A-Z) and the remaining characters may be, an underscore (_) or a dollar sign, or a number for example sum, counter, firstName, bar2x amount_Paid are all valid variable names. 9x, 0value are invalid. b. Embedded blank spaces may not be included in variable names though an underscore may be used to join variable names that comprises of compound words. Example x 10 is not valid, it could be written as x_10 or x10. c. Reserved words (words defined for specific use in Java) may not be employed as variables names. Example loop, do, for, while, switch are reserved. d. Special symbols such as arithmetic operators, comma (,), ?, /, ! are not allowed. e. Variable name may be of any length. Variable Declaration When declaring variable names the scope (visibility) of variables from other part of the program may be specified, the type of data that should be stored in the area of memory. Variable names may also represent either primitive data or reference data. The general form for creating or declaring variable is presented below. accessModifierdataType variableList or variableNames accessModifier determines the visibility of the variable to other part of the program e.g. public or private. dataType represents either primitive (int, char, float) or reference type data (array, String). variableList is one or more valid variables separated using commas. Examples: a. private int x, y, z; In this example the access modifier is private, the data type is int and the variables that are permitted to hold integer values are the identifiers x, y and z. b. private float balance, initTemperature; c. private boolean alreadyPaid; d. public long population; Alternatively the initial values to be stored in the memory may be specified when declaring the variables. The general form for declaring and initializing the variables is presented below: AccessModifier dataType variable1= value1, variable=value2, variable..n=value..n; examples. private int x = 10; private int a = 0, b= 0, c = 0; public double amountLoaned = 100; Note: when declaring variables in a method (e.g. main method) do not include the access modifiers because all variables declared in methods are implicitly private hence localized to that method. The examples given above can be used to create instance variables. The following are examples of numeric variable declarations in Java: int marks = 100; int x1, x2; short a = 5; byte smallNo1, smallNo2; long total_Balance = 83456.43;
  • 6. [email protected] 08107072658 Page 6 float ratio = 0.2363; double pi=3.142; OPERATORS IN JAVA Arithmetic Operators Arithmetic operators are special symbols for carrying out calculations. These operators enable programmers to write arithmetic expressions. An expression is an algebraic like term that evaluates to a value; it comprises of one or more operands (values) joined together by one or more operators. Below is a summary of Java arithmetic operators in their order of precedence, that is, the order in which the arithmetic expression are evaluated. Order of Precedence Operator Symbol Algebraic Expression Java Expression Association First Multiplication * a x c a * c Left to Right Division / x/y or x ÷ y or x/y Left to Right Modulus or Remainder % w mod 3 w % 3 Left to Right Second Addition + d+ p d + p Right to Left Subtraction - j – 2 j - 2 Right to Left Precedence of Arithmetic Operators The order in which arithmetic operators are applied on data values (operand) is termed rules of operator precedence. These rules are similar to that of algebra. They enable Java to evaluate arithmetic expressions consistently and correctly. The rules are summarized below: a. Multiplication, division and modulus are applied first. Arithmetic expressions with several of these operators are evaluated from the left to the right. b. Addition and subtraction are applied next. In the situation that an expression contains several of these operators they are evaluated from right to left. The order in which the expressions are evaluated is referred to as their association. Algebra: Java: (x + y + z)/3; This expression calculates the average of three values. The parentheses is required so that the values represented by x, y and z will be added and the result divided by three. If the parentheses is omitted only z will be divided by three because division has a higher precedence over addition. Algebra: y = mx + c Java: y = m * x + c; In this case the parentheses is not required because multiplication has higher precedence over addition. Algebra: z = pr % q + w/x – y Java: z = p * r % q + w/x – y; In this example, the expression contains the operators *, % followed by +, / and -. The order of execution is listed below:
  • 7. [email protected] 08107072658 Page 7 Note: the order of precedence may be overwritten by using parentheses. that is to say if we desire addition before multiplication or division for example we can include the part of the expression in parentheses. In the above expression, if x - y is written as (x – y), then the value represented by the y will be subtracted from that of x then the result will be divided by w. Exercises Show the order of execution the following arithmetic expressions and write their Java equivalents: a. T= 4r + d mod 4 b. V= y - z x 6/2 c. X = p mod q + r/3 d. Z= (a-b)+cd/2 Relational operators Relational operators are used to compare numeric values. Each operator takes as operands two expressions that evaluate to numeric values. The following are examples of relational operators. >, <, >=,<=,<>,!=,== Logical Operators Logical operators compare Boolean expressions and return a Boolean result that true or false. E.g &&, ||. The && Operator performs logical conjunction on two Boolean expressions. If both expressions evaluate to True, then && returns True. If at least one of the expressions evaluates to False, then && returns False. The || Operator performs logical disjunction or inclusion on two Boolean expressions. If either expression evaluates to True, or both evaluate to True, then Or returns True. If neither expression evaluates to True, || returns False. The following example illustrates the && and || operators. Boolean a, b, c, d, e, f, g; a. 23 > 14 && 11 > 8 b. 14 > 23 && 11 > 8 The preceding statements set a to True and b to False. c. 23 > 14 || 8 > 11 d. 23 > 67 || 8 > 11 The preceding statements set c to True and d to False. Components of a Java Application Program Every Java application program comprises of a class declaration header, fields (instance variables – which is optional), the main method and several other methods as required for solving the problem. The methods and fields are members of the class. In order to explore these components let us write our first Java program.
  • 8. [email protected] 08107072658 Page 8 /* * HelloWorld.java * Displays Hello world!!! to the output window */ public class HelloWorld // class definition header { public static void main( String[] args ) { System.out.println( “Hello World!!! “ ); // print text } // end method main } // end class HelloWorld The above program is a simple yet complete program containing the basic features of all Java application programs. We will consider each of these features and explain them accordingly. The first few lines of the program are comments. /* * HelloWorld.java * Displays Hello world!!! to the output window * */ The comments are enclosed between the /* */ symbols. Comments are used for documenting a program, that is, for passing across vital information concerning the program. Comments are not executed by the computer. Comments may also be created by using the // symbols either at the beginning of a line: // This is a comment Or on the same line after with an executable statement. System.out.println( “Hello World!!! “ ); // in-line comment. The rest of the program is the class declaration, starting with the class definition header: public class HelloWorld, followed by a pair of opening and closing curly brackets. { } The class definition header starts with the access modifier public followed by the keyword class then the name of the class HelloWorld. The access modifier tells the Java compiler that the class can be accessed outside the program file that it is declared in. The keyword class tells Java that we want to define a class using the name HelloWorld. Note: The file containing this class must be saved using the name HelloWorld.java. The name of the file and the class name must be the same both in capitalization and sequence. Java is very case sensitive thus HelloWorld is different from helloworld and also different from HELLOWORLD. The next part of the program is the declaration of the main method. Methods are used for carrying out the desired tasks in a Java program, they are akin to functions used in C/C++ programming languages. public static void main( String[] args ) { } is the main method definition header. It starts with the access modifier public, followed by the
  • 9. [email protected] 08107072658 Page 9 keyword static which implies that the method main( ) may be called before an object of the class has been created. The keyword void implies that the method will not return any value on completion of its task. These keywords public, static, and void should always be placed in the sequenced shown. Any information that you need to pass to a method is received by variables specified within the set of parentheses that follow the name of the method. These variables are called parameters. If no parameters are required for a given method, you still need to include theempty parentheses. In main( ) there is only one parameter, String[] args, which declares a parameter named args. This is an array of objects of type String. (Arrays are collections of similar objects.) Objects of type String store sequences of characters. In this case, args receives any command-line arguments present when the program is executed. Note that the parameters could have been written as String args[]. This is perfectly correct. The instructions (statements) enclosed within the curly braces will be executed once the main method is run. The above program contains the instruction that tells Java to display the output “Hello World!!!” followed by a carriage return. This instruction is: System.out.println( “Hello World!!!” ); //print text This line outputs the string followed by a new line on the screen.Output is actually accomplished by the built-in println( ) method. In this case, println( ) displays the string which is passed to it. As you will see, println( ) can be used to display other types of information, too. The line begins with System.out. While too complicated to explain in detail at this time, briefly, System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. Thus, System.out is an object that encapsulates console output. The fact that Java uses an object to define console output is further evidence of its object-oriented nature. Notice that the println( ) statement ends with a semicolon. All statements in Java end with a semicolon. The reason that the other lines in the program do not end in a semicolon is that they are not, technically, statements. The first closing brace -}- in the program ends main( ), and the last } ends the HelloWorld class definition. (1)program that will display hello word. public class HelloWorld { public static void main ( String [ ] args ) { system.out.println(“Hello World”) } (2) program that will display strings in different lines. public class Example { public static void main ( String [ ] args ) { System.out.print("Musa "); System.out.println("Abubakar "); System.out.print("Computer Science "); System.out.println("Department "); System.out.print("Abdu Gusau "); System.out.println("Polytechnic "); System.out.println("Talata Mafara "); System.out.println("Zamfara State "); } }
  • 10. [email protected] 08107072658 USING (Import.java.util.Scanner) TO ACCEPT INPUT FROM THE USER AND (System.out.println) TO DISPLAY OUTPUT TO THE USER (3) program that will ask the user to enter two numbers and display the sum of the two numbers. import java.util.Scanner; public class sum { public static void main ( String [ ] args) { int Num1,Num2,Sum; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter the first number "); Num1 = input.nextInt(); System.out.println( "Enter the second number "); Num2 = input.nextInt(); Sum = Num1 + Num2; System.out.println(" the sum is " + Sum); } } (3) program that will ask the user to enter radius and display the sum of the two numbers. import java.util.Scanner; public class Area { public static void main ( String [ ] args) { double pi,r,area; pi=3.142; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter the radius "); r = input.nextDouble(); area= pi*r*r; System.out.println(" the area of a circle is " + area); } } (4) program that will ask the user to enter base and height of a triangle. The program will display the area of a triangle . import java.util.Scanner; public class Triangle { public static void main(String[] args) { double b,h,area; Scanner input = new Scanner (System.in); System.out.print("Enter the base:-"); b = input.nextDouble(); System.out.print("Enter the height:-"); h = input.nextDouble(); area = 1/2*b*h; System.out.print("The area= " + area); } } Page 10
  • 11. [email protected] 08107072658 Page 11 (4) program that will accept the value of x,y and z from the user, calculate the expression v = (x*y)/z and display the value of V. import java.util.Scanner; public class Example { public static void main ( String [ ] args) { double x,y,z,v; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter the value of x "); x = input.nextInt(); System.out.println( "Enter the value of y "); y = input.nextInt(); System.out.println( "Enter the value of z "); z = input.nextInt(); v = (x*y)/z; System.out.println("the answer is " + v); } } (5) program that will allow the user to enter price and quantity of the goods purchased, calculate the total amount and display the result. import java.util.Scanner; public class Example { public static void main ( String [ ] args) { double price,quantity,total_amount; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter the unit price "); price = input.nextDouble(); System.out.println( "Enter the quantity "); quantity = input.nextDouble(); total_amount=quantity*price; System.out.println(" Your Total Amount Is " + total_amount); } } (6) program that will ask the user to enter his name, the program will display WELCOM E TO AGP and his name. import java.util.Scanner; public class Example { public static void main ( String [ ] args) { String fullname; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter your fullname please "); fullname = input.next(); System.out.println(" WELCOME TOAGP " + fullname); } }
  • 12. [email protected] 08107072658 Page 12 CONTROL STRUCTURES If Statement Conditionally executes a group of statements when the given condition is true. Syntax Single-line syntax: if ( condition ) { statements } Multi-line syntax: if (condition1) { Statements1 } else if (condition2) { Statements2 } else if (condition….n) { Statements….n } else { statement } The if statement performs an action if a condition is true and performs a different action if the condition is false. The if statement is a single-selection statement because it selects or ignores a single action. The if...else statement is called a double- selection statement because it selects between two different actions (or groups of actions). if Single-S election Statement Programs use selection statements to choose among alternative courses of action. For example, suppose that the passing grade on an exam is 40. The java statement if ( studentGrade >= 40 ) System.out.println( "Passed" ); if...else Double-Selection Statement The if...else double-selection statement allows the programmer to specify an action to perform when the condition is true and a different action when the condition is false. For example, the java statement if ( grade >= 60 ) System.out.println( "Passed" ); else System.out.println( "Failed" ); Note that the body of the else is also indented. Whatever indentation convention you choose should be applied consistently throughout your programs. It is difficult to read programs that do not obey uniform spacing conventions. Conditio nal Operator (?:) Java provides the conditional operator (?:) that can be used in place of an if...else statement. This is Java's only ternary operator this means that it takes three operands. Together, the operands and the ?: symbol form a conditional expression. The first operand (to the left of the ?) is a boolean expression (i.e., a condition that evaluates to a boolean value true or false), the
  • 13. [email protected] 08107072658 Page 13 second operand (between the ? and :) is the value of the conditional expression if the boolean expression is True and 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 statement System.out.println( studentGrade >= 40 ? "Passed" : "Failed" ); prints the value of println's conditional-expression argument. The conditional expression in this statement evaluates to the string "Passed" if the boolean expression studentGrade >= 40 is true and evaluates to the string "Failed" if the boolean expression is false. Thus, this statement with the conditional operator performs essentially the same function as the if...else statement shown earlier in this section. The precedence of the conditional operator is low, so the entire conditional expression is normally placed in parentheses. We will see that conditional expressions can be used in some situations where if...else statements cannot. Nested if...else Statements A program can test multiple cases by placing if...else statements inside other if...else statements to create nested if...else statements. For example, the following java statements 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 if ( studentGrade >= 60 ) System.out.println( "D" ); else System.out.println( "F" ); If studentGrade is greater than or equal to 90, the first four conditions will be true, but only the statement in the if-part of the first if...else statement will execute. After that statement executes, the else-part of the "outermost" if...else statement is skipped. (7) program that will ask the user to enter any number and determine whether it is negative or positive. import java.util.Scanner; public class Decision { public static void main ( String [ ] args) { int n; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter any number "); n = input.nextInt(); if (n>= 0) { System.out.println(" the number you entered is positive"); } else if (n<0) { System.out.println(" the number you entered is negative"); } }
  • 14. (8) program that will ask the user to enter two numbers and determine the maximum among the two numbers. import java.util.Scanner; public class Decision { public static void main ( String [ ] args) { double a,b; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter the value of a "); a = input.nextInt(); System.out.println( "Enter the value of b "); b = input.nextInt(); if (a > b) { System.out.println(" a is greater than b"); } else if (b > a) { System.out.println(" b is greater than a"); } else if (a == b) { System.out.println(" a and b are equal"); } } } (9) program that will ask the user to enter his score and display the grade of the score entered by the user. import java.util.Scanner; public class Decision { public static void main ( String [ ] args) { int score; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Please Enter your score"); score = input.nextInt(); if (score > 100) { System.out.println("Invalid Score"); } else if ( score >= 70) { System.out.println("Your Grade is A"); } else if (score >=60 ) { System.out.println("Your Grade is B"); } else if (score >=50 ) { System.out.println("Your Grade is C"); } else if (score >=45 ) { System.out.println("Your Grade is D"); } else if (score >=40 ) { System.out.println("Your Grade is E"); } else if (score <40 ) { System.out.println("Your Grade is F"); } } } [email protected] 08107072658 Page 14
  • 15. The while Repetition Statement A repetition statement (also called a looping statement or a loop) allows the programmer to specify that a program should repeat an action while some condition remains true. As an example of Java's while repetition statement, consider a program segment designed to find the first power of 3 larger than 100. Suppose that the int variable product is initialized to 3. When the following while statement finishes executing, product contains the result: int product = 3; while ( product <= 100 ) product = 3 * product; When this while statement begins execution, the value of variable product is 3. Each iteration of the while statement multiplies product by 3, so product takes on the values 9, 27, 81 and 243 successively. When variable product becomes 243, the while statement condition product <= 100becomes false. This terminates the repetition, so the final value of product is 243. At this point, program execution continues with the next statement after the while statement. (10) increment program usingDo…While Loop. import java.util.Scanner; public class Loop { public static void main ( String [ ] args) { inti; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter a number "); i = input.nextInt(); do { System.out.println(i); i=i+1; } while (i<=20); } } (11) decrement program using Do..While Loop. import java.util.Scanner; public class Loop { public static void main ( String [ ] args) { inti; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter any number "); i = input.nextInt(); do { System.out.println(i); i=i-1; } while (i>0); } } [email protected] 08107072658 Page 15
  • 16. [email protected] 08107072658 Page 16 For loop The For loop is one of the oldest loop structures in programming languages. Unlike the other two loops, the For loop requires that you know how many times the statements in the loop will be executed. The For loop has the following syntax: For (initialization,condition,increment) { Statement(s) } Example: For (i=10;i>0;i--) { System.out.println(i); } (12) increment program using For..Loop. import java.util.Scanner; public class Loop { public static void main ( String [ ] args) { inti; Scanner input = new Scanner( System.in ); // Accept values from the user System.out.println( "Enter a number "); i=input.nextInt(); for (i=1;i<=20;i++) { System.out.println(i); } } } (13) program that will print the factorial of any number entered by user import java.util.Scanner; public class Loop { public static void main ( String [ ] args) { int i, fact, x; Scanner input = new Scanner(System.in); System.out.println("ENTER the number to get it factorial:-"); x = input.nextInt(); fact = 1; for (i=1; i<=x; i++) { fact = fact * i; } System.out.println("The factorial of :-" + x + "= " + fact); } }
  • 17. [email protected] 08107072658 Page 17 (1) program that will display Hello World to the user and allow him to enter his name and display WELCOME TO AGP and his name USING JOptionPane. import javax.swing.JOptionP ane; public class HelloGUI { public static void main(String[] args) { String msg = "Hello World"; String name; JOptionPane.showMessageDialog(null, msg ); // accept the users name name = JOptionPane.showInputDialog( null, "Enter your Name Please"); // say hello to the user JOptionPane.showMessageDialog(null, "Welcome To AGP " + name ); } // end method main } // end of class HelloWorldGUI (2) program that will allow the user enter two numbers and display the sum of the two numbers USING JOptionPane. import javax.swing.JOptionP ane; public class AddTwoNo { public static void main(String[] args) { int FirstNumber, SecondNumber, Sum; String input; // accept the NUMBERS FROM THE USER input = JOptionPane.showInputDialog( null,"EN TER THE FIRST NUMBER"); FirstNumber = Integer.parseInt(input); input = JOptionPane.showInputDialog( null,"EN TER THE SECOND NUMBER"); SecondNumber = Integer.parseInt(input); Sum = FirstNumber + SecondNumber; JOptionPane.showMessageDialog( null, "The Sum Is " + Sum); } // end method main } // end of class AddTwoNo Using Graphical User Interfaces The entire program we have written so far has inputted or displayed prompts to the user via the output window. In most real world programs, this will not be the case. Most modern applications display messages to the user using windows form, dialog boxes, and use same to accept data from the user. In our next examples, we will improve on the programs that will be using dialog boxes. USING JOptionPane The JOptionPane class (javax.swing package) enables the user to use its static methods showInputDialog and showMessageDialog to accept data and display information graphically. The HelloWorldGUI.java which implements JOptionPane static methods for displaying hello world to the user is presented below
  • 18. (3) program that will allow the user to enter principal, rate, and time, the program will calculate simple interest and display the result USING JOptionPane. import javax.swing.JOptionPane; public class SimpleInterest { public static void main(String[] args) { double p,r,t,si; String input; input=JOptionPane.showInputDi alog(null,"EN TER THE PRINCIPAL AMOUNT"); p=Double.parseDouble(input); input=JOptionPane.showInputDi alog(null,"EN TER THE RATE"); r=Double.parseDouble(input); input=JOptionPane.showInputDi alog(null,"EN TER THE TIME"); t=Double.parseDouble(input); si = (p*r*t)/100; JOptionPane.showMessageDi alog(null,"THE SIMPLE INTEREST IS " + si); } } (4) program that will allow the user enter two numbers and display the maximum among the two numbers USING JOptionPane. import javax.swing.JOptionPane; public class DecisionGUI { public static void main(String[] args) { inta,b; String input; input=JOptionPane.showInputDialog(null,"ENTERTHE VALUE OF A"); a=Integer.parseInt(input); input=JOptionPane.showInputDialog(null,"ENTERTHE VALUE OF B"); b=Integer.parseInt(input); if (a > b){ JOptionPane.showMessageDialog(null,"AISGREATER THAN B”); } else if (b > a){ JOptionPane.showMessageDialog(null,"B ISGREATER THAN A”); } else if (a==b){ JOptionPane.showMessageDialog(null,"Aand B are equal"); } } } [email protected] 08107072658 Page 18
  • 19. (5) program that will ask the user to enter his total marks and display whether the user pass or failed USING JOptionPane. import javax.swing.JOptionPane; public class DecisionGUI { public static void main(String[] args) { intTotal_Marks; String input; input=JOptionPane.showInputDialog(null,"ENTERYOUR TOTAL MARKS "); Total_Marks=Integer.parseInt(input); if (Total_Marks > 40 ){ JOptionPane.showMessageDialog(null,"YOU PASS THIS COURSE"); } else if ( Total_Marks < 40 ){ JOptionPane.showMessageDialog(null,"YOU FAILTHIS COURSE"); } } } [email protected] 08107072658 Page 19