Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 58

Chapter 3: Introduction to

Objects and Input/Output

Java Programming:
From Problem Analysis to Program Design,
Second Edition
Chapter Objectives
 Learn about objects and reference variables.

 Explore how to use predefined methods in a


program.

 Become familiar with the class String.

 Learn how to use input and output dialog boxes in a


program.

Java Programming: From Problem Analysis to Program Design, Second Edition 2


Chapter Objectives
 Explore how to format the output of decimal
numbers with the String method format.

 Become familiar with file input and output.

Java Programming: From Problem Analysis to Program Design, Second Edition 3


Object and Reference Variables
 Declare a reference variable of a class type.

 Allocate memory space for data.

 Instantiate an object of that class type.

 Store the address of the object in a reference


variable.

Java Programming: From Problem Analysis to Program Design, Second Edition 4


Java Variables
 There are two types of variables in Java:
 primitive type variables
 reference variables.
 Primitive type variables directly store data into their
memory space. For instance, consider the following
statements:
int x;
x = 45;

 The variable x can store an int value in its memory space.


The second statement stores 45 in x.

Java Programming: From Problem Analysis to Program Design, Second Edition 5


Object and Reference Variables
 Reference variables are variables that store the address of
the object containing the data.
 An object is an instance of a class and the operator new is
used to instantiate an object.
 For instance, consider the following statements:

String str = new String("Java Programming");

Java Programming: From Problem Analysis to Program Design, Second Edition 6


Object and Reference Variables
 The variable str cannot directly store data in its memory
space. The variable str stores the memory location, that is,
the address of the memory space where the actual data is
stored.
 In Java, new is an operator. It causes the system to:
 allocate memory space of a specific type.
 store specific data in that memory space
 return the address of that memory space.
 The assignment operator stores the address of that memory
space into the variable str.

Java Programming: From Problem Analysis to Program Design, Second Edition 7


Object and Reference Variables
 Consequently, str is a reference variable and the
memory space where the string data is stored is
called string object or instance of class String .
 String objects are immutable ; that is , once they
are created ,they cannot be changed .
 String objects can be instantiated without using the
new operator.

Java Programming: From Problem Analysis to Program Design, Second Edition 8


Object and Reference Variables
String str;
str = "Hello there!";

Java Programming: From Problem Analysis to Program Design, Second Edition 9


Using Predefined Classes and
Methods in a Program
 There are many predefined packages, classes, and
methods in Java.
 Library: A collection of packages.
 Package: Contains several classes.
 Class: Contains several methods.
 Method: A set of instructions.

Java Programming: From Problem Analysis to Program Design, Second Edition 10


Using Predefined Classes and
Methods in a Program
To use a method ( pow) you must know:
 Name of the class containing the method. (Math).

 Name of the package containing the class (java.lang).

 Name of the method - (pow), what the method does ,


number of its parameters (its has two parameters), type of
each parameter and the return type.

 Math.pow(x, y) = xy

Java Programming: From Problem Analysis to Program Design, Second Edition 11


Using Predefined Classes and
Methods in a Program
 Example method call:

import java.lang; //imports package

Math.pow(2, 3); //calls power method


// in class Math ,executes it and
// returns the value of 23.

 Dot (.)operator: Used to access the method in the


class.

Java Programming: From Problem Analysis to Program Design, Second Edition 12


The class String
 String variables are reference variables.
 Given:

String name;

 Equivalent statements:
name = new String("Lisa Johnson");
name = "Lisa Johnson";

Java Programming: From Problem Analysis to Program Design, Second Edition 13


The class String
 A String object is an instance of class String.

 A String object with the value "Lisa Johnson" is


instantiated.

 The address of the object is stored in name.

 The new operator is unnecessary when instantiating Java


strings.

 String methods are called using the dot operator.

Java Programming: From Problem Analysis to Program Design, Second Edition 14


The class String
 Java system automatically makes the class String
available (i.e no need to import this class )
 Example :
Consider the following declaration :
String sentence ;
sentence = “programming with java”

Java Programming: From Problem Analysis to Program Design, Second Edition 15


Some Commonly Used String Methods

Java Programming: From Problem Analysis to Program Design, Second Edition 16


Some Commonly Used String Methods

Java Programming: From Problem Analysis to Program Design, Second Edition 17


Some Commonly Used String Methods

Java Programming: From Problem Analysis to Program Design, Second Edition 18


Some Commonly Used String Methods

Java Programming: From Problem Analysis to Program Design, Second Edition 19


 Examples on string methods:
String s1 , s2 , s3 ;
s1 = “abcdefeg” ;
System.out.println( s1.length() ); // 8
System.out.println(s1.charAt(3)); //d
System.out.println(s1.indexOf(‘e’)); //4
System.out.println(s1.indexOf(“cd”)); //2
System.out.println(s1.toUpperCase());
Java Programming: From Problem Analysis to Program Design, Second Edition 20
System.out.println(s1.substring(1 , 4)); //bcd
System.out.println(s1 + “xyz”);
System.out.println( s1.replace(‘d’ ,’D’);
System.out.println(s1.charAt(4) ); // e
System.out.println(s1.indexOf(‘b’); // 1
System.out.println(s1.indexOf(‘e’,5); // 6

Java Programming: From Problem Analysis to Program Design, Second Edition 21


Input/Output
 Input data

 Output results

 Format output using method printf()

 Format output of decimal numbers .

Java Programming: From Problem Analysis to Program Design, Second Edition 22


Formatting Output with printf
 The syntax to use the method printf to produce output on the
standard output device is:
System.out.printf(formatString);
or
System.out.printf(formatString,argumentList);
 formatString is a string specifying the format of the output and
argumentList is a list of arguments.
 argumentList is a list of arguments that consists of constant
values, variables, or expressions.
 If there is more than one argument in argumentList, the
arguments are separated with commas.

Java Programming: From Problem Analysis to Program Design, Second Edition 23


Formatting Output with printf
System.out.printf("Hello there!");

Consists of only the format string and the statement:

System.out.printf("There are %.2f inches in %d centimeters.%n",


centimeters / 2.54, centimeters);

 Consists of both the format string and argumentList.


 %.2f and %d are called format specifiers.
 By default, there is a one-to-one correspondence between
format specifiers and the arguments in argumentList.
 The first format specifier, %.2f, is matched with the first
argument, which is the expression centimeters /
2.54.
Java Programming: From Problem Analysis to Program Design, Second Edition 24
Formatting Output with printf
 The second format specifier, %d, is matched with the second
argument, which is centimeters.
 The format specifier %n positions the insertion point at the
beginning of the next line.
 If centimeters = 150  150/2.54 =59.05511811023
 The o/p would be :
There are 59.06 inches in 150 centimeters
 The output of a printf statement is right-justified by default.
To force the output to be left-justified, negative column
widths may be used.

Java Programming: From Problem Analysis to Program Design, Second Edition 25


Formatting Output with printf
 A format specifier for general, character, and numeric types has the
following syntax:

%[argument_index$][flags][width][.precision]conversion

 The expressions in square brackets are optional. That is, they may or
may not appear in a format specifier.
 The optional argument_index is a (decimal) integer that indicates the
position of the argument in the argument list. The first argument is
referenced by "1$," the second by "2$," etc.
 The optional flags is a set of characters that modify the output format.
 The optional width is a (decimal) integer that indicates the minimum
number of characters to be written to the output.
 The optional precision is a (decimal) integer that is usually used to
restrict the number of characters.
 The required conversion is a character that indicates how the argument
should be formatted.

Java Programming: From Problem Analysis to Program Design, Second Edition 26


Example3_6
public class Example3_6 System.out.printf("num = %5d %n",
{ num);
public static void main (String[] args) System.out.printf("x = %10.2f
{ %n", x);
int num = 763; System.out.printf("str = %15s %n",
double x = 658.75; str);
String str = "Java Program.";
System.out.printf("%10s%7d
%n","Program No.", 4);
System.out.println("1234567890123456789 }
01234567890"); System.out.printf("%5d
%7.2f%15s%n", num, x, str); }
System.out.printf("%15s%6d%9.2f %n",
str, num, x);
System.out.printf("%8.2f%7d%15s %n", x,
num, str);

Java Programming: From Problem Analysis to Program Design, Second Edition 27


Example3_6

Sample run :
123456789012345678901234567890
763 658.75 Java Program.
Java Program. 763 658.75
658.75 763 Java Program.
num = 763
x= 658.75
str = Java Program.
Program No. 4

Java Programming: From Problem Analysis to Program Design, Second Edition 28


Example3_7
public class Example3_7 System.out.printf("%-8.2f%-7d%-15s
{ ***%n", x, num, str);
public static void main (String[] args) System.out.printf("num = %-5d ***
{ %n", num);
int num = 763; System.out.printf("x = %-10.2f ***%n",
double x = 658.75; x);
System.out.printf("str = %-15s ***%n",
String str = "Java Program."; str);
System.out.printf("%-10s%-7d ***%n",
System.out.println("1234567890123456
"Program No.", 4);
78901234567890"); }
System.out.printf("%-5d%-7.2f%-15s }
***%n", num, x, str);
System.out.printf("%-15s%-6d%- 9.2f
***%n", str, num, x);

Java Programming: From Problem Analysis to Program Design, Second Edition 29


Example3_7

Sample Run :
123456789012345678901234567890
763 658.75 Java Program. ***
Java Program. 763 658.75 ***
658.75 763 Java Program. ***
num = 763 ***
x = 658.75 ***
str = Java Program. ***
Program No.4 ***

Java Programming: From Problem Analysis to Program Design, Second Edition 30


Formatting Output with printf

Java Programming: From Problem Analysis to Program Design, Second Edition 31


Parsing Numeric Strings
 A string consisting of only integers or decimal numbers is
called a numeric string.

 To convert a string consisting of an integer to a value of the


type int, we use the following expression:

Integer.parseInt(strExpression)
• Example:
Integer.parseInt("6723") = 6723
Integer.parseInt("-823") = -823

Java Programming: From Problem Analysis to Program Design, Second Edition 32


Parsing Numeric Strings
 To convert a string consisting of a decimal number to a value
of the type float, we use the following expression:

Float.parseFloat(strExpression)
• Example:
Float.parseFloat("34.56") = 34.56
Float.parseFloat("-542.97") = -542.97

 To convert a string consisting of a decimal number to a value


of the type double, we use the following expression:

Double.parseDouble(strExpression)
• Example:
Double.parseDouble("345.78") = 345.78
Double.parseDouble("-782.873") = -782.873
Java Programming: From Problem Analysis to Program Design, Second Edition 33
Parsing Numeric Strings
 Integer, Float, and Double are classes designed to
convert a numeric string into a number.
 These classes are called wrapper classes.
 parseInt is a method of the class Integer, which
converts a numeric integer string into a value of the type
int.
 parseFloat is a method of the class Float and is used
to convert a numeric decimal string into an equivalent value
of the type float.
 parseDouble is a method of the class Double, which
is used to convert a numeric decimal string into an
equivalent value of the type double.

Java Programming: From Problem Analysis to Program Design, Second Edition 34


Using Dialog Boxes for
Input/Output
 Use a graphical user interface (GUI).
 class JOptionPane:
 Allows programmer to use GUI components for I/O.
 Contained in package javax.swing.
 Contains methods :
 showInputDialog :allows programmer to input a string from
keyboard .
 showMessageDialog : allows programmer to display results .
 Syntax:
str = JOptionPane.showInputDialog(strExpression)
 Program must end with System.exit(0);

Java Programming: From Problem Analysis to Program Design, Second Edition 35


Parameters for the Method
showMessageDialog

Java Programming: From Problem Analysis to Program Design, Second Edition 36


JOptionPane Options for the
Parameter messageType

Java Programming: From Problem Analysis to Program Design, Second Edition 37


JOptionPane Example

Java Programming: From Problem Analysis to Program Design, Second Edition 38


JOptionPane Example
 You must import class JOptionPane into your
program using one of the two stmts :
 Import java.swing.* ;
 Import java.swing.JOptionPane ;

Java Programming: From Problem Analysis to Program Design, Second Edition 39


Example 3-12
//Program to determine the area and area = PI * radius * radius;
circumference of a circle
import javax.swing.JOptionPane;
circumference = 2 * PI * radius;
public class AreaAndCircumferenceProgram
{ outputStr = "Radius: " + radius + "\n"
+"Area: " + area + " square units\n"
public static final double PI = 3.14; + "Circumference: " +circumference
public static void main(String[] args) { + " units";
double radius; JOptionPane.showMessageDialog
double area; (null, outputStr, "Circle",
double circumference; JOptionPane.INFORMATION_MESSAGE);
String radiusString;
String outputStr; System.exit(0);
radiusString =JOptionPane.showInputDialog
("Enter the radius: "); }
radius = Double.parseDouble(radiusString) ;
}

Java Programming: From Problem Analysis to Program Design, Second Edition 40


Example 3-12

Java Programming: From Problem Analysis to Program Design, Second Edition 41


Formatting the Output Using the
String Method format
Example 3-13
double x = 15.674;
double y = 235.73;
double z = 9525.9864;
int num = 83;
String str;

Java Programming: From Problem Analysis to Program Design, Second Edition 42


Example3_15
import javax.swing.JOptionPane;
JOptionPane.showMessageDialog
public class Example3_15 (null, str,
{ "Formatting with the String Method format",
public static void main(String[] args)
{
double x = 15.674; JOptionPane.INFORMATION_MESSAGE );
double y = 235.73;
double z = 9525.9864; System.exit(0);
String str;
}
str = String.format("The value of x with two }
decimal places = %.2f%n", x)
+ String.format("The value of y with two
decimal places = %.2f%n", y)
+ String.format("The value of z with two
decimal places = %.2f%n", z);

Java Programming: From Problem Analysis to Program Design, Second Edition 43


Programming Example: Movie
Ticket Sale and Donation to Charity
 Input: Movie name, adult ticket price, child ticket price, number of adult
tickets sold, number of child tickets sold, percentage of gross amount to
be donated to charity.
 Output:

Java Programming: From Problem Analysis to Program Design, Second Edition 44


Programming Example: Movie Ticket
Sale and Donation to Charity
1. Import appropriate packages.
2. Get inputs from user using
JOptionPane.showInputDialog.
3. Perform appropriate calculations.
4. Display output using
JOptionPane.showMessageDialog.

Java Programming: From Problem Analysis to Program Design, Second Edition 45


File Input/Output

 This passage discusses the limitations of obtaining


input from the keyboard and outputting to the
screen and introduces the concept of using files as
an alternate form of input and output. By using
files, data can be prepared before running a program
and output can be saved and distributed to others.

Java Programming: From Problem Analysis to Program Design, Second Edition 46


Here it provides an example of initializing a Scanner
object to read from a file using the FileReader class in
Java.

Scanner console = new Scanner(System.in);


Scanner inFile = new Scanner(new FileReader("prog.dat"));

Java Programming: From Problem Analysis to Program Design, Second Edition 47


Java file I/O is a four-step process:
1.Import the necessary classes from the package
java.util and java.io into the program.
2.Create and associate the appropriate objects with the
input/output sources.
3.Use the appropriate methods associated with the
variables created in Step 2 to input/output the data.
4.Close the files.

Java Programming: From Problem Analysis to Program Design, Second Edition 48


Java Programming: From Problem Analysis to Program Design, Second Edition 49
To send the output to a file, you use the class
PrintWriter. This class is contained in the package java.io.
The PrintWriter class in Java is used to store the output of a
program in a file. To associate the PrintWriter object with
the output file, you can use the constructor method with the
file path as an argument. Methods like print, println, and
printf can be used with the PrintWriter object to write to the
output file. To ensure that the output is sent to the file, You
should close the PrintWriter object with the close method.

Java Programming: From Problem Analysis to Program Design, Second Edition 50


(throws clause) During program execution,
various things can happen—for example, division by
zero or inputting a letter for a number. If such things
happen, the system will not tolerate it. In such cases,
we say that an exception has occurred. If an exception
occurs in a method, then the method should either
handle the exception or throw it for the calling
environment to handle.

Java Programming: From Problem Analysis to Program Design, Second Edition 51


Java Programming: From Problem Analysis to Program Design, Second Edition 52
Debugging with print or println
Statements
Syntax errors are reported by the compiler, and
the compiler not only reports syntax errors, but it also
gives some explanation about the error. On the other
hand, logic errors are typically not caught by the
compiler except the trivial ones such as using a
variable without properly initializing it. In this section,
we illustrate how to spot and correct logic errors using
print statements.

Java Programming: From Problem Analysis to Program Design, Second Edition 53


Suppose that we want to write a program that takes as
input the temperature in Fahrenheit and output the
equivalent temperature in Celsius.

The formula to convert the temperature is:


Celsius ¼ 5/9*(Fahrenheit – 32).

So, consider the following program.

Java Programming: From Problem Analysis to Program Design, Second Edition 54


Sample Run 1: The user input is shaded. Enter temperature in
Fahrenheit: 32
32 degrees F = 0 degrees C.

Sample Run 2: The user input is shaded. Enter temperature in


Fahrenheit: 110
110 degrees F = 0 degrees C.

As we can see, using temporary println statements, we were able to find


the problem. After correcting the problem, the temporary println
statements are removed.

Java Programming: From Problem Analysis to Program Design, Second Edition 56


Java Programming: From Problem Analysis to Program Design, Second Edition 58

You might also like