You are on page 1of 49

• A variable is a sequence of characters that consist of

letters, digits, underscores (_), and dollar signs ($).


• A variable must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
• A variable cannot be a reserved word.
• A variable cannot be true, false, or null.
• A variable can be of any length.
• Cannot use reserve keywords.

42
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable;

43
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;

44
• int x = 1;
• double d = 1.4;

45
Name Range Storage Size

byte –27 to 27 – 1 (-128 to 127) 8-bit signed

short –215 to 215 – 1 (-32768 to 32767) 16-bit signed

int –231 to 231 – 1 (-2147483648 to 2147483647) 32-bit signed

long –263 to 263 – 1 64-bit signed


(i.e., -9223372036854775808 to 9223372036854775807)

float Negative range: 32-bit IEEE 754


-3.4028235E+38 to -1.4E-45
Positive range:
1.4E-45 to 3.4028235E+38
double Negative range: 64-bit IEEE 754
-1.7976931348623157E+308 to -4.9E-324

Positive range:
4.9E-324 to 1.7976931348623157E+308

46
Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

47
+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

48
• Remainder is very useful in programming.
• For example, an even number % 2 is always 0 and an odd number
% 2 is always 1.
• So you can use this property to determine whether a number is
even or odd.
• Suppose today is Saturday and you and your friends are going
to meet in 10 days. What day is in 10 days? You can find that
day is Tuesday using the following expression:
Saturday is the 6th day in a week
A week has 7 days
(6 + 10) % 7 is 2
The 2nd day in a week is Tuesday
After 10 days

49
System.out.println(Math.pow(2, 3));
// Displays 8.0
System.out.println(Math.pow(4, 0.5));
// Displays 2.0
System.out.println(Math.pow(2.5, 2));
// Displays 6.25
System.out.println(Math.pow(2.5, -2));
// Displays 0.16

50
3  4 x 10( y  5)(a  b  c) 4 9 x
  9(  )
5 x x y
is translated to

(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

51
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
52
Write a program that converts a Fahrenheit degree to
Celsius using the formula:
celsius  ( 95 )( fahrenheit  32)

Note: you have to write


celsius = (5.0 / 9) * (fahrenheit – 32)

53
Operator Example Equivalent
+= i += 8 i = i + 8
-= f -= 8.0 f = f - 8.0
*= i *= 8 i = i * 8
/= i /= 8 i = i / 8
%= i %= 8 i = i % 8

54
Operator Name Description
++var preincrement The expression (++var) increments var by 1 and evaluates
to the new value in var after the increment.
var++ postincrement The expression (var++) evaluates to the original value
in var and increments var by 1.
--var predecrement The expression (--var) decrements var by 1 and evaluates
to the new value in var after the decrement.
var-- postdecrement The expression (var--) evaluates to the original value
in var and decrements var by 1.

55
Examples:
int num = 6;
num ++;
The value of variable num is increased by 1 to be 7

int row = 15;


--row;
The value of variable row is decreased by 1 to be 14

int m= 10;
int n;
n = ++ m;
Both m and n are set to 11

int x = 5 ;
int y ;
y = x ++;
x is set to 6 and y is 5
int i = 10; Same effect as
int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

Avoid using these operators in expressions that modify


multiple variables, or the same variable for multiple times
such as this: int k = ++i + i.

57
Consider the following statements:
byte i = 100;
long k = i * 3 + 4;
double d = i * 3.1 + k / 2;

58
When performing a binary operation involving two
operands of different types, Java automatically
converts the operand based on the following rules:

1. If one of the operands is double, the other is


converted into double.
2. Otherwise, if one of the operands is float, the other is
converted into float.
3. Otherwise, if one of the operands is long, the other is
converted into long.
4. Otherwise, both operands are converted into int.

59
The char type only represents one character. To represent a string
of characters, use the data type called String. For example,

String message = "Welcome to Java";

60
// Three strings are concatenated
String message = "Welcome " + "to " + "Java";

// String Chapter is concatenated with number 2


String s = "Chapter" + 2; // s becomes Chapter2

// String Supplement is concatenated with character B


String s1 = "Supplement" + 'B'; // s1 becomes SupplementB

61
Program title:
Computes the area of the circle

62
allocate memory
public class ComputeArea { for radius
/** Main method */
public static void main(String[] args) {
double radius; radius no value
double area;

// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

63
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius no value
double area; area no value

// Assign a radius
radius = 20;
allocate memory
for area
// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

64
public class ComputeArea { assign 20 to radius
/** Main method */
public static void main(String[] args) {
double radius; radius 20
double area;
area no value
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

65
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;
compute area and assign
// Compute area it to variable area
area = radius * radius * 3.14159;

// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

66
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
double radius; radius 20
double area;
area 1256.636
// Assign a radius
radius = 20;

// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

67
Two ways of obtaining input by using import classes.

1. Using JOptionPane (input dialogs)


• import javax.swing.JOptionPane;
2. Using the Scanner class (input Console)
• import java.util.Scanner;
Class JOptionPane
• JOptionPane makes it easy to pop up a standard dialog box that prompts users
for a value or informs them of something.
• Require to “import javax.swing.JOptionPane;”.

Method Name Description


showConfirmDialog Asks a confirming question,
like yes/no/cancel.
showInputDialog Prompt for some input.
showMessageDialog Tell the user about something
that has happened.
showOptionDialog The Grand Unification of the
above three.
• Show an error dialog that displays the message, ‘Wrong number':
JOptionPane.showMessageDialog(null,“Wrong number","alert",JOptionPane.ERROR_MESSAGE);

• Show an internal information dialog with the message, ' Welcome to Java!","':
JOptionPane.showMessageDialog(null,"Welcome to Java!","Display
Message",JOptionPane.INFORMATION_MESSAGE);
• Show an information panel with the options yes/no and message ‘Please
choose one':
JOptionPane.showConfirmDialog(null,“Please choose one",“Choose
one",JOptionPane.YES_NO_OPTION);

• Show a warning dialog with the options OK, CANCEL, title 'Warning', and
message 'Click OK to continue':
Object[] options = { "OK", "CANCEL" };
JOptionPane.showOptionDialog(null, "Click OK to continue",
"Warning",JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,null, options,
options[0]);
• Show a dialog asking the user to type in a String:
String inputValue = JOptionPane.showInputDialog("Please input a value");

• Show a dialog asking the user to select a String:


Object[] possibleValues = { "First", "Second", "Third" };
Object selectedValue = JOptionPane.showInputDialog(null,"Choose one",
"Input",JOptionPane.INFORMATION_MESSAGE, null,possibleValues,
possibleValues[0]);
Program title:
Payroll (DialogBox)

73
import javax.swing.JOptionPane;

/** This program demonstrates using dialogs with JOptionPane. */


public class PayrollDialog
{
public static void main(String[] args)
{
String inputString; // For reading input
String name; // The user's name
int hours; // The number of hours worked
double payRate; // The user's hourly pay rate
double grossPay; // The user's gross pay

// Get the user's name.


name = JOptionPane.showInputDialog("What is " + "your name? ");
// Get the hours worked.
inputString =
JOptionPane.showInputDialog("How many hours " +
"did you work this week? ");

// Convert the input to an int.


hours = Integer.parseInt(inputString);

// Get the hourly pay rate.


inputString =
JOptionPane.showInputDialog("What is your " +
"hourly pay rate? ");

// Convert the input to a double.


payRate = Double.parseDouble(inputString);
// Calculate the gross pay.
grossPay = hours * payRate;

// Display the results.


JOptionPane.showMessageDialog(null, "Hello " +
name + ". Your gross pay is $" +
grossPay);

// End the program.


System.exit(0);
}
}
1. Create a Scanner object
Scanner input = new Scanner(System.in);
import java.util.Scanner; // Needed for the Scanner class

2. Methods for number-next(), nextByte(), nextShort(),


nextInt(), nextLong(), nextFloat(), nextDouble(), or
nextBoolean()
3.Method for string- byte, short, int, long, float,
double, or boolean value.

79
Program title:
Payroll(Console)

80
import java.util.Scanner; // Needed for the Scanner class

/** This program demonstrates the Scanner class. */

public class Payroll


{
public static void main(String[] args)
{
String name; // To hold a name
int hours; // Hours worked
double payRate; // Hourly pay rate
double grossPay; // Gross pay

// Create a Scanner object to read input.


Scanner keyboard = new Scanner(System.in);
// Get the user's name.
System.out.print("What is your name? ");
name = keyboard.nextLine();

// Get the number of hours worked this week.


System.out.print("How many hours did you work this week? ");
hours = keyboard.nextInt();

// Get the user's hourly pay rate.


System.out.print("What is your hourly pay rate? ");
payRate = keyboard.nextDouble();

// Calculate the gross pay.


grossPay = hours * payRate;
// Display the resulting information.
System.out.println("Hello, " + name);
System.out.println("Your gross pay is $" + grossPay);
}
}
• Choose meaningful and descriptive names.
• Variables and method names:
• Use lowercase.
• If the name consists of several words, concatenate all
in one, use lowercase for the first word, and capitalize
the first letter of each subsequent word in the name.
• For example, the variables radius and area, and
the method computeArea.

86
• Class names:
• Capitalize the first letter of each word in
the name. For example, the class name
ComputeArea.

• Constants:
• Capitalize all letters in constants, and use
underscores to connect words. For
example, the constant PI

87
The input returned from the input dialog box is a string. If
you enter a numeric value such as 123, it returns “123”.
To obtain the input as a number, you have to convert a
string into a number.

To convert a string into an int value, you can use the


static parseInt method in the Integer class as follows:

int intValue = Integer.parseInt(intString);

where intString is a numeric string such as “123”.


88
To convert a string into a double value, you can use the
static parseDouble method in the Double class as follows:

double doubleValue =Double.parseDouble(doubleString);

where doubleString is a numeric string such as “123.45”.

89
In Java, an augmented expression of the form x1 op= x2 is
implemented as x1 = (T)(x1 op x2), where T is the type for
x1. Therefore, the following code is correct.
int sum = 0;
sum += 4.5; // sum becomes 4 after this statement

sum += 4.5 is equivalent to sum = (int)(sum + 4.5).

90

You might also like