SlideShare a Scribd company logo
Meeting 2
Introduction to programming usingJava
Part 2
1
• Arrays
• Strings
• StringBuilder
• Wrapper Classes
2
8. Arrays
An array is a collection of items of the same type.
Use the element’s index,
An index must be a nonnegative integer
Array index
Array declaration
–In Java,array variables are references, not primitives. Becausearrays
are objects, they have instance variables we can accessand we can invoke
methods on them. Twowaysto declare arrays ofintegers:
or
Array
elements
int[] holder; € preferable
int holder[];
double[], and
– other types of arrays are boolean[],char[],
String[].
Array initializers
• Example of declaration andassignment:
int[] holder = {1,1,1,1,1};
3
8. Arrays
8.1 Array creation with newoperator
• All array types in Javaare reference types, not primitives. As such, array objects
also can be created using the new keyword. We could create an array with room
for five int values as follows:
• int[] holder = new int[5];
Here, we have only stated that there should be room for four integers to be
stored. Wecaninitialize these elements (they will default to the value 0) using
assignment to individuallocations:
holder[0]= 1;
holder[1]= 1;
holder[2]= 1;
holder[3]= 1;
holder[4]= 1;
• This is equivalent to thefollowing:
int[] myArray = {1,1,1,1,1};
4
8. Arrays
8.2Assigning values to individualelements
• Example of changing the value stored in holder's second location to 10:
holder [1]= 10;
Changing an array reference
• Aswith strings (and it is true of all references), we can make an array reference
variable refer to adifferentobject.
int[] holder2 = {1, 2, 3};
holder = holder2;
8.3 Accessing array data
we can refer to an item using the index enclosed in square brackets after the name
of the array.
holder[1]= holder[0]*10 ;
5
8. Arrays
8.4- The array instance variable length
• Arrays have an instance variable length, which gives the capacity of the array.
The expression:
holder.length represents the number of locations in the array holder.
• The array length will give the number of locations in an array, not the number of
initialized locations (the capacity).
• Any array length is fixed at the point when the array is created.
• Accessingan array element beyond the array's capacity, causearun-time error.
• Note that length is an instance variable associated witharrays, while
length() is amethod associated with strings.
• int[]num= {10, 11, 12, 13, 14, 15};
• System.out.println ("First item is " + num.length); 6
• System.out.println ("Last item is " +num[num.length -1] ); 15
6
8. Arrays
8.5- Mutability of strings andarrays
• Arrays and strings are both fixed-length entities: they cannot be
extended or evenshrunk.
int []holder ={1, 1, 1, 1,1};
int []holder2 ={1, 2,3};
holder=holder2; // doesn't change first array
• The third line above does not change the length of the original array
referenced by holder (with all 1sinit).
• Itmakesholder reference adifferent array of smaller length(which is also
referenced by holder2).
• Any array length is fixed at the point when the array is created.
• (The contents of the array can be changed, provided wehave areference
to the array).
7
8. Arrays
8.6- Mutability of strings andarrays
S
tring s="fish";
s="cat";
• and this does not change the length of the original string, "fish". What changes
is the reference s,which at first points to aString object with value "fish", and
then subsequently points to a different String object with value "cat".
• Whereas contents of arrays can bechanged,
• contents of strings cannot.
• Strings are said to be immutable: they cannot bechanged
at all, oncecreated…
8
8. Arrays
Traversing the elements of the array:
String[] names = {"Hadi", "Dalia", "Rami", "Manar"};
1) Using for statement :
for (int i=0; i<names.length; i++)
System.out.println(names[i]);
2) Using enhanced for statement:
for (String s: names)
System.out.println(s);
• Enhanced for statement visits all the elements of the array without using
the index. (So, there is no need for a counter)
• It simplifies the code but cannot be used to modify elements of the array.
String s;
for (int i=0; i<names.length; i++) {
s = names[i];
System.out.println(s);
}
≡
9
8. Arrays
Remember with reference variable asString andArray
There are several steps taken to create ausefulobject,
referenced by avariable. they are:
• declaration of a reference variable of the appropriate
type;
• creation (and initialization) of an object of the chosen
type;
• making the reference variable refer to the created object.
10
9. Strings
Astring is asequence of characters.
– For example, astring could be used to store aperson'sname
• Strings are represented using the reference typecalled String
• String literals are denoted by enclosing their characters in double quotation
marks.
String declaration
String name, address;
• declares two variables of type String. No strings are created by such a
declaration and the reference values in these variables have not yet been
initialized.
String Creation
String name;
name ="Ali";
// declare
// initialize
• declare the variable name of type String, and initialize that variable to contain a
reference to the String object storing the characters "Ali".
11
Constructing Strings
There are 2 ways to construct a String:
1. Using new String()// invoke constructor
String = new String(string Literal);
String s = new String();
String message = new String("Welcome to Java");
2. Using String Initializer:
o String message = “literal value”;
o String s = s1;
String message = "Welcome to Java";
String s = message;
12
Strings
• Aspecial String literal is the string with no contents, called the empty string
(written "").As: name="";
13
Strings Are Immutable
A String object is immutable; Once its created, its
contents cannot be changed.
Does the following code change the contents of
the string?
String s = "Java";
s = "HTML";
14
Trace Code
String s = "Java";
s = "HTML";
15
: String
String object for "Java"
s
After executing String s = "Java"; After executing s = "HTML";
: String
String object for "Java"
: String
String object for "HTML"
Contents cannot be changed
This string object is
now unreferenced
s
Trace Code
String s = "Java";
s = "HTML";
16
: String
String object for "Java"
s
After executing String s = "Java"; After executing s = "HTML";
: String
String object for "Java"
: String
String object for "HTML"
Contents cannot be changed
This string object is
now unreferenced
s
Trace Code
17
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
: String
Interned string object for
"Welcome to Java"
: String
A string object for
"Welcome to Java"
s1
s2
s3
Strings
The length method
• For example: name.length()
– This evaluates to the number of characters in the string referenced by name.
– If this string were "Roderick", the length method would return the value 8.
– Theempty string haslength zero.
String concatenation (+)
• Theconcatenation operator, +, will automatically turn any
arguments into strings before carrying outaconcatenation.
• Example:
Theoutput is "Filby Lanehas2occupants".
18
Strings
19
public class StringsEquality {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = new String("Hello");
if (s1 == s2)
System.out.println("s1 and s2 refer to the same object");
else
System.out.println("s1 and s2 refer to different objects");
if ( s1.equals(s2) )
System.out.println("s1 and s2 have the same contents");
else
System.out.println("s1 and s2 have different contents");
String s3 = "hello";
// s1.equals(s3) --> false
// s1.equalsIgnoreCase(s3) --> true
String s4 = s3;
// s3 == s4 --> true
// s3.equals(s4) --> true
String s5 = "hello";
String s6 = "Hello";
} // end main method
} // end class
--output--
s1 and s2 refer to different objects
s1 and s2 have the same contents
s1
Hello
s2
s3
hello
s4
Hello
s5
s6
// s3 == s5 --> true
// s1 == s6 --> true
Strings
public class StringsComparing {
public static void main(String[] args) {
String s1 = "Java nights";
String s2 = "java nights";
String s3 = "java rights";
String s4 = "Help";
String s5 = "Helping";
System.out.println(s1.compareTo(s4));
System.out.println(s4.compareTo(s1));
System.out.println(s2.compareTo(s1));
System.out.println(s1.compareTo(s2));
System.out.println(s2.compareTo(s3));
System.out.println(s5.compareTo(s4));
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s3.compareToIgnoreCase(s4));
System.out.println(s1.contains("night"));
System.out.println(s1.contains("nght"));
System.out.println(s1.startsWith("Java"));
System.out.println(s1.endsWith("hts"));
} // end main method
} // end class
--output--
2
-2
32
-32
-4
3
0
2
true
false
true
true
20
Strings
public class StringsMoreMethods {
public static void main(String[] args) {
String s1 = "Systems Analysis";
String s2 = " Ten nights ";
System.out.println(s1.indexOf('s'));
System.out.println(s1.indexOf('s', 3));
System.out.println(s1.indexOf('N'));
System.out.println(s1.indexOf("em"));
System.out.println(s1.lastIndexOf('s'));
System.out.println(s1.substring(8));
System.out.println(s1.substring(10, 13));
System.out.println(s1.toUpperCase());
System.out.println(s1); // s1 did not changed
s1 = s1.toLowerCase();
System.out.println(s1);
System.out.println(s2.trim());
s2 = s2.replace('n', 'l');
System.out.println(s2);
} // end main method
} // end class
2
6
-1
4
aly
15
Analysis
SYSTEMS ANALYSIS
Systems Analysis
systems analysis
Ten nights
Tel lights
--output--
21
Replacing and Splitting Strings
22
java.lang.String
+replace(oldChar: char, newChar: char): String
+replaceFirst(oldString: String, newString: String): String
+replaceAll(oldString: String, newString: String): String
+split(delimiter: String): String[]
Returns a new string that replaces all matching
character in this string with the new character.
Returns a new string that replaces the first matching
substring in this string with the new substring.
Returns a new string that replace all matching
substrings in this string with the new substring.
Returns an array of strings consisting of the
substrings split by the delimiter.
Examples
System.out.prinltn("Welcome".replace('e', 'A'));
System.out.println("Welcome".replaceFirst("e", "AB") );
System.out.println("Welcome".replace("e", "AB"));
System.out.println("Welcome".replace("el", "AB"));
String s = "a+b$#c".replaceAll("[$+#]", "NNN");
System.out.println(s);
23
OutPut:
WAlcomA
WABlcome
WABlcomAB
WABcome
aNNNbNNNNNNc
Splitting a String
String[] tokens = "Java#HTML#Perl".split("#");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
System.out.println();
String text = " Good morning. Have fun!";
String[] words = text.trim().split("W+");
// split text into words , this mean the delimiter will be anything that is not
a word (Why do we need trim()?)
for (int i = 0; i < words.length; i++)
System.out.print(words[i] + " ");
24
Java HTML Perl
Good morning Have fun
Outputs:
Convert Character and Numbers to Strings
The String class provides several static valueOf
methods for converting a character, an array of
characters, and numeric values to strings.
These methods have the same name valueOf with
different argument types char, char[], double, long, int,
and float.
For example, to convert a double value to a string,
use String.valueOf(5.44). The return value is string
consists of characters ‘5’, ‘.’, ‘4’, and ‘4’. 25
Strings
public class ArraysVsStrings {
public static void main(String[] args) {
char[] array = {'n', 'i', 'g', 'h', 't'};
String word = "night";
System.out.println("first char at array: " + array[0]);
System.out.println("first char at word: " + word.charAt(0));
System.out.println("The length of array: " + array.length );
System.out.println("The length of word: " + word.length() );
array[0] = 'l';
word = word.replace('n', 'l');
System.out.println(word);
String k = "cat";
char[] small = k.toCharArray();
System.out.println(
"first char at small: " + small[0] );
small[0] = 'r';
String m = new String(small);
System.out.println("m = " + m);
} // end main method
} // end class
--output--
first char at array: n
first char at word: n
The length of array: 5
The length of word: 5
m = rat
light
first char at small: c
night
light
word
array
[0] n
[1] i
[2] g
[3] h
[4] t
 l
This object will be
garbage collected
cat
k
rat
m
small
[0] c
[1] a
[2] t
 r
26
Strings
public class StringArrays {
public static String longestWord(String[] words) {
String longest = "";
for (int i=0; i < words.length ; i++)
if ( words[i].length() > longest.length() )
longest = words[i];
return longest;
} // end method longestWord
public static void main(String[] args) {
String[] array = { "All", "Arab", "countries", "are", "here"};
System.out.println("The longest word is: "+ longestWord(array));
System.out.printf("There are %d words starts with 'A'n",
startsWithA(array));
} // end main method
public static int startsWithA(String[] words) {
int count = 0;
for (int i=0; i < words.length ; i++)
if (words[i].charAt(0) == 'A') count++;
return count;
} // end method startsWithA
} // end class StringArrays
--output--
The longest word is: countries
There are 2 words starts with 'A'
27
10. StringBuilder and StringBuffer
The StringBuilder/StringBuffer class is an
alternative to the String class. In general, a
StringBuilder/StringBuffer can be used wherever a
string is used.
StringBuilder/StringBuffer is more flexible than
String. You can add, insert, or append new contents
into a string buffer without the need to create new
string.
StringBuffer/StringBuilder is mutable.
28
StringBuilder Constructors
29
java.lang.StringBuilder
+StringBuilder()
+StringBuilder(capacity: int)
+StringBuilder(s: String)
Constructs an empty string builder with capacity 16.
Constructs a string builder with the specified capacity.
Constructs a string builder with the specified string.
Example:
StringBuilder sb = new StringBuilder("Hello");
sb refers to the character sequence 'H' 'e' 'l' 'l' 'o', but with space for an
additional 16 characters, the object referenced by sb will contain 21 characters
in total.
StringBuilder Methods
30
java.lang.StringBuilder
+toString(): String
+capacity(): int
+charAt(index: int): char
+length(): int
+setLength(newLength: int): void
+substring(startIndex: int): String
+substring(startIndex: int, endIndex: int):
String
+trimToSize(): void
Returns a string object from the string builder.
Returns the capacity of this string builder.
Returns the character at the specified index.
Returns the number of characters in this builder.
Sets a new length in this builder.
Returns a substring starting at startIndex.
Returns a substring from startIndex to endIndex-1.
Reduces the storage size used for the string builder.
StringBuilder
Consider the following code:
String str = "";
for (int i = 1; i <= 10000; i++)
str = str + "*";
This code will create 10,001 different string objects and all but one of these is
unreferenced.
However, using StringBuilder which is mutable, we can avoid this action:
StringBuilder sb = new StringBuilder(10000);
for (int i=1; i <= 10000; i++)
sb.append("*");
31
StringBuilder
Consider the following statement:
StringBuilder aSB = new StringBuilder("Bob");
Expression Result
aSB.length(); 3
aSB.capacity(); 19
aSB.append(" is "); 'B' 'o' 'b' ' ' 'i' 's' ' '
aSB.append(50); 'B' 'o' 'b' ' ' 'i' 's' ' ' '5' '0'
aSB.length(); 9
aSB.capacity(); 19
aSB.deleteCharAt(0); 'o' 'b' ' ' 'i' 's' ' ' '5' '0'
aSB.insert(0, 'J'); 'J' 'o' 'b' ' ' 'i' 's' ' ' '5' '0'
aSB.reverse(); '0' '5' ' ' 's' 'i' ' ' 'b' 'o' 'J'
aSB.toString(); "05 si boJ"
32
11. Wrapper Classes
33
The instances of all wrapper
classes are immutable, i.e., their
internal values cannot be
changed once the objects are
created.
Java employed object wrappers, which 'wrap around' or
encapsulate all the primitive data types and allow them to be
treated as objects (See table). Primitive
type
Object Wrapper Class
int Integer
long Long
short Short
byte Byte
boolean Boolean
double Double
float Float
char Character
The Integer and Double Classes
34
java.lang.Integer
-value: int
+MAX_VALUE: int
+MIN_VALUE: int
+Integer(value: int)
+Integer(s: String)
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longVlaue(): long
+floatValue(): float
+doubleValue():double
+compareTo(o: Integer): int
+toString(): String
+valueOf(s: String): Integer
+valueOf(s: String, radix: int): Integer
+parseInt(s: String): int
+parseInt(s: String, radix: int): int
java.lang.Double
-value: double
+MAX_VALUE: double
+MIN_VALUE: double
+Double(value: double)
+Double(s: String)
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longVlaue(): long
+floatValue(): float
+doubleValue():double
+compareTo(o: Double): int
+toString(): String
+valueOf(s: String): Double
+valueOf(s: String, radix: int): Double
+parseDouble(s: String): double
+parseDouble(s: String, radix: int): double
The Static valueOf Methods
The numeric wrapper classes have a useful class
method, valueOf(String s). This method creates a new
object initialized to the value represented by the
specified string.
For example:
Double x = Double.valueOf("12.4"); // x= 12.4
Integer y= Integer.valueOf("12"); // y = 12
String s = String.valueOf(5.44). // s = “5.44”
35
The Methods for Parsing Strings into Numbers
You can also use:
Integer.parseInt(String s);
// take a string and return an integer.
Double.parseDouble(String s);
//take a string and return double
int x = Integer.parseInt(“13”); // x= 13;
int y = Double.parseDouble(“13.5”); // y = 13.5;
36
Please solve the Activity of Meetings 1-2.
37

More Related Content

Similar to M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)

Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
Prem Kumar Badri
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Lecture 6 - Arrays
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - Arrays
Syed Afaq Shah MACS CP
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
valerie5142000
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ansariparveen06
 
array Details
array Detailsarray Details
array Details
shivas379526
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Java String
Java String Java String
Java String
SATYAM SHRIVASTAV
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
Kashif Nawab
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
eShikshak
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
GC University Faisalabad
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8mlrbrown
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
Martin Chapman
 

Similar to M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf) (20)

Unit ii data structure-converted
Unit  ii data structure-convertedUnit  ii data structure-converted
Unit ii data structure-converted
 
Module 7 : Arrays
Module 7 : ArraysModule 7 : Arrays
Module 7 : Arrays
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Lecture 6 - Arrays
Lecture 6 - ArraysLecture 6 - Arrays
Lecture 6 - Arrays
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
array Details
array Detailsarray Details
array Details
 
Java Strings
Java StringsJava Strings
Java Strings
 
javaarray
javaarrayjavaarray
javaarray
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Java String
Java String Java String
Java String
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Mesics lecture 8 arrays in 'c'
Mesics lecture 8   arrays in 'c'Mesics lecture 8   arrays in 'c'
Mesics lecture 8 arrays in 'c'
 
Arrays and strings in c++
Arrays and strings in c++Arrays and strings in c++
Arrays and strings in c++
 
Cso gaddis java_chapter8
Cso gaddis java_chapter8Cso gaddis java_chapter8
Cso gaddis java_chapter8
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
An Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: ArraysAn Introduction to Programming in Java: Arrays
An Introduction to Programming in Java: Arrays
 

Recently uploaded

Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
PedroFerreira53928
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
PedroFerreira53928
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
Vivekanand Anglo Vedic Academy
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
AzmatAli747758
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
Fundacja Rozwoju Społeczeństwa Przedsiębiorczego
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

Basic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumersBasic phrases for greeting and assisting costumers
Basic phrases for greeting and assisting costumers
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
PART A. Introduction to Costumer Service
PART A. Introduction to Costumer ServicePART A. Introduction to Costumer Service
PART A. Introduction to Costumer Service
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
Sectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdfSectors of the Indian Economy - Class 10 Study Notes pdf
Sectors of the Indian Economy - Class 10 Study Notes pdf
 
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...Cambridge International AS  A Level Biology Coursebook - EBook (MaryFosbery J...
Cambridge International AS A Level Biology Coursebook - EBook (MaryFosbery J...
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdfESC Beyond Borders _From EU to You_ InfoPack general.pdf
ESC Beyond Borders _From EU to You_ InfoPack general.pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 

M251_Meeting 2_updated_2.pdf(M251_Meeting 2_updated_2.pdf)

  • 1. Meeting 2 Introduction to programming usingJava Part 2 1
  • 2. • Arrays • Strings • StringBuilder • Wrapper Classes 2
  • 3. 8. Arrays An array is a collection of items of the same type. Use the element’s index, An index must be a nonnegative integer Array index Array declaration –In Java,array variables are references, not primitives. Becausearrays are objects, they have instance variables we can accessand we can invoke methods on them. Twowaysto declare arrays ofintegers: or Array elements int[] holder; € preferable int holder[]; double[], and – other types of arrays are boolean[],char[], String[]. Array initializers • Example of declaration andassignment: int[] holder = {1,1,1,1,1}; 3
  • 4. 8. Arrays 8.1 Array creation with newoperator • All array types in Javaare reference types, not primitives. As such, array objects also can be created using the new keyword. We could create an array with room for five int values as follows: • int[] holder = new int[5]; Here, we have only stated that there should be room for four integers to be stored. Wecaninitialize these elements (they will default to the value 0) using assignment to individuallocations: holder[0]= 1; holder[1]= 1; holder[2]= 1; holder[3]= 1; holder[4]= 1; • This is equivalent to thefollowing: int[] myArray = {1,1,1,1,1}; 4
  • 5. 8. Arrays 8.2Assigning values to individualelements • Example of changing the value stored in holder's second location to 10: holder [1]= 10; Changing an array reference • Aswith strings (and it is true of all references), we can make an array reference variable refer to adifferentobject. int[] holder2 = {1, 2, 3}; holder = holder2; 8.3 Accessing array data we can refer to an item using the index enclosed in square brackets after the name of the array. holder[1]= holder[0]*10 ; 5
  • 6. 8. Arrays 8.4- The array instance variable length • Arrays have an instance variable length, which gives the capacity of the array. The expression: holder.length represents the number of locations in the array holder. • The array length will give the number of locations in an array, not the number of initialized locations (the capacity). • Any array length is fixed at the point when the array is created. • Accessingan array element beyond the array's capacity, causearun-time error. • Note that length is an instance variable associated witharrays, while length() is amethod associated with strings. • int[]num= {10, 11, 12, 13, 14, 15}; • System.out.println ("First item is " + num.length); 6 • System.out.println ("Last item is " +num[num.length -1] ); 15 6
  • 7. 8. Arrays 8.5- Mutability of strings andarrays • Arrays and strings are both fixed-length entities: they cannot be extended or evenshrunk. int []holder ={1, 1, 1, 1,1}; int []holder2 ={1, 2,3}; holder=holder2; // doesn't change first array • The third line above does not change the length of the original array referenced by holder (with all 1sinit). • Itmakesholder reference adifferent array of smaller length(which is also referenced by holder2). • Any array length is fixed at the point when the array is created. • (The contents of the array can be changed, provided wehave areference to the array). 7
  • 8. 8. Arrays 8.6- Mutability of strings andarrays S tring s="fish"; s="cat"; • and this does not change the length of the original string, "fish". What changes is the reference s,which at first points to aString object with value "fish", and then subsequently points to a different String object with value "cat". • Whereas contents of arrays can bechanged, • contents of strings cannot. • Strings are said to be immutable: they cannot bechanged at all, oncecreated… 8
  • 9. 8. Arrays Traversing the elements of the array: String[] names = {"Hadi", "Dalia", "Rami", "Manar"}; 1) Using for statement : for (int i=0; i<names.length; i++) System.out.println(names[i]); 2) Using enhanced for statement: for (String s: names) System.out.println(s); • Enhanced for statement visits all the elements of the array without using the index. (So, there is no need for a counter) • It simplifies the code but cannot be used to modify elements of the array. String s; for (int i=0; i<names.length; i++) { s = names[i]; System.out.println(s); } ≡ 9
  • 10. 8. Arrays Remember with reference variable asString andArray There are several steps taken to create ausefulobject, referenced by avariable. they are: • declaration of a reference variable of the appropriate type; • creation (and initialization) of an object of the chosen type; • making the reference variable refer to the created object. 10
  • 11. 9. Strings Astring is asequence of characters. – For example, astring could be used to store aperson'sname • Strings are represented using the reference typecalled String • String literals are denoted by enclosing their characters in double quotation marks. String declaration String name, address; • declares two variables of type String. No strings are created by such a declaration and the reference values in these variables have not yet been initialized. String Creation String name; name ="Ali"; // declare // initialize • declare the variable name of type String, and initialize that variable to contain a reference to the String object storing the characters "Ali". 11
  • 12. Constructing Strings There are 2 ways to construct a String: 1. Using new String()// invoke constructor String = new String(string Literal); String s = new String(); String message = new String("Welcome to Java"); 2. Using String Initializer: o String message = “literal value”; o String s = s1; String message = "Welcome to Java"; String s = message; 12
  • 13. Strings • Aspecial String literal is the string with no contents, called the empty string (written "").As: name=""; 13
  • 14. Strings Are Immutable A String object is immutable; Once its created, its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; 14
  • 15. Trace Code String s = "Java"; s = "HTML"; 15 : String String object for "Java" s After executing String s = "Java"; After executing s = "HTML"; : String String object for "Java" : String String object for "HTML" Contents cannot be changed This string object is now unreferenced s
  • 16. Trace Code String s = "Java"; s = "HTML"; 16 : String String object for "Java" s After executing String s = "Java"; After executing s = "HTML"; : String String object for "Java" : String String object for "HTML" Contents cannot be changed This string object is now unreferenced s
  • 17. Trace Code 17 String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; : String Interned string object for "Welcome to Java" : String A string object for "Welcome to Java" s1 s2 s3
  • 18. Strings The length method • For example: name.length() – This evaluates to the number of characters in the string referenced by name. – If this string were "Roderick", the length method would return the value 8. – Theempty string haslength zero. String concatenation (+) • Theconcatenation operator, +, will automatically turn any arguments into strings before carrying outaconcatenation. • Example: Theoutput is "Filby Lanehas2occupants". 18
  • 19. Strings 19 public class StringsEquality { public static void main(String[] args) { String s1 = "Hello"; String s2 = new String("Hello"); if (s1 == s2) System.out.println("s1 and s2 refer to the same object"); else System.out.println("s1 and s2 refer to different objects"); if ( s1.equals(s2) ) System.out.println("s1 and s2 have the same contents"); else System.out.println("s1 and s2 have different contents"); String s3 = "hello"; // s1.equals(s3) --> false // s1.equalsIgnoreCase(s3) --> true String s4 = s3; // s3 == s4 --> true // s3.equals(s4) --> true String s5 = "hello"; String s6 = "Hello"; } // end main method } // end class --output-- s1 and s2 refer to different objects s1 and s2 have the same contents s1 Hello s2 s3 hello s4 Hello s5 s6 // s3 == s5 --> true // s1 == s6 --> true
  • 20. Strings public class StringsComparing { public static void main(String[] args) { String s1 = "Java nights"; String s2 = "java nights"; String s3 = "java rights"; String s4 = "Help"; String s5 = "Helping"; System.out.println(s1.compareTo(s4)); System.out.println(s4.compareTo(s1)); System.out.println(s2.compareTo(s1)); System.out.println(s1.compareTo(s2)); System.out.println(s2.compareTo(s3)); System.out.println(s5.compareTo(s4)); System.out.println(s1.compareToIgnoreCase(s2)); System.out.println(s3.compareToIgnoreCase(s4)); System.out.println(s1.contains("night")); System.out.println(s1.contains("nght")); System.out.println(s1.startsWith("Java")); System.out.println(s1.endsWith("hts")); } // end main method } // end class --output-- 2 -2 32 -32 -4 3 0 2 true false true true 20
  • 21. Strings public class StringsMoreMethods { public static void main(String[] args) { String s1 = "Systems Analysis"; String s2 = " Ten nights "; System.out.println(s1.indexOf('s')); System.out.println(s1.indexOf('s', 3)); System.out.println(s1.indexOf('N')); System.out.println(s1.indexOf("em")); System.out.println(s1.lastIndexOf('s')); System.out.println(s1.substring(8)); System.out.println(s1.substring(10, 13)); System.out.println(s1.toUpperCase()); System.out.println(s1); // s1 did not changed s1 = s1.toLowerCase(); System.out.println(s1); System.out.println(s2.trim()); s2 = s2.replace('n', 'l'); System.out.println(s2); } // end main method } // end class 2 6 -1 4 aly 15 Analysis SYSTEMS ANALYSIS Systems Analysis systems analysis Ten nights Tel lights --output-- 21
  • 22. Replacing and Splitting Strings 22 java.lang.String +replace(oldChar: char, newChar: char): String +replaceFirst(oldString: String, newString: String): String +replaceAll(oldString: String, newString: String): String +split(delimiter: String): String[] Returns a new string that replaces all matching character in this string with the new character. Returns a new string that replaces the first matching substring in this string with the new substring. Returns a new string that replace all matching substrings in this string with the new substring. Returns an array of strings consisting of the substrings split by the delimiter.
  • 23. Examples System.out.prinltn("Welcome".replace('e', 'A')); System.out.println("Welcome".replaceFirst("e", "AB") ); System.out.println("Welcome".replace("e", "AB")); System.out.println("Welcome".replace("el", "AB")); String s = "a+b$#c".replaceAll("[$+#]", "NNN"); System.out.println(s); 23 OutPut: WAlcomA WABlcome WABlcomAB WABcome aNNNbNNNNNNc
  • 24. Splitting a String String[] tokens = "Java#HTML#Perl".split("#"); for (int i = 0; i < tokens.length; i++) System.out.print(tokens[i] + " "); System.out.println(); String text = " Good morning. Have fun!"; String[] words = text.trim().split("W+"); // split text into words , this mean the delimiter will be anything that is not a word (Why do we need trim()?) for (int i = 0; i < words.length; i++) System.out.print(words[i] + " "); 24 Java HTML Perl Good morning Have fun Outputs:
  • 25. Convert Character and Numbers to Strings The String class provides several static valueOf methods for converting a character, an array of characters, and numeric values to strings. These methods have the same name valueOf with different argument types char, char[], double, long, int, and float. For example, to convert a double value to a string, use String.valueOf(5.44). The return value is string consists of characters ‘5’, ‘.’, ‘4’, and ‘4’. 25
  • 26. Strings public class ArraysVsStrings { public static void main(String[] args) { char[] array = {'n', 'i', 'g', 'h', 't'}; String word = "night"; System.out.println("first char at array: " + array[0]); System.out.println("first char at word: " + word.charAt(0)); System.out.println("The length of array: " + array.length ); System.out.println("The length of word: " + word.length() ); array[0] = 'l'; word = word.replace('n', 'l'); System.out.println(word); String k = "cat"; char[] small = k.toCharArray(); System.out.println( "first char at small: " + small[0] ); small[0] = 'r'; String m = new String(small); System.out.println("m = " + m); } // end main method } // end class --output-- first char at array: n first char at word: n The length of array: 5 The length of word: 5 m = rat light first char at small: c night light word array [0] n [1] i [2] g [3] h [4] t  l This object will be garbage collected cat k rat m small [0] c [1] a [2] t  r 26
  • 27. Strings public class StringArrays { public static String longestWord(String[] words) { String longest = ""; for (int i=0; i < words.length ; i++) if ( words[i].length() > longest.length() ) longest = words[i]; return longest; } // end method longestWord public static void main(String[] args) { String[] array = { "All", "Arab", "countries", "are", "here"}; System.out.println("The longest word is: "+ longestWord(array)); System.out.printf("There are %d words starts with 'A'n", startsWithA(array)); } // end main method public static int startsWithA(String[] words) { int count = 0; for (int i=0; i < words.length ; i++) if (words[i].charAt(0) == 'A') count++; return count; } // end method startsWithA } // end class StringArrays --output-- The longest word is: countries There are 2 words starts with 'A' 27
  • 28. 10. StringBuilder and StringBuffer The StringBuilder/StringBuffer class is an alternative to the String class. In general, a StringBuilder/StringBuffer can be used wherever a string is used. StringBuilder/StringBuffer is more flexible than String. You can add, insert, or append new contents into a string buffer without the need to create new string. StringBuffer/StringBuilder is mutable. 28
  • 29. StringBuilder Constructors 29 java.lang.StringBuilder +StringBuilder() +StringBuilder(capacity: int) +StringBuilder(s: String) Constructs an empty string builder with capacity 16. Constructs a string builder with the specified capacity. Constructs a string builder with the specified string. Example: StringBuilder sb = new StringBuilder("Hello"); sb refers to the character sequence 'H' 'e' 'l' 'l' 'o', but with space for an additional 16 characters, the object referenced by sb will contain 21 characters in total.
  • 30. StringBuilder Methods 30 java.lang.StringBuilder +toString(): String +capacity(): int +charAt(index: int): char +length(): int +setLength(newLength: int): void +substring(startIndex: int): String +substring(startIndex: int, endIndex: int): String +trimToSize(): void Returns a string object from the string builder. Returns the capacity of this string builder. Returns the character at the specified index. Returns the number of characters in this builder. Sets a new length in this builder. Returns a substring starting at startIndex. Returns a substring from startIndex to endIndex-1. Reduces the storage size used for the string builder.
  • 31. StringBuilder Consider the following code: String str = ""; for (int i = 1; i <= 10000; i++) str = str + "*"; This code will create 10,001 different string objects and all but one of these is unreferenced. However, using StringBuilder which is mutable, we can avoid this action: StringBuilder sb = new StringBuilder(10000); for (int i=1; i <= 10000; i++) sb.append("*"); 31
  • 32. StringBuilder Consider the following statement: StringBuilder aSB = new StringBuilder("Bob"); Expression Result aSB.length(); 3 aSB.capacity(); 19 aSB.append(" is "); 'B' 'o' 'b' ' ' 'i' 's' ' ' aSB.append(50); 'B' 'o' 'b' ' ' 'i' 's' ' ' '5' '0' aSB.length(); 9 aSB.capacity(); 19 aSB.deleteCharAt(0); 'o' 'b' ' ' 'i' 's' ' ' '5' '0' aSB.insert(0, 'J'); 'J' 'o' 'b' ' ' 'i' 's' ' ' '5' '0' aSB.reverse(); '0' '5' ' ' 's' 'i' ' ' 'b' 'o' 'J' aSB.toString(); "05 si boJ" 32
  • 33. 11. Wrapper Classes 33 The instances of all wrapper classes are immutable, i.e., their internal values cannot be changed once the objects are created. Java employed object wrappers, which 'wrap around' or encapsulate all the primitive data types and allow them to be treated as objects (See table). Primitive type Object Wrapper Class int Integer long Long short Short byte Byte boolean Boolean double Double float Float char Character
  • 34. The Integer and Double Classes 34 java.lang.Integer -value: int +MAX_VALUE: int +MIN_VALUE: int +Integer(value: int) +Integer(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double +compareTo(o: Integer): int +toString(): String +valueOf(s: String): Integer +valueOf(s: String, radix: int): Integer +parseInt(s: String): int +parseInt(s: String, radix: int): int java.lang.Double -value: double +MAX_VALUE: double +MIN_VALUE: double +Double(value: double) +Double(s: String) +byteValue(): byte +shortValue(): short +intValue(): int +longVlaue(): long +floatValue(): float +doubleValue():double +compareTo(o: Double): int +toString(): String +valueOf(s: String): Double +valueOf(s: String, radix: int): Double +parseDouble(s: String): double +parseDouble(s: String, radix: int): double
  • 35. The Static valueOf Methods The numeric wrapper classes have a useful class method, valueOf(String s). This method creates a new object initialized to the value represented by the specified string. For example: Double x = Double.valueOf("12.4"); // x= 12.4 Integer y= Integer.valueOf("12"); // y = 12 String s = String.valueOf(5.44). // s = “5.44” 35
  • 36. The Methods for Parsing Strings into Numbers You can also use: Integer.parseInt(String s); // take a string and return an integer. Double.parseDouble(String s); //take a string and return double int x = Integer.parseInt(“13”); // x= 13; int y = Double.parseDouble(“13.5”); // y = 13.5; 36
  • 37. Please solve the Activity of Meetings 1-2. 37