examples of String library class in java

0

the following contributions are examples of String class methods in java:

All Contributions

Write a Java program that asks the user to enter his name and prints the number of letters and the first letter in his name. 

import java.util.Scanner; 
public class Exercise3 
{ 
 public static void main(String[] args) { 
 Scanner console = new Scanner(System.in); 
System.out.print("What is your name? "); 
String name = console.next(); 
name = name.toUpperCase(); 
System.out.println(name + " has " + name.length() + 
 " letters and starts with " + name.substring(0, 1)); 
 } 
}

 Write a Java program to compare two strings lexicographically. Two strings are lexicographically equal if they are the same length and contain the same characters in the same positions.

public class Exercise2 { 
public static void main(String[] args) 
 { 
 String str1 = "This is Exercise 1"; 
 String str2 = "This is Exercise 2"; 
 
 System.out.println("String 1: " + str1); 
 System.out.println("String 2: " + str2); 
 
 // Compare the two strings. 
 int result = str1.compareTo(str2); 
 // Display the results of the comparison. 
 if (result < 0) 
 { 
 System.out.println(""" + str1 + """ + 
 " is less than " + 
 """ + str2 + """); 
 } 
 else if (result == 0) 
 { 
 System.out.println(""" + str1 + """ + 
 " is equal to " + 
 """ + str2 + """); 
 } 
 else // if (result > 0) 
 { 
 System.out.println(""" + str1 + """ + 
 " is greater than " + 
 """ + str2 + """); 
 } 
 } 
} 

Write a Java program to get the character at the given index within the considered string. 

public class Exercise1 { 
 public static void main(String[] args) 
 { 
 String str = "Java Exercises!"; 
 System.out.println("Original String = " + str); 
 // Get the character at positions 0 and 10. 
 int index1 = str.charAt(0); 
 int index2 = str.charAt(10); 
 // Print out the results. 
 System.out.println("The character at position 0 is " + 
 (char)index1); 
 System.out.println("The character at position 10 is " + 
 (char)index2); 
 } 
} 

 

total contributions (3)

New to examplegeek.com?

Join us