SlideShare a Scribd company logo
1 of 65
Java Basics, Strings
Kavita Ganesan, Ph.D.
www.kavita-ganesan.com
1
Lecture Outline
• Intro to Strings + Creating String Objects
• String Methods + Concatenation
• String Immutability + StringBuilder
• String Equality/Inequality
• Wrapper Classes
• Review + Quiz
• Download code samples + take home exercise
2
STRINGS - INTRO, CREATION
What is a String?
String  a sequence of characters
Example of strings:
“The cow jumps over the moon”
“PRESIDENT OBAMA”
“12345”
What is a String class in Java?
• String class in Java: holds a “sequence of
characters”
String greeting = new String("Hello world!“);
• Creating new String object
• Contains sequence of chars
String Class
• Why use String class vs. char array?
• Advantage: provides many useful methods for
string manipulation
– Print length of string – str.length()
– Convert to lowercase – str.toLowerCase()
– Convert to uppercase – str.toUpperCase()
* Many others
6
There are 2 ways to create String objects
String greeting1 = new String(“Hello World!”) ;Method 1:
• Variable of type String
• Name of variable is greeting1
Creating String Objects
• new operator for creating
instance of the String class
• Recall: Instance of a class is an
object
• String value aka string literal
• String literal: series of
characters enclosed in
double quotes.
There are 2 ways to create String objects
String greeting2 = “Hello World Again!” ;Method 2:
Creating String Objects
• Shorthand for String creation (most used)
• Behind the scenes: new instance of String
class with “Hello World Again!” as the value
There are 2 ways to create String objects
String greeting2 = “Hello World Again!” ;Method 2:
Creating String Objects
String greeting1 = new String(“Hello World!”) ;Method 1:
greeting1
Local Variable Table String Objects
“Hello World!”
greeting2 “Hello World Again!”
Holds a reference
Holds a reference
String Constructor
• Recall: when new object created  the
constructor method is always called first
• Pass initial arguments or empty object
• String class has multiple constructors
10
String Constructor
11
* few others
String str1= new String() ; //empty object
String str2= new String(“string”) ; //string input
String str3= new String(char[]) ; //char array input
String str4= new String(byte[]) ; //byte array input
Strings: Defining and initializing
Simple example
String s1 = "Welcome to Java!";
String s2 = new String("Welcome to Java!"); //same as s1
Numbers as strings
String s3 =“12345”;
String s4 = new String(s3); //s4 will hold same value as s3
Char array as strings
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String s5= new String(helloArray);
12
Strings: Defining and initializing
Empty Strings
String s5 = "";
String s6 = new String(“”);
Null String
String s7 = null;
13
String object created;
String value is empty “”
String variable not pointing to
any String object
NetBeans Examples…
14
Understanding String Creation
Does Java create 2 String objects internally?
Without “new” operator for String creation:
• Java looks into a String pool (collection of String objects)
– Try to find objects with same string value
• If object exists  new variable points to existing object
• If object does not exist  new object is created
• Efficiency reasons – to limit object creation
15
String greeting1 = “Hello Utah!”
String greeting2 = “Hello Utah!”
Understanding String Creation
16
String greeting1 = “Hello Utah!”
String greeting2 = “Hello Utah!”
Pool of String Objects
“Hello Utah!”
Local Variable Table
greeting1
greeting2
Concept of String pooling
Understanding String Creation
17
String greeting1 = new String (“Hello Utah!”);
String greeting2 = new String (“Hello Utah!”);
String Objects
“Hello Utah!”
“Hello Utah!”
greeting1
Local Variable Table
greeting2
NetBeans Examples…
18
STRINGS - METHODS,
CONCATENATION
String Methods
Advantage of String class: many built-in methods
for String manipulation
str.length(); // get length of string
str.toLowerCase() // convert to lower case
str.toUpperCase() // convert to upper case
str.charAt(i) // what is at character i?
str.contains(..) // String contains another string?
str.startsWith(..) // String starts with some prefix?
str.indexOf(..) // what is the position of a character?
….many more
20
String Methods - length, charAt
str.length()  Returns the number of chars in String
str.charAt(i)  Returns the character at position i
Character positions in strings are numbered
starting from 0 – just like arrays
String Methods - length, charAt
str.length()  Returns the number of chars in String
str.charAt(i)  Returns the character at position i
22
“Utah”.length();
“Utah”.charAt (2);
Returns:
4
a
0123
String Methods – valueOf(X)
String.valueOf(X) - Returns String representation of X
• X: char, int, char array, double, float, Object
• Useful for converting different data types into String
23
String str1 = String.valueOf(4); //returns “4”
String str2 = String.valueOf(‘A’); //returns “A”
String str3 = String.valueOf(40.02); //returns “40.02”
String Methods – substring(..)
str.substring(..)  returns a new String by
copying characters from an existing String.
• str.substring (i, k)
– returns substring of chars from pos i to k-1
• str.substring (i);
– returns substring from the i-th char to the end
24
“” (empty)
String Methods – substring(..)
25
Returns:
“Be”
“ohn”
“Ben”.substring(0,2);
012
“John”.substring(1);
0123
“Tom”.substring(9);
012
String Concatenation – Combine Strings
• What if we wanted to combine String values?
String word1 = “re”;
String word2 = “think”;
String word3 = “ing”;
How to combine and make  “rethinking” ?
• Different ways to concatenate Strings in Java
26
String Concatenation – Combine Strings
String word1 = “re”;
String word2 = “think”;
String word3 = “ing”;
Method 1: Plus “+” operator
String str = word1 + word2;
– concatenates word1 and word2  “rethink”
Method 2: Use String’s “concat” method
String str = word1.concat (word2);
– the same as word1 + word2  “rethink”
27
String Concatenation – Combine Strings
Now str has value “rethink”, how to make “rethinking”?
String word3 = “ing”;
Method 1: Plus “+” operator
str = str + word3; //results in “rethinking”
Method 2: Use String’s “concat” method
str = str.concat(word3); //results in “rethinking”
Method 3: Shorthand
str += word3; //results in “rethinking” (same as method 1)
28
String Concatenation: Strings, Numbers &
Characters
String myWord= “Rethinking”;
int myInt=2;
char myChar=‘!’;
Method 1: Plus “+” operator
29
String result = myWord + myInt + myChar;
//Results in “Rethinking2!”
Internally: myInt &
myChar converted to
String objects
String Concatenation: Strings, Numbers &
Characters
String myWord= “Rethinking”;
int myInt=2;
char myChar=‘!’;
Method 2: Use String’s “concat” method
30
String strMyInt= String.valueOf(myInt);
String strMyChar=String.valueOf(myChar);
String result = myWord.concat(strMyInt).concat(strMyChar);
//Results in “Rethinking2!”
NetBeans Examples…
31
STRING IMMUTABILITY
32
String Immutability
• Strings in Java are immutable
• Meaning: cannot change its value, once created
33
String str;
str = “Java is Fun!”;
str = “I hate Java!”;
Did we change the
value of “Java is Fun!”
to “I hate Java!”?
String Immutability
34
String str;
str = “Java is Fun!”;
str = “I hate Java!”;
String Objects
“Java is Fun!”
“I hate Java!”
str
Local Variable Table
Cannot insert or
remove a value
e.g. remove “Fun”
String Immutability
35
String str;
str = “Re”;
str = str + “think”; //Rethink
str = str + “ing”; // Rethinking
String Objects
“Re”
“Rethink”
str
Local Variable Table
“Rethinking”
Every concat: Create new
String object
Unused objects: “Re”,
“Rethink” go to garb. coll.
String Immutability
• Problem: With frequent modifications of Strings
– Create many new objects – uses up memory
– Destroy many unused ones – increase JVM workload
– Overall: can slow down performance
• Solution for frequently changing Strings:
– StringBuilder Class instead of String
36
StringBuilder Class
• StringBuilders used for String concatenation
• StringBuilder class is “mutable”
Meaning: values within StringBuilder can be
changed or modified as needed
• In contrast to Strings where Strings are
immutable
37
StringBuilder - “append” method
• append(X)  most used method
– Appends a value X to end of StringBuilder
– X: int, char, String, double, object (almost anything)
38
sb
Local Variable Table StringBuilder Object
StringBuilder sb = new StringBuilder(); //obj creation
sb.append(“Re”); //add “Re” to sb
sb.append(“think”); //add “think” to sb
sb.append(“ing”); //add “ing” to sb
String str= sb.toString(); //return String value
StringBuilder for String Construction
39
Rethinking
• Only 1 object
• All 3 words appended
to same object
Bottom-line: Use StringBuilder when you
have frequent string modification
STRING EQUALITY/INEQUALITY
40
Testing String Equality
• How to check if two Strings contain same value?
41
String str1=new String(“Hello World!”);
String str2=new String(“Hello World!”);
if(str1==str2) { //eval to false
System.out.println(“same”);
}
String Objects
“Hello World!”
“Hello World!”
str1
Local Variable Table
str2
if str1 referencing
same object as str2?
Testing String Equality
• How to check if two Strings contain same value?
42
String str1=new String(“Hello World!”);
String str2=new String(“Hello World!”);
if(str1==str2) { //eval to false
System.out.println(“same”);
}
if(str1.equals(str2)) { //eval to true
System.out.println(“same”);
}
if content of str1 same
as str2?
Testing String Equality
• What if “new” operator not used?
43
String str1 = “Hello World!”;
String str2 = “Hello World!”;
if(str1==str2) { //eval to true
System.out.println(“same”);
}
String Objects
“Hello World!”str1
Local Variable Table
str2
if str1 referencing
same object as str2?
Testing String Equality
• What if “new” operator not used?
44
String str1 = “Hello World!”;
String str2 = “Hello World!”;
if(str1==str2) { //eval to true
System.out.println(“same”);
}
if(str1.equals(str2)) { //eval to true
System.out.println(“same”);
}
Testing String Equality
• Point to note: String variables are references to
String objects (i.e. memory addresses)
• “str1==str2” on String objects compares
memory addresses, not the contents
• Always use “str1.equals(str2)” to compare
contents
45
NetBeans Examples…
46
WRAPPER CLASSES
(SIDE TOPIC)
47
Wrapper Classes
• Recall: primitive data types int, double, long are not
objects
• Wrapper classes: convert primitive types into objects
– int: Integer wrapper class
– double: Double wrapper class
– char: Character wrapper class
• 8 Wrapper classes:
– Boolean, Byte, Character, Double, Float, Integer, Long, Short
Wrapper Classes
• Why are they nice to have?
– Primitives have a limited set of in-built operations
– Wrapper classes provide many common functions to work
with primitives efficiently
• How to convert a String “22”  int?
– Cannot do this with primitive type int
– Can use Integer wrapper class; Integer.parseInt(..)
49
String myStr = “22”;
int myInt= Integer.parseInt(myStr);
Wrapper Classes
• Reverse: How to convert int 22  String?
– Cannot do this with primitive int
– Can use Integer wrapper class; Integer.toString(..)
• Each Wrapper class has its own set of methods
50
int myInt= 22;
String myStr= Integer.toString(myInt); // “22”
String myStr2 = String.valueOf(myInt); // “22”
equivalent
Integer Wrapper Class Methods
51
Character Wrapper Class Methods
52
Double Wrapper Class Methods
53
Review + Quiz
54
Review + Quiz (1)
• What is the purpose of a String class?
– String class holds a sequence of characters
• Why use a String class vs. a char array?
– String class has many built-in methods
– Makes string manipulation easy
• What are the 2 ways to create Strings?
– new operator; String str=new String(“Hello World”);
– direct assignment; String str=“Hello World”;
55
Review + Quiz (2)
• Can we directly modify String objects?
– No, Strings are immutable by design
– Once created cannot be changed in any way
– Only the variable references are changed
• For frequent modification of Strings should we
use the String class?
– No, use StringBuilder class instead of String class
– String class creates many new objects for
concatenation – slows things down
56
Review + Quiz (3)
• What are the different ways to concatenate
Strings?
- Use plus “+” operator or in-built “concat” method
• When you use “==“ when comparing 2 String
objects, what are you comparing?
– comparing references (address in memory)
• How do you compare contents of two String
objects?
– string1.equals(string2)
57
Review + Quiz (4)
• What are Wrapper classes and why do we need
them?
– convert primitive types into objects
– provide many functions to work with primitives
efficiently
• What method do you use to convert a primitive int
or double into a String representation?
- Double.toString(doubleVal), Integer.toString(intVal)
- String.valueOf(primitiveType)
58
End of Quiz!
59
Take-Home Exercise & Code Samples
• Go to https://bitbucket.org/kganes2/is4415/downloads
• Download StringNetBeans.zip
• Import Code into NetBeans
1. Select File -> Import Project -> From Zip
2. Select downloaded StringNetBeans.zip
3. You should see TestProject in NetBeans
• Complete all tasks in StringExercise.java
• Code samples in “examples” package
60
61
Example code run in class
Take-home exercise
62
StringExercise.java
Take-home exercise
Further Questions…
Kavita Ganesan
ganesan.kavita@gmail.com
www.kavita-ganesan.com
63
Online videos
• https://www.youtube.com/results?search_qu
ery=java+strings
64
65

More Related Content

What's hot

What's hot (20)

20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java arrays
Java arraysJava arrays
Java arrays
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 
Java arrays
Java arraysJava arrays
Java arrays
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
String Handling
String HandlingString Handling
String Handling
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 

Similar to Introduction to Java Strings, By Kavita Ganesan

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdflearnEnglish51
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packagesSardar Alam
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processingmaznabili
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string classfedcoordinator
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Danial Virk
 

Similar to Introduction to Java Strings, By Kavita Ganesan (20)

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Java string handling
Java string handlingJava string handling
Java string handling
 
Module-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdfModule-1 Strings Handling.ppt.pdf
Module-1 Strings Handling.ppt.pdf
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
M C6java7
M C6java7M C6java7
M C6java7
 
Strings in java
Strings in javaStrings in java
Strings in java
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
07slide
07slide07slide
07slide
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
Day_5.1.pptx
Day_5.1.pptxDay_5.1.pptx
Day_5.1.pptx
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
8. String
8. String8. String
8. String
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
javastringexample problems using string class
javastringexample problems using string classjavastringexample problems using string class
javastringexample problems using string class
 
Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 

More from Kavita Ganesan

Comparison between cbow, skip gram and skip-gram with subword information (1)
Comparison between cbow, skip gram and skip-gram with subword information (1)Comparison between cbow, skip gram and skip-gram with subword information (1)
Comparison between cbow, skip gram and skip-gram with subword information (1)Kavita Ganesan
 
Comparison between cbow, skip gram and skip-gram with subword information
Comparison between cbow, skip gram and skip-gram with subword informationComparison between cbow, skip gram and skip-gram with subword information
Comparison between cbow, skip gram and skip-gram with subword informationKavita Ganesan
 
Statistical Methods for Integration and Analysis of Online Opinionated Text...
Statistical Methods for Integration and Analysis of Online Opinionated Text...Statistical Methods for Integration and Analysis of Online Opinionated Text...
Statistical Methods for Integration and Analysis of Online Opinionated Text...Kavita Ganesan
 
Segmentation of Clinical Texts
Segmentation of Clinical TextsSegmentation of Clinical Texts
Segmentation of Clinical TextsKavita Ganesan
 
In situ evaluation of entity retrieval and opinion summarization
In situ evaluation of entity retrieval and opinion summarizationIn situ evaluation of entity retrieval and opinion summarization
In situ evaluation of entity retrieval and opinion summarizationKavita Ganesan
 
Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit
Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit
Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit Kavita Ganesan
 
Very Small Tutorial on Terrier 3.0 Retrieval Toolkit
Very Small Tutorial on Terrier 3.0 Retrieval ToolkitVery Small Tutorial on Terrier 3.0 Retrieval Toolkit
Very Small Tutorial on Terrier 3.0 Retrieval ToolkitKavita Ganesan
 
Opinion Driven Decision Support System
Opinion Driven Decision Support SystemOpinion Driven Decision Support System
Opinion Driven Decision Support SystemKavita Ganesan
 
Micropinion Generation
Micropinion GenerationMicropinion Generation
Micropinion GenerationKavita Ganesan
 
Opinion-Based Entity Ranking
Opinion-Based Entity RankingOpinion-Based Entity Ranking
Opinion-Based Entity RankingKavita Ganesan
 
Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...
Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...
Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...Kavita Ganesan
 
Opinion Mining Tutorial (Sentiment Analysis)
Opinion Mining Tutorial (Sentiment Analysis)Opinion Mining Tutorial (Sentiment Analysis)
Opinion Mining Tutorial (Sentiment Analysis)Kavita Ganesan
 

More from Kavita Ganesan (12)

Comparison between cbow, skip gram and skip-gram with subword information (1)
Comparison between cbow, skip gram and skip-gram with subword information (1)Comparison between cbow, skip gram and skip-gram with subword information (1)
Comparison between cbow, skip gram and skip-gram with subword information (1)
 
Comparison between cbow, skip gram and skip-gram with subword information
Comparison between cbow, skip gram and skip-gram with subword informationComparison between cbow, skip gram and skip-gram with subword information
Comparison between cbow, skip gram and skip-gram with subword information
 
Statistical Methods for Integration and Analysis of Online Opinionated Text...
Statistical Methods for Integration and Analysis of Online Opinionated Text...Statistical Methods for Integration and Analysis of Online Opinionated Text...
Statistical Methods for Integration and Analysis of Online Opinionated Text...
 
Segmentation of Clinical Texts
Segmentation of Clinical TextsSegmentation of Clinical Texts
Segmentation of Clinical Texts
 
In situ evaluation of entity retrieval and opinion summarization
In situ evaluation of entity retrieval and opinion summarizationIn situ evaluation of entity retrieval and opinion summarization
In situ evaluation of entity retrieval and opinion summarization
 
Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit
Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit
Enabling Opinion-Driven Decision Making - Sentiment Analysis Innovation Summit
 
Very Small Tutorial on Terrier 3.0 Retrieval Toolkit
Very Small Tutorial on Terrier 3.0 Retrieval ToolkitVery Small Tutorial on Terrier 3.0 Retrieval Toolkit
Very Small Tutorial on Terrier 3.0 Retrieval Toolkit
 
Opinion Driven Decision Support System
Opinion Driven Decision Support SystemOpinion Driven Decision Support System
Opinion Driven Decision Support System
 
Micropinion Generation
Micropinion GenerationMicropinion Generation
Micropinion Generation
 
Opinion-Based Entity Ranking
Opinion-Based Entity RankingOpinion-Based Entity Ranking
Opinion-Based Entity Ranking
 
Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...
Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...
Opinosis Presentation @ Coling 2010: Opinosis - A Graph Based Approach to Abs...
 
Opinion Mining Tutorial (Sentiment Analysis)
Opinion Mining Tutorial (Sentiment Analysis)Opinion Mining Tutorial (Sentiment Analysis)
Opinion Mining Tutorial (Sentiment Analysis)
 

Recently uploaded

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 

Recently uploaded (20)

Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 

Introduction to Java Strings, By Kavita Ganesan

  • 1. Java Basics, Strings Kavita Ganesan, Ph.D. www.kavita-ganesan.com 1
  • 2. Lecture Outline • Intro to Strings + Creating String Objects • String Methods + Concatenation • String Immutability + StringBuilder • String Equality/Inequality • Wrapper Classes • Review + Quiz • Download code samples + take home exercise 2
  • 3. STRINGS - INTRO, CREATION
  • 4. What is a String? String  a sequence of characters Example of strings: “The cow jumps over the moon” “PRESIDENT OBAMA” “12345”
  • 5. What is a String class in Java? • String class in Java: holds a “sequence of characters” String greeting = new String("Hello world!“); • Creating new String object • Contains sequence of chars
  • 6. String Class • Why use String class vs. char array? • Advantage: provides many useful methods for string manipulation – Print length of string – str.length() – Convert to lowercase – str.toLowerCase() – Convert to uppercase – str.toUpperCase() * Many others 6
  • 7. There are 2 ways to create String objects String greeting1 = new String(“Hello World!”) ;Method 1: • Variable of type String • Name of variable is greeting1 Creating String Objects • new operator for creating instance of the String class • Recall: Instance of a class is an object • String value aka string literal • String literal: series of characters enclosed in double quotes.
  • 8. There are 2 ways to create String objects String greeting2 = “Hello World Again!” ;Method 2: Creating String Objects • Shorthand for String creation (most used) • Behind the scenes: new instance of String class with “Hello World Again!” as the value
  • 9. There are 2 ways to create String objects String greeting2 = “Hello World Again!” ;Method 2: Creating String Objects String greeting1 = new String(“Hello World!”) ;Method 1: greeting1 Local Variable Table String Objects “Hello World!” greeting2 “Hello World Again!” Holds a reference Holds a reference
  • 10. String Constructor • Recall: when new object created  the constructor method is always called first • Pass initial arguments or empty object • String class has multiple constructors 10
  • 11. String Constructor 11 * few others String str1= new String() ; //empty object String str2= new String(“string”) ; //string input String str3= new String(char[]) ; //char array input String str4= new String(byte[]) ; //byte array input
  • 12. Strings: Defining and initializing Simple example String s1 = "Welcome to Java!"; String s2 = new String("Welcome to Java!"); //same as s1 Numbers as strings String s3 =“12345”; String s4 = new String(s3); //s4 will hold same value as s3 Char array as strings char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' }; String s5= new String(helloArray); 12
  • 13. Strings: Defining and initializing Empty Strings String s5 = ""; String s6 = new String(“”); Null String String s7 = null; 13 String object created; String value is empty “” String variable not pointing to any String object
  • 15. Understanding String Creation Does Java create 2 String objects internally? Without “new” operator for String creation: • Java looks into a String pool (collection of String objects) – Try to find objects with same string value • If object exists  new variable points to existing object • If object does not exist  new object is created • Efficiency reasons – to limit object creation 15 String greeting1 = “Hello Utah!” String greeting2 = “Hello Utah!”
  • 16. Understanding String Creation 16 String greeting1 = “Hello Utah!” String greeting2 = “Hello Utah!” Pool of String Objects “Hello Utah!” Local Variable Table greeting1 greeting2 Concept of String pooling
  • 17. Understanding String Creation 17 String greeting1 = new String (“Hello Utah!”); String greeting2 = new String (“Hello Utah!”); String Objects “Hello Utah!” “Hello Utah!” greeting1 Local Variable Table greeting2
  • 20. String Methods Advantage of String class: many built-in methods for String manipulation str.length(); // get length of string str.toLowerCase() // convert to lower case str.toUpperCase() // convert to upper case str.charAt(i) // what is at character i? str.contains(..) // String contains another string? str.startsWith(..) // String starts with some prefix? str.indexOf(..) // what is the position of a character? ….many more 20
  • 21. String Methods - length, charAt str.length()  Returns the number of chars in String str.charAt(i)  Returns the character at position i Character positions in strings are numbered starting from 0 – just like arrays
  • 22. String Methods - length, charAt str.length()  Returns the number of chars in String str.charAt(i)  Returns the character at position i 22 “Utah”.length(); “Utah”.charAt (2); Returns: 4 a 0123
  • 23. String Methods – valueOf(X) String.valueOf(X) - Returns String representation of X • X: char, int, char array, double, float, Object • Useful for converting different data types into String 23 String str1 = String.valueOf(4); //returns “4” String str2 = String.valueOf(‘A’); //returns “A” String str3 = String.valueOf(40.02); //returns “40.02”
  • 24. String Methods – substring(..) str.substring(..)  returns a new String by copying characters from an existing String. • str.substring (i, k) – returns substring of chars from pos i to k-1 • str.substring (i); – returns substring from the i-th char to the end 24
  • 25. “” (empty) String Methods – substring(..) 25 Returns: “Be” “ohn” “Ben”.substring(0,2); 012 “John”.substring(1); 0123 “Tom”.substring(9); 012
  • 26. String Concatenation – Combine Strings • What if we wanted to combine String values? String word1 = “re”; String word2 = “think”; String word3 = “ing”; How to combine and make  “rethinking” ? • Different ways to concatenate Strings in Java 26
  • 27. String Concatenation – Combine Strings String word1 = “re”; String word2 = “think”; String word3 = “ing”; Method 1: Plus “+” operator String str = word1 + word2; – concatenates word1 and word2  “rethink” Method 2: Use String’s “concat” method String str = word1.concat (word2); – the same as word1 + word2  “rethink” 27
  • 28. String Concatenation – Combine Strings Now str has value “rethink”, how to make “rethinking”? String word3 = “ing”; Method 1: Plus “+” operator str = str + word3; //results in “rethinking” Method 2: Use String’s “concat” method str = str.concat(word3); //results in “rethinking” Method 3: Shorthand str += word3; //results in “rethinking” (same as method 1) 28
  • 29. String Concatenation: Strings, Numbers & Characters String myWord= “Rethinking”; int myInt=2; char myChar=‘!’; Method 1: Plus “+” operator 29 String result = myWord + myInt + myChar; //Results in “Rethinking2!” Internally: myInt & myChar converted to String objects
  • 30. String Concatenation: Strings, Numbers & Characters String myWord= “Rethinking”; int myInt=2; char myChar=‘!’; Method 2: Use String’s “concat” method 30 String strMyInt= String.valueOf(myInt); String strMyChar=String.valueOf(myChar); String result = myWord.concat(strMyInt).concat(strMyChar); //Results in “Rethinking2!”
  • 33. String Immutability • Strings in Java are immutable • Meaning: cannot change its value, once created 33 String str; str = “Java is Fun!”; str = “I hate Java!”; Did we change the value of “Java is Fun!” to “I hate Java!”?
  • 34. String Immutability 34 String str; str = “Java is Fun!”; str = “I hate Java!”; String Objects “Java is Fun!” “I hate Java!” str Local Variable Table Cannot insert or remove a value e.g. remove “Fun”
  • 35. String Immutability 35 String str; str = “Re”; str = str + “think”; //Rethink str = str + “ing”; // Rethinking String Objects “Re” “Rethink” str Local Variable Table “Rethinking” Every concat: Create new String object Unused objects: “Re”, “Rethink” go to garb. coll.
  • 36. String Immutability • Problem: With frequent modifications of Strings – Create many new objects – uses up memory – Destroy many unused ones – increase JVM workload – Overall: can slow down performance • Solution for frequently changing Strings: – StringBuilder Class instead of String 36
  • 37. StringBuilder Class • StringBuilders used for String concatenation • StringBuilder class is “mutable” Meaning: values within StringBuilder can be changed or modified as needed • In contrast to Strings where Strings are immutable 37
  • 38. StringBuilder - “append” method • append(X)  most used method – Appends a value X to end of StringBuilder – X: int, char, String, double, object (almost anything) 38
  • 39. sb Local Variable Table StringBuilder Object StringBuilder sb = new StringBuilder(); //obj creation sb.append(“Re”); //add “Re” to sb sb.append(“think”); //add “think” to sb sb.append(“ing”); //add “ing” to sb String str= sb.toString(); //return String value StringBuilder for String Construction 39 Rethinking • Only 1 object • All 3 words appended to same object Bottom-line: Use StringBuilder when you have frequent string modification
  • 41. Testing String Equality • How to check if two Strings contain same value? 41 String str1=new String(“Hello World!”); String str2=new String(“Hello World!”); if(str1==str2) { //eval to false System.out.println(“same”); } String Objects “Hello World!” “Hello World!” str1 Local Variable Table str2 if str1 referencing same object as str2?
  • 42. Testing String Equality • How to check if two Strings contain same value? 42 String str1=new String(“Hello World!”); String str2=new String(“Hello World!”); if(str1==str2) { //eval to false System.out.println(“same”); } if(str1.equals(str2)) { //eval to true System.out.println(“same”); } if content of str1 same as str2?
  • 43. Testing String Equality • What if “new” operator not used? 43 String str1 = “Hello World!”; String str2 = “Hello World!”; if(str1==str2) { //eval to true System.out.println(“same”); } String Objects “Hello World!”str1 Local Variable Table str2 if str1 referencing same object as str2?
  • 44. Testing String Equality • What if “new” operator not used? 44 String str1 = “Hello World!”; String str2 = “Hello World!”; if(str1==str2) { //eval to true System.out.println(“same”); } if(str1.equals(str2)) { //eval to true System.out.println(“same”); }
  • 45. Testing String Equality • Point to note: String variables are references to String objects (i.e. memory addresses) • “str1==str2” on String objects compares memory addresses, not the contents • Always use “str1.equals(str2)” to compare contents 45
  • 48. Wrapper Classes • Recall: primitive data types int, double, long are not objects • Wrapper classes: convert primitive types into objects – int: Integer wrapper class – double: Double wrapper class – char: Character wrapper class • 8 Wrapper classes: – Boolean, Byte, Character, Double, Float, Integer, Long, Short
  • 49. Wrapper Classes • Why are they nice to have? – Primitives have a limited set of in-built operations – Wrapper classes provide many common functions to work with primitives efficiently • How to convert a String “22”  int? – Cannot do this with primitive type int – Can use Integer wrapper class; Integer.parseInt(..) 49 String myStr = “22”; int myInt= Integer.parseInt(myStr);
  • 50. Wrapper Classes • Reverse: How to convert int 22  String? – Cannot do this with primitive int – Can use Integer wrapper class; Integer.toString(..) • Each Wrapper class has its own set of methods 50 int myInt= 22; String myStr= Integer.toString(myInt); // “22” String myStr2 = String.valueOf(myInt); // “22” equivalent
  • 51. Integer Wrapper Class Methods 51
  • 53. Double Wrapper Class Methods 53
  • 55. Review + Quiz (1) • What is the purpose of a String class? – String class holds a sequence of characters • Why use a String class vs. a char array? – String class has many built-in methods – Makes string manipulation easy • What are the 2 ways to create Strings? – new operator; String str=new String(“Hello World”); – direct assignment; String str=“Hello World”; 55
  • 56. Review + Quiz (2) • Can we directly modify String objects? – No, Strings are immutable by design – Once created cannot be changed in any way – Only the variable references are changed • For frequent modification of Strings should we use the String class? – No, use StringBuilder class instead of String class – String class creates many new objects for concatenation – slows things down 56
  • 57. Review + Quiz (3) • What are the different ways to concatenate Strings? - Use plus “+” operator or in-built “concat” method • When you use “==“ when comparing 2 String objects, what are you comparing? – comparing references (address in memory) • How do you compare contents of two String objects? – string1.equals(string2) 57
  • 58. Review + Quiz (4) • What are Wrapper classes and why do we need them? – convert primitive types into objects – provide many functions to work with primitives efficiently • What method do you use to convert a primitive int or double into a String representation? - Double.toString(doubleVal), Integer.toString(intVal) - String.valueOf(primitiveType) 58
  • 60. Take-Home Exercise & Code Samples • Go to https://bitbucket.org/kganes2/is4415/downloads • Download StringNetBeans.zip • Import Code into NetBeans 1. Select File -> Import Project -> From Zip 2. Select downloaded StringNetBeans.zip 3. You should see TestProject in NetBeans • Complete all tasks in StringExercise.java • Code samples in “examples” package 60
  • 61. 61 Example code run in class Take-home exercise
  • 65. 65