Java Prog2
Java Prog2
import java.util.Scanner;
public class ReverseNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int reverse = 0;
while (num != 0) {
int digit = num % 10; // Get the last digit
reverse = reverse * 10 + digit; // Append digit to the reverse number
num /= 10; // Remove the last digit
}
System.out.println("Reversed number: " + reverse);
}
}
3. Reverse an Array
• This program reverses an array and prints its elements in reverse order.
• It first reads the array elements from the user and then prints them in reverse.
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
int[] arr = new int[size];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
arr[i] = scanner.nextInt();
}
System.out.println("Array in reverse order:");
for (int i = size - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
4. Count Digits in a Number
• This program counts the total number of digits in a given number.
• It removes the last digit repeatedly by dividing the number by 10 until the number
becomes 0.
import java.util.Scanner;
public class CountDigits {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int count = 0;
while (num != 0) {
num /= 10; // Remove the last digit
count++; // Increase the count
}
System.out.println("Total digits: " + count);
}
}
5. Write an applet program to display the text “Hello, Welcome to Java Applet” using
html.
import java.applet.Applet;
import java.awt.Graphics;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, welcome to Java Applet!", 20, 20);
}
}
Html code:
<html>
<head>
<title>Simple Java Applet</title>
</head>
<body>
<h1>Java Applet Example</h1>
<applet code="SimpleApplet.class" width="300" height="100">
</applet>
</body>
</html>