0% found this document useful (0 votes)
47 views43 pages

Java String Basics and Operations Guide

soft skill material includes different topics related to basic programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views43 pages

Java String Basics and Operations Guide

soft skill material includes different topics related to basic programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Java

Strings
Strings

• Sequence of characters and not a primitive data type


• Example: Hello
• In java, strings are objects.
• The class “String” comes under java.lang package.
• Internally string is implemented as a character array.
• E.g:
H e l l 0
How to create a string?

Two ways to create a string:


1) String literal
2) Using new keyword
String literal:
String str = “Hello”
Using new Keyword:
String s = new String(“Hello”)
// Predict the output

class Main{
public static void main(String args[]){
String str = "Programming";
String s = new String("World");
System.out.println(str);
System.out.println(s);
}
}
String Literal - String str = “Hello”

How it is working in the backend?


String str1 = “Hello”
Hello
str

String objects are stored in a


special memory area known
as the "string constant pool".
String pool

Heap
String Literal - String str = “Hello”

How it is working in the backend?

Hello
str

str1

String pool

Heap
If we create an object using String literal. It may return an existing object from the
String pool, if it already exists.
Otherwise, it will create a new String object and put in the string pool for future
re-use.

The same reference will be assigned to str and str1.

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it
exists already in the string constant pool).
String Literal - String str = “Hello”

How it is working in the backend?

Hello
str

str1

s
String pool

Heap
new - String s = new String(“Hello”)

How it is working in the backend?

Hello
str

str1

s Hello
String pool

Heap
new - String s = new String(“Hello”)

new - String s = new String(“Hello”)


In such case, JVM will create a new string object in heap memory, and the literal
“Hello" will be placed in the string constant pool.
The variable “s” will refer to the object in a heap.

Therefore, if we compare performance of string literal and string object, string


object will always take more time to execute than string literal because it will
construct a new string every time it is executed.
Note: Execution time is compiler dependent.
// Predict the output of the below code

class Main{
public static void main(String args[]){
String str = "Hello";
String str1 = "Hello";
String str2 = new String("Hello");
System.out.println(str == str1);
System.out.println(str == str2);
}
}
// Predict the output of the below code

class Main{
public static void main(String args[]){
String str1 = "Hello";
String str2 = "Hello";
String s1 = new String("Hello");
String s2 = new String("Hello");
System.out.println(str1 == str2);
System.out.println(str2 == s1);
System.out.println(s1 == s2);
}
}
// Predict the output of the below code

class Main{
public static void main(String args[]){
String s1 = new String("Noughat");
String s2 = new String("Noughat");
System.out.println(s1 == s2);
System.out.println(s1.equals(s2));
}
}
Question 1

Write a Java code to check whether the input string matches with the
word “Dhoni”

Sample Sample
Input: Output:
Kohli Not matching
// Solution
import java.util.Scanner;
class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String str = "Dhoni";
String s = in.next();
if(str.equals(s)){
System.out.print("Matching");
}
else{
System.out.print("Not matching");
}
}
}
The length() method

● The java String length() method returns the length of the string
● The length of the string will be an integer
// Predict the output of the below code

class Main{
public static void main(String args[]){
String str = "Programming";
System.out.println(str.length());
String s = "Let's continue";
System.out.println(s.length());
}
}

11
14
The charAt() method

● The java String charAt() method returns a char value at the given
index number
● The index number starts from 0 and goes up to (n-1), where n is
length of the string.
// Predict the output of the below code
class Main{
public static void main(String args[]){
String str = "Java";
char ch = str.charAt(2);
System.out.println(ch);
System.out.println(str.charAt(3));
System.out.println(str.charAt(4));
System.out.println(str.charAt(-1));
}
} v
a
Error
The toUpperCase() method

● The java String toUpperCase() method converts all the lowercase


characters of a string into uppercase
● It will not alter the already existing uppercase characters in the
string.
● E.g: System.out.print(“You are on the right track”.toUpperCase());
● Output: YOU ARE ON THE RIGHT TRACK
The toLowerCase() method

● The java String toLowerCase() method converts all the uppercase


characters of a string into lowercase
● It will not alter the already existing lowercase characters in the
string.
● E.g: System.out.print(“YOU ARE ON THE RIGHT
TRACK”.toLowerCase());
● Output: you are on the right track
The concat() method

● The Java string concat() method allows you to join two strings.
● This method returns a string with the value of the string passed into
the method is appended to the end of the string.
● E.g:
● String s1 = "Nice ";
● String s2 = " Day";
● System.out.println(s1.concat(s2));
● Output: Nice Day
The concat() method

The Java string concat() method allows you to join two strings.
This method returns a string with the value of the string passed into
the method is appended to the end of the string.
E.g:
String s1 = "Nice ";
String s2 = " Day";
System.out.println(s1.concat(s2));
Output: Nice Day
+ operator

+ operator is also used to concatenate strings


E.g:
System.out.println("You " + "are " + "the " + "best");
Output:
You are the best
// Predict the output

class Main{
public static void main(String[] args) {
String s = "Are", t = "you", u = "ready";
System.out.println(s + t + u);
System.out.println(s.concat(t));
}
}
Output:
Areyouready
Areyou

Number of arguments the concat() method and + operator takes:


concat() method takes only one argument of string and concatenate it with other
string.
+ operator takes any number of arguments and concatenates all the strings.
// Predict the output
class Main{
public static void main(String args[]){
String s = 50 + 50 + "error" + 50 + 50;
System.out.println(s);
}
}
Output:
100error5050

After a string literal, all the + will be treated as string concatenation operator.
// Predict the output
class Main{
public static void main(String args[]){
String s = "Apple";
int a = 10;
System.out.println(s + a);
System.out.println(s.concat(a));
}
}
Output:
Error
prog.java:6: error: incompatible types: int cannot be converted to String
System.out.println(s.concat(a));

● Number of arguments the concat() method and + operator takes:


● concat() method takes only one argument of string and concatenate it with
other string.
● + operator takes any number of arguments and concatenates all the strings.
// Predict the output
class Main{
public static void main(String args[]){
String s = "Apple";
String r = null;
System.out.println(s + r);
System.out.println(s.concat(r));
}
}
Output:
Applenull
Exception in thread "main" java.lang.NullPointerException at java.lang.String.
concat(String.java:2027)
at Main.main(File.java:6)
● concat() method throws NullPointer Exception when string is concatenated
with null
● + operator did not raise any Exception when the string is concatenated with
null.
// Predict the output
class Main{
public static void main(String args[]){
String s = "Great", t = "";
String u = s.concat(t);
if(u == s){
System.out.println("Same"); }
else{
System.out.println("Not same"); }
String e = s + t;
if (e == s){
System.out.println("Same");
}
else{
System.out.println("Not same"); } } }
Output:
Same
Not same
● concat() method takes concatenates two strings and return new string object only
string length is greater than 0, otherwise it returns same object.
● + operator creates a new string object every time irrespective of length of string.
Which is better + operator or concat() method?
concat() method is better than + operator because it creates a new object only when the
string length is greater than zero(0) but + operator always a creates a new string
irrespective of length of string.
// Predict the output
class Main{
public static void main(String args[]){
String s = "Great", t = "H";
String u = s.concat(t);
if(u == s){
System.out.println("Same"); }
else{
System.out.println("Not same"); }
String e = s + t;
if (e == s){
System.out.println("Same");
}
else{
System.out.println("Not same"); } } }
Output:
Not Same
Not same
● concat() method takes concatenates two strings and return new string object only string length is
greater than 0, otherwise it returns same object.
● + operator creates a new string object every time irrespective of length of string.

Which is better + operator or concat() method?


concat() method is better than + operator because it creates a new object only when the string length
is greater than zero(0) but + operator always a creates a new string irrespective of length of string.
Question 2

● Write a Java program to accept two strings from user and perform
the following operations:
1) Find the length of both input strings
2) Concatenation of two strings
3) Convert the first string into uppercase

Sample Input: Sample Output:

Hello 5 10
Developers Hello Developers
HELLO
// Solution
import java.util.Scanner;
class Main{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
String str1 = in.nextLine();
String str2 = in.nextLine();
System.out.println(str1.length() + " " + str2.length());
System.out.println(str1.concat(str2));
System.out.print(str1.toUpperCase());
}}
Question 3

● Write a Java code to check whether the given string is palindrome or


not.
● If the given string is a palindrome, then print “Yes”. Otherwise, print
“No”.

Sample Input: Sample Output:

spacecaps Yes
// Solution
import java.util.Scanner;
class Main{
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
int str_len = str.length();
int end = str_len - 1;
int front = 0;
boolean is_palindrome = true;
while(front < end){
if(str.charAt(front) != str.charAt(end))
{
is_palindrome = false;
break;
}
front++;
end--; }
// Solution

if(is_palindrome == true){
System.out.println("Yes");
}
else{
System.out.println("No");
}
}
}
THANK YOU

You might also like