Q.
1 Java Program to Make a Simple Calculator Using
switch...case and Scanner class.
import [Link];
public class JavaExample {
public static void main(String[] args) {
double num1, num2;
Scanner scanner = new Scanner([Link]);
[Link]("Enter first number:");
num1 = [Link]();
[Link]("Enter second number:");
num2 = [Link]();
[Link]("Enter an operator (+, -, *, /): ");
char operator = [Link]().charAt(0);
[Link]();
double output;
switch(operator)
{
case '+':
output = num1 + num2;
break;
case '-':
output = num1 - num2;
break;
case '*':
output = num1 * num2;
break;
case '/':
output = num1 / num2;
break;
default:
[Link]("You have entered wrong operator");
return;
}
[Link](num1+" "+operator+" "+num2+": "+output);
}
}
Output:
Enter first number:40
Enter second number:4
Enter an operator (+, -, *, /): /
40.0 / 4.0: 10.0
Q.2 Write a program to Print Sum of Series 1+x+x2+x3+......+xn in java
class GFG {
static double sum(int x, int n)
{
double i, total = 1.0, multi = x;
[Link]("1 ");
for (i = 1; i < n; i++) {
total = total + multi;
[Link](multi);
[Link](" ");
multi = multi * x;
}
[Link]();
return total;
}
public static void main(String[] args)
{
int x = 2;
int n = 5;
[Link](
"%.2f", sum(x, n));
}
}
Output:
1 2.0 4.0 8.0 16.0
31.00
Q.3 Write a program to find factorial of a number with
recursion and iteration
public class Factorial {
public static void main(String[] args) {
int num = 6;
long factorial = multiplyNumbers(num);
[Link]("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}
Output
Factorial of 6 = 720
Q. 4 Write a program to Search an Element in an Array in java.
import [Link];
import [Link];
public class Search_Element {
private static void checkElement(int[] arr, int key)
{
// check if the specified element
// is present in the array
boolean flag = false;
for (int element : arr) {
if (element == key) {
flag = true;
break;
}
}
// Print the result
[Link]("Element found.");
}
public static void main(String[] args)
{
// Initialize array
int arr[] = { 78, 42, 89, 11, 56, 10 };
// Get the value to be checked
int key = 11;
[Link]("Array: " + [Link](arr));
checkElement(arr, key);
}
}
Output of the above code:
Array: [78, 42, 89, 11, 56, 10]
Element found.
Q.5 Write a program to add two matrices of order 3X3
1. public class MatrixAdditionExample{
2. public static void main(String args[]){
3. //creating two matrices
4. int a[][]={{1,3,4},{2,4,3},{3,4,5}};
5. int b[][]={{1,3,4},{2,4,3},{1,2,4}};
6.
7. //creating another matrix to store the sum of two matrices
8. int c[][]=new int[3][3]; //3 rows and 3 columns
9.
10. //adding and printing addition of 2 matrices
11. for(int i=0;i<3;i++){
12. for(int j=0;j<3;j++){
13. c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
14. [Link](c[i][j]+" ");
15. }
16. [Link]();//new line
17. }
18. }}
Output:
2 6 8
4 8 6
4 6 9
Q.6 Java IO program to take input through keyboard at
runtime
Import [Link];
Public class KeyboardInput {
Public static void main(String[] args) {
// Creating a Scanner object to read input from the keyboard
Scanner scanner = new Scanner([Link]);
// Taking input for different data types
[Link](“Enter an integer: “);
Int intValue = [Link]();
[Link](“Enter a double: “);
Double doubleValue = [Link]();
[Link](); // Consume the newline character left by nextDouble()
[Link](“Enter a string: “);
String stringValue = [Link]();
// Displaying the input values [Link](“Entered integer: “ +
intValue);
[Link](“Entered double: “ + doubleValue);
[Link](“Entered string: “ + stringValue);
// Closing the Scanner to avoid resource leaks
[Link]();
}
}
Q.7 Count Vowels and Consonants in a String
import [Link].*;
class GFG {
public static void count(String str)
{
int vow = 0, con = 0;
String ref = "aeiouAEIOU";
for (int i = 0; i < [Link](); i++) {
if (([Link](i) >= 'A'
&& [Link](i) <= 'Z')
|| ([Link](i) >= 'a'
&& [Link](i) <= 'z')) {
if ([Link]([Link](i)) != -1)
vow++;
else
con++;
}
}
[Link]("Number of Vowels = " + vow
+ "\nNumber of Consonants = "
+ con);
}
public static void main(String[] args)
{
String str = "#GeeksforGeeks";
count(str);
}
}
Output
Number of Vowels = 5
Number of Consonants = 8
Q.8 Count the Number of Duplicate Words in a String
import [Link];
import [Link];
public class DuplicateWordCounter {
public static void main(String[] args) {
String inputString = "This is a sample string with duplicate words. This is a
sample string.";
// Split the input string into words
String[] words = [Link]("\\s+");
// Create a map to store word counts
Map<String, Integer> wordCountMap = new HashMap<>();
// Count the occurrences of each word
for (String word : words) {
// Convert to lowercase to make the comparison case-insensitive
String lowercaseWord = [Link]();
// Update the count in the map
[Link](lowercaseWord,
[Link](lowercaseWord, 0) + 1);
}
// Display the duplicate words and their counts
[Link]("Duplicate words and their counts:");
for ([Link]<String, Integer> entry : [Link]()) {
if ([Link]() > 1) {
[Link]([Link]() + ": " + [Link]());
}
}
}
}
Q.9 Count Number of Words in Given String
1. public class WordCount {
2. static int wordcount(String string)
3. {
4. int count=0;
5.
6. char ch[]= new char[[Link]()];
7. for(int i=0;i<[Link]();i++)
8. {
9. ch[i]= [Link](i);
10. if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!='
')&&(i==0)) )
11. count++;
12. }
13. return count;
14. }
15. public static void main(String[] args) {
16. String string =" India Is My Country";
17. [Link](wordcount(string) + " words.");
18. }
19. }
Output:
4 words.
Q.10 Count the Number of Occurrences of Substring in a
String
public class SubstringCount {
public static void main(String[] args) {
String inputString = "Java is a widely used programming language.
Java is versatile and has a large community.";
String substring = "Java";
int count = countSubstringOccurrences(inputString, substring);
[Link]("Number of occurrences of \"" + substring + "\":
" + count);
}
private static int countSubstringOccurrences(String inputString, String
substring) {
int count = 0;
int index = 0;
while ((index = [Link](substring, index)) != -1) {
count++;
index += [Link]();
}
return count;
}
}
Output:
Number of occurrences of "Java": 2
Q.11 Count the Occurrences of Each Character in String
class NoOfOccurrenceOfCharacters {
static final int MAX_CHAR = 256;
static void getOccurringChar(String str)
{
// Create an array of size 256
// i.e. ASCII_SIZE
int count[] = new int[MAX_CHAR];
int len = [Link]();
// Initialize count array index
for (int i = 0; i < len; i++)
count[[Link](i)]++;
// Create an array of given String size
char ch[] = new char[[Link]()];
for (int i = 0; i < len; i++) {
ch[i] = [Link](i);
int find = 0;
for (int j = 0; j <= i; j++) {
// If any matches found
if ([Link](i) == ch[j])
find++;
}
if (find == 1)
[Link](
"Number of Occurrence of "
+ [Link](i)
+ " is:" + count[[Link](i)]);
}
}
// Driver Code
public static void main(String[] args)
{
String str = "geeksforgeeks";
getOccurringChar(str);
}
}
Output
Number of Occurrence of g is:2
Number of Occurrence of e is:4
Number of Occurrence of k is:2
Number of Occurrence of s is:2
Number of Occurrence of f is:1
Number of Occurrence of o is:1
Number of Occurrence of r is:1
Q.12 Java Program to Remove Duplicate Words from String
import [Link];
import [Link];
public class DuplicateWordRemover {
public static void main(String[] args) {
String inputString = "Java is a programming language and Java is
widely used in the software industry.";
// Removing duplicate words
String result = removeDuplicateWords(inputString);
[Link]("String after removing duplicate words: " +
result);
}
private static String removeDuplicateWords(String inputString) {
// Splitting the string into words
String[] words = [Link]("\\s+");
// Creating a set to store unique words
Set<String> uniqueWords = new HashSet<>();
// Removing duplicate words
StringBuilder resultBuilder = new StringBuilder();
for (String word : words) {
if ([Link](word)) {
[Link](word).append(" ");
}
}
// Converting the StringBuilder to a string
String result = [Link]().trim();
return result;
}
}
Output:
String after removing duplicate words: Java is a programming language and
widely used in the software industry.
Q.8 Count the Number of Duplicate Words in a String