[Go to site: main page, start]

0% found this document useful (0 votes)
12 views6 pages

Java String and Array Operations Guide

Uploaded by

Nitin Gorde
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)
12 views6 pages

Java String and Array Operations Guide

Uploaded by

Nitin Gorde
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

//Program to count number of words in a string.

public class CountWords {

public static void main(String[] args) {


Scanner sc=new Scanner([Link]);
String s;
[Link]("Enter a string");
s=[Link]();
String name[]=[Link]("\\s");//to split string at spaces
[Link]("No. of words :"+[Link]);
}

//Program to print initials of a name

public class PrintInitials {

public static void main(String[] args) {


Scanner sc=new Scanner([Link]);
String s;
[Link]("Enter full name");
s=[Link]();
String name[]=[Link]("\\s");
for(String r:name)
{
[Link]([Link](0)+".");
}
}

//Program to count number of alphabets, numbers and special symbols in a string

public class AlphabetNumberCount {


public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
String s;
char c;
int ac=0,nc=0,sct=0;
[Link]("Enter a string");
s=[Link]();
for(int i=0;i<[Link]();i++)
{
c=[Link](i);
if([Link](c))
ac++;
else if([Link](c))
nc++;
else
sct++;

}
[Link]("Number of alphabets :"+ac);
[Link]("Number of digits :"+nc);
[Link]("Number of special characters :"+sct);
}
}

//Program to find second minimum element in array

public class SecondMin {


public static void main(String[] args) {
int ar[]=new int[5];
int i,min2;
Scanner sc=new Scanner([Link]);
[Link]("Enter 5 ele");
for( i=0;i<5;i++)
ar[i]=[Link]();

int min=ar[0];//Integer.MAX_VALUE;
min2=ar[0];//Integer.MAX_VALUE;
for( i=1;i<5;i++)
{

if(ar[i]<min)
{
min2=min;
min=ar[i];

}
else if((ar[i]< min2)|| (min==min2))
min2=ar[i];

}
[Link]("min :"+min);
[Link]("second min ele :"+min2);
}

//Program to count number of lines,words and characters in a file

public class CharCount {


public static void main(String[] args)
{
BufferedReader reader = null;

//Initializing charCount, wordCount and lineCount to 0

int charCount = 0;

int wordCount = 0;

int lineCount = 0;

try
{
//Creating BufferedReader object

reader = new BufferedReader(new FileReader("e:/[Link]"));

//Reading the first line into currentLine

String currentLine = [Link]();

while (currentLine != null)


{
//Updating the lineCount

lineCount++;

//Getting number of words in currentLine

String[] words = [Link](" ");

//Updating the wordCount

wordCount = wordCount + [Link];

//Iterating each word

for (String word : words)


{
//Updating the charCount

charCount = charCount + [Link]();


}

//Reading next line into currentLine

currentLine = [Link]();
}

//Printing charCount, wordCount and lineCount

[Link]("Number Of Chars In A File : "+charCount);

[Link]("Number Of Words In A File : "+wordCount);

[Link]("Number Of Lines In A File : "+lineCount);


}
catch (IOException e)
{
[Link]();
}
finally
{
try
{
[Link](); //Closing the reader
}
catch (IOException e)
{
[Link]();
}
}
}
}

//Program to search a word in a file

public class WordSearch {


public static void main(String[] args) throws Exception {
Scanner sc=new Scanner([Link]);

String str,a;
boolean b=false;
//File file = new File("e:/[Link]");
FileReader file = new FileReader("e:/[Link]");
Scanner s=new Scanner(file);
[Link]("enter string to be searched");
str=[Link]();
while([Link]())
{
if([Link]([Link]()))
{
[Link]( str +" is present in file");
b=true;
break;
}
}
if(b==false)
[Link]( str +" not present in file");

//Program to convert an array to ArrayList

public class ArrayToList {


public static void main(String[] args) {
Integer ar[]={10,29,30,20};//array should be of class type ,not of primitive type
ArrayList<Integer> al=new ArrayList<Integer>();
[Link](al,ar);
[Link](al);
[Link](27);
[Link](al);

String[] geeks = {"Rahul", "Utkarsh",


"Shubham", "Neelam"};

List<String> al2 = new ArrayList<String>();

// adding elements of array to arrayList.


[Link](al2, geeks);

[Link](al2);

}
}

//Program to convert ArrayList to an array

public class ListToArray {

public static void main(String[] args) {


ArrayList<Integer> al=new ArrayList<Integer>();
[Link](12);
[Link](23);
[Link](34);

//Method 1
Object ar[]=[Link]();
for(Object r:ar)
[Link](r);

//Method 2
Integer arr[]=new Integer[5];
[Link](arr);
for(Integer r:arr)
[Link](r);

arr[3]=23;
arr[4]=90;
for(Integer r:arr)
[Link](r);

//Program to convert ArrayList to Set to remove duplicates

public class ListToSet {

public static void main(String[] args) {


ArrayList< Integer> al=new ArrayList<>();

[Link](12);
[Link](23);
[Link](22);
[Link](11);
[Link](12);
[Link]("ArrayList :"+al);
LinkedHashSet<Integer> hs=new LinkedHashSet<Integer>(al);
[Link]("Set :"+hs);

}
//Program for substring
public class subString {
public static void main(String[] args) {
String s1="welcome";
[Link]([Link](6));//e
[Link]([Link](7));//no character returned
[Link]([Link](7,7));//no character returned
[Link]([Link](4,4));//no character returned
[Link]([Link](7,4));//[Link]:
String index out of range: -3
}

//counting occurence of every character in a string


public class CharCountClass {
public static void main(String[] args) {
String s;
Scanner sc=new Scanner([Link]);
[Link]("Enter a string");
s=[Link]();
TreeMap<Character,Integer> hm=new TreeMap<Character,Integer>();
char c[]=[Link]();
//char ch;
for(char r:c)
{
if([Link](r))
{
[Link](r,[Link](r)+1);
}
else
{
[Link](r,1);
}

}
[Link](hm);

Common questions

Powered by AI

`Collections.addAll()` simplifies the process of adding each element of an array to a list in a single call, making the code concise and less error-prone compared to manually iterating and adding elements. This also potentially improves performance due to internal optimizations in `Collections.addAll()`. However, it requires all elements to be compatible types, namely reference data types, and lacks explicit control that might be necessary in complex conversion logic .

Converting an ArrayList to a Set can remove duplicates because sets inherently do not allow duplicate elements. Using a `LinkedHashSet` not only removes duplicates but also maintains the insertion order of the elements, which is beneficial for cases where order matters. However, a potential trade-off is that `LinkedHashSet` can have slower performance than `HashSet` due to its ordering constraints, which may not be ideal if insertion order is not important .

Separating different data types, such as alphabets, numbers, and special characters, enhances data processing by allowing targeted operations and analysis on specific data types. Java provides methods like `Character.isAlphabetic()`, `Character.isDigit()`, and others within the `Character` class to facilitate this distinction, useful in data validation, format checking, and parsing operations .

In the provided Java program, scanning and counting elements in a string are achieved through iteration. The program uses `Character.isAlphabetic()` to recognize alphabets and `Character.isDigit()` for digits. Each character is checked one-by-one using a loop: if it is an alphabet, the alphabet counter (`ac`) increases; if it's a digit, the digit counter (`nc`) increments; otherwise, it increments the special character counter (`sct`). This systematic iteration ensures all characters are accounted for .

To find the second minimum element, the approach involves initializing two variables—`min` and `min2`—to hold the smallest and the second smallest values. Initially, both are set to the first element of the array. The array is traversed with a loop where the current element is compared against `min`; if smaller, `min2` takes the value of `min`, and `min` takes the new minimum value. If the current element is only less than `min2`, it updates `min2`. A pitfall to avoid is not properly initializing `min` and `min2` (e.g., using Integer.MAX_VALUE) or not handling cases where the array may not have distinct enough values to define a second minimum .

To transform an array into an ArrayList in Java, you can use the `Collections.addAll()` method. Start by declaring your array and ArrayList. For instance, if using an Integer array `Integer ar[] = {10, 29, 30, 20};`, you initialize an ArrayList `ArrayList<Integer> al = new ArrayList<Integer>();`. Then, you call `Collections.addAll(al, ar);`, effectively adding all elements of the array into the ArrayList. This method requires the array elements to be of a class type, not primitive type, as shown in the source .

A `StringIndexOutOfBoundsException` in Java results from attempting to access an index within a string that doesn't exist. This can occur if the starting index of the `substring()` method is greater than the length of the string or if the starting index is greater than the ending index. For instance, calling `s1.substring(7, 4)` throws this exception because the starting index is greater than the ending index. To avoid this, always check boundaries by ensuring indices are within the valid range of the string length .

For an efficient word search in a file, use `BufferedReader` or `Scanner` to minimize I/O operations, and ensure that you read the file line-by-line rather than loading it completely into memory, which conserves resources. Utilize efficient string comparison methods and handle exceptions properly to maintain robustness. Consider using algorithms like binary search if the data structure and order permit, and implement early exits from loops upon finding the word to save processing time .

Using the `split()` method with a space delimiter is effective for counting words because it divides the string into substrings wherever it encounters spaces. This directly corresponds to typical word boundaries in text input. However, the limitation is that it doesn't account for multiple spaces or different types of space characters (e.g., tab or newline). This method also ignores punctuation connected to words, potentially overestimating the word count if not addressed. Additional logic would be needed to handle these exceptions .

Reading and counting lines, words, and characters from a file is done using a `BufferedReader` to read through the file line-by-line. For each line, the line count increments. The line is then split by spaces to count words, adding the length of each split string to a character count. This iterates until the end of the file, resulting in the total line, word, and character counts. To effectively handle files, ensure proper exception handling for `IOException` and always close the reader in a `finally` block .

You might also like