Primitive types

Post on 04-Feb-2016

73 views 0 download

description

Primitive types. logical : boolean textual : char integral: byte8 bits-2 7 to 2 7 – 1 short16 bits -2 15 to 2 15 – 1 int 32 bits -2 31 to 2 31 – 1 long64 bits -2 63 to 2 63 – 1 floating: float32 bits double 64 bits. Everything else. - PowerPoint PPT Presentation

Transcript of Primitive types

Columbia University JETT 13/28/2003

Primitive types

– logical : boolean– textual: char– integral:

• byte 8 bits -27 to 27 – 1• short 16 bits -215 to 215 – 1• int 32 bits -231 to 231 – 1• long 64 bits -263 to 263 – 1

– floating:• float 32 bits• double 64 bits

Columbia University JETT 23/28/2003

Everything else• Everything that is not a primitive type is a reference type• A reference variable contains a reference to an object• Circle sun = new Circle();

– allocates memory for this new object– initializes attributes sun– executes constructor– assigns reference to reference variable

Columbia University JETT 33/28/2003

Object-Oriented Programming

• Each object has– its own memory– belongs to a class (instance of a class)

• Class defines– attributes (defines state)– behavior (methods)– Building blocks of Java programs

• Every program creates a class

Intro to Strings• String not built into Java• String is a class, part of java.lang package• Automatically imported• Declare:

– String greeting; // note caps• Allocate space

– greeting = new String ("hello world!");• or

– String greeting = new String ("hello world!");• Strings are so common, we can do:

• String greeting = "hello world!";

Java Elements 4

String Objects• Strings can be created implicitly by using a quoted string

– String name = "Tom Jones";– String s1 = "Hello";– String s2 = "World!";

• Class - String • Object – s1• or, by using + on two String objects to create a new one

– String combo = s1 + " " + s2;

• String is capitalized• String is a sequence of characters

Java Elements 5

Java Elements 6

String Objects• Performing operations on objects is different than primitives• Call methods• Using variable name

– s1.length()– System.out.println("Length of s1 = " + s1.length()); Length of s1 = 5

• <variable>.<method name>(<expression>,<expression>,…,<expression>)

7

String objects – method length

• String s1 = “hello”;• String s2 = “how are you?”;• System.out.println(“Length of s1 = “ + s1.length();• System.out.println(“Length of s2 = “ + s2.length(); Length of s1 = 5 Length of s2 = 12

8

String objects – method charAt

• Zero based indexing• String s1 = "hello";• h e l l o• 0 1 2 3 4• s1.charAt(0) => h• s1.charAt(3) => l

9

String objects – method substring

• substring(starting index, ending index+1)• String s2 = “how are you?”;• s2. substring(0,3) => how• s2.substring(8,12) => you?

10

String objects - index• Index – integer used to indicate location• Zero based• Beware of index• 0 <= index < length()• Out of bounds• any String method requiring an index will throw an

IndexOutOfBoundsException if 0 <= index <= length() is violated• Exception – runtime error• Exception is thrown when an error is encountered

Java Elements 11

Method Description Example: s = “hello”;

charAt(index) Character at a specific index s.charAt(1) returns ‘e’

endsWith(text) Whether or not the string ends with some text

s.endsWith(“llo”) => true

indexOf(text) Index of a particular character or String (-1 if not present)

s.indexOf(“o”) => 4

length() Number of characters in the string

s.Length() => 5

startsWith(text) Whether or not the string starts with some text

s.startsWith(“hi”) => false

substring(start, stop);

Characters from start index to just before stop index

s.substring(1,3) => “el”

toLowerCase() A new string with all lowercase letters

s.toLowerCase() => “hello”

toUpperCase() A new string with all uppercase letters

s.toUpperCase() => “HELLO”

12

String

• x = 45; x 45• String is not a primitive type, class• String str;• str = “Java Programming”;str 2500 2500 Java Programmingreference variable object• str = new String (“Java Programming”);• Reference variable

13

new

• new is an operator• Causes the system to allocate space for object• Returns address• Instantiates a class object

14

Example of new

• Scanner console = new Scanner(System.in);• String str = “Hello”; // = new String implied• int[] arr = new int[20];• Time time1 = new Time;

15

String str = "Hello";

• Reference variable– Variables that store the address– Any variable declared using a class is a reference

variable– str is a reference variable of type String– Memory space with Hello is an object or instance

of type String

16

Strings are immutable

str 2500 2500 Java ProgrammingCannot change value at address 2500Strings are immutable (once created they

cannot be changed)New assignment creates new objectstr = “Hello There!”;str 3850 3850 Hello There!str Hello There!

17

Garbage collection

• “Java Programming” gets reclaimed later• Happens automatically

– An object is eligible for garbage collection when there are no more references to that object.

– References that are held in a variable are usually dropped when the variable goes out of scope.

– Or, you can explicitly drop an object reference by setting the variable to the special value null.

18

Summary

• Two types of variables in Java– Primitive

• Store data directly into memory– Reference

• Store address of object containing data

• An object is an instance of a class• new is used to instantiate an object

Java Elements 19

Packages, Classes, Methods, import

• import packageName.*;• java.lang- provides fundamental classes• String, Math• import java.util.*; // compiler determines

relevant classes• import java.util.Scanner;

Java Elements 20

Console Input• Scanner is a class• Need to import java.utilimport java.util.*; //allows use of Scanner classScanner console = new Scanner (System.in);• Creates object console (can use any identifier name)• Associates console with standard input device• System.in – standard input device

Java Elements 21

Console input• console.nextInt() // retrieves next item as an integer• console.nextDouble() //retrieves next item as double• console.next() //retrieves next item as string• console.nextLine() // retrieves next item as string up to

newline

• ch = console.next().charAt(0); // reads a single character

• Inappropriate type -> exception

Java Elements 22

import java.util.*;public class BMICalculator{ public static void main(String [] args) { double height; double weight; double bmi; Scanner console = new Scanner(System.in); System.out.println("Enter height"); height = console.nextDouble(); System.out.println("Enter weight"); weight = console.nextDouble(); bmi = weight/(height * height) * 703;//No range checking // so this value could // divide by zero. //more on this later System.out.println("Current BMI:"); System.out.println(bmi); }}

Java Elements 23

Java application programimport statements if anypublic class ClassName{ declare names constants and/or stream objects

public static void main(String[] args) {

variable declarations

executable statements}

}

24

Predefined classes and methods

• Predefined classes• Contain predefined methods• Package contains classes• static method – belongs to class, can be used

by calling the name of the class• Non-static method – belongs to object of class

25

Using predefined classes and methods

• class Math• import java.lang.*; // package, automatically // imported• Math contains all static methods• Math.pow(2, 3) // method call• // 2 arguments. member access operator

26

Math methods• static double abs (double) Returns the absolute value of the argument • static float abs (float) Returns the absolute value of the argument• static int abs (int) Returns the absolute value of the argument • static long abs (long) Returns the absolute value of the argument• static double exp (double) Returns e raised to the power of the argument • static double log (double) Returns the natural logarithm of the argument • static double pow (double base, double exp) Returns the base raised to the

exp power • static double random () Returns a pseudorandom number in the range [0, 1)• static long round (double) Returns the nearest integer to the argument • static int round (float) Returns the nearest integer to the argument • static double sqrt (double) Returns the square root of the argument

27

Formatting output with printf• System.out.printf (formatString);• System.out.printf (“Hello There!”);• System.out.printf (formatString, argumentList);• System.out.printf (“There are %.2f inches in %d centimeters.

%n”, centimeters/2.54, centimeters);• %.2f and %d – format specifiers• Each format specifier in formatString must have one

corresponding argument in the argumentList• When outputting the format string, the format specifiers are

replaced with the formatted values of the corresponding arguments

28

%[argument_index$][flags][width][.precision]conversion

• Expressions in square brackets are optional• argument_list - integer indicating the position of the

argument in the argument list• flags – set of characters modifies the output format• width – integer indicating minimum number of

characters to be written to the output• precision – integer used to restrict the nymber of

characters• conversion – character indicating how the argument

should be formatted

29

Supported conversionsConversion Result is

s General A string

c Character A Unicode character

d Integral Formatted as a decimal integer

e Floating point Formatted as a decimal number in computerized scientific notation

f Floating point Formatted as a decimal number

% Percent %

n Line separator Platform-specific line separator

30

double x = 15.674; double y = 235.73; double z = 9525.9864; System.out.printf("x = %.2f %n", x); System.out.printf("y = %.2f %n", y); System.out.printf("z = %.2f %n", z);

x = 15.67 // note roundingy = 235.73 z = 9525.99

31

double x = 15.674; double y = 235.73; double z = 9525.9864; System.out.printf("x = %.3f %n", x); System.out.printf("y = %.3f %n", y); System.out.printf("z = %.3f %n", z);

x = 15.674 y = 235.730 z = 9525.986

32

int num = 96;rate = 15.50;System.out.println("123456789012345");System.out.printf("%5d %n", num);System.out.printf("%5.2f %n", rate);System.out.printf("%5d%6.2f %n", num, rate);System.out.printf("%5d %6.2f %n", num, rate);

123456789012345 96 15.50 96 15.50 96 15.50

33

width represents minimum

System.out.printf("%1d %n", 8756);8756 System.out.printf("%2d %n", 8756);8756 System.out.printf("%3d %n", 8756);8756 System.out.printf("%4d %n", 8756);8756 System.out.printf("%5d %n", 8756); 8756

34

Exercises1. How does the variable of a primitive type differ from a reference variable?2. What is an object?3. Consider the following statements:String str = “Going to the park.”;char ch;int len;int position;a. What value is stored in ch by the following statement?ch = str.charAt(0);b. What value is stored in ch by the following statement?ch = str.charAt(10);c. What value is stored in len by the following statement?len = str.length();d. What value is stored in position by the following statement?position = str.indexOf(‘t’);e. What value is stored in position by the following statement?position = str.indexOf(“park”);

35

4. Consider the following statements:String str = “Going to the amusement park.”;char ch;int len;int position;What is the output of the following statements?a. System.out.println (str.substring (0,5));b. System.out.println (str.substring (13,22);c. System.out.println (str.toUpperCase());d. System.out.println (str.toLowerCase());e. System.out.println (str.replace(‘t’,’*’));

36

5. Consider the following statements:double x = 75.3987;double y = 987.89764;What is the output of the following statements?a. System.out.printf(“%5.2f %n”, x);b. System.out.printf(“%6.2f %n”, y);c. System.out.printf(“%7.3f %n”, x);d. System.out.printf(“%6.3f %n”, y);