0% found this document useful (0 votes)
4 views22 pages

strings in java

The document provides an overview of Java Strings, StringBuffer, and StringBuilder, highlighting their characteristics and use cases. It explains various string operations such as finding length, concatenation, and checking for anagrams, along with examples of Java code. Additionally, it includes a password validation program that checks for specific criteria to determine if a password is valid.

Uploaded by

mirshakishok
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)
4 views22 pages

strings in java

The document provides an overview of Java Strings, StringBuffer, and StringBuilder, highlighting their characteristics and use cases. It explains various string operations such as finding length, concatenation, and checking for anagrams, along with examples of Java code. Additionally, it includes a password validation program that checks for specific criteria to determine if a password is valid.

Uploaded by

mirshakishok
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
You are on page 1/ 22

Java Strings

• It is a sequence of characters. In Java, objects of String


are immutable which means a constant and cannot be
changed once created.

• String is an immutable class which means a constant


and cannot be changed once created and if wish to
change , we need to create an new object and even the
functionality it provides like toupper, tolower, etc all
these return a new object , its not modify the original
object. It is automatically thread safe.
StringBuffer

• StringBuffer is a peer class of String, it is mutable in nature and it is thread


safe class , we can use it when we have multi threaded environment and
shared object of string buffer i.e, used by mutiple thread. As it is thread
safe so there is extra overhead, so it is mainly used for multithreaded
program.

• Syntax:

• StringBuffer demoString = new StringBuffer(“RAMKUMAR");


StringBuilder

• StringBuilder in Java represents an alternative to String and


StringBuffer Class, as it creates a mutable sequence of characters and
it is not thread safe. It is used only within the thread , so there is no
extra overhead , so it is mainly used for single threaded program.

• Syntax:

• StringBuilder demoString = new StringBuilder();


demoString.append("GFG");
• Strings are used for storing text.
• A String variable contains a collection of characters surrounded by
double quotes
Example
Create a variable of type String and assign it a value:

• String greeting = "Hello";


String Length

• A String in Java is actually an object, which contain methods that can


perform certain operations on strings. For example, the length of a string
can be found with the length() method
• Example
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
• There are many string methods available, for example toUpperCase()
More String Methods

and toLowerCase():

• Example
• String txt = "Hello World";
• System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
• System.out.println(txt.toLowerCase()); // Outputs "hello world"
Finding a Character in a String

• The indexOf() method returns the index (the position) of the first
occurrencExample
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
String Concatenation

• The + operator can be used between strings to combine them.


• Example
String firstName = “Ram";
String lastName = “Kumar";
System.out.println(firstName + " " + lastName);
Note that we have added an empty text (" ") to create a space between
firstName and lastName on print.

• use the concat() method to concatenate two strings:

• Example
String firstName = “Ram ";
String lastName = “Kumar";
System.out.println(firstName.concat(lastName));
Adding Numbers and Strings

• Java uses the + operator for both addition and concatenation.


• Numbers are addIf you add two numbers, the result will be a number:
• Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)ed. Strings are concatenated.

If you add two strings, the result will be a string concatenation:

Example
String x = "10";
String y = "20";
String z = x + y; // z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:
Example
String x = "10";
int y = 20;
Special Characters

• The backslash (\) escape character turns special characters into string
characters:
• Escape character Result Description
• \’ ‘ Single quote
• \" " Double quote
• \\ \ Backslash
• Other characters
• Code Result
• \n New Line
• \r Carriage Return
• \t Tab
• \b Backspace
• \f Form Feed
print Even length words in a String

// Java program to print


// even length words in a string

class One
{
public static void printWords(String s)
{
for (String w : s.split(" ")){
// if length is even
if (w.length() % 2 == 0)
System.out.println(w);
}
}

public static void main(String[] args)


{
String s = "i am Ramkumar";
printWords(s);
}
}
Explanation of the above
Program
• Take the string
• Break the string into words with the help of
split() method in String class. It takes the string by which
the sentence is to be broken. So here " "(space) is
passed as the parameter. As a result, the words of the
string are split and returned as a string array
• Traverse each word in the string array returned with the
help of Foreach loop in Java.
• Calculate the length of each word using function.
• If the length is even, then print the word.
To Check Whether Two Strings Are Anagram

• Write a function to check whether two given strings are anagrams of each other or not. An anagram
of a string is another string that contains the same characters, only the order of characters can be
different.
For example, "abcd" and "dabc" are an anagram of each other
// Java program to check whether two strings
// are anagrams of each other
import java.io.*;
import java.util.Arrays;
import java.util.Collections;

class GFG {
// Function to check whether two strings
// are anagram of each other
static boolean areAnagram(char[] str1, char[] str2)
{
// Get lengths of both strings
int n1 = str1.length;
int n2 = str2.length;
// If length of both strings is not
// same, then they cannot be anagram
if (n1 != n2)
return false;

// Sort both strings


Arrays.sort(str1);
Arrays.sort(str2);

// Compare sorted strings


for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;

return true;
}
// Driver Code
public static void main(String args[])
{
char str1[] = { 't', 'e', 's', 't' };
char str2[] = { 't', 't', 'e', 'w' };

// Function Call
if (areAnagram(str1, str2))
System.out.println("The two strings are"
+ " anagram of each other");
else
System.out.println("The two strings are not"
+ " anagram of each other");
}
}
Add Characters to a String

At the end
One can add character at the start of String using the '+' operator.
// Java Program to Add Characters to a String
// At the End

// Importing input output classes


import java.io.*;

// Main class
public class GFG {

// Main driver method


public static void main(String args[])
{

// Input character and string


char a = 's';
String str = “RamkumarRajesh";

// Inserting at the end


String str2 = str + a;
// Print and display the above string
System.out.println(str2);
}
Compare two Strings

• Comparing strings is the most common task in different scenarios such as input validation or searching algorithms.
• To compare strings mainly used method is equals().This method compares the content of two strings. == refrence
address of two strings.

• // Java Program to compare two strings


// using equals() method
public class CompareStrings {

public static void main(String[] args) {

String s1 = “Ram";
String s2 = “Kumar";
String s3 = “Ram";

// Comparing strings
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
}
}
Scenario: Password Validator

Write a Java program that checks whether a given password is valid or not based on the following rules:
•Password must be at least 8 characters long
•Must contain at least one uppercase letter
•Must contain at least one lowercase letter
•Must contain at least one digit
•Must contain at least one special character (e.g. @#$%^&+=!)
Password Validator

import java.util.Scanner;

public class PasswordValidator {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Step 1: Take password input


System.out.print("Enter a password: ");
String password = scanner.nextLine();
// Step 2: Validate password using custom function
if (isValidPassword(password)) {
System.out.println("Password is valid ✅");
} else {
System.out.println("Password is INVALID ❌");
}

scanner.close();
}
// Step 3: Define function to validate password
public static boolean isValidPassword(String password) {
if (password.length() < 8)
return false;

boolean hasUpper = false;


boolean hasLower = false;
boolean hasDigit = false;
boolean hasSpecial = false;
// Step 4: Check each character in the string
for (char ch : password.toCharArray()) {
if (Character.isUpperCase(ch)) hasUpper = true;
else if (Character.isLowerCase(ch)) hasLower = true;
else if (Character.isDigit(ch)) hasDigit = true;
else if ("@#$%^&+=!".contains(String.valueOf(ch))) hasSpecial = true;
}

// Step 5: Return true if all conditions are met


return hasUpper && hasLower && hasDigit && hasSpecial;
}
Explanation
• Take input using Scanner
• Call a function to validate the password
• Use flags to check if conditions are satisfied
• Iterate through each character in the password
• Use Character.isUpperCase() etc. to check types
• Return true only if all required conditions are met

You might also like