0% found this document useful (0 votes)
2 views

Lecture 2 Primitive Data types in Java

The document outlines the content of a lecture on Java programming, covering topics such as computer hardware, software development models, Java advantages, and basic programming concepts. It includes examples of simple programs, primitive data types, variable declarations, and type conversions. Additionally, it provides practice problems and exercises to reinforce learning.

Uploaded by

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

Lecture 2 Primitive Data types in Java

The document outlines the content of a lecture on Java programming, covering topics such as computer hardware, software development models, Java advantages, and basic programming concepts. It includes examples of simple programs, primitive data types, variable declarations, and type conversions. Additionally, it provides practice problems and exercises to reinforce learning.

Uploaded by

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

5/24/2020

IN2203

Fundamentals of
Programming (Java)

Instructor
Dr. Muhammad Waqar
[email protected]

An Overview of Lecture 1
We discussed the following in lecture1
Tests
• Computer Hardware, software and languages
• Software development model
• A comparison of Java with other languages
• Advantages of Java
• Using NetBeans to compile java programs
• Discussed different parts of a simple program

1
5/24/2020

A Simple Program
public class Example2 {
Tests
public static void main(String args[]) {
System.out.println("John Smith");
}
}
Output of this program is

John Smith

Practice Problems
1- Write a program which prints your name vertically
Tests
2- Write a program that displays your name on two lines inside a
rectangle of asterisks as
follows:
******************
* First name *
* Surname *
******************

Make sure the asterisks are properly aligned. To do this you will need
to insert spaces (blanks) in the right place.

2
5/24/2020

Practice Problem 1 code


public class Example2 {
public static void main(String args[]) {
System.out.println("J"); Tests
System.out.println("o");
System.out.println("h");
System.out.println("n");
System.out.println("");
System.out.println("S");
System.out.println("m");
System.out.println("i");
System.out.println("t");
System.out.print("h");
}
}

Practice Problem 2 code

public class Example2 { Tests

public static void main(String args[]) {


System.out.println("***************");
System.out.println("* John *");
System.out.println("* Smith *");
System.out.println("***************");
}
}

3
5/24/2020

The Primitive Data Types


• Java defines eight primitive data types: byte, short, int, long, float,
double, char and boolean Tests

• Integers: This group includes which are for whole valued numbers

• Floating point numbers: This group includes float and double which
represent numbers with fractional precision

• Characters: This group includes char which represents symbols in a


character set, like letters and numbers

• boolean: This group includes boolean which is a special type for


true/false values

Integers
• Java has four integer types: byte, int, short and long
• All of these are signed, positive and Tests
negative values
• Java does not support positive only, unsigned integers

4
5/24/2020

Byte and short


• The smallest integer type is byte. This is a signed 8-bit type that has a
range from –128 to 127.
Testsraw binary data that may not
• Byte is useful when you’re working with
be directly compatible with Java’s other built-in types.
• Byte variables are declared by use of the byte keyword.

byte b, c;

• short is a signed 16-bit type. It has a range from –32,768 to 32,767.


• It is probably the least-used Java type.
• Here are some examples of short variable declarations:

short s;
short t;

10

Integer
• The most commonly used integer type is int. It is a signed 32-bit type
that has a range from –2,147,483,648 to 2,147,483,647.
Tests
• In addition to other uses, variables of type int are commonly
employed to control loops and to index arrays.

• When byte and short values are used in an expression they are
promoted to int when the expression is evaluated. Therefore, int is
often the best choice when an integer is needed.

int a, b;

10

5
5/24/2020

11

long

• The long is a signed 64-bit type and is useful for those occasions
Tests
where an int type is not large enough to hold the desired value.

• The range of a long is quite large. This makes it useful when big,
whole numbers are needed.

11

12

Variables
• The variable is the basic unit of storage in a Java program. A variable
is defined by the combination of an identifier, a type, and an optional
initializer. Tests

• In addition, all variables have a scope, which defines their visibility,


and a lifetime.

• In Java, all variables must be declared before they can be used.

12

6
5/24/2020

13

Variables
type identifier = value, identifier = value ;

• The type is one of Java’s atomic types,Tests


or the name of a class or
interface.
• The identifier is the name of the variable.
• You can initialize the variable by specifying an equal sign and a
value.
• To declare more than one variable of the specified type, use a comma
separated list.

13

14

Variables Examples
int a, b, c; // declares three ints, a, b, and c.
Tests
a=5; // assigns a value 5 to already declared int variable a (initiliazation)

int d = 3, e, f = 5; // declares three more ints, initializing d and f.

byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

int g = d*f; // dynamic initialization

14

7
5/24/2020

15

Simple program using Integers


• This program calculates square of a number
Tests
public class Example2 {

public static void main(String args[]) {

int number = 5;
System.out.println("Square of 5 is: " + (number*number));

}
}

15

16

Another simple program using Integers


• Write a program which converts 3 hours and 25 minutes into
seconds.
Tests
Steps

1- Define four int variables ‘hours’, ‘minutes’, ‘total_minutes’,


‘total_seconds’
1- Assign value 3 to variable ‘hours’ for saving hours value
2- Assign value 25 to variable ‘minutes’ for saving minutes
3- Calculate value of ‘total_minutes’ by converting ‘hours’ into minutes
and by adding ‘minutes’ to it.
4- Calculate value of ‘total_seconds’ by multiplying ‘total_minutes’ to
60
5- Print ‘total_seconds’

16

8
5/24/2020

17

Program Code
public class Example {
public static void main(String args[]) {
Tests
int hours, minutes, total_minutes, total_seconds;
hours = 3;
minutes = 25;
total_minutes = hours * 60 + minutes;
total_seconds = total_minutes * 60;
System.out.println("3 hours and 25 minutes = : " + total_seconds + "
seconds");
}
}

17

18

Floating-Point Types
• Floating-point numbers, also known as real numbers, are used when
evaluating expressions that require fractional precision.
• Calculations such as square root, sineTests
and cosine, result in a value
whose precision requires a floating-point type.

• float high_temp = 33.9f; #Always append f declaring float


• double pi = 3.14;

18

9
5/24/2020

19

A simple program
Write a program which converts 25 miles into kilometers.
Tests
Steps:

1- Define a double variable ‘miles’ which has value equal to 25. (stores
miles)
2- Dynamically initialize another double variable ‘Kilo_meters’ by
converting 25 miles into kilometers. (Hint: 1 mile = 1.609 km)
3- Print value of Kilo_meters

19

20

Code
public class conversion {

Tests
public static void main(String args[]) {

double miles = 25;


double kilo_meters = miles * 1.609;
System.out.println("25 miles is = : " + kilo_meters + " kilometers");

}
}

20

10
5/24/2020

21

Another simple program


Write a program which calculates area of a circle with radius = 10.8
Tests
Steps:

1- initialize variable ‘radius’ with radius value


2- initialize variable ‘pi’ with 3.1416
3- dynamically initialize ‘area’ using ‘radius’ and ‘pi’ (Hint: area = pi*𝒓𝟐 )

21

22

Code
// Compute the area of a circle.
Tests
class Area {
public static void main(String args[]) {
double pi, radius, area;
radius = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
area = pi * radius * radius; // compute area
System.out.println("Area of circle is: " + area);

22

11
5/24/2020

23

Characters
• In Java, the data type used to store characters is char.
• char in Java is not the same as char in C or C++.
• In C/C++, char is 8 bits wide. Tests

• Java uses Unicode to represent characters. Unicode defines a fully


international character set that can represent all of the characters
found in all human languages.
• It is a unification of dozens of character sets, such as Latin, Greek,
Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this
purpose, it requires 16 bits.
• Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536
and there are no negative chars.
• Char value is declared in single quotes in order to be taken as
character

23

24

Sample program using char


Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo { Tests

public static void main(String args[]) {


char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

24

12
5/24/2020

25

Exercise Program
In previous program you printed ‘X’ by using its Unicode. Now try to get
this out put i.e.
Tests
ch1 and ch2: X x

But this time X must be saved in ch1 as character using single quotes
and x (lowercase) must be saved in ch2 using its Unicode.

(Hint: Unicode of a is 97 so you can predict Unicode of x)

25

26

booleans
• Java has a primitive type, called boolean, for logical values.
• It can have only one of two possible values, true or false.
Tests
• This is the type returned by all relational operators, as in the case of
a < b.
• boolean is also the type required by the conditional expressions that
govern the control statements such as if and for.
• The true literal in Java does not equal 1, nor does the false literal
equal 0.
• Below are examples of boolean variables.

bolean a = true;
boolean b =false;

26

13
5/24/2020

27

Sample Program
Public class booltest{
public static void main(String args[]) {
int number1 = 10; Tests

int number2 = 20;


boolean check = number1>number2;

System.out.println("The statement that number1 is greater than


number2 is " + check);
}

Now try changing statement boolean check = number2>number1 and


see what result you get.

27

28

Strings
• String literals in Java are specified like they are in most other
languages—by enclosing a sequence of characters between a pair of
double quotes. Tests

• Examples of string literals are

String String1 = “Hello World”;


System.out.println(String1);

The above example prints “Hello World” stored in string1.

28

14
5/24/2020

29

Escape sequences
• Escape sequences are used for special character insertion or for
special action
Tests

29

30

Examples of Escape Sequences


• If you want to print “Hello World”, you need escape sequence
Tests
• System.out.println("Hello world"); // just prints Hello World
• System.out.println(""Hello world""); // gives error as text is out of “”
• System.out.println("\"Hello world\""); // Correct

• System.out.println(“This is backslash \"); // error


• System.out.println(“This is backslash \\");

• \r and \n behave same in most windows platforms i.e. any text after
these will move to next line

30

15
5/24/2020

31

Practice programs
• Write a program that displays your name vertically. Use print()
statement only once. (Hine: use escape sequence)
Tests

• Write a program which produces the following output and use \t


escape sequence to give tab

My name is: Bob Smith

31

32

The scope of variables

• Java allows variables to be declared within any block.


Tests
• A block begins with an opening curly brace and ended by a closing
curly brace. A block defines a scope.
• A variable defined inside a scope is only known inside that scope.
• A scope determines what objects are visible to other parts of your
program. It also determines the lifetime of those objects.
• Many other computer languages define two general categories of
scopes: global and local. However, these traditional scopes do not fit
well with Java’s strict, object-oriented model.

32

16
5/24/2020

33

Example of variables scope


class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
Tests
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}

33

34

Type Conversions and Casting


• It is fairly common to assign a value of one type to a variable of
another type.
Tests
• If the two types are compatible, then Java will perform the conversion
automatically. For example, it is always possible to assign an int
value to a long variable.
• Not all types are compatible, and thus, not all type conversions are
implicitly allowed. For instance, there is no automatic conversion
defined from double to byte.
• It is still possible to obtain a conversion between incompatible types.
To do so, you must use a cast, which performs an explicit conversion
between incompatible types

34

17
5/24/2020

35

Java’s Automatic Conversions


• An automatic type conversion will take place if the following two
conditions are met:
Tests
1- The two types are compatible.
2- The destination type is larger than the source type.

• When these two conditions are met, a widening conversion takes


place. For example, the int type is always large enough to hold all
valid byte values, so no explicit cast statement is required.
• For widening conversions, the numeric types, including integer and
floating-point types, are compatible with each other.
• However, there are no automatic conversions from the numeric types
to boolean.

35

36

Java’s Automatic Conversions


• byte to short, int, long, float, or double

• short to int, long, float, or double Tests

• char to int, long, float, or double

• int to long, float, or double

• long to float or double

• float to double

36

18
5/24/2020

37

Java’s Automatic Conversion Examples


int integer1 = 23;

float float1 = 23.45f, float2;

long long1; Tests


double double1;

float2 = integer1; // same width integer to float, correct

long1 = integer1; // integer to bigger width integer, correct

float1 = long1; // long to float also allowed

double1 = integer1; // integer to bigger width float, correct

double1 = float1; // float to double, correct

// integer1 = long1; // bigger integer to smaller not allowed

//long1 = float1; // not allowed float to integer

// float1 = double1; // not allowed

37

38

Casting Incompatible types


• If you want to assign an int value to a byte variable, this conversion
will not be performed automatically, because a byte is smaller than an
int. You will have to do casting for thisTests
• This kind of conversion is sometimes called narrowing conversion,
since you are explicitly making the value narrower so that it will fit into
the target type.
• For example, the following fragment casts an int to a byte. If the
integer’s value is larger than the range of a byte, it will be reduced
modulo (the remainder of an integer division by the) byte’s range.
• int a; byte b;
• b = (byte) a;

38

19
5/24/2020

39

Example of Casting
public class int_to_byte {

Tests
public static void main(String args[]) {
int integer1 = 100;
byte byte1 = (byte) integer1;
System.out.println("Value of integer and byte is " + integer1 + " " +
byte1);
}
}

What is the maximum value of int that could be casted to byte?

39

40

Truncation
• A different type of conversion will occur when a floating-point value is
assigned to an integer type: truncation.
• Since integers do not have fractional components,
Tests when a floating-
point value is assigned to an integer type, the fractional component is
lost.
• For example, if the value 1.23 is assigned to an integer, the resulting
value will simply be 1.The 0.23 will have been truncated.
• If the size of the whole number component is too large to fit into the
target integer type, then that value will be reduced modulo the target
type’s range.

40

20
5/24/2020

41

Truncation example
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257; Tests
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}

41

42

Automatic Type Promotions


• In certain expression, Java automatically promotes types of variables during
operation. For example
byte a = 40;
Tests
byte b = 50;
byte c = 100;
int d = a * b / c;
• The result of the intermediate term a * b easily exceeds the range of either of its
byte operands.
• To handle this kind of problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. This means that the
subexpression a * b is performed using integers—not bytes. Thus, 2,000, the result
of the intermediate expression, 50 * 40, is legal even though a and b are both
specified as type byte.

42

21
5/24/2020

43

Automatic Type Promotions


• Automatic promotions can sometimes cause confusing compile-time
errors. For example, this seemingly correct code causes a problem:
byte b = 50; Tests
b = b * 2; // Error! Cannot assign an int to a byte!

• In this case when the expression was evaluated, the result has also
been promoted to int. Thus, the result of the expression is now of type
int, which cannot be assigned to a byte without the use of a cast.
• This is true even if, as in this particular case, the value being
assigned would still fit in the target type.
• If you still want to save result into a byte, casting would be required.

43

44

The Type Promotion Rules


• All byte, short, and char values are promoted to int.
• Then, if one operand is a long, the whole expression is promoted to
long. Tests

• If one operand is a float, the entire expression is promoted to float. If


any of the operands is double, the result is double.
• An example on next page gives detailed explanation of automatic
promotions.

44

22
5/24/2020

45

Automatic Promotion Example


class Promote {
In the first subexpression, f * b, b is
public static void main(String args[]) {
promoted to a float and the result of the
byte b = 42; Testssubexpression is float.
char c = 'a'; Next, in the subexpression i / c, c is
short s = 1024; promoted to int, and the result is of type
int.
int i = 50000;
Then, in d * s, the value of s is
float f = 5.67f; promoted to double, and the type of the
double d = .1234; subexpression is double.
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

45

Thank You

46

23

You might also like