String in java
Last Updated on : 28th Nov 2024 15:48:46 PM
- CharAt():
The Java String class charAt() method returns a char value at the given index number.
The index number starts from 0 and goes to n-1, where n is the length of the string. It returns StringIndexOutOfBoundsException, if the given index number is greater than or equal to this string length or a negative number.
Example:
public class Student {
public static void main(String[] args) {
String s = new String("aaru");
System.out.println(s.charAt(2));
}
}
Example 2 :
Frequency of char
public class Student {
public static void main(String[] args) {
String str = "sandip kumar jaiswal";
int count = 0;
for (int i=0; i<=str.length()-1; i++) {
if(str.charAt(i) == 'a') {
count++;
}
}
System.out.println("Frequency of a is: "+count);
}
}
2. Length(): it return lenght of string.
public class Student {
public static void main(String[] args) {
String str = "sandip kumar jaiswal";
int strlen=str.length();
System.out.println("length of string is "+strlen);
}
}
Example 2
public class Student {
public static void main(String[] args) {
String str = "sandip kumar jaiswal";
if(str.length()>0) {
System.out.println("String is not empty and length is: "+str.length());
}
str = "";
if(str.length()==0) {
System.out.println("String is empty now: "+str.length());
}
}
}
Output :
String is not empty and length is: 10
String is empty now: 0
3.equals()
The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.
true if characters of both strings are equal otherwise false.
public class Student {
public static void main(String[] args) {
String s1="sandip";
String s2="sandip";
String s3="SANDIP";
String s4="aarti";
System.out.println(s1.equals(s2));//true because content and case is same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}
}
Example 2:
public class Student {
public static void main(String[] args) {
String s1="sandip";
String s2="sandip";
String s3="sandip";
System.out.println(s1.equals(s2)); // True because content is same
if (s1.equals(s3)) {
System.out.println("both strings are equal");
}else System.out.println("both strings are unequal");
}
}
4. Concate():
The Java String class concat() method combines specified string at the end of this string. It returns a combined string. It is like appending another string.
public class Student {
public static void main(String[] args) {
String s1="java string";
// The string s1 does not get changed, even though it is invoking the method
// concat(), as it is immutable. Therefore, the explicit assignment is required here.
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}
}
5. Replace()
The Java String class replace() method returns a string replacing all the old char or CharSequence to new char or CharSequence.
public class Student {
public static void main(String[] args) {
String s1="androidsikho is a very good website";
// String replaceString=s1.replace("a","e");//replaces all occurrences of "a" to "e"
String replaceString=s1.replace("good","best");//replaces all occurrences of "a" to "e"
System.out.println(replaceString);
}
}
Method overloading
public class ShoppingCart {
// Method to add items to the cart
public void addItem(String itemName)
{
// Logic to add a single item to the cart.
System.out.println(itemName + " added to the cart.");
}
// Overloaded method to add items with quantity.
public void addItem(String itemName, int quantity)
{
// Logic to add multiple items with a specific quantity to the cart.
System.out.println(quantity + " " + itemName + "s added to the cart.");
}
// Overloaded method to add items with quantity and price.
public void addItem(String itemName, int quantity, double price)
{
// Logic to add items with quantity and price to the cart.
double totalCost = quantity * price;
System.out.println(quantity + " " + itemName + "s added to the cart. Total cost: $" + totalCost);
}
public static void main(String[] args)
{
// Creating an instance of class shoppingCart.
ShoppingCart cart = new ShoppingCart();
// Calling methods by passing argument values.
cart.addItem("T-shirt");
cart.addItem("Shoes", 2);
cart.addItem("Sunglasses", 3, 25.99);
}
}
Output: T-shirt added to the cart. 2 Shoes added to the cart. 3 Sunglasses added to the cart. Total cost: $77.97
Example : 2 Method Overloading :
class MathOperations {
// Method overloading for integer addition
public int add(int a, int b) {
return a + b;
}
// Method overloading for double addition
public double add(double a, double b) {
return a + b;
}
// Method for string concatenation
public String concatenate(String a, String b) {
return a + b;
}
// Method for array sum
public int add(int[] numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
// More methods...
}
public class Demo {
public static void main(String[] args) {
MathOperations m = new MathOperations();
int num[] = { 3, 4, 54, 6, 7 };
int r = m.add(num);
System.out.println(r);
}
}
Method Overriding :
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
}
class Horse extends Animal {
void makeSound() {
System.out.println("Neigh");
}
}
class Bird extends Animal {
void makeSound() {
System.out.println("Chirp");
}
}
public class Demo {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
Animal horse = new Horse();
Animal bird = new Bird();
dog.makeSound(); // Output: Bark
cat.makeSound(); // Output: Meow
horse.makeSound(); // Output: Neigh
bird.makeSound(); // Output: Chirp
}
}
abstraction example
// Java Program to implement
// Java Abstraction
// Abstract Class declared
abstract class Animal {
private String name;
public Animal(String name) { this.name = name; }
public abstract void makeSound();
public String getName() { return name; }
}
// Abstracted class
class Dog extends Animal {
public Dog(String name) { super(name); }
public void makeSound()
{
System.out.println(getName() + " barks");
}
}
// Abstracted class
class Cat extends Animal {
public Cat(String name) { super(name); }
public void makeSound()
{
System.out.println(getName() + " meows");
}
}
// Driver Class
public class Demo {
// Main Function
public static void main(String[] args)
{
Animal myDog = new Dog("Buddy");
Animal myCat = new Cat("Fluffy");
myDog.makeSound();
myCat.makeSound();
}
}