Data Types Chapter 3

52
Data Types, Arrays Data Types, Arrays

Transcript of Data Types Chapter 3

Page 1: Data Types Chapter 3

Data Types, ArraysData Types, Arrays

Page 2: Data Types Chapter 3

Data TypesData Types Java defines eight simple (or elemental) types of data: Java defines eight simple (or elemental) types of data:

bytebyte, , shortshort, , intint, , longlong, , charchar, , float, doublefloat, double, and , and booleanboolean. .

These can be put in four groups:These can be put in four groups: Integers This group includes Integers This group includes bytebyte, , shortshort, , intint, and , and longlong, ,

which are for whole valued signed numbers.which are for whole valued signed numbers. Floating-point numbers This group includes Floating-point numbers This group includes float float and and

doubledouble, which represent numbers with fractional , which represent numbers with fractional precision.precision.

Characters This group includes Characters This group includes charchar, which represents , which represents symbols in a character set, like letters and numbers.symbols in a character set, like letters and numbers.

Boolean This group includes Boolean This group includes BooleanBoolean, which is a special , which is a special type for representing true/false valuestype for representing true/false values

Page 3: Data Types Chapter 3

IntegersIntegers Java defines four integer types: Java defines four integer types: bytebyte, , shortshort, , intint, and , and longlong. All of these . All of these

are signed, positive and negative values.are signed, positive and negative values. long long 64, 64, int int 32, 32, short 16, byte short 16, byte 88

ByteByte

The smallest integer type is The smallest integer type is bytebyte. This is a signed 8-bit type that has a . This is a signed 8-bit type that has a range from –128 to 127. range from –128 to 127.

Variables of type Variables of type byte byte are especially useful when you’re working with are especially useful when you’re working with a stream of data from a network or file. They are also useful when a stream of data from a network or file. They are also useful when you’re working with raw binary data that may not be directly you’re working with raw binary data that may not be directly compatible with Java’s other built-in types.compatible with Java’s other built-in types.

Page 4: Data Types Chapter 3

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

32,767. It is probably the least-used Java type, since it is defined 32,767. It is probably the least-used Java type, since it is defined as having its high byte firstas having its high byte first

intint The most commonly used integer type is The most commonly used integer type is intint. It is a signed 32-bit . It is a signed 32-bit

type that has a range from –2,147,483,648 to 2,147,483,647. In type that has a range from –2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type addition to other uses, variables of type int int are commonly are commonly employed to control loops and to index arrays.employed to control loops and to index arrays.

LongLong

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

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

Page 5: Data Types Chapter 3

Floating-Point TypesFloating-Point Types Floating-point numbers, also known as Floating-point numbers, also known as real real numbers, are numbers, are

used when evaluating expressions that require fractional used when evaluating expressions that require fractional precision.precision.

floatfloat The type The type float float specifies a specifies a single-precision single-precision value that uses value that uses

32 bits of storage. Single precision is faster on some 32 bits of storage. Single precision is faster on some processors and takes half as much space as double processors and takes half as much space as double precision, but will become imprecise when the values are precision, but will become imprecise when the values are either very large or very smalleither very large or very small

doubledouble Double precision, as denoted by the Double precision, as denoted by the double double keyword, keyword,

uses 64 bits to store a value. Double precision is actually uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors faster than single precision on some modern processors that have been optimized for high-speed mathematical that have been optimized for high-speed mathematical calculations. All transcendental math functions, such as calculations. All transcendental math functions, such as sin( )sin( ), , cos( )cos( ), and , and sqrt( )sqrt( ), return , return double double values.values.

Page 6: Data Types Chapter 3

CharactersCharacters In Java, the data type used to store characters is In Java, the data type used to store characters is charchar. .

However, C/C++ programmers beware: However, C/C++ programmers beware: char char in Java in Java is not the same as is not the same as char char in C or C++. In C/C++, in C or C++. In C/C++, char char is an integer type that is 8 bits wide. This is is an integer type that is 8 bits wide. This is not not the the case in Java. Instead, Java uses Unicode to represent case in Java. Instead, Java uses Unicode to represent characters. characters. Unicode Unicode defines a fully international defines a fully international character set that can represent all of the characters character set that can represent all of the characters found in all human languages, in Java found in all human languages, in Java char char is a 16-bit is a 16-bit type.type.

BooleansBooleans Java has a simple type, called Java has a simple type, called booleanboolean, for logical , for logical

values. It can have only one of twovalues. It can have only one of two possible values, possible values, true true or or falsefalse..

Page 7: Data Types Chapter 3

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

Page 8: Data Types Chapter 3

Type Conversion and CastingType Conversion and Casting Java’s Automatic ConversionsJava’s Automatic Conversions When one type of data is assigned to another type of variable, an When one type of data is assigned to another type of variable, an

automatic type conversion automatic type conversion will take place if the following two conditions will take place if the following two conditions are met:are met:

■ ■ The two types are compatible e.g. an The two types are compatible e.g. an int int value to a value to a long long variable..variable..■ ■ The destination type is larger than the source type, e.g. the The destination type is larger than the source type, e.g. the int int type is type is

always large enough to hold all valid always large enough to hold all valid byte byte values.values. Casting Incompatible TypesCasting Incompatible Types If you want to assign an If you want to assign an int int value to a value to a byte byte variable, This conversion variable, This conversion

will not be performed automatically, because a will not be performed automatically, because a byte byte is smaller than an is smaller than an intint. This kind of conversion is sometimes called a . This kind of conversion is sometimes called a narrowing narrowing conversion, conversion, since you are explicitly making the value narrower so that it since you are explicitly making the value narrower so that it will fit into the target type.will fit into the target type.

((targettarget--typetype) ) value, value, If the integer’s value is larger than the range of a If the integer’s value is larger than the range of a bytebyte, it will be , it will be

reduced modulo (the remainder of an integer division by the) reduced modulo (the remainder of an integer division by the) bytebyte’s ’s range.range.

int a;int a;byte b;byte b;// ...// ...b = (byte) a;b = (byte) a;

Page 9: Data Types Chapter 3

Example of type conversionExample of type conversion// Demonstrate casts.// Demonstrate casts.class Conversion {class Conversion { public static void main(String args[]) {public static void main(String args[]) { byte b;byte b; int i = 257;int i = 257; double d = 323.142; double d = 323.142; System.out.println("\nConversion of int to byte.");System.out.println("\nConversion of int to byte."); b = (byte) i;b = (byte) i; System.out.println("i and b " + i + " " + b);System.out.println("i and b " + i + " " + b); System.out.println("\nConversion of double to int.");System.out.println("\nConversion of double to int."); i = (int) d;i = (int) d; System.out.println("d and i " + d + " " + i);System.out.println("d and i " + d + " " + i); System.out.println("\nConversion of double to byte.");System.out.println("\nConversion of double to byte."); b = (byte) d;b = (byte) d; System.out.println("d and b " + d + " " + b);System.out.println("d and b " + d + " " + b); } }} }Conversion of int to byte.i and b 257 1Conversion of double to int.d and i 323.142 323Conversion of double to byte.d and b 323.142 67

Page 10: Data Types Chapter 3

ArraysArrays Array is a linear homogeneous data structure, it is simply a Array is a linear homogeneous data structure, it is simply a

collection of similar type elements.collection of similar type elements. A specific element of an array is accessed by the index.A specific element of an array is accessed by the index. One-dimensional array declaration is:One-dimensional array declaration is: Data_Type Variable_name []= new Data_Type[size];Data_Type Variable_name []= new Data_Type[size];

ororData_Type [] Variable_name = new Data_Type[size];Data_Type [] Variable_name = new Data_Type[size]; In general to create an array three steps are to be followed.In general to create an array three steps are to be followed.(a)(a) Declaration Declaration (b) construction (b) construction ( c) initialization ( c) initialization Declaration conveys array name and the type of its elements Declaration conveys array name and the type of its elements

to the java compiler e.g. int [] inta;to the java compiler e.g. int [] inta; Construction means calling the new operator to allocate Construction means calling the new operator to allocate

memory for the array variable.memory for the array variable. During the initialization process, elements of array initialized to During the initialization process, elements of array initialized to

their default values.their default values.

Page 11: Data Types Chapter 3

Byte – 0, int -0,Byte – 0, int -0, float- o.o f,float- o.o f, char-’\u0000’ ,char-’\u0000’ , short- 0, short- 0,

long-oL ,long-oL , double- 0.od,double- 0.od, boolean-false ,boolean-false , reference-null.reference-null.

Public class DemoPublic class Demo { {

int [] arr = new int [2];int [] arr = new int [2];system.out.println(arr[0]);system.out.println(arr[0]);system.out.println(arr[1]);system.out.println(arr[1]);

}}}}Out put: 0 0Out put: 0 0

Page 12: Data Types Chapter 3

public class Demopublic class Demo{{ public static void main (String[] args)public static void main (String[] args){{ int [] mak = new int[3];int [] mak = new int[3]; mak[0] =1;mak[0] =1; mak[1] =2;mak[1] =2; mak[3] =3;mak[3] =3;System.out.println(mak[0]);System.out.println(mak[0]);System.out.println(mak[1]);System.out.println(mak[1]);System.out.println(mak[2]);System.out.println(mak[2]);}}}}O/P= O/P= 11

2233

The new operator will allocate memory from heap, mak is a reference type The new operator will allocate memory from heap, mak is a reference type variable, which mean that it will hold the address of memory location. variable, which mean that it will hold the address of memory location.

Page 13: Data Types Chapter 3

mak

6556

stack Heap

1 2 3

Mak[0] Mak[1] Mak[2]

6556 6560 6564

Representation of array in memory

mak

stack

6556

mak

stack

6556

mak

stack

Page 14: Data Types Chapter 3

Explicit Initialization of ArraysExplicit Initialization of Arrays Java provides a declaration form to explicitly specify the initial values of the Java provides a declaration form to explicitly specify the initial values of the

elements of an array. elements of an array. Assuming an Assuming an nn element array, the general form is: element array, the general form is:

ElementType[] id = {exprElementType[] id = {expr00, expr, expr11, ..., expr, ..., exprn-1n-1};};

where each where each exprexprii is an expression that evaluates to type is an expression that evaluates to type ElementTypeElementType..

Examples:Examples:

int[] fibonacci = {1, 1, 2, 3, 5, 8, 13, 21, 34};int[] fibonacci = {1, 1, 2, 3, 5, 8, 13, 21, 34};String[] cats = {“bug”, “squeaky”, “paris”, “kitty String[] cats = {“bug”, “squeaky”, “paris”, “kitty kat”};kat”};int[] unit = {1};int[] unit = {1};

Page 15: Data Types Chapter 3

Constant Arrays

• As in other declarations, the modifier final can be applied in an array declaration. The modifier has the usual effect – after its initialization, the array variable is treated as a constant. In this case, the array variable cannot change which array it references, however, the values in the array can be changed!

final int[] B = {10, 20};• Graphically this would look like the following:

where indicates that the value of the reference cannot be changed.B = new int[2]; //illegal: a final cannot be the

//target of an assignmentB[1] = 30; //legal: B[1] is not final

B 10 20

Page 16: Data Types Chapter 3

Arrays of Objects

• If the element type of an array is an object type, then the elements hold either the value null or references to element type values rather than holding element type values themselves. This is illustrated graphically below:

String[] s = new String[2];

s[0] = “Orlando”;

s[1] = “Florida”;

s

“Orlando” “Florida”

Page 17: Data Types Chapter 3

Array Bounds• Unlike many programming languages, Java automatically checks

that proper array subscripts are used. If a subscript is determined to be invalid, an exception of type IndexOutOfBoundsException is generated. (Unless the program provides exception handling code, this exception causes the program to terminate.)

• The following code segment contains two misuses of array sample.int[] sample = new int[40];sample[-1] = 0; //subscript too smallsample[40] = 10; //subscript too large

Page 18: Data Types Chapter 3

Member Methods and Arrays

• Because an array is a Java object, an array as associated with it all of the member methods of an Object (e.g., clone() and equals()). However, the array clone() method is overridden specifically for arrays.

• In addition to member methods, an array also has a public final data field length specifying the number of elements in the array. Designers of Java were quite helpful to programmer by including this field as it is a convenience not found in many other programming languages. This allows the programmer to do the following:

int fibonacci = {1, 1, 2, 3, 5, 7, 13, 21, 34, 55};for (int i = 0; i < fibonacci.length; ++i){

System.out.println(“Fibonacci Number “ + i + “ is: “, fibonacci[i]);

}

Page 19: Data Types Chapter 3

Cloning an Array• Array method clone() returns a duplicate of the array. The new

array object has the same number of elements as the invoking array. The values of the clone array are duplicates of the invoking array.

• A clone produced in this manner is known as a shallow copy. The corresponding elements in the two arrays reference the same objects. The shallowness can be seen by viewing the representation of the array variables u and v defined in the following code segment

Point[] u = {new Point(0,0), new Point(1,1),new Point(2,2) };

Point[] v = u.clone();Point[] u = {new Point(0,0), new Point(1,1),

new Point(2,2) };Point[] v = u.clone();

Page 20: Data Types Chapter 3

Cloning an Array

u

Point: (0,0) Point: (1,1) Point: (2,2)

v

u[0] u[1] u[2]

Page 21: Data Types Chapter 3

Distinct Element by Element Cloning• If a distinct element-by-element clone, say w, of u is needed, it can

be created in the following manner.

Point[] w = new Point[u.length];for (int i = 0; i < u.length; ++i) {

w[i] = u[i].clone();}

• Array clones created in this fashion are called deep copies.• The result of executing the code shown above is illustrated on the

next page.

Page 22: Data Types Chapter 3

Cloning an Array of a Primitive Type

• Using the method clone() on an array with a primitive element type (not an object type) automatically produces a deep copy.

• The code shown below illustrates this concept.

int[] x = {4, 5, 6, 7};int[] y = x.clone();

• These two arrays have the following depiction:

x[0] x[1] x[2] x[3]

y[0] y[1] y[2] y[3]

4 5 6 7x

4 5 6 7y

Page 23: Data Types Chapter 3

Clone of preemptive data typepublic class ArrayClone{public static void main( String[] args ){int[] primes = { 1, 2, 3, 5, 7, 11, 13, 17 };int[] backup;backup = primes.clone();backup[0] = 0;System.out.println( "Primes: " );for( int i=0 ; i < primes.length ; i++ )System.out.print( " " + primes[i] );System.out.println( "\nbackup: With first Element Modified" );for( int j=0 ; j < backup.length ; j++ )System.out.print(" " + backup[j] );System.out.println();}}

Page 24: Data Types Chapter 3

Difference b/w copy and cloneclass copy{public static void main(String [] args)/*{int [] numbers = { 2, 3, 4, 5};int [] numbersCopy = numbers; // in case of copy array;numbersCopy[2] = 0;System.out.println(numbers[2]);System.out.println(numbersCopy[2]);} }*/ {

int [] numbers = { 2, 3, 4, 5}; int [] numbersClone = (int[])numbers.clone(); //in case of clone array; numbersClone[2] = 0; System.out.println(numbers[2]); System.out.println(numbersClone[2]); } }

Page 25: Data Types Chapter 3

Passing Arrays to Methods

• Arrays are passed as reference parameters to methods.• Since arrays are passed as reference parameters their

cell values can be modified in the method.• Arrays are mutable in methods.

Page 26: Data Types Chapter 3

AddArrays.javaclass AddArrays {

public static void main (String [] args) {

int[] array1 = {1, 3, 5, 7, 9}; int[] array2 = {2, 4, 6, 8}; System.out.println (“Array 1 sum: “ + sum (array1); System.out.println (“Array 2 sum: “ + sum (array2); } public static int sum (int[] x) { int sum = 0; for (int i = 0; i < length.x; i++) sum = sum + x [i]; return sum; } }

Page 27: Data Types Chapter 3

Copying an array

• An array is an object and like as any object its name actually the name of the reference to that object. Assigning an array to another does not duplicate the array. It merely assigns another reference to the same object.

System.arraycopy( src, srcpos, dest, destpos, length)arraycopy( a, 4, b, 2, 3);would copy 3 elements from a[] to b[].here elements { a[4], a[5], a[6] } get copied to { b[2], b[3], b[4] }

Page 28: Data Types Chapter 3

CopyArrays

class CopyArrays { public static void main (String [] args) { int[] Array1 = {1, 2, 3, 4}; int[] Array2 = {5, 6, 7, 8}; copy (Array1, Array2); for (int i=0; i< Array1.length; i++) System.out.println(Array1[i] + " "); System.out.flush(); for (int i=0; i< Array2.length; i++) System.out.print (Array2[i] + " "); System.out.flush(); } public static void copy (int[] x, int[] y) { for (int i=0; i<x.length;i++) y[i]=x[i]; } }

Page 29: Data Types Chapter 3

Multi-Dimensional Array

• Multi-dimensional arrays are actually arrays of array. It is like a pointer to an array of pointers.

• Two-Dimensional Array Syntax: datatype [][] variable=new type[n][m]; int [][] town= new int [3][3];

Town

1000

Stack

1000

Heap6556

6556Town[0]

96656

13665Town[2]

Town[1]

Town[0][0] Town[0][1] Town[0][2]

96656

13665

1000

Representation of multidimensional array in memory

Page 30: Data Types Chapter 3

Two dimensional array

class demo{ public static void main(String args[]){ int [] [] town= new intb[4] []; system.out.println(town[0]); system.out.println(town[1]); system.out.println(town[2]);} }

Output:NullNullNull

Page 31: Data Types Chapter 3

two-dimensional array

int twoD[][] = new int[4][5];This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented

as an array of arrays of int.// Demonstrate a two-dimensional array.class TwoDArray {public static void main(String args[]) {int twoD[][]= new int[4][5];int i, j, k = 0;for(i=0; i<4; i++)for(j=0; j<5; j++) {twoD[i][j] = k;k++;}for(i=0; i<4; i++) {for(j=0; j<5; j++)System.out.print(twoD[i][j] + " ");System.out.println();} } }This program generates the following output:0 1 2 3 45 6 7 8 910 11 12 13 1415 16 17 18 19

Page 32: Data Types Chapter 3

Unequal second dimension array class demo{Public static void main( String args[]){ int [] []town= new int[3] []; town[0] = new int [1]; town[1] = new int [2]; town[2] = new int [3]; int i, j, k=0; for (i=0;i<3;i++) for (j=0;j<3;j++){ town [i] [j]= k; k++; }For (i=0;i<3;i++){For (j=0;j<3;j++){ system.out.println ( town [i] [j] +” ”);}System.out.println();} } }Output:01 23 4 5

Page 33: Data Types Chapter 3

Three-dimensional arrayclass threeDMatrix {public static void main(String args[]) {int threeD[][][] = new int[3][4][5];int i, j, k;for(i=0; i<3; i++)for(j=0; j<4; j++)for(k=0; k<5; k++)threeD[i][j][k] = i * j * k;for(i=0; i<3; i++) {for(j=0; j<4; j++) {for(k=0; k<5; k++)System.out.print(threeD[i][j][k] + " ");System.out.println(); }System.out.println();} } }This program generates the following output:0 0 0 0 00 0 0 0 00 0 0 0 00 0 0 0 0

0 0 0 0 00 1 2 3 40 2 4 6 80 3 6 9 12

0 0 0 0 00 2 4 6 80 4 8 12 160 6 12 18 24

Page 34: Data Types Chapter 3

ArraysArrays AdvantagesAdvantages

Very efficient, quick to access and add toVery efficient, quick to access and add to Type-safe, can only add items that match the Type-safe, can only add items that match the

declared type of the arraydeclared type of the array DisadvantagesDisadvantages

Fixed size, some overhead in copying/resizingFixed size, some overhead in copying/resizing Can’t tell how many items in the array, just how large Can’t tell how many items in the array, just how large

it was declared to beit was declared to be Limited functionality, need more general functionalityLimited functionality, need more general functionality

Page 35: Data Types Chapter 3

Strings• A string is a sequence of characters.• Java provides two classes to support strings:

– String class – the instances of String class are constants, i.e., the content of a String object cannot be changed after its creation.

– StringBuffer class – the instances of StringBuffer class are mutable, i.e., the content of a StringBuffer object can be changed after its creation.

• The String class has some unique privileges not shared by ordinary classes.– A string can be created using string literals.– Operator + can be applicable to strings.

• The characters in a string are indexed by 0 to n-1, where n is the length of the string.

Page 36: Data Types Chapter 3

Strings• Each quoted string is an object of the string class and

it is created inside the heap.• Strings are object of predefined class.• Strings in java do not have null character at the end.• String is predefined class present in java.lang

package.• It is final class that means string class can not be

inherited.

Page 37: Data Types Chapter 3

String Class• Creation of a String object.

String s = new String(“abc”);String s = “abc”;

• Add operator:String s1 = “abc”;String s2 = “de”;String s3 = s1 + s2; //s3 = “abcde”

• The String class has a lot of methods. These methods are useful to manipulate strings.

Page 38: Data Types Chapter 3

length and charAt methodsint length() – this instance method returns the

length of the string.String s=“abc”;s.length() returns 3

char charAt(int index) – this instance method returns the character at a specific index.String s=“abcde”;s.length(); 5s.charAt(0); ‘a’s.charAt(1); ‘b’s.charAt(4); ‘e’s.charAt(5); error

Page 39: Data Types Chapter 3

indexOf methodint indexOf(char c)int indexOf(char c, int index)

Returns the index of the first occurrence of the character c in the current object starting at position index (default 0). Returns –1 if there is no such occurrence. [overloaded method]String s=“ababc”;s.indexOf(‘b’);//returns 1s.indexOf(‘b’,2); //returns 3s.indexOf(‘d’,2); //returns -1

Page 40: Data Types Chapter 3

indexOf method (cont.)int indexOf(String s2)int indexOf(String s2, int index)

Returns the index of the first occurrence of the substring s2 in the current object, beginning at position index (default 0). Returns –1 if there is no such occurrence.String s=“daabcabc”;String s2=“ab”;s.indexOf(s2); //returns 2s.indexOf(s2,3); //returns 5s.indexOf(s2,6); //returns -1

Page 41: Data Types Chapter 3

substring methodString substring(int startindex)String substring(int startindex, int lastindex)

Returns the substring of the current object starting from startindex and ending with lastindex-1 (or the last index of the string if lastindex is not given). [overloaded method]String s=“abcdef”;s.substring(1); //returns “bcdef”s.substring(3); //returns “def”s.substring(1,4);//returns “bcd”  s.substring(3,5);//returns “de” 

Page 42: Data Types Chapter 3

equals and equalsIgnoreCaseboolean equals(String s2)boolean equalsIgnoreCase(String s2)

Returns true if the current object is equal to s2; otherwise false.The method equalsIgnorecase disregards the case of the characters.

String s=“abc”;s.equals(“abc”)//returns trues.equals(“abcd”) //returns falses.equals(“aBc”)//returns falses.equalsIgnoreCase(“aBc”)//returns true

Page 43: Data Types Chapter 3

String programclass String01{ String str1 = "THIS STRING IS NAMED str1"; String str2 = "This string is named str2";

public static void main(String[] args){ String01 obj = new String01(); System.out.println("Display original string values"); System.out.println(obj.str1); System.out.println(obj.str2); System.out.println("Replace str1 with another string"); obj.str1 = obj.str1 + " " + obj.str2; System.out.println("Display new string named str1"); System.out.println(obj.str1); System.out.println("Terminating program"); }//end main()}

Page 44: Data Types Chapter 3

StringBuffer Class• StringBuffer constructors:

StringBuffer()StringBuffer(int size)Returns an instance of the StringBuffer class that is empty but has an initial capacity of size characters (default 16 characters).

StringBuffer(String arg)Creates an instance of the StringBuffer class from the string arg.

• length and charAt methods are also defined for StringBuffer class.

Page 45: Data Types Chapter 3

StringBuffer length vs. capacity

class StringBufferDemo {public static void main(String args[]) {StringBuffer sb = new StringBuffer("Hello");System.out.println("buffer = " + sb);System.out.println("length = " + sb.length());System.out.println("capacity = " + sb.capacity());}} output:buffer = Hellolength = 5capacity = 21

Page 46: Data Types Chapter 3

Reading strings using BufferedReader

• Recall from our earlier look at using BufferedReader that we need to first declare a BufferedReader object that was directed to read from the input stream attached to the standard input device. Once this is done, reading strings from the keyboard is straightforward.

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

Page 47: Data Types Chapter 3

BufferedReader Exampleimport java.io.*;

public class readName {public static void main(String[] args)throws IOException{

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter your first name: "); String firstName = stdin.readLine(); System.out.println("Enter your last name: "); String lastName = stdin.readLine();System.out.println("Your name is " + firstName + " "+ lastName + ".");

}}

Page 48: Data Types Chapter 3

Wordlength Exampleimport java.io.*;

public class Wordlength { public static void main(String[] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

//read the word from the userSystem.out.println(“Enter a word: “);String word = stdin.readLine();

//determine the length of the wordint wordLength = word.length();

//output resultsSystem.out.println(“Word “ + word + “ has a length of “ + wordLength + “ characters.”);}

}

Page 49: Data Types Chapter 3

Palindrome Example//Checks words to see if they are palindromesimport java.io.*;

public class Palindrome { static boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; boolean flag = true; while ((i<j) && flag){ if (s.charAt(i) != s.charAt(j)) flag = false; else {i++; j--; } } return flag; }

Page 50: Data Types Chapter 3

Palindrome Example (cont.)

public static void main(String args[]) throws IOException { String s; BufferedReader stdin = new BufferedReader (new InputStreamReader

(System.in));

System.out.print("A String > "); System.out.flush(); s = stdin.readLine();

if (isPalindrome(s)) System.out.println(s + " is a palindrome"); else System.out.println(s + " is not a palindrome"); } }

Page 51: Data Types Chapter 3

Decimal to Binary -- Exampleimport java.io.*; public class DecToBinary { static StringBuffer toBinary(int decVal) { StringBuffer sb = new StringBuffer(""); if (decVal == 0) sb.insert(0,"0"); //note insert position else while (decVal != 0) { if (decVal%2 == 0) sb.insert(0,"0"); //note insert position else sb.insert(0,"1"); //note insert position decVal = decVal / 2; } return sb; }

Page 52: Data Types Chapter 3

Decimal to Binary – Example (cont.)

public static void main(String args[]) throws IOException { int num; BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); System.out.print("An integer > "); System.out.flush(); num = Integer.parseInt(stdin.readLine().trim());

System.out.println("Decimal Number: " + num + " Corresponding Binary Number: " + toBinary(num));

} }