SlideShare a Scribd company logo
Java Strings
Using Strings in practice
Java String
• Character sequence
• Immutable
• Class defined in the java.lang package
• Instantiate a String Object:
• Using a String literal (series of characters enclosed in double quotes)
String s1 = “Cat”;
• Via the String constructor (see API for different constructors)
String s2 = new String(“Cat”);
Java String – Memory
• Output of the following code?
Java String – Memory
• Output of the following code?
s1 == s2 :true
s1 == s3 :false
Java String – Memory
• Java Memory Heap as a Java
Object
String s2 = new String(“Cat”);
• String pool in the Java Memory
Heap
• String interning
• Flyweight pattern
String s1 = “Cat”;
Java String – API
• Extends java.lang.Object
• E.g.: equals(other: Object) : boolean, hashCode() : int, …
• Implements: Serializable, CharSequence, Comparable<String>
• E.g.: compareTo(other: String) : int, charAt(index: int) : char, …
• String specific API
• E.g.: isEmpty() : boolean, …
StringBuilder
• Mutable
StringBuffer
• Mutable
• Thread-safe
• Slower
Java String – Formatting
• String.format
• Conversion specifiers: %d (decimal integer), %f (floating point), %c (any character), …
• Many more options (see documentation)
String fs;
fs = String.format("Variable 1 (%f) is of type float, while " +
"the 2nd variable (%d) is an integer, " +
"and the 3rd one, %s, is a string...",
floatVar, intVar, stringVar);
• Formatter class (java.util)
StringBuilder sbuf = new StringBuilder();
Formatter fmt = new Formatter(sbuf);
fmt.format("PI = %f%n", Math.PI);
System.out.print(sbuf.toString());
// you can continue to append data to sbuf here.
Use cases
• String instantiation
• String concatenation
• String duplication
• String manipulation
• …
=> Questions:
• Performance?
• Thread-safe?
• …
Use cases – Instantiation
• Benchmarking:
• String Object: new (with various constructors), literal
• StringBuffer constructor(s)
• StringBuilder constructor(s)
Use cases – Concatenation
• Benchmarking:
• String Object: Operator +, concat method
• StringBuffer append
• StringBuilder append
• …
Conclusion
• Creating Java String objects
• Concatenating strings
Discussion / Questions?
References
• Java String
• https://docs.oracle.com/javase/tutorial/java/data/strings.html
• Java String – Memory:
• https://www.journaldev.com/797/what-is-java-string-pool
• https://en.wikipedia.org/wiki/String_interning
• https://en.wikipedia.org/wiki/Flyweight_pattern
• https://www.javatpoint.com/how-to-optimize-java-string-creation
• Java String – API
• https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
References
• Java String - Formatting
• https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
• https://dzone.com/articles/java-string-format-examples
• StringBuilder
• StringBuffer

More Related Content

Similar to Java Strings - using Strings in practice (20)

Java R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdfJava R20 - UNIT-5.pdf
Java R20 - UNIT-5.pdf
Pamarthi Kumar
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
Łukasz Bałamut
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
String Handling
String HandlingString Handling
String Handling
Bharat17485
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
Pamarthi Kumar
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
Mario Camou Riveroll
 
DAY_1.3.pptx
DAY_1.3.pptxDAY_1.3.pptx
DAY_1.3.pptx
ishasharma835109
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Brian Hsu
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
Databricks
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
Brian Hsu
 
Text processing
Text processingText processing
Text processing
Icancode
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
Scala
ScalaScala
Scala
Sven Efftinge
 
Lecture 3.pptx
Lecture 3.pptxLecture 3.pptx
Lecture 3.pptx
ShehabEldinSaid
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
Santosh Rajan
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 
Java R20 - UNIT-5.docx
Java R20 - UNIT-5.docxJava R20 - UNIT-5.docx
Java R20 - UNIT-5.docx
Pamarthi Kumar
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
myrajendra
 
Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?Static or Dynamic Typing? Why not both?
Static or Dynamic Typing? Why not both?
Mario Camou Riveroll
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Brian Hsu
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.pptCharcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
Spark schema for free with David Szakallas
Spark schema for free with David SzakallasSpark schema for free with David Szakallas
Spark schema for free with David Szakallas
Databricks
 
Programming Android Application in Scala.
Programming Android Application in Scala.Programming Android Application in Scala.
Programming Android Application in Scala.
Brian Hsu
 
Text processing
Text processingText processing
Text processing
Icancode
 
In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...In the given example only one object will be created. Firstly JVM will not fi...
In the given example only one object will be created. Firstly JVM will not fi...
Indu32
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
allanh0526
 

Recently uploaded (20)

Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
The State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry ReportThe State of Web3 Industry- Industry Report
The State of Web3 Industry- Industry Report
Liveplex
 
Ad

Java Strings - using Strings in practice

  • 2. Java String • Character sequence • Immutable • Class defined in the java.lang package • Instantiate a String Object: • Using a String literal (series of characters enclosed in double quotes) String s1 = “Cat”; • Via the String constructor (see API for different constructors) String s2 = new String(“Cat”);
  • 3. Java String – Memory • Output of the following code?
  • 4. Java String – Memory • Output of the following code? s1 == s2 :true s1 == s3 :false
  • 5. Java String – Memory • Java Memory Heap as a Java Object String s2 = new String(“Cat”); • String pool in the Java Memory Heap • String interning • Flyweight pattern String s1 = “Cat”;
  • 6. Java String – API • Extends java.lang.Object • E.g.: equals(other: Object) : boolean, hashCode() : int, … • Implements: Serializable, CharSequence, Comparable<String> • E.g.: compareTo(other: String) : int, charAt(index: int) : char, … • String specific API • E.g.: isEmpty() : boolean, …
  • 9. Java String – Formatting • String.format • Conversion specifiers: %d (decimal integer), %f (floating point), %c (any character), … • Many more options (see documentation) String fs; fs = String.format("Variable 1 (%f) is of type float, while " + "the 2nd variable (%d) is an integer, " + "and the 3rd one, %s, is a string...", floatVar, intVar, stringVar); • Formatter class (java.util) StringBuilder sbuf = new StringBuilder(); Formatter fmt = new Formatter(sbuf); fmt.format("PI = %f%n", Math.PI); System.out.print(sbuf.toString()); // you can continue to append data to sbuf here.
  • 10. Use cases • String instantiation • String concatenation • String duplication • String manipulation • … => Questions: • Performance? • Thread-safe? • …
  • 11. Use cases – Instantiation • Benchmarking: • String Object: new (with various constructors), literal • StringBuffer constructor(s) • StringBuilder constructor(s)
  • 12. Use cases – Concatenation • Benchmarking: • String Object: Operator +, concat method • StringBuffer append • StringBuilder append • …
  • 13. Conclusion • Creating Java String objects • Concatenating strings
  • 15. References • Java String • https://docs.oracle.com/javase/tutorial/java/data/strings.html • Java String – Memory: • https://www.journaldev.com/797/what-is-java-string-pool • https://en.wikipedia.org/wiki/String_interning • https://en.wikipedia.org/wiki/Flyweight_pattern • https://www.javatpoint.com/how-to-optimize-java-string-creation • Java String – API • https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
  • 16. References • Java String - Formatting • https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html • https://dzone.com/articles/java-string-format-examples • StringBuilder • StringBuffer

Editor's Notes

  • #3: https://www.journaldev.com/1321/java-string-interview-questions-and-answers#java-string https://docs.oracle.com/javase/tutorial/java/data/strings.html
  • #6: When we create a String using double quotes, JVM looks in the String pool to find if any other String is stored with the same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool. When we use the new operator, JVM creates the String object but don’t store it into the String Pool. We can use intern() method to store the String object into String pool or return the reference if there is already a String with equal value present in the pool.
  • #7: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html char : charAt(int index) Returns the char value at the specified index. String : concat(String str) Concatenates the specified string to the end of this string. boolean : contains(CharSequence s) Returns true if and only if this string contains the specified sequence of char values. int : indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. String : intern() Returns a canonical representation for the string object. Boolean : isEmpty() Returns true if, and only if, length() is 0. …
  • #9: The string is immutable and final in Java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations – StringBuffer and StringBuilder. StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So in a multi-threaded environment, we should use StringBuffer but in the single-threaded environment, we should use StringBuilder. StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.