Java String Programs

As so far we were learned fundamental Java Programs, java inheritance programs etc.. in this post you will learn String programs in Java. These programs will ask in written Test and Technical round also. Before go to the Test you should brush up the following String Examples to get more confident.

1. Java Program to reverse a String

import java.util.Scanner;
public class StrRev{
    public static void main(String[] args){
    Scanner in=new Scanner(System.in);
    System.out.println("Enter the string to reverse: ");
    String str=in.nextLine();
    String reverse = new StringBuffer(str).reverse().toString();
    System.out.println("String after reverse:"+reverse);
    }
}
Output:

Javac StrRev.java
java StrRev
Enter the string to reverse: lucky
String after reverse: ykcul

2. Java Program to make first alphabet capital in each word of given String

import java.util.Scanner;
public class MakeCapitalFirstWordInLine
{
public static void main(String[] args)
{
// create object of scanner class.
Scanner in = new Scanner(System.in);
// enter sentence here
System.out.print("Enter sentence here : ");
String line = in.nextLine();
String upper_case_line = "";
// this is for the new line which is generated after conversion.
Scanner lineScan = new Scanner(line);
while(lineScan.hasNext())
{
String word = lineScan.next();
upper_case_line += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
}
// print original line with output.
System.out.println("Original sentence is : " +line);
System.out.println("Sentence after convert : " +upper_case_line.trim());
}
}

Output:
Enter Sentence here: welcome to coding2world
Original Sentence here: welcome to coding2world
Sentence after convert: Welcome To Coding2world

3.Java Program to String comparison 

import java.util.Scanner;

class StringComparison{
public static void main(String args[]){
String str1, str2;
Scanner in = new Scanner(System.in);
System.out.println("Enter first string");
str1 = in.nextLine();
System.out.println("Enter second string");
str2 = in.nextLine();
if ( str1.compareTo(str2) > 0 ){
System.out.println("First string is greater");
}
else if ( str1.compareTo(str2) < 0 ){
System.out.println("First string is smaller");
}
else{
System.out.println("The strings are equal");// Strings are compared based on the length of the strings.
}
}
}
Output:

Enter first string
javacoding
Enter second string
java
First string is greater

4. Java Program to convert String to Array

import java.util.*;
  class StringToArrayList  { 
public static void main(String[] args)  { 
String[] words = {"hai", "ram", "hello", "lakshman", "anji"}; 
List list = Arrays.asList(words); 
System.out.println("As a list:");
for (String e : list) 

System.out.println(""+e); 


}
Output:
As a list:
hai
ram
hello
lakshman
anji

5. Java Program to find the Occurrence of each character
import java.io.*;
import java.util.Scanner;
public class FindDuplicateChar
{
public static void main(String[] args) throws IOException
{
// create object of the string.
String S;
Scanner scan = new Scanner (System.in);
// enter your statement here.
System.out.print("Enter the Statement : ");
// will read statement and store it in "S" for further process.
S = scan.nextLine();
int count=0,len=0;
do

try
{
// this loop will identify character and find how many times it occurs.
char name[]=S.toCharArray();
len=name.length;
count=0;
for(int j=0;j<len;j++)
{
// use ASCII codes for searching.
if((name[0]==name[j])&&((name[0]>=65&&name[0]<=91)||(name[0]>=97&&name[0]<=123)))
count++;
}
if(count!=0){
// print all the repeated characters.
System.out.println(name[0]+" "+count+" Times");
}
S=S.replace(""+name[0],"");         
}
catch(Exception e)
{
System.out.println(e);
}
}
while(len!=1);
}
}

Output:
First run:
Enter the statement: I love coding
i 1 times
l 2 times
o 3 times
v 4 times
e 5 times
c 6 times
o 7 times
v 8 times
e 9 times
 Second run:
Enter the statement: miss you
m 1 times
i  2 times
s  3 times
s  4 times
y  5 times
o 6  times
u  7 times

6. Java program to count the no of words in given String

import java.util.Scanner;

public class CountWordsInString {
   
    /**
     * Method to count no. of words in provided String
     * @param inputString
     * @return
     */
 static int countWords(String inputString){
 String[] strarray = inputString.split(" ");  // Spilt String by Space
 StringBuilder sb = new StringBuilder();
 int count=0;
 for(String s:strarray){
 if(!s.equals("")){
 count++;
 }   
 }
 return  count;
 }
 public static void main(String[] args) {
 Scanner sc = new Scanner(System.in);
 System.out.println("Enter String : ");
 String str = sc.nextLine();
 System.out.println("No. of Words in String : "+countWords(str));
}
}
Output:
Enter String: welcome to coding2world
no of words in String: 4

 7.Java Program to check the given String Palindrome or not

import java.util.Scanner;
public class PalindromString {
static boolean isPalindromString(String inputStr){
StringBuilder sb  = new StringBuilder(inputStr);
String reverseStr = sb.reverse().toString();
return (inputStr.equalsIgnoreCase(reverseStr));             
}
   
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String : ");
String inString = sc.next();
if(isPalindromString(inString)){
System.out.println(inString +" is a Palindrom String");
}
else{
System.out.println(inString +" is not a Palindrom String");
}
}
}
Output:
Enter String: lucky
lucky is not a palindrom string

Enter String: madam
madam is a palindrom String

8. Java Program to reverse a String without using StringBuffer.reverse() method

import java.util.*;
class ReverseString
{
public static void main(String args[])
{
//declaring string objects
String str="",revStr="";
Scanner in = new Scanner(System.in);
//input string
System.out.print("Enter a string :");
str= in.nextLine();
//get length of the input string
int len= str.length();
//code to reverse string
for ( int i = len- 1 ; i >= 0 ; i-- )
revStr= revStr+ str.charAt(i);
//print reversed string
System.out.println("Reverse String is: "+revStr);
}
}
Output:
Enter a String: program
Reverse String is:margorp

9. Java SubString Example

public class JavaSubstringExample{
public static void main(String args[]){
String name="Hello World";
System.out.println(name.substring(0,5));
}
}

OUTPUT:
World
Hello









No comments:

Post a Comment

Basics of CPP Programs

In this post you will learn fundamental C++ programs. These programs for freshers or beginners. 1 .write a cpp program to display hello w...