SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Generics in java
Generics in javaGenerics in java
Generics in java
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Java String
Java StringJava String
Java String
 
Basic i/o & file handling in java
Basic i/o & file handling in javaBasic i/o & file handling in java
Basic i/o & file handling in java
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
String Handling
String HandlingString Handling
String Handling
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java program structure
Java program structureJava program structure
Java program structure
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Data Types, Variables, and Operators
Data Types, Variables, and OperatorsData Types, Variables, and Operators
Data Types, Variables, and Operators
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
 
Java input
Java inputJava input
Java input
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 

Ähnlich wie 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
 

Ähnlich wie 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)
 

Mehr von 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
 

Mehr von 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)
 

Kürzlich hochgeladen

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Kürzlich hochgeladen (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

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