Professional Documents
Culture Documents
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
package javaprograms;
2
3importava.util.Arraya:
public class ArraySortDeno2
public static void nain (String ii args)
System.out.print(names[4] + ");
Syatem.out.printin():
Output-HelloWorld (run)
W zun:
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
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)
121
Output-HelloWorld (run)
zun:
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 ( ) )
bookl.display(0:
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)
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
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
112
do
:Output-HelloWorld (run)
run:
Area of the rectangle = 3571.75
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.
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 (
Output-HelloWorld (run)
run
CLASS REPORT
---------------===
Rol1No Marks Percentage Result
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:
statements
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)
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) ;
++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:
++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().
StatPge Stregbemjve
pacage avaprogra
pube cias itrigpen
ngt] arg9)
T
Byatem.oot.printin("operCaner mydtring.sopperCane() 17
Output-HelloWorld (run)
zun:
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.
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)
EOutput-HelloWorld (run)
run:
Student1's Percentage 86.5
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).
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)
Syatem.out.printin ("PASSED")
at (percentage 75)
Syatem. out.printin ("wath Distinction ! ")
else
Syatem.out.printin(FAILED")
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)
package avaprograms:
Output-HelloWorld (run)
un:
b yzero
BUILD SUcCESSFUL (total time: 1 second)