Anda di halaman 1dari 51

Business Applications

Programming

Data Types and Variable


The Java language
• Data Types
• Java Variables
• Types of Variables
• Symbolic Constants
• Packaging Constants
• Java's Math class
• Input from the keyboard
Data Types
• A Data type specifies the size and type of values
that can be stored in an identifier.
• The Java language is rich in its data types.
Different data types allow you to select the type
appropriate to the needs of the application.
• Data types in Java are classified into two types:
– Primitive—which include Integer, Character,
Boolean, and Floating Point.
– Non-primitive—which include Classes, Interfaces,
and Arrays.
Data Types
Primitive Data Types
• A primitive type is predefined by the
language and is named by a reserved
keyword.
• Primitive values do not share state with other
primitive values.
• There are 8 primitive types:
– byte, short, int, long, char, float, double, and
boolean.
Integer
• Integer types can hold whole numbers such as
123 and −96.
• The size of the values that can be stored
depends on the integer type that we choose
(see table next page)
Integer
Type Size Range of values that can be stored

byte 1 byte −128 to 127

short 2 bytes −32768 to 32767

int 4 bytes −2,147,483,648 to 2,147,483,647

9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,755,807
Integer
Integer
• The range of values is calculated as −(2n−1) to
(2n−1)−1; where n is the number of bits
required.
• For example, the byte data type requires 1
byte = 8 bits. Therefore, the range of values
that can be stored in the byte data type is
−(28−1) to (28−1)−1
= −27 to (27) -1
= −128 to 127
Floating Point
• Floating point data types are used to represent
numbers with a fractional part.
• Single precision floating point numbers occupy 4
bytes and Double precision floating point
numbers occupy 8 bytes.
• There are two subtypes:
Range of values
Type Size that can be
stored
3.4e−038 to
float 4 bytes
3.4e+038
1.7e−308 to
double 8 bytes
1.7e+038
Character
• It stores character constants in the memory.
• It assumes a size of 2 bytes, but basically it can
hold only a single character because char stores
unicode character sets.
• It has a minimum value of ‘u0000’ (or 0) and a
maximum value of ‘uffff’ (or 65,535,
inclusive).
Boolean
• Boolean data types are used to store values
with two states:
– true or false.
Java Variables
• What is a Variable?
– A variable can be thought of as a container
which holds values for you, during the life of a
Java program.
– A variable is a name of a reserved area
allocated in memory. In other words, it is a
name of memory location.
– Every variable is assigned a data type which
designates the type and quantity of value it can
hold.
Java Variables
• Fields in classes are also variables.
Remember the bicycle class fields: cadence,
speed and gear
• In order to use a variable in a program you
need to perform 2 steps
– Variable Declaration
– Variable Initialization
Java Variables
• Variable Declaration
– To declare a variable, you must specify the data
type & give the variable a unique name
Java Variables
• Variable Declaration
– Examples of other Valid Declarations are:
• int a,b,c;
• float pi;
• double d;
• char a;
Java Variables
• Variable Initialization
– To initialize a variable, you must assign it a
valid value.
Java Variables
• Variable Initialization
– Example of other Valid Initializations are
• int a=2,b=4,c=6;
• pi =3.14f;
• do =20.22d;
• a=’v’;
Java Variables
• Variable Initialization
– Examples of other Valid Initializations are
• Numbers
– To declare and assign a number use the following syntax:
int myNumber;
myNumber = 5;
– Or you can combine them:
int myNumber = 5;
Java Variables
• Variable Initialization
– Examples of other Valid Initializations are
• Numbers
– To define a double floating point number, use the following
syntax:
double d = 4.5;
d = 3.0;
– If you want to use float, you will have to cast:
float f = (float) 4.5;
Java Variables
• Variable Initialization
– Examples of other Valid Initializations are
• Characters and Strings
char c = 'g';
– String is not a primitive. It's a real type, but Java has special
treatment for String.
– Here are some ways to use a string:

// Create a string with a constructor


String s1 = new String("Who let the dogs out?");

// Just using "" creates a string, so no need to write it the


previous way.
String s2 = "Who who who who!";
Java Variables
• Variable Initialization
– Examples of other Valid Initializations are
• Characters and Strings
// Java defined the operator + on strings to concatenate:
String s3 = s1 + s2;

– You can also concatenate string to primitives:


int num = 5; String s = "I have " + num + " cookies"; //Be
sure not to use "" with primitives.
Java Variables
• Types of variables
– In Java, there are three types of variables:
• Local Variables
• Instance Variables
• Static Variables
Types of Variables
• Local Variables
– Local Variables are variables that are declared
inside the body of a method.
• Instance Variables
– Instance variables are defined without the
STATIC keyword .They are defined Outside a
method declaration. They are Object specific and
are known as instance variables.
Types of Variables
• Static Variables
– A variable which is declared as static is called a static
variable. It cannot be local.
– Static variables are also known as class variables; it is
any field declared with the static modifier; this tells the
compiler that there is exactly one copy of this variable in
existence, regardless of how many times the class has
been instantiated.
• A field defining the number of gears for a particular kind of
bicycle could be marked as static since, conceptually, the same
number of gears will apply to all instances.
• The code static int numGears = 6; would create such a static
field.
– Static variables are initialized only once, at the start of the
program execution. These variables should be initialized
first, before the initialization of any instance variables.
Example: Types of Variables in
Java
class VariableTypes {
int data = 99; //instance variable
static int a = 1; //static variable
void method() {
int b = 90; //local variable
}
}
Java Variable Example: Add
Two Numbers
class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Java Variable Example:
Widening
class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Java Variable Example:
Narrowing (Typecasting)
class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}
Java Variable Example:
Overflow
class Simple{
public static void main(String[] args){
//Overflow
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);
}
}
Java Variable Example: Adding
Lower Type
class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will
be int
byte c=(byte)(a+b);
System.out.println(c);
}
}
Symbolic Constants
• A constant in Java refers to fixed value that does
not change during the execution of a program.
• Java supports several types of constants namely:
– Numeric and character constants.
– Numeric constants are again divided into two types
integer and real constants.
– Character constants are divided into character and
string constants.
– We can also define symbolic constants using the
keyword " final" like the const keyword in C
Programming.
• A symbolic constant is a "variable" whose value does not
change during the entire lifetime of the program
Symbolic Constants
• If any numeric value is repeatedly appearing in
your program, such type of value is defined as a
constant like:
PI= 3.14159;
PASS_MARKS=35;
• In Java, a keyword called" final" is used to define
symbolic constants and it has the following
syntax:
final type symbolic_name = Value
Example:
final int STRENGTH=100;
final float PI =3.14159;
Final int PASS_MARKS=35;
Symbolic Constants
• Rules for Using Symbolic constants:-
– Symbolic names take the some form of
variable names. But they are written in
capitals to differentiate them from
variable names. This is only a convention and
not a rule.
– After declaration of symbolic constants they
shouldn’t be assigned any other value with in
the program by using an assignment statement.
• For example:- STRENTH = 200 is illegal
– Symbolic constants must be declared with types
Symbolic Constants
• A symbolic constant can be defined:
– inside a method - such a constant can only be used by
the method in which it is defined, or
– inside a class (outside all methods) - the access of such
a constant is determined by the given access specifier
• Syntax to define a constant inside a method:
final typeName variableName = expression;
• Syntax to define a constant inside a class
(outside methods):
accessSpecifier static final typeName variableName =
expression;
Symbolic Constants
• The use of the keyword final means:
– the value is "finalized" (once a value is given to the
variable, the value cannot be changed further)
• The use of the keyword static means that:
– the variable belongs to the class and the variable
exists from the start of the program
• accessSpecifier can be either public or private
Private constants (and variables) can only be
accessed from within the class
Example how to define a
constant:
public class MyClassName {
public void Method1() {
final double e = 2.718281828; // Constant in method
}
public void Method2() {
final int c = 299792458; // Constant in method
}
public static final double Pi = 3.1415926535; // Constant in class

}
Example how to define a
constant:
public class Constant1 {
public void Method1() {
final double e = 2.718281828;
// e = 1.0; // Try to change e - forbidden if e is "final".
}
public void Method2() {
final int c = 299792458;
}
public final double Pi = 3.1415926535;
}
Packaging Constants
• If your program uses many constants, then it
would be a good idea to put all the constants in
one place.
• In Java, a class is uses to hold:
– Constructors
– Methods
– Variables
– Constants
• You may want write a class that only holds
constants.
Packaging Constants
public class MyConstants {
public static final double PI = 3.1415926535;
public static final double E = 2.718281828;

}
Packaging Constants
public class UseConstants {
public static void main(String[] args) {
// TODO code application logic here
double r = 10;
double area;

area = MyConstants.PI * r * r;

System.out.print("radius = ");
System.out.println(r);
System.out.print("area = ");
System.out.println(area);
}
}
Java's Math class
• Java has provided (i.e., packaged) the above
constants in their API.
• The class that contains these Mathematical
constants is called: Math
• We can rewrite the above program using the
constants in Java's API as follows: ( see
next slide)
Java's Math class
public class UseConstants {
public static void main(String[] args) {
// TODO code application logic here
double r = 10;
double area;

area = Math.PI * r * r;

System.out.print("radius = ");
System.out.println(r);
System.out.print("area = ");
System.out.println(area);
}
}
Input from the keyboard
• In Java, there are many ways to read strings
from input.
• The simplest one is to make use of the class
Scanner, which is part of the java.util library.
• Using this class, we can create an object to
read input from the standard input channel
System.in (typically, the keyboard), as follows:
Scanner scanner = new Scanner(System.in);
Input from the keyboard
• Then, we can use the nextLine() method of the
Scanner class to get from standard input the next
line (a sequence of characters delimited by a
newline character), according to the following
schema:
import java.util.Scanner;
public class KeyboardInput {
public static void main (String[] args) {
Scanner scanner = new Scanner(System.in);
String inputString = scanner.nextLine();
System.out.println(inputString);
}
}
Input from the keyboard
• Explanation:
– import java.util.Scanner; - imports the class Scanner from
the library java.util
– Scanner scanner = new Scanner(System.in); - creates a
new Scanner object, that is connected to standard input
(the keyboard)
– String inputString = scanner.nextLine(); temporarily
suspends the execution of the program, waiting for input
from the keyboard;
– the input is accepted as soon as the user digits a carriage
return;
– (a reference to) the string entered by the user (up to the
first newline) is returned by the nextLine() method;
– (the reference to) the string is assigned to the variable
inputString.
Input from the keyboard
• We can also read in a single word (i.e., a
sequence of characters delimited by a
whitespace character) by making use of the
next() method of the Scanner class.
• The example shown on the next slide, on Java
Keyboard Input, takes from the Student name,
circle radius and rectangle height and length.
Input from the keyboard
import java.util.Scanner;
public class StringExample {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
System.out.println("Enter Student Name:");
String stdName = scan1.nextLine();
System.out.println("Enter Circle Radius as a whole number:");
int radius = scan1.nextInt();
System.out.println("Enter Rectangle length as a floating point value:");
double length = scan1.nextDouble();
System.err.println("Enter Rectangle width as a floating point value:");
double width = scan1.nextDouble();
//Display the results of computation
System.out.println("\nStudent Name "+ stdName);
System.out.println("Circle Perimetre: " + 2*Math.PI*radius);
System.out.println("Rectangle Area: " + width*length);
}
}
Input from the keyboard
• The Java Scanner class breaks the input into
tokens using a delimiter that is whitespace
bydefault.
• It provides many methods to read and parse
various primitive values.
• Java Scanner class is widely used to parse text
for string and primitive types using regular
expressions.
• Java Scanner class extends Object class and
implements Iterator and Closeable interfaces.
Commonly used methods of Scanner class
Method Description

public String next() it returns the next token from the scanner.

it moves the scanner position to the next line and returns the value as
public String nextLine()
a string.

public byte nextByte() it scans the next token as a byte.

public short nextShort() it scans the next token as a short value.

public int nextInt() it scans the next token as an int value.

public long nextLong() it scans the next token as a long value.

public float nextFloat() it scans the next token as a float value.

public double
it scans the next token as a double value.
nextDouble()
Java Scanner Example with delimiter
import java.util.*;
public class ScannerTest2{
public static void main(String args[]){
String input = "10 tea 20 coffee 30 tea buiscuits";
Scanner s = new Scanner(input).useDelimiter("\\s");
//System.out.println(s.nextInt());
//System.out.println(s.next());
//System.out.println(s.nextInt());
//System.out.println(s.next());
while (s.hasNextInt()|| s.hasNext())
{
if(s.hasNextInt())
System.out.println(s.nextInt());
else
System.out.println(s.next());
}

s.close();
}
}

Anda mungkin juga menyukai