Você está na página 1de 74

Arrays and Wrapper Classes in Java

Dr.Ami Tusharkant Choksi


Associate Professor,
Computer Engineering Department,
C.K.Pithawala College of Engineering & Technology, Surat, Gujarat
State, India.
email: ami.choksi@ckpcet.ac.in

2018

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 1 / 74


1 Syllabus

2 Arrays

3 Section

4 StringBuffer

5 Scanner

6 StringTokenizer

7 Wrapper Classes

1
For each package/class/interface for constructors, methods and exception, please
refer to Java API documentation
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 2 / 74
Syllabus

Arrays2 , Command Line Argument, String class, StringBuffer class,


Operations on String, Wrapper Classes Properties
2 TEACHING HOURS, 5.00% MODULE WEIGHTAGE

2
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 3 / 74
Arrays I

Definition: An Array 2 is a container object that holds a fixed number


of values of a single type.
The length of array is developed as its contents are added.
After creation, its length is fixed.
Each item in an array is called an element, each element is accessed by
its numerical index.
Length of array is not needed to be maintained as in ’C’ language, with
a variable, as arrays length in Java is found with array.length property.

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 4 / 74


Arrays I

Declaration
1 int [] arrayname ; // declares an array of
integer
2 String [] names ; // String array
3 int [][] matrix ; // this is an array of
arrays or 2D array

Assign Size:
1 arrayname = new int [5]; // size 5
2 matrix = new int [5][5];

Assign and Print Values:

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 5 / 74


Arrays II
1 1. simplest way 1-D
2 int arr[] = {1,3,5,7,9,11};
3 2. using for loop 1-D
4 int array = new int[10]
5 for (int i =0; i < array.length ; i++) {
6 array[i] = i + 1;
7 System.out.println ( array[i]) ;
8 }
9 3.simplest way 2-D
10 int arr[][] = {{1,2,3},{4,5,6},{7,8,9}};
11 4. using for loop 2-D
12 int arr[] = new int[10];
13 for(int i=0;i<arr.length;i++){
14 //assign value to array elements
15 arr[i] = i+1;
16 //print value of array elements
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 6 / 74
Arrays III

17 System.out.println("arr["+i+"]:" + arr[i]);
18 }

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 7 / 74


Array Example Programs I

1 class ArrayBasics{
2 public static void main(String args[]){
3 int arr[] = new int[10];
4 for(int i=0;i<arr.length;i++){
5 //assign value to array elements
6 arr[i] = i+1;
7 //print value of array elements
8 System.out.println("arr["+i+"]:" + arr[i]);
9 }
10 }
11 }
12 /*
13 Output:
14 arr[0]:1
15 arr[1]:2

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 8 / 74


Array Example Programs II

16 arr[2]:3
17 arr[3]:4
18 arr[4]:5
19 arr[5]:6
20 arr[6]:7
21 arr[7]:8
22 arr[8]:9
23 arr[9]:10
24 */
Program 1: Array Values Assign and Print Program

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 9 / 74


Array Example Programs III
1 import java.util.*;
2 class sortArray{
3 public static void main(String args[]){
4 int arr[] = {70, 90, 50, 10, 5, 6, 1, 4, 7,
10};
5 //before sorting
6 System.out.println("Before Sorting");
7 for(int i=0;i<arr.length;i++){
8 System.out.println("arr["+i+"]:"+arr[i]);
9 }
10 //use of Arrays.sort requires java.util.* to be
imported
11 Arrays.sort(arr);
12 System.out.println("After Sorting");
13 //after sorting
14 for(int i=0;i<arr.length;i++){
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 10 / 74
Array Example Programs IV
15 System.out.println("arr["+i+"]:"+arr[i]);
16 }
17 }
18 }
19 /*
20 Output:
21 Before Sorting
22 arr[0]:70
23 arr[1]:90
24 arr[2]:50
25 arr[3]:10
26 arr[4]:5
27 arr[5]:6
28 arr[6]:1
29 arr[7]:4
30 arr[8]:7
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 11 / 74
Array Example Programs V
31 arr[9]:10
32 After Sorting
33 arr[0]:1
34 arr[1]:4
35 arr[2]:5
36 arr[3]:6
37 arr[4]:7
38 arr[5]:10
39 arr[6]:10
40 arr[7]:50
41 arr[8]:70
42 arr[9]:90
43 */
Program 2: Sorting of Array

Java Array Copy Methods:


Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 12 / 74
Array Example Programs VI

Simple For Loop: Applies in any language.


Object.clone(): Object class provides clone() method and since array in
java is also an Object, you can use this method to achieve full array
copy. This method will not suit you if you want partial copy of the
array.
System.arraycopy(): System class arraycopy() is the best way to do
partial copy of an array. It provides you an easy way to specify the total
number of elements to copy and the source and destination array index
positions. For example System.arraycopy(source, 3, destination, 2, 5)
will copy 5 elements from source to destination, beginning from 3rd
index of source to 2nd index of destination.
Arrays.copyOf(): If you want to copy first few elements of an array or
full copy of array, you can use this method. Obviously it’s not versatile
like System.arraycopy() but it’s also not confusing and easy to use.
Arrays.copyOfRange(): If you want few elements of an array to be
copied, where starting index is not 0, you can use this method to copy
partial array.

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 13 / 74


Array Example Programs VII
1 1. for loop: independent of language
2 int A[]={1,2,3,4,5};
3 int B[]=new int[A.length];
4 for(int i=0; i<5; i++){
5 B[i]=A[i];
6 }
7
8 2. Cloning
9 int[] a = new int[]{1,2,3,4,5};
10 int[] b = a.clone();
11
12 3. System.arraycopy
13 int[] src = new int[]{1,2,3,4,5};
14 int[] dest = new int[5];
15
16 System.arraycopy( src, 0, dest, 0, src.length );
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 14 / 74
Array Example Programs VIII

17
18 4. copyOf
19 import java.util.Arrays;
20 int[] a = {1,2,3,4,5};
21 int[] b = Arrays.copyOf(a, a.length);//import
java.util.Arrays required
22
23 5. Arrays.copyOfRange
24 int[] a = {1,2,3};
25 int[] b = Arrays.copyOfRange(a, 0, a.length);
26 a[0] = 5;
27 System.out.println(Arrays.toString(a)); //
[5,2,3]

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 15 / 74


Array Example Programs IX
28 System.out.println(Arrays.toString(b)); //
[1,2,3]
Program 3: Copying of Array

1
2 import java.util.Arrays;
3
4 public class ArrayCopy {
5
6 public static void main(String args[]) {
7 int A[] = {1, 2, 3, 4, 5};
8 int B[] = new int[A.length];
9 System.out.println("Copying element by element
using for loop");
10 for (int i = 0; i < 5; i++) {

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 16 / 74


Array Example Programs X
11 B[i] = A[i];
12 System.out.println("A[" + i + "] :" + A[i]);
13 System.out.println("B[" + i + "] :" + B[i]);
14 }
15 int[] src = new int[]{1, 2, 3, 4, 5};
16 int[] dst = new int[5];
17
18 System.out.println("\narraycopy");
19 System.arraycopy(src, 0, dst, 0, src.length);
20 for (int i = 0; i < src.length; i++) {
21 System.out.println("src[" + i + "]: " + src[i]);
22 System.out.println("dst[" + i + "]: " + dst[i]);
23 }
24
25 int[] a = new int[]{1, 2, 3, 4, 5};
26 int[] b = a.clone();
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 17 / 74
Array Example Programs XI
27
28 System.out.println("\nCloning");
29 for (int i = 0; i < a.length; i++) {
30 System.out.println("a[" + i + "]: " + a[i]);
31 System.out.println("b[" + i + "]: " + b[i]);
32 }
33
34 int[] ar = {1, 2, 3, 4, 5};
35 int[] br = Arrays.copyOf(ar, ar.length);//import
java.util.Arrays required
36
37 System.out.println("\nCopyOf");
38 for (int i = 0; i < ar.length; i++) {
39 System.out.println("ar[" + i + "]: " + ar[i]);
40 System.out.println("br[" + i + "]: " + br[i]);
41 }
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 18 / 74
Array Example Programs XII
42
43 int[] arr = {1,2,3};
44 int[] brr = Arrays.copyOfRange(arr, 0, arr.
length);
45 arr[0] = 5;
46 System.out.println("\nArrays.copyOfRange");
47 System.out.println("arr: "+Arrays.toString(arr))
; // [5,2,3]
48 System.out.println("brr: "+Arrays.toString(brr))
; // [1,2,3]
49 }
50 }
51 /*
52 Copying element by element using for loop
53 A[0] :1
54 B[0] :1
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 19 / 74
Array Example Programs XIII
55 A[1] :2
56 B[1] :2
57 A[2] :3
58 B[2] :3
59 A[3] :4
60 B[3] :4
61 A[4] :5
62 B[4] :5
63
64 arraycopy
65 src[0]: 1
66 dst[0]: 1
67 src[1]: 2
68 dst[1]: 2
69 src[2]: 3
70 dst[2]: 3
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 20 / 74
Array Example Programs XIV
71 src[3]: 4
72 dst[3]: 4
73 src[4]: 5
74 dst[4]: 5
75
76 Cloning
77 a[0]: 1
78 b[0]: 1
79 a[1]: 2
80 b[1]: 2
81 a[2]: 3
82 b[2]: 3
83 a[3]: 4
84 b[3]: 4
85 a[4]: 5
86 b[4]: 5
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 21 / 74
Array Example Programs XV
87
88 CopyOf
89 ar[0]: 1
90 br[0]: 1
91 ar[1]: 2
92 br[1]: 2
93 ar[2]: 3
94 br[2]: 3
95 ar[3]: 4
96 br[3]: 4
97 ar[4]: 5
98 br[4]: 5
99
100 Arrays.copyOfRange
101 arr: [5, 2, 3]
102 brr: [1, 2, 3]
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 22 / 74
Array Example Programs XVI

103 */

Arrays.copyOf may be faster than a.clone() on small arrays. Both copy


elements equally fast, but clone() returns Object so the compiler has
to insert an implicit cast to int[]. You can see it in the bytecode,
something like this:

1 ALOAD 1
2 INVOKEVIRTUAL [I.clone ()Ljava/lang/Object;
3 CHECKCAST [I
4 ASTORE 2

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 23 / 74


Array Example Programs XVII
1 class TwodArray{
2 public static void main(String args[]){
3 int[][] arr=new int[3][3];//3x3 array
4
5 for(int i=0;i<3;i++){
6 for(int j=0;j<3;j++){
7 arr[i][j] = (i*3)+j+1;
8 //print values of array
9 System.out.print(arr[i][j]+" ");
10 }
11 System.out.println();
12 }
13 }
14 }
15 /*
16 Output:
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 24 / 74
Array Example Programs XVIII
17 1 2 3
18 4 5 6
19 7 8 9
20 */
Program 4: 2D array values assigment and printing

1 class TwoDArrayAddition{
2 public static void main(String args[]){
3 int[][] arr1 = {{1,2,3},{4,5,6},{7,8,9}};
4 int arr2[][]={{1,2,3},{4,5,6},{7,8,9}};
5 int[][] resultarr[][]=new int[3][3];
6
7 for(int i=0;i<3;i++){
8 for(int j=0;j<3;j++){
9 //Addition of two arrays

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 25 / 74


Array Example Programs XIX
10 resultarr[i][j] = arr1[i][j] + arr2[i][j];
11 //print values of result array
12 System.out.print(resultarr[i][j]+" ");
13 }
14 System.out.println();
15 }
16 }
17 }
18 /*
19 Output:
20 2 4 6
21 8 10 12
22 14 16 18
23 */
Program 5: "Addition of two matrix"

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 26 / 74


Array Example Programs XX
1 int mat[][] = new int[3][2];
2 int row = mat.length;
3 int col= mat[0].length;
Program 6: "Get 2D arrays row and column length"

1 class TwoDArrayMultiplication{
2 public static void main(String args[]){
3
4 int arr1[][] = {{1,2,3},{4,5,6},{7,8,9}};
5 int arr2[][]={{1,2,3},{4,5,6},{7,8,9}};
6
7 int r1 = arr1.length;
8 int c1 = arr1[0].length;
9
10 int r2 = arr2.length;

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 27 / 74


Array Example Programs XXI
11 int c2 = arr2[0].length;
12 //for matrix multiplication of arr1[r1xc1],arr2[
r2xc2], c1=r2 is required, resultant matrix
will be of size r1xc2
13 if(c1==r2)
14 {
15 int resultarr[][]=new int[r1][c2];
16 for(int i=0;i<r1;i++){
17 for(int j=0;j<c2;j++){
18 for(int k=0;k<c1;k++)
19 //Multiplication of two arrays
20 resultarr[i][j] += arr1[i][k] * arr2[k][j];
21 //print values of result array
22 System.out.print(resultarr[i][j]+" ");
23 }
24 System.out.println();
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 28 / 74
Array Example Programs XXII

25 }
26 }
27 }
28 }
29 /*
30 30 36 42
31 66 81 96
32 102 126 150
33 */
Program 7: "Matrix Multiplication"

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 29 / 74


Ragged Array I

A Ragged array is an n-dimensional array that needs not the be


reactangular
e.g.int[][] array = 3, 4, 5, 77, 50;

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 30 / 74


ArrayCopy for 2-D Array I

1 1. For loop
2 int src[][] = new int [3][3];
3 int dst[][]=new int[src.length][src[0].length];
4 for(int i=0;i<src.length;i++){
5 for(int j=0;j<src.length;j++){
6 dst[i][j] = src[i][j];
7 }
8
9 2.Cloning
10 int A[][] = {{1, 2}, {3, 4,}, {5,6}};
11 int B[][] = A.clone();
12 //new int[A.length][A[0].length];
13 for(int i=0;i<B.length;i++)
14 {
15 System.out.println(Arrays.toString(B[i]));

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 31 / 74


ArrayCopy for 2-D Array II
16 }
17
18 3.System.arraycopy
19 int A[][] = {{1, 2}, {3, 4,}, {5,6}};
20 int B[][] = new int[A.length][A[0].length];
21 for (int i = 0; i < src.length; i++) {
22 System.arraycopy(A[i], 0, B[i], 0, A[0].length);
23 System.out.println(Arrays.toString(B[i]));
24 }
25
26 4. Arrays.copyOf
27 int A[][] = {{1, 2}, {3, 4,}, {5,6}};
28 int B[][] = new int[A.length][A[0].length];
29 for (int i = 0; i < A.length; i++) {
30 B[i]=Arrays.copyOf(A[i], A[i].length);
31 System.out.println(Arrays.toString(B[i]));
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 32 / 74
ArrayCopy for 2-D Array III

32 }
33
34 5.Arrays.copyOfRange
35 String[][] sss = { {"1", "2"}, {"3", "4"},{"5","
6"}};
36 String[][] sss1 = Arrays.copyOfRange(sss, 0, 3);
37 for(int i=0;i<sss1.length;i++){
38 System.out.println(Arrays.toString(sss1[i]));
39 }

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 33 / 74


String I

See Constructors, methods, exceptions related to String at https:


//docs.oracle.com/javase/8/docs/api/java/lang/String.html

1 public class StringMethodsDemo {


2
3 public static void main(String[] args) {
4 String s1 = " Hello and welcome to the world of
Computers ";
5
6 System.out.println(" String length : " + s1.
length());
7 // inbuilt funtion finding the string length
8 String s2 = new StringBuffer(s1).reverse().
toString();
9 System.out.println(" Reverse string : " + s2);

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 34 / 74


String II
10
11 // Convert to char array
12 char r[] = new char[50];
13 r = s2.toCharArray();
14 System.out.println(" Char array : ");
15 for (char c : r) {
16 System.out.println(c);
17 }
18 // Copy
19 String s3 = s1;
20 System.out.println(" String Copy : " + s3);
21 // Concat
22 String s4 = " of CKPCET ";
23 String com = s1.concat(s4);
24 System.out.println(" Concated string : " + com);
25 // Extract bytes from string
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 35 / 74
String III
26 byte arr[] = s1.getBytes();
27 System.out.println(" Extracted bytes : ");
28 for (byte b : arr) {
29 System.out.println(b);
30 }
31 // * Extract more than one chartater from string
32 String s5 = " extractiOn of the charachtErs frOm
striNg ";
33 int start = 4;
34 int end = 11;
35 char chrarr[] = new char[end - start];
36 s5.getChars(start, end, chrarr, 0);
37 System.out.print(" Extracted chars : ");
38 for (char c : chrarr) {
39 System.out.println(c);
40 }
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 36 / 74
String IV

41 String s6 = " the substring problem ";


42 String s7 = s6.substring(4, 15);
43 System.out.println(" Substring : " + s7); //
Check string starts and ends with particular
string String s8 = " India is the greatest
country " ;
44 // Check string starts and ends with particular
string
45 String s8 = " India is the greatest country ";
46
47 System.out.println(" Starts with : " + s8.
startsWith(" India "));
48 System.out.println(" Ends with : " + s8.endsWith
(" country "));
49 // Replace string

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 37 / 74


String V
50 String s11 = " The domestic cat is a small ,
typically furry , carnivorous mammal . They
are often called house cats when kept as
indoor pets or simply cats when there is no
need to distinguish them from other felids
and felines . ";
51 s11 = s11.replaceAll(" cat ", " pari ");
52 System.out.println(" Replaced string : " + s11);
53 // IndexOf a string
54 int index = s11.indexOf(" pari ");
55 System.out.println(" the index of pari : " +
index);
56 // Upper and Lower case Conversion
57 String lower = s11.toLowerCase();
58 System.out.println(" Lowecase : " + lower);
59 String upper = s11.toUpperCase();
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 38 / 74
String VI
60 System.out.println(" Uppercase : " + upper);
61 // Equals and EqualsIgnoreCase ()
62 String s12 = " Ami Tusharkant Choksi ";
63 String s13 = " ami tusharkant choksi ";
64 System.out.println(" Equals : " + s12.equals(s13
));
65 System.out.println(" EqualsIgnoreCase : " + s12.
equalsIgnoreCase(s13));
66 }
67 }
68 /*
69 String length : 45
70 Reverse string : sretupmoC fo dlrow eht ot
emoclew dna olleH
71 Char array :
72
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 39 / 74
String VII
73 s
74 r
75 e
76 t
77 u
78 p
79 m
80 o
81 C
82
83 f
84 o
85
86 d
87 l
88 r
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 40 / 74
String VIII
89 o
90 w
91
92 e
93 h
94 t
95
96 o
97 t
98
99 e
100 m
101 o
102 c
103 l
104 e
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 41 / 74
String IX
105 w
106
107 d
108 n
109 a
110
111 o
112 l
113 l
114 e
115 H
116
117 String Copy : Hello and welcome to the world of
Computers
118 Concated string : Hello and welcome to the
world of Computers of CKPCET
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 42 / 74
String X
119 Extracted bytes :
120 32
121 72
122 101
123 108
124 108
125 111
126 32
127 97
128 110
129 100
130 32
131 119
132 101
133 108
134 99
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 43 / 74
String XI
135 111
136 109
137 101
138 32
139 116
140 111
141 32
142 116
143 104
144 101
145 32
146 119
147 111
148 114
149 108
150 100
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 44 / 74
String XII
151 32
152 111
153 102
154 32
155 67
156 111
157 109
158 112
159 117
160 116
161 101
162 114
163 115
164 32
165 Extracted chars : r
166 a
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 45 / 74
String XIII

167 c
168 t
169 i
170 O
171 n
172 Substring : substring
173 Starts with : true
174 Ends with : true
175 Replaced string : The domestic pari is a small
, typically furry , carnivorous mammal . They
are often called house cats when kept as
indoor pets or simply cats when there is no
need to distinguish them from other felids
and felines .
176 the index of pari : 13

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 46 / 74


String XIV

177 Lowecase : the domestic pari is a small ,


typically furry , carnivorous mammal . they
are often called house cats when kept as
indoor pets or simply cats when there is no
need to distinguish them from other felids
and felines .
178 Uppercase : THE DOMESTIC PARI IS A SMALL ,
TYPICALLY FURRY , CARNIVOROUS MAMMAL . THEY
ARE OFTEN CALLED HOUSE CATS WHEN KEPT AS
INDOOR PETS OR SIMPLY CATS WHEN THERE IS NO
NEED TO DISTINGUISH THEM FROM OTHER FELIDS
AND FELINES .
179 // Equals and EqualsIgnoreCase ()
180 String s12 = " Ami Tusharkant Choksi ";
181 String s13 = " ami tusharkant choksi ";

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 47 / 74


String XV

182 System.out.println(" Equals : " + s12.equals(s13


));
183 System.out.println(" EqualsIgnoreCase : " + s12.
equalsIgnoreCase(s13));
184 */
Program 8: String Methods Demo

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 48 / 74


StringBuffer I
See Constructors, methods, exceptions related to StringBuffer at
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
It is mutable String.

Table: String vs. StringBuffer


Feature String StringBuffer
Mutable/ Immutable Mutable
immutable
Concatena- Slow, because every time it Fast and consumes less
tion creates new instance. memory, as it only appends
and doesn’t create new in-
stance.
equals() Object’s equals method is Object’s equals method is
overridden by String not overridden by String-
Buffer
Performance Fast Very Slow
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 49 / 74
StringBuffer II
1 public class StringBufferMethodsDemo {
2 public static void main(String[] args) {
3 StringBuffer s1 = new StringBuffer(" Hello and
welcome to the world of Computers ");
4 // inbuilt funtion finding the string length
5 System.out.println(" StringBuffer length : " +
s1.length());
6 StringBuffer s2 = new StringBuffer(s1).reverse()
;
7 System.out.println(" Reverse string : " + s2);
8 // Append 12
9 StringBuffer s3 = s1.append(" of CKPCET ");
10 System.out.println(" Appended : " + s3);
11 //Substirng
12 StringBuffer s6 = new StringBuffer(" the
substring problem ");
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 50 / 74
StringBuffer III
13 String s7 = s6.substring(4, 15);
14 System.out.println(" Substring : " + s7);
15 // indexOf
16 StringBuffer s8 = new StringBuffer(" India is
the greatest country ");
17 System.out.println(" indexOf : " + s8.indexOf("
India "));
18 // Replace string
19 StringBuffer s11 = new StringBuffer(" The
domestic cat is a small , typically furry ,
carnivorous mammal . They are often called
house cats when kept as indoor pets or simply
cats when there is no need to distinguish
them from other felids and felines . ");
20 s11 = s11.replace(5, 25, " pari ");
21 System.out.println(" Replaced string : " + s11);
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 51 / 74
StringBuffer IV

22 System.out.println(" Last Index of : " + s11.


lastIndexOf(" cat "));
23 }
24 }
25 /*
26 Output:
27 StringBuffer length : 45
28 Reverse string : sretupmoC fo dlrow eht ot
emoclew dna olleH
29 Appended : Hello and welcome to the world of
Computers of CKPCET
30 Substring : substring
31 Starts with : 0

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 52 / 74


StringBuffer V

32 Replaced string : The pari all , typically


furry , carnivorous mammal . They are often
called house cats when kept as indoor pets or
simply cats when there is no need to
distinguish them from other felids and
felines .
33 Last Index of : -1
34 */
Program 9: StringBuffer Methods Demo

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 53 / 74


StringBuilder I

StringBuilder is faster than StringBuffer because it’s not synchronized.


Meaning of synchronized (synchronization): When some thing is
synchronized, then multiple threads can access, and modify it with out
any problem or side effect. StringBuffer is synchronized, so you can
use it with multiple threads with out any problem.
Which one to use when? StringBuilder : When you need a string,
which can be modifiable, and only one thread is accessing and
modifying it. StringBuffer : When you need a string, which can be
modifiable, and multiple threads are accessing and modifying it.
StringBuilder has almost same methods as StringBuffer
So, in single model application we must use StringBuilder, so that
object locking and unlocking will not be there, hence performance is
increased.

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 54 / 74


StringBuilder II
1 public class StringBuilderMethodsDemo {
2 public static void main(String[] args) {
3 StringBuilder s1 = new StringBuilder(" Hello and
welcome to the world of Computers ");
4 // inbuilt funtion finding the string length
5 System.out.println(" StringBuilder length : " +
s1.length());
6 StringBuilder s2 = new StringBuilder(s1).reverse
();
7 System.out.println(" Reverse string : " + s2);
8 // Append 12
9 StringBuilder s3 = s1.append(" of CKPCET ");
10 System.out.println(" Appended : " + s3);
11 //Substirng
12 StringBuilder s6 = new StringBuilder(" the
substring problem ");
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 55 / 74
StringBuilder III
13 String s7 = s6.substring(4, 15);
14 System.out.println(" Substring : " + s7);
15 // indexOf
16 StringBuilder s8 = new StringBuilder(" India is
the greatest country ");
17 System.out.println(" Starts with : " + s8.
indexOf(" India "));
18 // Replace string
19 StringBuilder s11 = new StringBuilder(" The
domestic cat is a small , typically furry ,
carnivorous mammal . They are often called
house cats when kept as indoor pets or simply
cats when there is no need to distinguish
them from other felids and felines . ");
20 s11 = s11.replace(5, 25, " pari ");
21 System.out.println(" Replaced string : " + s11);
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 56 / 74
StringBuilder IV

22 System.out.println(" Last Index of : " + s11.


lastIndexOf(" cat "));
23 }
24 }
25 /*
26 Output:
27 StringBuilder length : 45
28 Reverse string : sretupmoC fo dlrow eht ot
emoclew dna olleH
29 Appended : Hello and welcome to the world of
Computers of CKPCET
30 Substring : substring
31 Starts with : 0

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 57 / 74


StringBuilder V

32 Replaced string : The pari all , typically


furry , carnivorous mammal . They are often
called house cats when kept as indoor pets or
simply cats when there is no need to
distinguish them from other felids and
felines .
33 Last Index of : -1
34 */
Program 10: StringBuilder Methods Demo

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 58 / 74


String, StringBuffer, StringBuilder

When should we choose String and StringBuffer? :


If we do not want to store string modifications in the same memory we
must choose String.
To do modifications in the same memory, we must choose StringBuffer
or StringBuilder.
Advantage and disadvantage in String:
Advantage : Since modifications are preserving in another memory
location, we will have both original and modified values.
Disadvantage : It consumes lot memory for every operation, as it stores
it modifications in new memory. So it leads to performance issue.
Solution : To solve this performance issue , in projects developers store
string data using StringBuilder or StringBuffer after all modifications
they convert into String and pass it back to user.
Advantage and disadvantage of StringBuffer or StringBuilder:
Advantage : It given high performance because consumes less memory
as all modifications stored in same memory.
Disadvantage : Original value will not be preserved.

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 59 / 74


Commandline Arguments in Java I

Command line arguments are taken using String[] args of main


method

1 /*
2 $terminal$: javac CommandLineArgs.java
3 $terminal$: java CommandLineArgs ami choksi
vikramaditya bhoj
4 args[0]: ami
5 args[1]: choksi
6 args[2]: vikramaditya
7 args[3]: bhoj
8 */
Program 11: Commandline Arguments Passing and Printing

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 60 / 74


Scanner-Input Text from Standard Input I

The API documentation of Scanner can be found at


https://docs.oracle.com/javase/8/docs/api/java/
util/Scanner.html
It is used to take input from Standard Input. i.e.System.in
To use Scanner, we have to import java.util.Scanner in Java program

1 import java.util.Scanner;
2 public class ScannerDemo {
3 public static void main(String[] args) {
4 Scanner input = new Scanner(System.in);
5 //input int no
6 System.out.println("Input int no");
7 int no = input.nextInt();
8 System.out.println("Int no: " + no);
9 //input int no in binary
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 61 / 74
Scanner-Input Text from Standard Input II
10 System.out.println("Input binary int no");
11 int bno = input.nextInt(2);
12 System.out.println("bno: " + bno);
13 //input double no
14 System.out.println("Input double no");
15 double dno = input.nextDouble();
16 System.out.println("Double no: " + dno);
17 //input text
18 System.out.println("Input text");
19 String inString = input.next();
20 System.out.println("String : " + inString);
21 //input line
22 System.out.println("Input a line");
23 String line = input.nextLine();
24 System.out.println("Line : " + line);
25 //input boolean
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 62 / 74
Scanner-Input Text from Standard Input III
26 System.out.println("Input boolean(true/false)");
27 boolean b = input.nextBoolean();
28 System.out.println("Boolean : " + b);
29 }
30 }
31 /*
32 Output:
33 Input int no
34 5
35 Int no: 5
36 Input binary int no
37 1010
38 bno: 10
39 Input double no
40 67.8
41 Double no: 67.8
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 63 / 74
Scanner-Input Text from Standard Input IV

42 Input text
43 ami tusharkant Choksi
44 String : ami
45 Input a line
46 Line : tusharkant Choksi
47 Input boolean(true/false)
48 true
49 Boolean : true
50 */

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 64 / 74


StringTokenizer I

The API documentation of StringTokenizer can be found at


https://docs.oracle.com/javase/8/docs/api/java/
util/StringTokenizer.html
The string tokenizer class allows an application to break a String into
tokens.
The set of delimiters (the characters that separate tokens) may be
specified either at creation time or on a per-token basis.
Constructor and Description:
StringTokenizer(String str) - Constructs a string tokenizer for the
specified string.
StringTokenizer(String str, String delim) - Constructs a string tokenizer
for the specified string.
StringTokenizer(String str, String delim, boolean returnDelims) -
Constructs a string tokenizer for the specified string.

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 65 / 74


StringTokenizer II
An instance of StringTokenizer behaves in one of two ways, depending
on whether it was created with the returnDelims flag having the value
true or false:
If the flag is false, delimiter characters serve to separate tokens. A
token is a maximal sequence of consecutive characters that are not
delimiters.
If the flag is true, delimiter characters are themselves considered to be
tokens. A token is thus either one delimiter character, or a maximal
sequence of consecutive characters that are not delimiters.

1 import java.util.StringTokenizer;
2 public class StringTokenizerDemo {
3 public static void main(String[] args) {
4 String s = "ami-choksi-associate professor-phd-
surat";
5 StringTokenizer st = new StringTokenizer(s, "-")
;
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 66 / 74
StringTokenizer III

6 int i = 1;
7 while (st.hasMoreTokens()) {
8 System.out.println("Token " + i++ + ": " + st.
nextToken());
9 }
10 }
11 }
12 /*
13 Output:
14 Token 1: ami
15 Token 2: choksi
16 Token 3: associate professor
17 Token 4: phd
18 Token 5: surat

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 67 / 74


StringTokenizer IV

19 */
Program 12: StringTokenizer Demo

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 68 / 74


Wrapper Classes I

The Number Classes framework had to be high-performance.


All of the numeric wrapper classes are subclasses of the abstract class
Number.

Table: Primitive and Wrapper Classes Relation


Primitive Type Wrapper Class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 69 / 74
Wrapper Classes II
1 public class WrapperClassesDemo {
2 public static void main(String[] args) {
3 // Converting Primitive to Wrapper
4 int a = 40;
5 Integer i = Integer.valueOf(a); // converting
int into
6 Integer j = a; // autoboxing , now compiler will
write Integer.valueOf(a) internally
7 Double d = Double.valueOf(0.5);
8 Boolean b = Boolean.valueOf(true);
9 Byte bt = Byte.valueOf("0");
10 System.out.println(" Integer : " + i);
11 System.out.println(" Double : " + d);
12 System.out.println(" Boolean : " + b);
13 System.out.println(" Byte : " + bt);
14 // Converting String to Primitive
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 70 / 74
Wrapper Classes III

15 int parseInt = Integer.parseInt("45");


16 double parseDouble = Double.parseDouble("55.70")
;
17 boolean parseBoolean = Boolean.parseBoolean("
true");
18 byte parseByte = Byte.parseByte("12");
19 System.out.println(" parseInt : " + parseInt);
20 System.out.println(" parseDouble : " +
parseDouble);
21 System.out.println(" parseBoolean : " +
parseBoolean);
22 System.out.println(" parseByte : " + parseByte);
23 // Wrapper to Primitive
24 int intValue = i.intValue();
25 System.out.println(" intValue : " + intValue);

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 71 / 74


Wrapper Classes IV
26 System.out.println(" doubleValue : " + d.
doubleValue());
27 System.out.println(" booleanValue : " + b.
booleanValue());
28 System.out.println(" byteValue : " + bt.
byteValue());
29 }
30 }
31 /*
32 Integer : 40
33 Double : 0.5
34 Boolean : true
35 Byte : 0
36 parseInt : 45
37 parseDouble : 55.7
38 parseBoolean : true
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 72 / 74
Wrapper Classes V

39 parseByte : 12
40 intValue : 40
41 doubleValue : 0.5
42 booleanValue : true
43 byteValue : 0
44 */
Program 13: Wrapper Classes Demo

Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 73 / 74


References
1 Arrays, https://docs.oracle.com/javase/tutorial/
java/nutsandbolts/arrays.html
2 Arrays, https://docs.oracle.com/javase/specs/jls/
se7/html/jls-10.html
3 Copying of Array, https://stackoverflow.com/questions/
5785745/make-copy-of-array-java
4 String vs. StringBuffer,
http://javahungry.blogspot.com/2013/06/
difference-between-string-stringbuilder.html
5 String vs. StringBuffer, http://www.javatpoint.com/
difference-between-string-and-stringbuffer
6 StringBuffer vs. String-
Builder, https://stackoverflow.com/questions/355089/
difference-between-stringbuilder-and-stringbuffer
7 Scanner, https://docs.oracle.com/javase/8/docs/api/
java/util/Scanner.html
8 StringTokenizer, https://docs.oracle.com/javase/8/
Dr.Ami Tusharkant Choksi OOPJ(2150704) 2018 74 / 74

Você também pode gostar