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

Java Programs for Number Operations

The document discusses various Java programs to demonstrate programming concepts like exception handling, inheritance, multithreading, packages and more. It includes programs to find the largest/smallest of three numbers, calculate average, perform string operations, count vowels, and handle exceptions.

Uploaded by

Kritika Sharma
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 views18 pages

Java Programs for Number Operations

The document discusses various Java programs to demonstrate programming concepts like exception handling, inheritance, multithreading, packages and more. It includes programs to find the largest/smallest of three numbers, calculate average, perform string operations, count vowels, and handle exceptions.

Uploaded by

Kritika Sharma
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 17. Write a Java program to determine greatest number of three numbers.

1. import [Link];
2. public class LargestNumberExample1
3. {
4. public static void main(String[] args)
5. {
6. int a, b, c, largest, temp;
7. //object of the Scanner class
8. Scanner sc = new Scanner([Link]);
9. //reading input from the user
10. [Link]("Enter the first number:");
11. a = [Link]();
12. [Link]("Enter the second number:");
13. b = [Link]();
14. [Link]("Enter the third number:");
15. c = [Link]();
16. //comparing a and b and storing the largest number in a temp variable
17. temp=a>b?a:b;
18. //comparing the temp variable with c and storing the result in the variable
19. largest=c>temp?c:temp;
20. //prints the largest number
21. [Link]("The largest number is: "+largest);
22. }
23. }
Program 18. Write a Java program to determine smallest number of three numbers.

1. import [Link];
2. public class SmallestNumberExample1
3. {
4. public static void main(String[] args)
5. {
6. int a, b, c, smallest, temp;
7. //object of the Scanner class
8. Scanner sc = new Scanner([Link]);
9. //reading input from the user
10. [Link]("Enter the first number:");
11. a = [Link]();
12. [Link]("Enter the second number:");
13. b = [Link]();
14. [Link]("Enter the third number:");
15. c = [Link]();
16. //comparing a and b and storing the smallest number in a temp variable
17. temp=a<b?a:b;
18. //comparing the temp variable with c and storing the result in the variable names smallest
19. smallest=c<temp?c:temp;
20. //prints the smallest number
21. [Link]("The smallest number is: "+smallest);
22. }
23. }

Output:

Enter the first number:


23
Enter the second number:
11
Enter the third number:
67
The smallest Number is: 11

Program 19. Compute the average of three numbers through a java program.

import [Link];

public class JavaExample {

public static void main(String[] args)


{
Scanner scan = new Scanner([Link]);

[Link]("Enter the first number: ");


double num1 = [Link]();
[Link]("Enter the second number: ");
double num2 = [Link]();
[Link]("Enter the third number: ");

double num3 = [Link]();


[Link]();
[Link]("The average of entered numbers is:" + avr(num1, num2, num3) );
}

public static double avr(double a, double b, double c)


{
return (a + b + c) / 3;
}
}
Program 20 . Write a program to perform following operations on strings:
1) Compare two strings.
2) Count string length.
3) Convert upper case to lower case & vice versa.
4) Concatenate two strings.
5) Print a substring.

class stringop
{
public static void stringCompare(String s1, String s2, String s3, String s4)
{
[Link]("Comparing " + s1 + " and " + s2
+ " : " + [Link](s2));
[Link]("Comparing " + s1 + " and " + s3
+ " : " + [Link](s3));
[Link]("Comparing " + s2 + " and " + s3
+ " : " + [Link](s3));
[Link]("Comparing " + s2 + " and " + s4
+ " : " + [Link](s4));
}
public static void countLength(String s1, String s2, String s3, String s4)
{
[Link]("Length of " + s1 + " is " + [Link]());
[Link]("Length of " + s2 + " is " + [Link]());
[Link]("Length of " + s3 + " is " + [Link]());
[Link]("Length of " + s4 + " is " + [Link]());
}
public static void changecaselower(String s1)
{
[Link]("lower case output is "+ [Link]());
}
public static void changecaseupper(String s1)
{
[Link]("upper case output is "+ [Link]());
}
public static void joinstring(String s1, String s2)
{

String s3=[Link](s2);
[Link]("The concatinated string is "+s3);
}
public static void Substr(String s1)
{
[Link]("The extracted substring is : ");
[Link]([Link](4,8));
}
}
class Main {
public static void main(String[] args) {
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
String four ="Python";

// print strings
[Link](first); // print Java
[Link](second); // print Python
[Link](third); // print JavaScript
stringop ob1 = new stringop();
[Link](first,second,third, four);
[Link](first,second,third, four);
[Link](third);
[Link](second);
[Link](first,second);
[Link](third);
}
}
Program 21 . Write a Program & design a method to count all vowels in a string.

import [Link];
public class CountingVowels {
public static void main(String args[]){
int count = 0;

[Link]("Enter a sentence :");


Scanner sc = new Scanner([Link]);
String sentence = [Link]();

for (int i=0 ; i<[Link](); i++){


char ch = [Link](i);
if(ch == 'a'|| ch == 'e'|| ch == 'i' ||ch == 'o' ||ch == 'u'||ch == ' '){
count ++;

}
}
[Link]("Number of vowels in the given sentence is "+count);
}
}

Program 22. Write a Java method to count all words in a string.

public class Example1 {

public static void main(String args[]) {


// initializing a string
String msg = "Tutorials Point Welcomes You!!";
[Link]("The given String is: " + msg);
// initial count of the words

int total = 1;
// loop variable
int i = 0;
// while loop to count the number of words
while (i < [Link]()) {
// checking if the current character is space or not
if (([Link](i) == ' ') && ([Link](i + 1) != ' ')) {
total++; // incrementing the word count
}
i++; // incrementing loop variable
}

// printing the result


[Link]("Number of words in the given string: " + total);
}
}

Program 23. To represent the concept of all types of inheritance supported by Java,
design a program.
Single Inheritance:
class Student {
void Play() {
[Link]("Playing Fooball...");
}
}
class Bob extends Student {
void Study() {
[Link]("Studing Physics...");
}
}
class Single {
public static void main(String args[]) {
Bob d = new Bob();
[Link]();
[Link]();
}
}

Multilevel inheritance:

1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){[Link]("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. [Link]();
14. [Link]();
15. [Link]();
16. }}
Hierarchical Inheritance:

class A {

public void print_A() { [Link]("Class A"); }

class B extends A {

public void print_B() { [Link]("Class B"); }

class C extends A {

public void print_C() { [Link]("Class C"); }

class D extends A {

public void print_D() { [Link]("Class D"); }

// Driver Class
class Test {

public static void main(String[] args)

B obj_B = new B();

obj_B.print_A();

obj_B.print_B();

C obj_C = new C();

obj_C.print_A();

obj_C.print_C();

D obj_D = new D();

obj_D.print_A();

obj_D.print_D();

Program 24. Write a Java program to handle the following exceptions:


1) Divide by Zero Exception.
2) Array Index Out Of bound Exception.
public class NewClass2 {
public static void main(String[] args)
{
int ar[] = { 0, 1, 2, 3, 4 };
try
{
for (int i = 0; i <= [Link]; i++)
[Link](ar[i]+" ");
}
catch (Exception e)
{
[Link]("\n out of bound Exception caught");
}
for (int i = 0; i < [Link]; i++)
try
{
[Link](ar[i+1] /ar[i]);
}
catch (ArithmeticException e)
{
[Link]("Divided by zero operation cannot possible");
}
}
}
Program 25. Write a program to implement Multiple Inheritance using interface.
interface Walkable {
void walk();
}

interface Swimmable {
void swim();
}

// Implement the interfaces in a class


class Duck implements Walkable, Swimmable {
public void walk()
{
[Link]("Duck is walking.");
}

public void swim()


{
[Link]("Duck is swimming.");
}
}

// Use the class to call the methods from the interfaces


class Main {
public static void main(String[] args)
{
Duck duck = new Duck();
[Link]();
[Link]();
}
}

Program 26. Construct a program to design a package in Java.


OUTPUT:
13
3

Program 27. To represent the concept of Multithreading write a Java program.


OUTPUT:
From Thread A : i = 1
From Thread B : j = 1
From Thread B : j = 2
From Thread C : k = 1
From Thread C : k = 2
From Thread B : j = 3
From Thread B : j = 4
From Thread B : j = 5
Exit from B
From Thread A : i = 2
From Thread A : i = 3
From Thread A : i = 4
From Thread A : i = 5
Exit from A
From Thread C : k = 3
From Thread C : k = 4
From Thread C : k = 5
Exit from C

Common questions

Powered by AI

The program creates multiple threads that execute independently, showcasing parallel execution of tasks. Each thread prints its own identifier alongside operation details, demonstrating concurrent computation. Performance considerations include the potential for race conditions, the overhead of context-switching, and resource contention, which could affect performance given poor thread management or complex shared states .

The program initializes a counter and iterates through the string, identifying word boundaries based on transitions from non-space to space characters. Each transition increases the count. This logic may fail with leading or trailing spaces or multiple spaces between words, potentially resulting in incorrect word counts. The program mitigates this by assuming consistent inner spacing but doesn't apply robust trimming .

The program employs try-catch blocks to handle exceptions. For array indexing, it catches a general 'Exception' to manage out of bounds accesses by terminating iteration and printing a message. For division by zero, it uses 'ArithmeticException' to catch attempts and notify the user. This approach prevents the program from crashing, managing foreseeable runtime errors by encapsulating risky operations within error-handling structures .

The program implements case conversion using 'toLowerCase()' and 'toUpperCase()' methods, demonstrating these by converting strings to lower and upper cases respectively. It demonstrates string concatenation by using 'concat()' to join two strings, illustrating Java's built-in methods for modifying string cases and combining multiple strings efficiently, maintaining immutability of original strings .

The program uses a method 'avr' that takes three double arguments and calculates their average by summation and division by three. This method is called in the 'main' method with user-inputted numbers, showcasing Java's ability to encapsulate logic in reusable methods that separate logic and input/output responsibilities. This separation allows the program to calculate the average without redundantly coding the formula in 'main' .

Single inheritance is shown via classes where 'Bob' extends the 'Student' class. Multilevel inheritance is illustrated where 'Dog' extends 'Animal', and 'BabyDog' extends 'Dog', forming a chain. Hierarchical inheritance is demonstrated with class 'A' as the base for multiple subclasses 'B', 'C', and 'D'. These examples illustrate Java's capability to support different types of inheritance, promoting code reusability and logical hierarchy structures .

The example achieves multiple inheritance via interfaces by defining 'Walkable' and 'Swimmable' interfaces, each with an abstract method. The 'Duck' class implements both interfaces and provides concrete implementations for the 'walk' and 'swim' methods. This demonstrates how Java allows a class to inherit multiple behaviors, circumventing its single inheritance limitation via interfaces, thereby enabling polymorphism .

The Java program determines the largest of three numbers by using conditional (ternary) operators to compare them. First, it compares the first two numbers, storing the larger one in a temporary variable. Then it compares this temporary variable with the third number. The greater of these two values is stored as the largest number and printed. The key steps are: compare 'a' and 'b', use 'a > b ? a : b' to assign the larger to 'temp', then compare 'temp' with 'c' using 'c > temp ? c : temp' to determine the final largest value .

Designing a Java package enhances code organization by logically grouping related classes and interfaces, facilitating maintenance and understanding. It promotes reusability across multiple projects by encapsulating common functionality, thereby reducing duplication. Packages also play a central role in access control and namespace management, helping prevent naming conflicts and allowing for more sophisticated code structures .

The method iterates over each character of the input string, checking if it is a vowel using a series of 'or' conditions and increments a count. It assumes all vowels are lowercase and does not account for uppercase vowels, which limits its effectiveness. While simple, the solution could be improved by converting input to lowercase or including uppercase vowels in the checks .

You might also like