[Go to site: main page, start]

0% found this document useful (0 votes)
6 views8 pages

Module 1 10 Java StringOperations

The document provides an overview of string operations in Java, highlighting the differences between characters and strings, as well as methods for declaring, initializing, and manipulating strings. It also compares string handling in Java with C, discusses mutability with String, StringBuilder, and StringBuffer, and outlines common pitfalls when using the Scanner class. Additionally, it includes examples of palindrome checks, character frequency counting, and sorting names lexicographically.

Uploaded by

nagadhanush700
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views8 pages

Module 1 10 Java StringOperations

The document provides an overview of string operations in Java, highlighting the differences between characters and strings, as well as methods for declaring, initializing, and manipulating strings. It also compares string handling in Java with C, discusses mutability with String, StringBuilder, and StringBuffer, and outlines common pitfalls when using the Scanner class. Additionally, it includes examples of palindrome checks, character frequency counting, and sorting names lexicographically.

Uploaded by

nagadhanush700
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

STRING OPERATIONS

Java Programming

Java Programming — Course Module

CHARACTER vs STRING IN JAVA


Unlike C (null-terminated char array), Java strings are objects.

Declaration Description

char c = 'a'; 1 character, primitive type, stored in 2 bytes (UTF-16)

String s = "a"; Object on heap, contains 'a' + metadata, immutable

String s = new String("a"); Explicit heap object (avoids string pool)

■ In Java, String is immutable. Operations like concatenation create new String objects. Use StringBuilder for
mutable strings.

DECLARE AND INITIALISE STRINGS


String s1 = "Hello"; // string literal (uses pool)

String s2 = new String("Hello"); // new heap object

char[] ch = {'H','e','l','l','o'};

String s3 = new String(ch); // from char array

// char array approach (like C)

char[] arr = new char[6];

arr[0]='H'; arr[1]='e'; arr[2]='l';

arr[3]='l'; arr[4]='o'; arr[5]='\0'; // '\0' not needed in Java

READ A STRING

Method Behaviour C Equivalent

[Link]() Reads one token (stops at whitespace) Like scanf("%s",str)


[Link]() Reads entire line including spaces Like fgets()

[Link]().charAt(0) Reads single character Like getchar()

[Link]() Reads raw byte Low-level (avoid)

import [Link];

Scanner sc = new Scanner([Link]);

String s1 = [Link](); // reads word

[Link](); // consume leftover newline

String s2 = [Link](); // reads full line

[Link](s1);

[Link](s2);
STRING METHODS — [Link]

Method Returns Description

[Link]() int Number of characters (no null term needed)

[Link](i) char Character at index i

[Link](ch) int First occurrence of ch (or substring)

[Link](ch) int Last occurrence of ch

[Link](i,j) String Chars from i to j-1

[Link]() String All lowercase

[Link]() String All uppercase

[Link]() String Remove leading/trailing whitespace

[Link](a,b) String Replace all a with b

[Link](sub) boolean True if sub is present

[Link](p) boolean True if starts with p

[Link](p) boolean True if ends with p

[Link](t) boolean True if equal (case-sensitive)

[Link](t) boolean True if equal ignoring case

[Link](t) int Lexicographic comparison (like strcmp)

[Link](t) String Append t (like strcat)

[Link](regex) String[] Split by pattern

[Link]() char[] Convert to char array

[Link](n) String Convert int/double to String

[Link](s) int Convert String to int

C vs JAVA — QUICK REFERENCE

C Function Java Equivalent

strlen(s) [Link]()

dst = src (Strings are immutable; assignment is


strcpy(dst,src) fine)

strcat(s1,s2) s1 + s2 or [Link](s2)

strcmp(s1,s2) [Link](s2)

strncmp(s1,s2,n) [Link](0,n).compareTo([Link](0,n))

strchr(s,c) [Link](c)
strstr(s1,s2) [Link](s2)

strrev(s) new StringBuilder(s).reverse().toString()

strlwr/strupr [Link]() / [Link]()

sprintf(buf,...) [Link]("...",...)
String vs StringBuilder vs StringBuffer

Class Mutability Thread Safety Performance Use When

String Immutable Thread-safe Slow for repeated concat General use

Fast for repeated Single-thread


StringBuilder Mutable Not thread-safe concat loops

StringBuffer Mutable Thread-safe Moderate speed Multi-thread

StringBuilder sb = new StringBuilder();

for (int i = 0; i < 5; i++) [Link](i).append(" ");

[Link]([Link]()); // 0 1 2 3 4

[Link](0, "Numbers: ");

[Link](0, 9);

[Link]();

[Link](sb);

PALINDROME CHECK
// Method 1 — two pointers // Method 2 — StringBuilder

static boolean isPalin(String s){ static boolean isPalin(String s){

int i=0, j=[Link]()-1; String rev = new StringBuilder(s)

while(i<j){ .reverse().toString();

if([Link](i)!=[Link](j)) return [Link](rev);

return false; }

i++; j--;

return true;

CHARACTER CLASS — [Link]

Method Returns true if C Equivalent

[Link](c) Alphabetic? Like isalpha(c)

[Link](c) Digit 0-9? Like isdigit(c)

[Link](c) Letter or digit? Like isalnum(c)

[Link](c) Lowercase? Like islower(c)

[Link](c) Uppercase? Like isupper(c)

[Link](c) Space/tab/newline? Like isspace(c)

[Link](c) To lowercase Like tolower(c)


[Link](c) To uppercase Like toupper(c)

[Link](c) Digit value —

FREQUENCY OF EACH CHARACTER


String str = "programming";

int[] freq = new int[26];

for (char c : [Link]())

if ([Link](c))

freq[[Link](c) - 'a']++;

for (int i = 0; i < 26; i++)

if (freq[i] > 0)

[Link]("%c : %d%n", (char)('a'+i), freq[i]);

SORTING NAMES LEXICOGRAPHICALLY


// Manual bubble sort // Using [Link] (recommended)

String[] names = {"Bob","Alice","Charlie"}; import [Link];

int n = [Link]; String[] names = {"Bob","Alice","Charlie"};

for(int i=0;i<n-1;i++) [Link](names);

for(int j=0;j<n-1-i;j++) // Case-insensitive:

if(names[j].compareTo(names[j+1])>0){ [Link](names,

String t=names[j]; String.CASE_INSENSITIVE_ORDER);

names[j]=names[j+1]; for(String nm : names)

names[j+1]=t; [Link](nm);

}
PATTERN PRINTING WITH STRINGS
public class Pattern {

public static void main(String[] args) {

String str = "JavaProgramming";

int len = [Link]();

// Expanding triangle

for (int c = 1; c <= len; c++)

[Link]([Link](0, c));

// Shrinking triangle

for (int c = len; c >= 1; c--)

[Link]([Link](0, c));

COMMON SCANNER PITFALLS

When mixing nextInt() and nextLine(), the newline left in the buffer will be consumed by the next nextLine() call,
giving an empty string. Always call [Link]() after [Link]() to flush the buffer.

Scanner sc = new Scanner([Link]);

int n = [Link]();

[Link](); // flush leftover newline

String[] names = new String[n];

for (int i = 0; i < n; i++)

names[i] = [Link](); // now reads correctly

STRING IMMUTABILITY — KEY RULE


String s = "Hello";

[Link](); // returns new String — s unchanged!

[Link](s); // still "Hello"

// Correct:

s = [Link]();

[Link](s); // "HELLO"

Every String method that 'modifies' text actually returns a new String. Always assign the result back: s =
[Link]();

PRACTICE QUESTIONS
# Task

1 Check anagram

2 Count vowels and consonants

3 Reverse words in a sentence

4 Remove duplicate characters

5 Find longest word in a sentence

You might also like