0% found this document useful (0 votes)
13 views31 pages

02 Var Data1

Uploaded by

1762689820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views31 pages

02 Var Data1

Uploaded by

1762689820
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Lecture 2: Variables and

Primitive Data Types

1
In this lecture, you will learn…
• What a variable is
– Types of variables
– Naming of variables
– Variable assignment
• What a primitive data type is
• Other data types (ex. String)

2
What is a Variable?
• In basic algebra, variables are symbols
that can represent values in formulas.

• Formula: y=x2+2
can represent any number value.

• Similarly, variables in computer program


are symbols for arbitrary data.

3
A Variable Analogy
• Think of variables as an empty box that you
can put values in.

We can label the box with a name like “Box a” and re-use it many times.

– “Move Box a to Shelf A”


– “Put item Z in box”
– “Remove contents from Box a”
4
Variables Types in Java
• Variables have a type.

The type defines what kinds of values a variable is allowed to store.

• The variable x in f(x)=x2+2 is implicitly a number.

• If x is a symbol representing the word


“Fish”, the formula doesn’t make sense.

5
Java Types
• Integer Types:
– int: Most numbers you’ll deal with.
– long: Big integers; science, finance, computing.
– short: Small integers. Legacy. Not very useful.
– byte: Very small integers, useful for generic data.
• Floating Point (Decimal) Types:
– float: Single-precision decimal numbers
– double: Double-precision decimal numbers.
• Other Types:
– String: Text strings.
– boolean: True or false.
– char: Latin Alphanumeric Characters

6
Declaring Variables in Java
• Variables are created by declaring their
type and their name as follows:
– type name;
• Declaring an integer named “x” :
– int x;
• Declaring a string named “greeting”:
– String greeting;
• We have not assigned values to these
variables; just made empty boxes.

8
Assigning Values to Variables
• Assign values to variables using the syntax:
– String name = "value";
• For example:
– int x = 100;
– String greeting = “Jambo”;
• Illegal to assign a variable the wrong type:
– int x = “Jambo”;
– int x = 1.2;
– String greeting = 123;
• Can declare and assign in one step:
– int x = 100;
– String greeting = “Jambo”;

9
Naming Variables
• Variable names (or identifiers) may be any
length, but must start with:
– A letter (a – z),

– A dollar sign ($),

– Or, an underscore ( _ ).

• Identifiers cannot contain special operation


symbols like +, -, *, /, &, %, ^, etc.
• Certain reserved keywords in the Java
language are illegal.
• For example, “class”, “static”, “int”,
etc.
10
Naming Variables

• Choose variable names that are informative.


– Good: int studentExamGrade;
studentExamGrade = 98 ;
– Bad: int tempvar3931;
tempvar3931 = 95 ;

11
Floating Point Types
• Initialize doubles as you would write a
decimal number:
– double y = 1.23;
• Use a trailing ‘d’ to force a value to be
double:
– double y = 1d/3; // y
= .333333333
– double z = 1/3; // z = 0.0 …
Why?

12
public class AdditionOperator
{
public static void main(String[] args)
{
int firstVal = 5;
int secondVal = 2;

int firstPlusSecond = firstVal +


secondVal;

System.out.println(firstPlusSecond);
}
}
Integer Division

in Java

5/2=2

5.0 / 2.0 = 2.5

When you use mixed division in your program


you will be returned a double.

5 / 2.0 = 2.5
public class TrickyJava
{
public static void main(String[] args)
{
int candyBars = 20;
int friends = 5;

System.out.print("Candy bars: ");


System.out.println(candyBars);
System.out.print("Friends: ");
System.out.println(friends);
int candyBarsPerPerson = candyBars / friends;
System.out.print("Candy per person: ");
System.out.println(candyBarsPerPerson);

friends = friends + 1;
System.out.print("Candy bars: ");
System.out.println(candyBars);
System.out.print("Friends: ");
System.out.println(friends);
candyBarsPerPerson = candyBars / friends;
System.out.print("Candy per person: ");
System.out.println(candyBarsPerPerson);
}
}
public class TrickyJava
{
public static void main(String[] args)
{
int candyBars = 20;
int friends = 5;

System.out.print("Candy bars: ");


System.out.println(candyBars);
System.out.print("Friends: ");
System.out.println(friends);
int candyBarsPerPerson = candyBars / friends;
System.out.print("Candy per person: ");
System.out.println(candyBarsPerPerson);

friends = friends + 1;
System.out.print("Candy bars: ");
System.out.println(candyBars);
System.out.print("Friends: ");
System.out.println(friends);
candyBarsPerPerson = candyBars / friends;
System.out.print("Candy per person: ");
System.out.println(candyBarsPerPerson);
}
}
public class MyProgram
{
public static void main(String[] args)
{
int intTempF = 70;

double convert1 = 5 / 9 * (intTempF - 32);


System.out.println(convert1);

double convert2 = 5.0 / 9 * (intTempF - 32);


System.out.println(convert2);

double doubleTempF = 70;

double convert3 = 5 / 9 * (doubleTempF - 32);


System.out.println(convert3);

double convert4 = (doubleTempF - 32) * 5 / 9;


System.out.println(convert4);
}
}
public class MyProgram
{
public static void main(String[] args)
{
int intTempF = 70;

double convert1 = 5 / 9 * (intTempF - 32);


System.out.println(convert1);

double convert2 = 5.0 / 9 * (intTempF - 32);


System.out.println(convert2);

double doubleTempF = 70;

double convert3 = 5 / 9 * (doubleTempF - 32);


System.out.println(convert3);

double convert4 = (doubleTempF - 32) * 5 / 9;


System.out.println(convert4);
}
}
Compound Assignment Operators

Evaluating What is Stored in a


Variable
int mysteryNum = (4 + 6 * (2 * 3) - 2);
public class AllFunctionsCalculator
{
public static void main(String[] args)
{
int num = 2;
int sum = 5;
int difference = 5;
int product = 5;
int dividend = 5;
int modulo = 5;
sum += num;
difference -= num;
product *= num;
dividend /= num;
modulo %= num;
System.out.print("The sum is ");
System.out.println(sum);
System.out.print("The difference is ");
System.out.println(difference);
System.out.print("The product is ");
System.out.println(product);
System.out.print("The dividend is ");
System.out.println(dividend);
System.out.print("The modulo is ");
System.out.println(modulo);
}
}
public class AllFunctionsCalculator
{
public static void main(String[] args)
{
int num = 2;
int sum = 5;
int difference = 5;
int product = 5;
int dividend = 5;
int modulo = 5;
sum += num;
difference -= num;
product *= num;
dividend /= num;
modulo %= num;
System.out.print("The sum is ");
System.out.println(sum);
System.out.print("The difference is ");
System.out.println(difference);
System.out.print("The product is ");
System.out.println(product);
System.out.print("The dividend is ");
System.out.println(dividend);
System.out.print("The modulo is ");
System.out.println(modulo);
}
}
public class IncreaseDecrease
{
public static void main(String args[])
{
int num1 = 4;
int num2 = 3;

System.out.print("num1 = ");
System.out.println(num1);
System.out.print("num2 = ");
System.out.println(num2);

System.out.println("Increasing the value of num1");


num1++;

System.out.println("Decreasing the value of num2");


num2--;

System.out.print("num1 = ");
System.out.println(num1);
System.out.print("num2 = ");
System.out.println(num2);
}
}
public class IncreaseDecrease
{
public static void main(String args[])
{
int num1 = 4;
int num2 = 3;

System.out.print("num1 = ");
System.out.println(num1);
System.out.print("num2 = ");
System.out.println(num2);

System.out.println("Increasing the value of num1");


num1++;

System.out.println("Decreasing the value of num2");


num2--;

System.out.print("num1 = ");
System.out.println(num1);
System.out.print("num2 = ");
System.out.println(num2);
}
}
Casting and Range of Variables

How Casting Works


int doubleToInt = (int)10.95; // This will become
'10'

int intVal = 10;


double doubleVal = (double)intVal;
// Our 'doubleVal' variable is now '10.0'

double doubleVal = 7.6;


int intVal = (int)doubleVal;
// Our 'intVal' variable is now '7'

int currResidents = 50;


int floorTotal = 56;
double average = (double)floorTotal /
currResidents;
// We now have the value of '1.12'
CAST

Compile-time Error

5.0 5.0

2.5
2.0

2.5
public class CastingOrderOfOperations
{
public static void main(String[] args)
{
int doubleCastedToInt = (int) 10.9 ;
System.out.print("(int) 10.9 = ");
System.out.println(doubleCastedToInt);

double castNumerator = (double) 2 / 3;


System.out.print("(double) 2 / 3 = ");
System.out.println(castNumerator);

double castDenominator = 2 / (double) 3;


System.out.print("2 / (double) 3 = ");
System.out.println(castDenominator);

double castNeither = 2 / 3;
System.out.print("2 / 3 = ");
System.out.println(castNeither);

double castOutsideOfParentheses = (double) (2 / 3);


System.out.print("(double) (2 / 3) = ");
System.out.println(castOutsideOfParentheses);

double castWrongElement = (double) 5 + 2 / 3;


System.out.print("(double) 5 + 2 / 3 = ");
System.out.println(castWrongElement);

double castCorrectElement = 5 + (double) 2 / 3;


System.out.print("5 + (double) 2 / 3 = ");
System.out.println(castCorrectElement); }}
public class CastingOrderOfOperations
{
public static void main(String[] args)
{
int doubleCastedToInt = (int) 10.9 ;
System.out.print("(int) 10.9 = ");
System.out.println(doubleCastedToInt);

double castNumerator = (double) 2 / 3;


System.out.print("(double) 2 / 3 = ");
System.out.println(castNumerator);

double castDenominator = 2 / (double) 3;


System.out.print("2 / (double) 3 = ");
System.out.println(castDenominator);

double castNeither = 2 / 3;
System.out.print("2 / 3 = ");
System.out.println(castNeither);

double castOutsideOfParentheses = (double) (2 / 3);


System.out.print("(double) (2 / 3) = ");
System.out.println(castOutsideOfParentheses);

double castWrongElement = (double) 5 + 2 / 3;


System.out.print("(double) 5 + 2 / 3 = ");
System.out.println(castWrongElement);

double castCorrectElement = 5 + (double) 2 / 3;


System.out.print("5 + (double) 2 / 3 = ");
System.out.println(castCorrectElement); }}
Math method : abs 、 pow 、 sqrt 、
int num=-89;
random
double newNum= Math.abs(num);
Min and Max Values of Integers

Integer.MIN_VALUE double number = Math.abs(-8.9);

double pow =
Integer.MAX_ VALUE
Math.pow(num,3);

double newPow = Math.pow(2,3);

double sqrt =

Math.sqrt(81.0);

double ran =
The minimium integer value in Java is -
2147483648
The maximum integer value in JavaMath.random();//[0,1)
is 2147483647
Boolean Type
• The values true or false are case-
sensitive keywords.

• Booleans will be used later for testing


properties of data.

• Example:
– boolean monsterHungry = true;
– boolean fileOpen = false;

29
String Type
• Strings are not a primitive. They are what’s
called an Object, which we will discuss later.

• Strings are sequences of characters


surrounded by “double quotations”.
– String greeting = “Jambo”;
– String Greet = new String(“Hi
”);

• Strings have a special append operator + that


creates a new String:
– String bigGreeting = Greet + greeting;
30
Escape Sequences
• The three escape sequences that you should
know for the AP exam are :

System.out.println("Welcome to\na new line");

System.out.println("He is known as \"Hothead Harry\".");


System.out.println("The file path is d:\\
myFiles\\..");

31

You might also like