Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Chapter 02 - Java Basics Part 2

Here are programs to calculate area and circumference of a circle using dialog boxes and console input/output: //Program using dialog boxes for input/output import javax.swing.JOptionPane; public class Circle { public static void main(String[] args){ String radiusInput = JOptionPane.showInputDialog("Enter radius"); double radius = Double.parseDouble(radiusInput); double area = Math.PI * radius * radius; double circumference = 2 * Math.PI * radius; JOptionPane.showMessageDialog(null, "Area is " + area + "\nCircumference is " + circumference); } } //Program using console input/output
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Chapter 02 - Java Basics Part 2

Here are programs to calculate area and circumference of a circle using dialog boxes and console input/output: //Program using dialog boxes for input/output import javax.swing.JOptionPane; public class Circle { public static void main(String[] args){ String radiusInput = JOptionPane.showInputDialog("Enter radius"); double radius = Double.parseDouble(radiusInput); double area = Math.PI * radius * radius; double circumference = 2 * Math.PI * radius; JOptionPane.showMessageDialog(null, "Area is " + area + "\nCircumference is " + circumference); } } //Program using console input/output
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Object Oriented Programming

19CSE (2nd Semester)


Chapter#02: Java basics Part-02

1
Outline
Java packages
Output and Input data from Java
console
Input and output data using Dialog
boxes
Type casting
Data types

2
Java packages
 A package in Java is used to group related classes.
 Think of it as a folder in a file directory.
 We use packages to avoid name conflicts, and to write a better
maintainable code.
 Packages are divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
Two groups of Built-in packages in Java API
Group of all packages known as Java class library or Java
applications programming interface (Java API)
Core packages
Begin with java
Included with Java 2 Software Development Kit
Extension packages
Begin with javax
3
New Java packages
Java packages
import declarations
Used by compiler to identify and locate classes used in Java
programs
For example
import javax.swing.JOptionPane;
Tells compiler to load class JOptionPane from javax.swing
package
JOptionPane is in the javax.swing package
Package has classes for using Graphical User Interfaces (GUIs)

package java.lang
Is a built-in package
No import declaration needed
java.lang automatically imported in every Java program
For example No import statement is
required for System.exit( 0 );because 4
Input data from Java Console
Scanner Class
 Scanner is a class in java.util package used for
obtaining the input of the primitive types like int,
double, etc. and strings. It is the easiest way to read
input in a Java program from console
 To create an object of Scanner class, we usually pass
the predefined object System.in, which represents the
standard input stream. We may pass an object of class
File if we want to read input from a file.
 To read numerical values of a certain data type XYZ,
the function to use is nextXYZ(). For example, to read a
value of type short, we can use nextShort()
 To read strings, we use nextLine(). 5
Input data from Java console
To read a single character, we use next().charAt(0). next()
function returns the next token/word in the input as a string
and charAt(0) function returns the first character in that string.

6
Scanner Class in Java

// Java program to read data of various types using Scanner class.


import java.util.Scanner;
public class ScannerDemo
{
public static void main(String[] args)
{
//Declare the object and initialize with predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
System.out.print("enter your name?");
String name = sc.nextLine();
System.out.print("enter your gender?");
char gender = sc.next().charAt(0);
// Numerical data input byte, short and float can be read using similar-named functions.
:
System.out.print("enter your age?");
int age = sc.nextInt();
System.out.print("enter your mobile number?");
long mobileNo = sc.nextLong();
System.out.print("enter your cgpa?");
double cgpa = sc.nextDouble();
// Print the values to check if the input was correctly obtained.
System.out.println("Name: "+name);
System.out.println("Gender: "+gender);
System.out.println("Age: "+age);
System.out.println("Mobile Number: "+mobileNo);
System.out.println("CGPA: "+cgpa);
}
}
7
Input data from Java Console

8
Input data from Java Console

9
Input & output using Dialog boxes
 JOptionPane Class allows us to use dialog boxex
 Dialog Box – is a small graphical window that displays a message to
the user or request input. We can quickly display dialog boxes with
JOptionPane class.
Ty p e s of DIALOG BOXES
Message Dialog – a dialog box that displays a message; an OK
button is also displayed.
Input Dialog – dialog box tat prompts the user for input & provides
text field where input is typed; an OK button and a CANCEL
button are also displayed.
 Beginning Statement in your code when using JoptionPane:
 import javax. swing.JOptionPane;
 Purpose: this statement tells the compiler where to find the JOptionPane
class, and make it available to your program.
 Switng Package has classes for using Graphical User Interfaces (GUIs)
 At the end use System.exit( 0 ); // terminate
application with window 10
Input & output using Dialog boxes
Message Dialog Boxes
 showMessageDialog method- is used to display a message dialog
box.
 Call method showMessageDialog of class
JOptionPane
Requires four arguments
First argument: null
Second: string to display
Third: string in title bar (optional by default Message)
Fourth: type of message dialog with icon (optional)
 JOptionPane.showMessageDialog(null,"The sum is
"+sum, "Results",OptionPane.PLAIN_MESSAGE);

 showMessageDialog is a static method of class


JOptionPane
static methods called using class name, dot (.) then method name
11
Input & output using Dialog boxes
Message Dialog Boxes
Me ssa g e d ia lo g typ e Ic o n De sc rip tio n
JOptionPane.ERROR_MESSAGE Displays a dialog that indicates an error
to the user.

JOptionPane.INFORMATION_MESSAGE Displays a dialog with an informational


message to the user. The user can simply
dismiss the dialog.

JOptionPane.WARNING_MESSAGE Displays a dialog that warns the user of a


potential problem.

JOptionPane.QUESTION_MESSAGE Displays a dialog that poses a question to


the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.

JOptionPane.PLAIN_MESSAGE no icon Displays a dialog that simply contains a


message, with no icon.

12
Input & output using Dialog boxes
 Input Dialog Box
 InputDialog method – to display an input dialog in
JOptionPane class.
 Statement to call the method:
String name;
 name = JOptionPane.showInputDialog(“Enter
first number”);

13
Input & output using Dialog boxes
Example program: Write a Java program to find area of rectangle
using input output dialog box.
import javax.swing.JOptionPane; // Needed for Dialog Box
public class RectangleTest
{
public static void main(String[] args)
{
String input; // To hold String input. output
int length; // To hold length.
int width; // To hold width.
int area; // To hold area.
// Prompt user to input length.
input = JOptionPane.showInputDialog("Enter Length");
// Convert the String input to an int.
length = Integer.parseInt(input); //Prompt user to input width.
input = JOptionPane.showInputDialog("Enter Width");
// Convert the String input to an int.
width = Integer.parseInt(input);
// Calculate area of rectangle.
area = length * width;
// Display area of rectangle.
14
JOptionPane.showMessageDialog(null, "Area of rectangle is " + area);
Input & output using Dialog boxes
E x a m p l e p ro g r a m : A d d i t i o n o f t w o n u m b e r s
// Importing JOptionPane package
import javax.swing.JOptionPane;
// Beginning of class Addition
public class Addition {
// Beginning of method main
public static void main(String[] args) {
// Declare variables
String firstNumber; // First string entered by user
String secondNumber; // Second string entered by user
int number1; // First number
int number2; // Second number
int sum; // Sum of number1 and number2
// Read in first number from user as a String
firstNumber = JOptionPane.showInputDialog("Enter first integer:");
// Read in second number from user as a String
secondNumber = JOptionPane.showInputDialog("Enter second integer:");
// Convert numbers from type String to type int
number1 = Integer.parseInt(firstNumber);
number2 = Integer.parseInt(secondNumber);
// Add numbers
sum = number1 + number2;
// Display result
JOptionPane.showMessageDialog(null,"The sum is " + sum + ".","Results", JOptionPane.PLAIN_MESSAGE);
// Terminating Java program with window
System.exit(0);
} // End of method main
15
} // End of class Addition
Exercise programs
Write a program to calculate and display area and
circumference of circle. Have the user input radius
of a circle and display area and circumference of a
circle. Use dialog boxes for input and output.
Write a program to calculate and display area and
circumference of circle. Have the user input radius
of a circle and display area and circumference of a
circle. Use System.in & System.out for input and
output on MS Dos prompt.

16
Data types
 Data types specify the different sizes and values that can be stored in the
variable.
 There are two types of data types in Java:
 Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double. (8 data types)
 Non-primitive data types: The non-primitive data types include Classes, 
Interfaces, and Arrays.
Data Type Size Description
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647
long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

boolean 1 bit Stores true or false values


char 2 bytes Stores a single character/letter or ASCII values
17
Type Casting
The process of converting one data type into another data type is called
casting
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
In the case of Widening Type Casting, the lower data type (having smaller size) is
converted into the higher data type (having larger size). Hence there is no loss in
data. This is why this type of conversion happens automatically. Also called implicit
casting
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
In the case of Narrowing Type Casting, the higher data types (having larger size)
are converted into lower data types (having smaller size). Hence there is the loss of
data. This is why this type of conversion does not happen automatically. Also called
explicit casting
Widening casting is done automatically when passing a smaller size type to
a larger size type:
Narrowing casting must be done manually by placing the type in
parentheses in front of the value: 18
Type Casting (example programs)
public class WideCastMain
{
public static void main(String[] args)
{ // create int type variable
int num = 10;
System.out.println("The integer value: " + num);
// convert into double type
double data = num;
System.out.println("The double value: " + data);
}
OUTPUT
} The integer value: 10
The double value: 10 19
Type Casting (example programs)
public class NarCast
{
public static void main(String[] args)
{
// create double type variable
double num = 10.99;
System.out.println("The double value: " + num);
// convert into int type
int data = (int)num;
System.out.println("The integer value: " + data);
} OUTPUT
} The double value: 10.99
The integer value: 10 20

You might also like