You are on page 1of 15

StartPage x ArraysearchDemojava

1package javaprograms:
39 import java.util.Arrays;
import java.util.scanner:
5 p u b l i c class ArraySearchDemo (
public static void main (5tringt args) t
double[ marks
(346, 144, 103, 256.5, 387.51
Scanner user_input new
Scanner ( 5yatem.in )
Syatem.out.print("Enter number to search: ")
int key Integer.parseInt (user input.next (0):
index
int
if (index
Arrays.binarySearch (marks, key)
-1)
Syatem.out. printin("Element found at position " (index+1))
else

Syatem.out.println(Element not found")

Figure 3.9(e): The AmaySearch Demo Program

Output- HelloWorld (run)

un: Enter number to search: 103

Element found a t position 3

BUILD SUCCESSFUL (total time: 16 seconds)

Figure 3.9(): Output from the Array Search Demo Program

Fiaures 3 9(e and 3 9(f show the Ar m and its Outnut


StartPage x ATaysortDemo,java xAray
SortDemo2java x

package javaprograms;
2

3importava.util.Arraya:
public class ArraySortDeno2
public static void nain (String ii args)

Stringl) names ("sleepy", "Doc", "Happy", "Grunpy", "Baahful", "Dopey", "Sneezy"1:


System.out.printin("lames Array befoze aorting: ")
for (int i 0 : 4 nanes.length: ++)
5yatem.out.print(names [4] "):
Syatem.out.println() :
Arrays.sort (names)
Syatem.out.println("lames Array after aorting: ");
for (int i 0: i naes. length; i++)
"

System.out.print(names[4] + ");
Syatem.out.printin():

Figure 3.9(c): The AraySortDemo2 Program

Output-HelloWorld (run)
W zun:

Names Array before aorting:


Sleepy Doc HappyGrumpy Bashful, Dopey.Sneezy
Names Array after aorting:
Bashful Doc,Dopey GrumpY Happy Sleepy Sneezy
BUILD SUcCESSFUL (total time: 1 second)

Figure 3.9(d): Output from the AraySortDemo2 Program

Figures 3.9(c) and 3.9(d) show the Arraysort Demo2 program and its output
StrtPage DataInputDemojava

2
package 3avaprograms
import java.util.scanner
public clans DataInpatDemo

publie statie void main (5tring tl arg


enner Syatem. 3
in

Svate
String naneuer input.next )#
yatem.out.print (Ente
ring age_atring user input.next(
t age Integer-parseInt (age_string)
yatem. o u t - p r i n t i n ( " e l l o "e nane)

Syatem.out.print ( i n 5 yearn you vi11 be (age 5 ) )


Syatem. out.printin " yeara old. ") z

Figure 3.9(a): Data Input Demo Program

121

Database Management Applications

Output-HelloWorld (run)
zun:

Enter your name: Kzishan


Enter your age: 21
Hello Krishan
9 Tn 5 years you will be 26 years old.
BUILD SUCCESSFUL (total time: 6 seconds)

Figure 3.9(b): Output from the Data Input Demo Program

Figures 3.9(a) and 3.9(b) show the Data Input Demo program and its output
caused a book objece's price to fall below 100, the setter method would not change the
price. Without a controlled setter function, the BookTest cdass could have changed
the book's price arbitrarily.

StartPagexBook-java xBookTest.java x

1packagejavaprograms;
2public class BookTest
3 public static void main (5tring ] args)
Book bocki new Book ("Game of Thzonea",
George R Martin",
Harper Collina",
FiCtion", 450.0)
booki.display ()
double b0okprice bookl.get Price () ;
bookprice -bookprice 20-bookprice/100;
bookl.set Price (bookprice)
Syatem.out.println("Bock Price discounted
5ystem.out.printin("New price i s : "
by 201"):
book1.getPrice ( ) )

Figure 3.8(6): Use of Getter and Setter Methods

Output- HelloWorld (run)

Drun: Game of Thrones


Title:
Author: George R Martin
Publisher: Harper Collins
Genre: Fiction
Pzice: 450.0
Book Pzice discounted by 204
New price is: 360.0

BUILD SUcCESSFUL (total time: 1 second)

Figure 3.80): Output from use of Getter and Setter Methods


Objects of class Book can invoke the method member defined in the class Figure
3.8(e). For example, in the following statement, the object book1 invokes the method
member display ().

bookl.display(0:

public static void main (String [] args)


Book bookl
Creatingan objectofthe Book
class using the new keyword
new
Book ():
bookl.title"Game of Thronea"
bookl.author"George R Martin"
bookl.publisher "Harper Collina";
bookl.genre"Fiction" Accessing a data member of the object
bookl.price450.0:
bookl.diaplay () - ACcessing a method member of the
o0)ect

Figure 3.8(e): Accessing the Members of an Object

The display () method as per its method body prints the data members of its
invoking object, in this case book1. Figure 3.8(f) displays the result of executing the
BookTest program.

117
Database Management Applications

Oa

:Output-HelloWorld (run)
run: Title: Game of Thrones
Author: George R Martin
Publisher: Harper Collins
Genre: Fiction
Price: 450.0
BUILD SUCCESSFUL (total time : 0 seconds)

Figure 3.8(): Output from the Book Test Program


3.8 Class Design

We are now ready to create a class in Java. A class in Java begins with the keyword class
followed by the name of the class. The body of the class is enclosed within curly braces. The
body contains the definitions of the data and method members of the class. The data
members are defined by specifying their type. The method members of the class are defined
just like the user defined methods we saw earlier. The method members have access to all the
data members of the class and can use them in their body. The data members of a class are
like global variables -they can be accessed by all the method members of the class. Figure
3.8(a) shows how to code the class Book in Java.

114

Start Pagex Bookjava


1 package javaprograma?
Public class Book Data Members of the Book class
String tatle
String authorz
String publisher
i n g genrez
double prLCe Method Member of the Book
class
void display ()
Syatem.out.println("Title: title) :
5yatem.out.println("Author +author)
Syatem.out.println (" Publiaher: "+ publisher)
Syatem.out.printin ("Genre: + genre):
Syatem.out.printin("Pricez price)

Figure 3.8(a);: The Book Class

3.8.1 Constructors
Figure 3.6(a) shows the complete program listing of the MethodDemo program and Figure
3.6(b) displays the output from the program.
StatPege Hethodbemojava

mo

atatic double rectangie_area (double ength, double breadth)


return (ength breadth)

publ1e static void main (5tring {i arga)t


ube 07

rectengie_eres (45.5, 78.S)


Syate.out-printin("area of the zectangle a)

Figure 3.6(a): User Defined Method Demo Program

112

do
:Output-HelloWorld (run)
run:
Area of the rectangle = 3571.75

BUILD SUCCESSFUL (total time: 0 seconds)

Figure 3.6(b): Output from User Defined Method Demo Program

Aspecial return type void can be used if a method does not retun any value. For example, a
method that just prints a string need not have a retum value can use void as the retum type.

void print_message(String message)


Notice the use of \t to print a tab between the numbers in the print statement. Also note that
the roll number of the student has to be printed as (i+1) since the array index begins from 0 but
roll numbers begin from 1. Figure 3.5(a) shows the complete program listing and Figure 3.5b
displays the output from the Ar ray Demo program.

Start Page ArayOemojava

package helloworld
public class ArrayDemo
public atatic vo1d main (Stringt1 arga)
doublet1 marks 316, 141, 103, 256.5, 397.5)
double
total marks 400
Syatem.out.printin(ecA5S REPOR)
5yatem.out.printin(
Syatem.out.println (otio Earka\tFercentage\tienult)
Syatem.out.printin ("-
for ( i n t - 0 4 < marks.length i++)
double percentage (mark»T&]/total marka) *100:
Stringeaultz
centage 40)
result "Pasned
else

reult Talled
Syatem.out.print( (a1)"\e)
5yatem.out-printmarks (a]
Syatem.out.print (Percentage\Et)z
Syatem.out.printin izemult) z

Syatem.out.printin (

Figure 3.5(a): Array Demo Program

Output-HelloWorld (run)
run
CLASS REPORT
---------------===
Rol1No Marks Percentage Result

346.0 86.5 Passed


144.0 36.0 Failed
103
3.0 25.75 Failed
256.5 64.125 Passed
387.5 96.875 Passed

BUILD SUcCESSFUL (total time: 0 seconds)

Figure 3.5(b): Output from Array Demo Program

110
9:59 PM 8ll 81D

Edit PS X
3.4.7 The for Statement

The for loop is the most widely used Java loop construct. The structure of the Java for
statement is as below:

for (counter=initial_val ue; test_condi tion;change counter)

statements

Semicolons separate the three parts of a for loop:

The initial_ value initializes the value of the loop


counter
The test_condition tests whether the loop should be executed again. The loopis
exited when the test condition fails.
The step updates the counter in each loop iter n.

For example, consider the following loop that prints the square of numbers from 1 to 5:
for ( i n t number = 1; number<= 5; ++number)

System.out .print ("Square of "+ number) ;


System.out . p r i n t l n (" = "+ number*number) ;
3.4.6 The Do While Statement

The do while statement evaluates the test after executing the body of a loop. The
structure of the Java do while statement is as shown:
do

statements

while (expression) ;

103
Database Management Applications

Let us write the same program to print the squares of numbers from 1 to 5. This time we
will use a do-while loop. The following steps need to be perfomed.
1. Initialize number= 1
2. Print the square of the number
3. Increment number (number= number+ 1)
4. Testifthe number<=5
5. Ifyes, Go back to step 2
Ifno, Exitthe loop
The tasks that need to be performed repeatedly are in steps 2 and 3-these constitute
the body of the loop. The test condition is in step 4.The corresponding Java code is as
below
public class DoWhileDemo
public static void main (Stringl] args)
i n t number = 1;
do
System.out. print ("Square of " + number) ;

System.out.println (" = " + number*number)

++number;
while (number <= 5);

The output of the DoWhi le Demo program is the same as Figure 3.4f. You might be
wondering if both the while and do-while loops give the same output, what is the
use of having two types of loop constructs. VWell, consider the case when the variable
number is initialized to 6.
3.4.5 The While Statement

The while statement evaluates the test before executing the body of a loop. The
structure of the Java while statementis as shown:
while (expression)

statements

Let us write a program to print the squares of numbers from 1 to 5. The following steps
need to be performed.

1. Initialize number = 1

2. Testifthe number<=5
3. Ifyes, print the square of the number
Increment number (number = number+ 1)

Go back to step 2
4. Ifno, exit the loop.

The tasks that need to be performed repeatedly are in step 3 these constitute the
body of the loop. The test condition is in step 2. The coresponding Java code is given
below:

public class WhileDemo (

public static void main (String[ ] args) (


i n t number = 1;

while (n umber < 5)


System.out.print ("Square of " + number) ;

System.out.println (" = " + number*number)

++number;

02

Note the use of the ++ operator to increment the value of number. The statement
++number or number++; has the same effect as the statement number = number

+1

The output from the while Demo program is displayed in Figure 3.4().

Output- HelloWorld (run)


run: 1 2
Square
quare of 2 4
Square of 3 6
of 4 8
Square
Square of 5 10

BUILD SUCCESSFUL (total time: 1 second)

Figure 3.4(): Output from While Demo Program


Figures 3.9(g) and 3.9(h) show the String Demo programand its output respectively.

StatPge Stregbemjve
pacage avaprogra
pube cias itrigpen
ngt] arg9)
T

Syatem.out.printin ( i Stzing +mydtzing)


yatem.out-printinazt potan 6 ng.charkt (0)
Syaten.out-printin(onatTodey ydtring-concat Today))z
Syatem.out.printin(eoetains e1 ydtring.containa("el3))
14"))
Syatem. out.printin (egualatgnozeCase el3o vezsa' myString.equaiatqnoreCase (ella weria"))
Syatem.out-printineindexor M myatring.indexot ("))
yetem.out-printin(aanexot ia"t ydtring-indexCf(°tia"))z
Byatem. out.printinurtnptz1 tring.iatmpty0)
yateout.printin(engthr string.2emgeh () ng.replaoe(,31
ila witheL ystng.eplace(ekaa, "yellov))
Syatem. out.printin (Lowercse t mytring.soLevercane 01

Byatem.oot.printin("operCaner mydtring.sopperCane() 17

Figure 3.9(g): The String Demo Program

Output-HelloWorld (run)
zun:

Given String: Hello Horld


chazAt position 6: W
concat Today' : Hello World Today

9 contains "Hell1': true


endsWith 'old': £alse
equals Goodbye Horld': £alse
equalsIgnoreCase 'hello wozld': true
indexOf W: 6
indexof 'zld': 8
isEmpty: false
length: 11
zeplace 1 with : He*o Wor d
zeplace Hello" with "Yellow": Yellow World
LowerCase: hello world
UpperCase: HELLO HORLD
BUILD SUCCESSFUL (total time: 2 seconds)

Figure 3.9(h): Output from the String Demo Program

126
Step 4: Cick in the Code Editor Window under the Percentage Calculator.
Java tab and type the code as shown in Figure 3.2(e). The comments inserted by
NetBeans have been deleted for simplicity.

Start Page x Heloworld.java PercentageCakculatorjava

package helloworld:
2/Program to caleulate Percentage from marka_obtained
3public class PercentageCalculator
public atatic void main (String [1 args)
int
total _marka
double marks_obtained
400
346;
double percentage- 0.02

percentage(marks_obtained/total _marke)*100;
System.out.println ("Studenti'a Fercentage +percentage):
marks_obtained 144:
percentage (marks_obtained/total _marka)*100
Syatem.out.println("Student2"s Percentage percentage)

Figure 3.2(e): The Percentage Calculator Program

Step 5: Click File > Save (Ctrl+S]to save the file.


Step 6: Click Run> Run File (Shift + F6) to execute the program. The output of the
program appears in the Output window as shown in Figure 3.2().

EOutput-HelloWorld (run)
run:
Student1's Percentage 86.5

Student2's Percentage = 36.0

BUILD SUCCESSFUL (total time: 1 second)

Figure 3.2(): Output from the Percentage Calculator Program

As vou may have noticed, the variables in a proaram act as placeholders for data
You can see the complete code listing of thee new Percentage Calculator program in
Figure 3.4(b) and its outputin Figure 3.4(c).

Start Page xHeloWorld.java PercentageCalculator.java NewPercentageCakculator.java

package helloworldz
2 p u b l i c class NewPercentagecalculator
3 public static void main (String [1 args)
ant total_marks 400
double marks_obtained 346
double p e r c e n t a g e 0 . 0 7

percentage(mark=_obtained/total_marks) 100
Syatem.out.println ("Studenti Fercentage- "percentage)
(percentse.out-println(PASSED)
t.println (
1t (PerCentage
Syatem. out-printin ("RLth Distinction ! )

else
syatem.out.printin (EAILED"):
marks_obtained 144
percentage (marks_obtained/total_marks) *100:
Syatem OuE.printin (Student2 " a Percentage percentage)

if (percentage > 40)

Syatem.out.printin ("PASSED")
at (percentage 75)
Syatem. out.printin ("wath Distinction ! ")

else
Syatem.out.printin(FAILED")

Figure 3.4(b): New Percentage Calculator

Output-HelloWorid (run)
run Student1's Percentage = 86.5

PASSED
With Distinction!
8 Student2 's Percent age 36.0
FAILED
BUILD SUcCESSFUL (total time: 1 second)

Figure 3.4();: Output from New Percentage Calculator


We catch an exception of the type Exception.An object of the class Ex ception is a "catch
all" exception that returns a general error message encountered during program execution.
The exception handler in the catch block uses the getMessage () method of the
Ex ception class to print the error the exception.
thatcaused
Start Page bxceptionDemojava

package avaprograms:

public class ExceptionDemo

atatic int divide (int dividend, int divisor) t


zeturn dividend/diviaorz

public atatic void main (String(] arge)


try
nt quotLent divide (10,0)
Syatem.out.println(quotient)
catch (Exception e)
Syatem.out.printin (e.getMeszage () )

Figure 3.10(); Exception Handling Demo Program

Output-HelloWorld (run)
un:
b yzero
BUILD SUcCESSFUL (total time: 1 second)

Figure 3.10(d): Output from the Exception Handling Demo Program

e 2 10/ ard 2 10ld abous to

You might also like