Вы находитесь на странице: 1из 29

Data types, declarations, and

expressions in Java
Variables
• A variable is a named memory location
capable of storing data

• Class variables
• Instance variables
Class Variables Instance Variables 
Class variables are declared with keyword Instance variables are declared without
static. static keyword. 
Class variables are common to all Instance variables are not shared between
instances of a class. These variables are the objects of a class. Each instance will
shared between the objects of a class. have their own copy of instance variables.

As class variables are common to all As each object will have its own copy of
objects of a class, changes made to these instance variables, changes made to these
variables through one object will reflect in variables through one object will not
another. reflect in another object.
 
Class variables can be accessed using Instance variables can be accessed only
either class name or object reference. through object reference.
 
Data declaration syntax
• The syntax for the declaration of a variable
is:
Data type identifier;
– “data type” may be the name of a class, as we
have seen, or may be one of the simple types,
“identifier” is a legal Java identifier; the rules
for simple variable identifiers are the same as
those for object identifiers
Variable declaration: examples
• For example:
int age; // int means integer
double cashAmount; // double is a real #
• We can also declare multiple variables of the same type
using a single instruction; for example:
int x, y, z; // or
int x,
y,
z;
•  The second way is preferable, because it’s easier to
document the purpose of each variable this way.
Numeric data types in Java:
integers
Data type name Minimum value Maximum value

byte -128 127

short -32,768 32,767

int -2,147,483,648 2,147,483,647

long - 9,223,372,036,85
9,223,372,036,85 4,775,807
4,775,808
Numeric data types in Java:
floating-point numbers
Data type Minimum value Maximum value
name
float -3.40282347 x 1038 3.40282347 x 1038

double - 1.79769313486231
1.79769313486231 570 x 10308
570 x 10308
Numeric data types: some notes
• Most programmers use int for whole numbers and
double for real numbers
• Numeric data types in Java are primitive (non-
object) types; this means that a numeric variable is
somewhat different from an object:
– You don’t use the new operator to initialize a numeric
variable – just assign it a value
– Memory for a numeric variable is allocated at
declaration
– Numeric variables actually store values; object names
store addresses
Assignment statements
• We can store a value in a variable using an
assignment statement
• Assignment statement syntax:
variableName = expression; 
– variableName must be the name of a declared
variable
– expression must evaluate to an appropriate
value for storage within the type of variable
specified
Arithmetic operators in Java
• Compound Operation Symbol
expressions are Addition +
formed by
combining simple Subtraction -
expressions using Multiplication *
arithmetic
operators Division /

Modulus %
Arithmetic operations in Java
• As in algebra, multiplication and division (and
modulus, which we’ll look at momentarily) take
precedence over addition and subtraction
• We can form larger expressions by adding more
operators and more operands
– Parentheses are used to group expressions, using the
same rule as in algebra: evaluate the innermost
parenthesized expression first, and work your way out
through the levels of nesting
– The one complication with this is we have only
parentheses to group with; you can’t use curly or square
brackets, as they have other specific meanings in Java
Examples
int x = 4, y = 9, z;

z = x + y * 2;
z = (x + y) * 2;
y = y – 1;
Examples
int x = 4, y = 9, z;

z = x + y * 2; // result is 22
z = (x + y) * 2; // result is 26
y = y – 1; // result is 8
Mixed-type expressions
• A mixed-type expression is one that involves operands of
different data types
– Like other expressions, such an expression will evaluate to a single
result
– The data type of that value will be the type of the operand with the
highest precision
– What this means, for all practical purposes, is that, if an
expression that involves both real numbers and whole
numbers, the result will be a real number.
• The numeric promotion that takes place in a mixed-type
expression is also known as implicit type casting
Assignment conversion
• Another kind of implicit conversion can
take place when an expression of one type
is assigned to a variable of another type
• For example, an integer can be assigned to a
real-number type variable; in this case, an
implicit promotion of the integer value
occurs
Compound arithmetic/assignment
operators
• Previous examples in the notes have included the
following statements:
y = y + 1;
y = y / 3;
• In each case, the current value of the variable is used to
evaluate the expression, and the resulting value is assigned
to the variable (erasing the previously-stored value)
• This type of operation is extremely common; so much so,
that Java (like C++ and C before it) provides a set of
shorthand operators to perform this type of operation. The
table on the next slide illustrates the use and meaning of
these operators
Compound arithmetic/assignment
operators
Operator Use Meaning

+= X += 1; X = X + 1;

-= X -= 1; X = X – 1;

*= X *= 5; X = X * 5;

/= X /= 2; X = X / 2;

%= X %= 10; X = X % 10;
Named constants
• A variable is a named memory location that can hold a
value of a specific data type; as we have seen, the value
stored at this location can change throughout the execution
of a program
• If we want to maintain a value in a named location, we use
the Java keyword final in the declaration and immediately
assign the desired value; with this mechanism, we declare
a named constant. Some examples:
final int LUCKY = 7;
final double PI = 3.14159;
final double LIGHTSPEED = 3.0e10.0 ;
Named constants
• The name of the constant is used in expressions but cannot
be assigned a new value. For example, to calculate the
value of variable circleArea using the variable radius and
the value , we could write:
circleArea = 2 * PI * radius * radius;
• The use of named constants is considered good
programming practice, because it:
– eliminates (or at least minimizes) the use of “magic” numbers in a
program; it is easier to read code that contains meaningful names
– allows a programmer to make global changes in calculations easily
Reading Input from the Console

Reading input from the console enables the


program to accept input from the user.
Java uses System.out to refer to the standard output
device and System.in to the standard input device. By
default, the output device is the display monitor and the
input device is the keyboard. To perform console output,
you simply use the print method to display a primitive
value or a string to the console. Console input is not
directly supported in Java, but you can use the Scanner
class to create an object to read input from System.in,
as follows:

Scanner input = new Scanner(System.in);


The syntax new Scanner(System.in)
creates an object of the Scanner type. The
syntax Scanner input declares that input
is a variable whose type is Scanner.
import java.util.Scanner;
public class Act7Geometry
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);

}
}
Console Input
Act8ReadingInput.java
Scanner input = new Scanner(System.in);

System.out.println("Enter whole number: ");


int num1 = input.nextInt();
System.out.print(num1);
Act8ReadingInput.java
System.out.println("Enter decimal number: ");
int num2 = input.nextDouble();
System.out.print(num2);
Act9AddingNumbers.java
Scanner input = new Scanner(System.in);

System.out.println("Enter firstnumber: ");


int firstnum = input.nextInt();

System.out.println("Enter secondnumber: ");


int secondnum = input.nextInt();

int sum = firstnum + secondnum;


int subtract = firstnum – secondnum;

System.out.println("Sum: " + sum);


System.out.print(“Difference : " + subtract);
Act10ReadingString.java
Scanner input = new Scanner(System.in);

System.out.println("Enter firstname: ");


String firstname = input.next();

System.out.print(firstname);
Programming Exercise 2
• PE3.java
• (Financial application: payroll) Write a program that reads the
following information and prints a payroll statement:

Employee’s name (e.g., Smith)


PAYSLIP:
Number of days worked in a week (e.g., 10) Employee Name:
Hourly pay rate (e.g., 65.75) Days Worked:
SSS: (e.g., 10%) Pay Rate:
Tax withholding rate (e.g., 9%) Gross Pay:
Deductions:
SSS (10%):
TAX(9.0%):
Total Deduction:
Net Pay:

Вам также может понравиться