0% found this document useful (0 votes)
1K views38 pages

100 Java Programs for Practice

Uploaded by

bhanudeshoju24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1K views38 pages

100 Java Programs for Practice

Uploaded by

bhanudeshoju24
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
  • 3. Command Line Argument in Java
  • 2. Print Integer in Java
  • 1. Simple Java Program
  • 5. How to Convert Fahrenheit to Celsius
  • 4. How to Get Input Using Scanner
  • 7. How to Swap 2 Numbers Without 3rd Variable
  • 6. How to Swap 2 Numbers Using 3rd Variable
  • 8. How to Add Two Numbers in Java
  • 9. Find Largest Number in Java
  • 10. If Else Clause in Java
  • 11. If Else Clause in Java - Program 2
  • 12. Nested If Else Clause in Java
  • 13. How to Check Odd and Even Number in Java
  • 14. Find Factorial for Given Number in Java
  • 15. How to Complete 2 Strings in Java
  • 16. Simple For Loop Program in Java
  • 17. Print Star Console Using Loop
  • 19. While Loop Using Break
  • 18. Print Reverse Number in Java
  • 20. Print All Alphabet Using For Loop
  • 21. Print Multiplication Table in Java
  • 22. Print Prime Numbers in Java
  • 23. Check if Number is Armstrong in Java
  • 24. Print Floyd's Triangle in Java
  • 25. Find All Substrings of a String in Java
  • 26. Print Reverse String in Java
  • 27. Check If Given Number is Palindrome or Not
  • 28. Add Two Matrices in Java
  • 29. Multiply Two Matrices in Java
  • 30. Transpose Matrix in Java

100 JAVA PROGRAMS

1. Simple Java Program


class HelloWorld

public static void main(String args[])

[Link]("Hello World by Technolamror");

2. Print Integer
in java

class Integers {

public static void main(String[] arguments) {

int c; //declaring a variable

/* Using for loop to repeat instruction execution */

for (c = 1; c <= 10; c++) {

[Link](c);

3. Command Line Argument in java


class Arguments {

public static void main(String[] args) {

for (String t: args) {

[Link](t);

4. How to get Using input using Scanner


Program in java

import [Link];
class GetInputFromUser

public static void main(String args[])

int a;

float b;

String s;

Scanner in = new Scanner([Link]);

[Link]("Enter a string");

s = [Link]();

[Link]("You entered string "+s);

[Link]("Enter an integer");

a = [Link]();

[Link]("You entered integer "+a);

[Link]("Enter a float");

b = [Link]();

[Link]("You entered float "+b);

5. How to convert Fahrenheit to Celsius


Program in java

import [Link].*;

class FahrenheitToCelsius {

public static void main(String[] args) {

float temperatue;

Scanner in = new Scanner([Link]);


}

6. How to swap 2 no using 3rd variable Program


in java

import [Link];

class SwapNumbers

public static void main(String args[])

int x, y, temp;

[Link]("Enter x and y");

Scanner in = new Scanner([Link]);

x = [Link]();

y = [Link]();

[Link]("Before Swapping\nx = "+x+"\ny = "+y);

temp = x;

x = y;

y = temp;

[Link]("After Swapping\nx = "+x+"\ny = "+y);

7. How to swap 2 no without using 3rd variable


Program in java

import [Link];

class SwapNumbers
{

public static void main(String args[])

int x, y;

[Link]("Enter x and y");

Scanner in = new Scanner([Link]);

x = [Link]();

y = [Link]();

[Link]("Before Swapping\nx = "+x+"\ny = "+y);

x = x + y;

y = x - y;

x = x - y;

[Link]("After Swapping\nx = "+x+"\ny = "+y);

8. How to add two number Program in java


import [Link];

class AddNumbers

public static void main(String args[])

int x, y, z;

[Link]("Enter two integers to calculate their sum ");

Scanner in = new Scanner([Link]);

x = [Link]();

y = [Link]();

z = x + y;

[Link]("Sum of entered integers = "+z);

}
}

//For Large Number

import [Link];

import [Link];

class AddingLargeNumbers {

public static void main(String[] args) {

String number1, number2;

Scanner in = new Scanner([Link]);

[Link]("Enter first large number");

number1 = [Link]();

[Link]("Enter second large number");

number2 = [Link]();

BigInteger first = new BigInteger(number1);

BigInteger second = new BigInteger(number2);

BigInteger sum;

sum = [Link](second);

[Link]("Result of addition = " + sum);

9. Find Largest no in java Program


import [Link];

class LargestOfThreeNumbers

public static void main(String args[])

int x, y, z;

[Link]("Enter three integers ");

Scanner in = new Scanner([Link]);

x = [Link]();

y = [Link]();
z = [Link]();

if ( x > y && x > z )

[Link]("First number is largest.");

else if ( y > x && y > z )

[Link]("Second number is largest.");

else if ( z > x && z > y )

[Link]("Third number is largest.");

else

[Link]("Entered numbers are not distinct.");

10. If Else clause in java


class Condition {

public static void main(String[] args) {

boolean learning = true;

if (learning) {

[Link]("Java programmer");

else {

[Link]("What are you doing here?");

11. If Else clause in java- Program 2


// If else in Java code

import [Link];

class IfElse {

public static void main(String[] args) {


int marksObtained, passingMarks;

passingMarks = 40;

Scanner input = new Scanner([Link]);

[Link]("Input marks scored by you");

marksObtained = [Link]();

if (marksObtained >= passingMarks) {

[Link]("You passed the exam.");

else {

[Link]("Unfortunately you failed to pass the exam.");

12. Nested If Else clause in java


import [Link];

class NestedIfElse {

public static void main(String[] args) {

int marksObtained, passingMarks;

char grade;

passingMarks = 40;

else if (marksObtained > 75)

grade = 'B';

else if (marksObtained > 60)

grade = 'C';
else

grade = 'D';

[Link]("You passed the exam and your grade is " + grade);

else {

grade = 'F';

[Link]("You failed and your grade is " + grade);

13. How to check Odd and Even Number in java.


import [Link];

class OddOrEven

public static void main(String args[])

int x;

[Link]("Enter an integer to check if it is odd or even ");

Scanner in = new Scanner([Link]);

x = [Link]();

if ( x % 2 == 0 )

[Link]("You entered an even number.");

else

[Link]("You entered an odd number.");

14. Find factorial for given no Program in Java


import [Link];
class Factorial

public static void main(String args[])

int n, c, fact = 1;

[Link]("Enter an integer to calculate it's factorial");

Scanner in = new Scanner([Link]);

n = [Link]();

if ( n < 0 )

[Link]("Number should be non-negative.");

else

for ( c = 1 ; c <= n ; c++ )

fact = fact*c;

[Link]("Factorial of "+n+" is = "+fact);

//Calculate factorial for large No

import [Link];

import [Link];

class BigFactorial

public static void main(String args[])

{
int n, c;

BigInteger inc = new BigInteger("1");

BigInteger fact = new BigInteger("1");

Scanner input = new Scanner([Link]);

[Link]("Input an integer");

n = [Link]();

for (c = 1; c <= n; c++) {

fact = [Link](inc);

inc = [Link]([Link]);

[Link](n + "! = " + fact);

15. How to complete 2 string in Java program


import [Link];

class CompareStrings

public static void main(String args[])

String s1, s2;

Scanner in = new Scanner([Link]);

[Link]("Enter the first string");

s1 = [Link]();

[Link]("Enter the second string");

s2 = [Link]();
if ( [Link](s2) > 0 )

[Link]("First string is greater than second.");

else if ( [Link](s2) < 0 )

[Link]("First string is smaller than second.");

else

[Link]("Both strings are equal.");

16. Simple For Loop Program in Java


//Java for loop program

class ForLoop {

public static void main(String[] args) {

int c;

for (c = 1; c <= 10; c++) {

[Link](c);

17. Print Star console using Loop


class Stars {

public static void main(String[] args) {

int row, numberOfStars;

for (row = 1; row <= 10; row++) {

for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {

[Link]("*");

[Link](); // Go to next line

}
}

18. Print Star console using Loop


class Stars {

public static void main(String[] args) {

int row, numberOfStars;

for (row = 1; row <= 10; row++) {

for(numberOfStars = 1; numberOfStars <= row; numberOfStars++) {

[Link]("*");

[Link](); // Go to next line

19. While loop


import [Link];

class WhileLoop {

Program in java

public static void main(String[] args) {

int n;

Scanner input = new Scanner([Link]);

[Link]("Input an integer");

while ((n = [Link]()) != 0) {

[Link]("You entered " + n);

[Link]("Input an integer");

[Link]("Out of loop");

20. Print Reverse number in java program


import [Link];
class ReverseNumber

public static void main(String args[])

int n, reverse = 0;

[Link]("Enter the number to reverse");

Scanner in = new Scanner([Link]);

n = [Link]();

while( n != 0 )

reverse = reverse * 10;

reverse = reverse + n%10;

n = n/10;

[Link]("Reverse of entered number is "+reverse);

21. While loop using break Program in java


import [Link];

class BreakWhileLoop {

public static void main(String[] args) {

int n;

Scanner input = new Scanner([Link]);

while (true) {

[Link]("Input an integer");
n = [Link]();

if (n == 0) {

break;

[Link]("You entered " + n);

22. While loop using break and continue


Program in java

import [Link];

class BreakContinueWhileLoop {

public static void main(String[] args) {

int n;

Scanner input = new Scanner([Link]);

while (true) {

[Link]("Input an integer");

n = [Link]();

if (n != 0) {

[Link]("You entered " + n);

continue;

else {

break;

}
}

23. Print all alphabet using for loop Program in


java

class Alphabets

public static void main(String args[])

char ch;

for( ch = 'a' ; ch <= 'z' ; ch++ )

[Link](ch);

24. Enhance loop in java Program


class EnhancedForLoop {

public static void main(String[] args) {

int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};

for (int t: primes) {

[Link](t);

//For String

class EnhancedForLoop {

public static void main(String[] args) {

String languages[] = { "C", "C++", "Java", "Python", "Ruby"};

for (String sample: languages) {

[Link](sample);
}

25. Print Multiplication table Program in java


import [Link];

class MultiplicationTable

public static void main(String args[])

int n, c;

[Link]("Enter an integer to print it's multiplication

table");

Scanner in = new Scanner([Link]);

n = [Link]();

[Link]("Multiplication table of "+n+" is :-");

for ( c = 1 ; c <= 10 ; c++ )

[Link](n+"*"+c+" = "+(n*c));

[Link]("Enter range of numbers to print their multiplication

table");

Scanner in = new Scanner([Link]);

a = [Link]();

b = [Link]();

for (c = a; c <= b; c++) {

[Link]("Multiplication table of "+c);


for (d = 1; d <= 10; d++) {

[Link](c+"*"+d+" = "+(c*d));

26. Print prime no Program in java


import [Link].*;

class PrimeNumbers

public static void main(String args[])

int n, status = 1, num = 3;

Scanner in = new Scanner([Link]);

[Link]("Enter the number of prime numbers you want");

n = [Link]();

if (n >= 1)

[Link]("First "+n+" prime numbers are :-");

[Link](2);

for ( int count = 2 ; count <=n ; )

for ( int j = 2 ; j <= [Link](num) ; j++ )

if ( num%j == 0 )

{
status = 0;

break;

if ( status != 0 )

[Link](num);

count++;

status = 1;

num++;

27. Check no is Armstrong or not in java


Program

import [Link];

class ArmstrongNumber

public static void main(String args[])

int n, sum = 0, temp, remainder, digits = 0;

Scanner in = new Scanner([Link]);

[Link]("Input a number to check if it is an Armstrong

number");

n = [Link]();

temp = n;
// Count number of digits

while (temp != 0) {

digits++;

temp = temp/10;

temp = n;

while (temp != 0) {

remainder = temp%10;

sum = sum + power(remainder, digits);

temp = temp/10;

if (n == sum)

[Link](n + " is an Armstrong number.");

else

[Link](n + " is not an Armstrong number.");

static int power(int n, int r) {

int c, p = 1;

for (c = 1; c <= r; c++)

p = p*n;

return p;

28. Print Floyd’s Triangle in java Program


import [Link];
class FloydTriangle

public static void main(String args[])

int n, num = 1, c, d;

Scanner in = new Scanner([Link]);

[Link]("Enter the number of rows of floyd's triangle you

want");

n = [Link]();

[Link]("Floyd's triangle :-");

for ( c = 1 ; c <= n ; c++ )

for ( d = 1 ; d <= c ; d++ )

[Link](num+" ");

num++;

[Link]();

29. Find All substring of string in java Program


import [Link];

class SubstringsOfAString

{
public static void main(String args[])

String string, sub;

int i, c, length;

Scanner in = new Scanner([Link]);

[Link]("Enter a string to print it's all substrings");

string = [Link]();

length = [Link]();

[Link]("Substrings of \""+string+"\" are :-");

for( c = 0 ; c < length ; c++ )

for( i = 1 ; i <= length - c ; i++ )

sub = [Link](c, c+i);

[Link](sub);

30. Print reverse string in java


import [Link].*;

class ReverseString

public static void main(String args[])

String original, reverse = "";

Scanner in = new Scanner([Link]);

Program

[Link]("Enter a string to reverse");


original = [Link]();

int length = [Link]();

for ( int i = length - 1 ; i >= 0 ; i-- )

reverse = reverse + [Link](i);

[Link]("Reverse of entered string is: "+reverse);

//Using Internal java Methog

class InvertString

public static void main(String args[])

StringBuffer a = new StringBuffer("Java programming is fun");

[Link]([Link]());

31. Check Given No is palindrome or Not in java


Program

import [Link].*;

class Palindrome

public static void main(String args[])

String original, reverse = "";

Scanner in = new Scanner([Link]);

[Link]("Enter a string to check if it is a palindrome");

original = [Link]();

int length = [Link]();


for ( int i = length - 1; i >= 0; i-- )

reverse = reverse + [Link](i);

if ([Link](reverse))

[Link]("Entered string is a palindrome.");

else

[Link]("Entered string is not a palindrome.");

//Another Method

import [Link].*;

class Palindrome

public static void main(String args[])

String inputString;

Scanner in = new Scanner([Link]);

[Link]("Input a string");

inputString = [Link]();

int length = [Link]();

int i, begin, end, middle;

begin = 0;

end = length - 1;

middle = (begin + end)/2;


for (i = begin; i <= middle; i++) {

if ([Link](begin) == [Link](end)) {

begin++;

end--;

else {

break;

if (i == middle + 1) {

[Link]("Palindrome");

else {

[Link]("Not a palindrome");

How to add two matrix in java Program

import [Link];

class AddTwoMatrix

public static void main(String args[])

int m, n, c, d;

Scanner in = new Scanner([Link]);

[Link]("Enter the number of rows and columns of matrix");

m = [Link]();

n = [Link]();
int first[][] = new int[m][n];

int second[][] = new int[m][n];

int sum[][] = new int[m][n];

[Link]("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

first[c][d] = [Link]();

[Link]("Enter the elements of second matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

second[c][d] = [Link]();

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-'

to subtract matrices

[Link]("Sum of entered matrices:-");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

[Link](sum[c][d]+"\t");

[Link]();

}
}

How to multiply two matrix in java Program

import [Link];

class MatrixMultiplication

public static void main(String args[])

int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner([Link]);

[Link]("Enter the number of rows and columns of first

matrix");

m = [Link]();

n = [Link]();

int first[][] = new int[m][n];

[Link]("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

first[c][d] = [Link]();

[Link]("Enter the number of rows and columns of second

matrix");

p = [Link]();

q = [Link]();

if ( n != p )

[Link]("Matrices with entered orders can't be multiplied


with each other.");

else

int second[][] = new int[p][q];

int multiply[][] = new int[m][q];

[Link]("Enter the elements of second matrix");

for ( c = 0 ; c < p ; c++ )

for ( d = 0 ; d < q ; d++ )

second[c][d] = [Link]();

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < q ; d++ )

for ( k = 0 ; k < p ; k++ )

sum = sum + first[c][k]*second[k][d];

multiply[c][d] = sum;

sum = 0;

[Link]("Product of entered matrices:-");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < q ; d++ )


[Link](multiply[c][d]+"\t");

[Link]("\n");

How to get transpose of matrix in java

Program

import [Link];

class TransposeAMatrix

public static void main(String args[])

int m, n, c, d;

Scanner in = new Scanner([Link]);

[Link]("Enter the number of rows and columns of matrix");

m = [Link]();

n = [Link]();

int matrix[][] = new int[m][n];

[Link]("Enter the elements of matrix");

for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

matrix[c][d] = [Link]();

int transpose[][] = new int[n][m];


for ( c = 0 ; c < m ; c++ )

for ( d = 0 ; d < n ; d++ )

transpose[d][c] = matrix[c][d];

[Link]("Transpose of entered matrix:-");

for ( c = 0 ; c < n ; c++ )

for ( d = 0 ; d < m ; d++ )

[Link](transpose[c][d]+"\t");

[Link]("\n");

How to compare 2 string in java

ublic class LastIndexOfExample

public static void main(String args[]){

String s1="hello";

String s2="hello";

String s3="meklo";

String s4="hemlo";

[Link]([Link](s2));

[Link]([Link](s3));

[Link]([Link](s4));

}}

How to string width with specific char in

java Program

class StringEndwith{
public static void main(String args[]){

String s1="java by TechnoLamror";

[Link]([Link]("r")); //true

[Link]([Link]("Lamror")); //true

[Link]([Link]("lamror"));//false

How to use indesOf() in java

ublic class IndexOfExample

public static void main(String args[]){

String s1="this is index of example";

//passing substring

Program

int index1=[Link]("is");//returns the index of is substring

int index2=[Link]("index");//returns the index of index substring

[Link](index1+" "+index2);//2 8

//passing substring with from index

int index3=[Link]("is",4);//returns the index of is substring after 4th index

[Link](index3);//5 i.e. the index of another is

//passing char value

int index4=[Link]('s');//returns the index of s char value

[Link](index4);//3

}}

How to replace string with another string in

java Program

ublic class ReplaceAllExample2

public static void main(String args[]){


String s1="My name is Rajendra. My name is lamror. My name is Technolamror.";

String replaceString=[Link]("is","was");//replaces all occurrences of "is" to

"was"

[Link](replaceString);

}}

How to split string in java Program

ublic class SplitExample

public static void main(String args[]){

String s1="java string split method by Technolamror";

String[] words=[Link]("\\s");//splits the string based on whitespace

//using java foreach

loop to print elements of string array

for(String w:words){

[Link](w);

}}

How to remove space in string both end in

java

ublic class StringTrimExample

public static void main(String args[]){

String s1=" hello string ";

[Link](s1+"Technolamror");//without trim()

[Link]([Link]()+"Technolamror");//with trim()

}}

How to convert all char in string lower case

in java Program

p
ublic class StringLowerExample

public static void main(String args[]){

String s1="TECHNOLAMROR by Rajendralamror HELLO stRIng";

String s1lower=[Link]();

[Link](s1lower);

}}

How to create method in java Program

class Methods {

// Constructor method

Methods() {

[Link]("Constructor method is called when an object of it's

class is created");

// Main method where program execution begins

public static void main(String[] args) {

staticMethod();

Methods object = new Methods();

[Link]();

// Static method

static void staticMethod() {

[Link]("Static method can be called without creating

object");

}
// Non static method

void nonStaticMethod() {

[Link]("Non static method must be called by creating an

object");

Find Length, Concatenate and Replace

String in Java Program

class StringMethods

public static void main(String args[])

int n;

String s = "Java programming", t = "", u = "";

[Link](s);

// Find length of string

n = [Link]();

[Link]("Number of characters = " + n);

// Replace characters in string

t = [Link]("Java", "C++");

[Link](s);

[Link](t);

// Concatenating string with another string


u = [Link](" is fun");

[Link](s);

[Link](u);

How Static block working in java Program

class StaticBlock {

public static void main(String[] args) {

[Link]("Main method is executed.");

static {

[Link]("Static block is executed before main method.");

//Static Block Application …. We need to open Program in speciif window

class StaticBlock {

public static void main(String[] args) {

[Link]("You are using Windows_NT operating system.");

static {

String os = [Link]("OS");

if ([Link]("Windows_NT") != true) {

[Link](1);

Difference between Static and Instance

method working in java Program

class Difference {
public static void main(String[] args) {

display(); //calling without object

Difference t = new Difference();

[Link](); //calling using object

static void display() {

[Link]("Programming is amazing.");

void show(){

[Link]("Java is awesome.");

How to create Multiple class in java Program

class Computer {

Computer() {

[Link]("Constructor of Computer class.");

void computer_method() {

[Link]("Power gone! Shut down your PC soon...");

public static void main(String[] args) {

Computer my = new Computer();

Laptop your = new Laptop();

my.computer_method();

your.laptop_method();

class Laptop {

Laptop() {

[Link]("Constructor of Laptop class.");


}

void laptop_method() {

[Link]("99% Battery available.");

How to create constructor in java Program

class Programming {

//constructor method

Programming() {

[Link]("Constructor method called.");

public static void main(String[] args) {

Programming object = new Programming(); //creating object

How to create constructor overloading in

java Program

class Language {

String name;

Language() {

[Link]("Constructor method called.");

Language(String t) {

name = t;

public static void main(String[] args) {

Language cpp = new Language();

Language java = new Language("Java");


[Link]("C++");

[Link]();

[Link]();

void setName(String t) {

name = t;

void getName() {

[Link]("Language name: " + name);

49. Exception Handling java Program

class Division {

public static void main(String[] args) {

int a, b, result;

Scanner input = new Scanner([Link]);

[Link]("Input two integers");

a = [Link]();

b = [Link]();

// try block

try {

result = a / b;

[Link]("Result = " + result);


}

// catch block

catch (ArithmeticException e) {

[Link]("Exception caught: Division by zero.");

How to throw exception in java Program

public class TestThrow1{

static void validate(int age){

if(age<18)

throw new ArithmeticException("not valid");

else

[Link]("welcome to vote on Technolamror");

public static void main(String args[]){

validate(13);

[Link]("rest of the code...");

Common questions

Powered by AI

If-else structures in Java create a decision-making control flow, where the program executes different code blocks based on the boolean evaluation of conditions. This allows for dynamic and responsive programs. An inadequately structured if-else can lead to overlapping conditions, ignoring certain cases, or creating extensive nested blocks that reduce readability and increase the complexity of debugging. Therefore, proper syntax, clear condition statements, and avoidance of unnecessary nesting are critical to maintain control flow clarity .

Command line arguments allow Java applications to be more flexible by accepting inputs directly from the command line at runtime without altering the code. This is beneficial for providing different inputs quickly and automating tasks with scripts. However, a major drawback is the management of input validation, as the user must ensure the provided arguments are correct in number and format. Furthermore, they might lack intuitiveness for users unfamiliar with command line operations .

For loops in Java are vital for creating iterative tasks such as printing patterns. They provide a controlled environment to repeat a block of code a specified number of times, crucial for generating patterns. Their structure – initialization, condition checking, and iteration expression – facilitates straightforward iteration through sequences of numbers or rows. For example, in printing stars, an outer loop controls the number of rows, and an inner loop controls the number of stars per row. This double loop mechanism effectively handles complex patterns by nesting multiple levels of iteration .

Using a third variable offers a straightforward method to swap two numbers by temporarily holding one of the numbers. In the given Java program, the process is as follows: assign the value of 'x' to 'temp', then assign the value of 'y' to 'x'. Finally, assign the value of 'temp' to 'y'. This ensures the values are swapped without being lost. This approach is simple and minimizes the chance of errors compared to methods without a third variable .

compareTo() and equals() are methods in Java for string comparison that serve different purposes. compareTo() is used for lexicographical comparison and returns an integer based on the relative position of two strings in dictionary order. It is useful in sorting operations. On the other hand, equals() checks for exact content equality, returning a boolean. It is simpler and preferred when exact matches are necessary. Understanding these differences ensures proper use in scenarios requiring ordering versus equality checks .

Swapping numbers using a third variable involves a more intuitive and straightforward approach where a temporary variable holds one number's value during the swap, reducing the risk of logical errors. Conversely, swapping using arithmetic operations involves adding both numbers, then subtracting to achieve the swap. This method is more memory efficient as it doesn't require additional space but is prone to overflow errors in some languages or cases. Both methods provide valid results, but the choice depends on constraints like memory usage and code readability .

BigInteger in Java allows for arithmetic on integers of arbitrary size, which is crucial for calculations that exceed the limits of standard integer types. This class methods like add(), subtract(), and multiply() support large-scale computations without overflow errors. However, BigInteger operations might be less performant than primitive types due to the overhead of managing larger memory. Also, operations are not as straightforward or as fast as with standard data types, so they should be used judiciously when performance is a concern .

The Scanner class in Java simplifies user input by parsing input tokens from various input sources, such as System.in, making it easy to read and process user input in different data types (e.g., int, float, double, String). However, potential issues with Scanner include 'input mismatch' errors if the input type doesn't match the expected data type, and not closing the Scanner, which can lead to resource leaks. Additionally, if not used carefully, it can result in skipping inputs due to the buffer handling between nextLine() and other next methods .

Exception handling in Java provides a mechanism to manage errors gracefully without terminating the program abruptly. By using try-catch blocks, programs can catch runtime exceptions, process them, and either recover or fail gracefully by logging errors and informing the user. A failure to handle exceptions, such as not catching a potential ArithmeticException due to division by zero, could pose issues, leading to a program crash, loss of data, or poor user experience, particularly in critical applications like transaction processing systems .

The program to find the largest among three numbers employs logical operators (&&) to compare multiple conditions within if-else branches. These operators are crucial in decision-making to ensure that all necessary comparisons are evaluated together to determine the correct logical path. By using &&, the program ensures that only when one number is greater than both others, it is deemed the largest. Logical operators help create efficient, clear, and concise expressions critical for ensuring program correctness and mitigating logical errors .

100 JAVA PROGRAMS
1. Simple Java Program
 class HelloWorld 
{ 
public static void main(String args[]) 
{ 
System.out.println(
class GetInputFromUser 
{ 
   public static void main(String args[]) 
   { 
      int a; 
      float b; 
      String s;
}
}
6. How to swap 2 no using 3rd variable   Program 
in java 
import java.util.Scanner; 
  
class SwapNumbers 
{ 
   public
{ 
   public static void main(String args[]) 
   { 
      int x, y; 
      System.out.println("Enter x and y"); 
      Scanne
} 
//For Large Number 
import java.util.Scanner; 
import java.math.BigInteger; 
class AddingLargeNumbers { 
public static voi
z = in.nextInt(); 
  
      if ( x > y && x > z ) 
         System.out.println("First number is largest."); 
      else
int marksObtained, passingMarks; 
  
    passingMarks = 40; 
  
    Scanner input = new Scanner(System.in); 
  
    Syste
else 
        grade = 'D';  
  
      System.out.println("You passed the exam and your grade is " + grade); 
    }
class Factorial 
{ 
   public static void main(String args[]) 
   { 
      int n, c, fact = 1; 
  
      System.out.printl
int n, c; 
    BigInteger inc = new BigInteger("1"); 
    BigInteger fact = new BigInteger("1"); 
  
    Scanner input =

You might also like