[Go to site: main page, start]

0% found this document useful (0 votes)
90 views8 pages

Basic Java Programs PDF

This Java program contains a collection of 30 basic programs that demonstrate fundamental programming concepts such as input/output, arithmetic operations, control structures, and object-oriented programming. Each program is accessible through a main menu, allowing users to choose which functionality to execute, including tasks like calculating sums, checking prime numbers, and manipulating arrays. The program is designed for educational purposes to help beginners learn Java programming.

Uploaded by

shaik9391469742
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)
90 views8 pages

Basic Java Programs PDF

This Java program contains a collection of 30 basic programs that demonstrate fundamental programming concepts such as input/output, arithmetic operations, control structures, and object-oriented programming. Each program is accessible through a main menu, allowing users to choose which functionality to execute, including tasks like calculating sums, checking prime numbers, and manipulating arrays. The program is designed for educational purposes to help beginners learn Java programming.

Uploaded by

shaik9391469742
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

import [Link].

Scanner;

public class BasicJavaPrograms {

static Scanner sc = new Scanner([Link]);

// 1. Hello World
public static void helloWorld() {
[Link]("Hello, World!");
}

// 2. Sum of Two Numbers


public static void sumTwoNumbers() {
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();
[Link]("Sum = " + (num1 + num2));
}

// 3. Even or Odd
public static void evenOdd() {
[Link]("Enter a number: ");
int num = [Link]();
[Link](num + (num % 2 == 0 ? " is even" : " is odd"));
}

// 4. Largest of Three Numbers


public static void largestOfThree() {
[Link]("Enter three numbers: ");
int a = [Link](), b = [Link](), c = [Link]();
int largest = (a > b && a > c) ? a : (b > c ? b : c);
[Link]("Largest number is " + largest);
}

// 5. Simple Calculator
public static void calculator() {
[Link]("Enter first number: ");
double num1 = [Link]();
[Link]("Enter second number: ");
double num2 = [Link]();
[Link]("Addition: " + (num1 + num2));
[Link]("Subtraction: " + (num1 - num2));
[Link]("Multiplication: " + (num1 * num2));
if (num2 != 0)
[Link]("Division: " + (num1 / num2));

1
else
[Link]("Division by zero is not allowed");
}

// 6. Multiplication Table
public static void multiplicationTable() {
[Link]("Enter a number: ");
int num = [Link]();
for (int i = 1; i <= 10; i++)
[Link](num + " x " + i + " = " + (num * i));
}

// 7. Factorial
public static void factorial() {
[Link]("Enter a number: ");
int num = [Link]();
int fact = 1;
for (int i = 1; i <= num; i++)
fact *= i;
[Link]("Factorial of " + num + " is " + fact);
}

// 8. Fibonacci Series
public static void fibonacci() {
[Link]("Enter number of terms: ");
int n = [Link]();
int a = 0, b = 1;
[Link]("Fibonacci Series: ");
for (int i = 1; i <= n; i++) {
[Link](a + " ");
int next = a + b;
a = b;
b = next;
}
[Link]();
}

// 9. Reverse a Number
public static void reverseNumber() {
[Link]("Enter a number: ");
int num = [Link]();
int rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
[Link]("Reversed number: " + rev);
}

2
// 10. Prime Number Check
public static void primeNumber() {
[Link]("Enter a number: ");
int num = [Link]();
boolean isPrime = true;
if (num <= 1) isPrime = false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) { isPrime = false; break; }
}
[Link](num + (isPrime ? " is prime" : " is not prime"));
}

// 11. Palindrome Number


public static void palindromeNumber() {
[Link]("Enter a number: ");
int num = [Link]();
int original = num, rev = 0;
while (num != 0) { rev = rev * 10 + num % 10; num /= 10; }
[Link](original + (original == rev ? " is a palindrome" : " is
not a palindrome"));
}

// 12. Sum of Array Elements


public static void sumArray() {
[Link]("Enter array size: "); int n = [Link]();
int[] arr = new int[n]; int sum = 0;
[Link]("Enter array elements: ");
for (int i = 0; i < n; i++) { arr[i] = [Link](); sum += arr[i]; }
[Link]("Sum of array elements = " + sum);
}

// 13. Maximum in Array


public static void maxArray() {
[Link]("Enter array size: "); int n = [Link]();
int[] arr = new int[n];
[Link]("Enter array elements: ");
for (int i = 0; i < n; i++) arr[i] = [Link]();
int max = arr[0];
for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i];
[Link]("Maximum element = " + max);
}

// 14. Reverse a String


public static void reverseString() {
[Link]("Enter a string: "); [Link]();
String str = [Link]();
String rev = new StringBuilder(str).reverse().toString();

3
[Link]("Reversed string: " + rev);
}

// 15. Count Vowels in String


public static void countVowels() {
[Link]("Enter a string: "); [Link]();
String str = [Link]().toLowerCase(); int count = 0;
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ("aeiou".indexOf(ch) != -1) count++;
}
[Link]("Number of vowels = " + count);
}

// 16. Swap Two Numbers


public static void swapNumbers() {
[Link]("Enter first number: "); int a = [Link]();
[Link]("Enter second number: "); int b = [Link]();
[Link]("Before swap: a=" + a + ", b=" + b);
int temp = a; a = b; b = temp;
[Link]("After swap: a=" + a + ", b=" + b);
}

// 17. Simple OOP Example


static class Person {
String name; int age;
Person(String name,int age){ [Link]=name; [Link]=age; }
void display(){ [Link]("Name: " + name + ", Age: " + age); }
}
public static void simpleOOP() {
[Link]();
[Link]("Enter name: "); String name = [Link]();
[Link]("Enter age: "); int age = [Link]();
Person p = new Person(name, age);
[Link]();
}

// 18. Count Digits in Number


public static void countDigits() {
[Link]("Enter a number: "); int num = [Link](); int count = 0;
int n = num;
while (n != 0) { n /= 10; count++; }
[Link]("Number of digits in " + num + " = " + count);
}

// 19. Sum of Natural Numbers


public static void sumNatural() {
[Link]("Enter a number: "); int n = [Link](); int sum = 0;

4
for (int i = 1; i <= n; i++) sum += i;
[Link]("Sum of first " + n + " natural numbers = " + sum);
}

// 20. Multiples of 5 up to N
public static void multiplesOfFive() {
[Link]("Enter a number: "); int n = [Link]();
[Link]("Multiples of 5 up to " + n + ": ");
for (int i = 5; i <= n; i += 5) [Link](i + " ");
[Link]();
}

// 21. Check Armstrong Number


public static void armstrongNumber() {
[Link]("Enter a number: "); int num = [Link]();
int original = num, sum = 0;
while (num != 0) { int digit = num % 10; sum += digit*digit*digit; num/
=10; }
[Link](original + (original==sum ? " is an Armstrong number" :
" is not an Armstrong number"));
}

// 22. GCD of Two Numbers


public static void gcdTwoNumbers() {
[Link]("Enter two numbers: "); int a=[Link](), b=[Link]();
int gcd=1;
for(int i=1;i<=[Link](a,b);i++) if(a%i==0 && b%i==0) gcd=i;
[Link]("GCD = " + gcd);
}

// 23. LCM of Two Numbers


public static void lcmTwoNumbers() {
[Link]("Enter two numbers: "); int a=[Link](), b=[Link]();
int lcm = (a>b?a:b);
while(true){ if(lcm%a==0 && lcm%b==0) break; lcm++;}
[Link]("LCM = " + lcm);
}

// 24. Check Perfect Number


public static void perfectNumber() {
[Link]("Enter a number: "); int num = [Link](); int sum=0;
for(int i=1;i<num;i++) if(num%i==0) sum+=i;
[Link](num + (sum==num ? " is a Perfect number" : " is not a
Perfect number"));
}

// 25. Fibonacci using Recursion


public static int fibRec(int n){ if(n==0) return 0; if(n==1) return 1; return

5
fibRec(n-1)+fibRec(n-2);}
public static void fibonacciRecursion(){
[Link]("Enter number of terms: "); int n = [Link]();
[Link]("Fibonacci Series: ");
for(int i=0;i<n;i++) [Link](fibRec(i)+" ");
[Link]();
}

// 26. Count Words in String


public static void countWords(){
[Link]("Enter a string: "); [Link](); String
str=[Link]().trim();
if([Link]()) [Link]("Word count = 0");
else [Link]("Word count = " + [Link]("\\s+").length);
}

// 27. Reverse Array


public static void reverseArray(){
[Link]("Enter array size: "); int n=[Link](); int[] arr=new
int[n];
[Link]("Enter array elements: "); for(int i=0;i<n;i++)
arr[i]=[Link]();
[Link]("Reversed array: "); for(int i=n-1;i>=0;i--)
[Link](arr[i]+" ");
[Link]();
}

// 28. Find Smallest in Array


public static void minArray(){
[Link]("Enter array size: "); int n=[Link](); int[] arr=new
int[n];
[Link]("Enter array elements: "); for(int i=0;i<n;i++)
arr[i]=[Link]();
int min=arr[0]; for(int i=1;i<n;i++) if(arr[i]<min) min=arr[i];
[Link]("Minimum element = " + min);
}

// 29. Check Palindrome String


public static void palindromeString(){
[Link]("Enter a string: "); [Link](); String
str=[Link]();
String rev=new StringBuilder(str).reverse().toString();
[Link](str + ([Link](rev) ? " is a palindrome" : " is not a
palindrome"));
}

// 30. Swap Two Numbers Without Temp


public static void swapWithoutTemp(){

6
[Link]("Enter first number: "); int a=[Link]();
[Link]("Enter second number: "); int b=[Link]();
[Link]("Before swap: a="+a+", b="+b);
a=a+b; b=a-b; a=a-b;
[Link]("After swap: a="+a+", b="+b);
}

// Main Menu
public static void main(String[] args){
while(true){
[Link]("\n--- Basic Java Programs ---");
for(int i=1;i<=30;i++) [Link](i+". Program "+i);
[Link]("0. Exit");
[Link]("Choose an option: "); int choice=[Link]();
switch(choice){
case 1: helloWorld(); break;
case 2: sumTwoNumbers(); break;
case 3: evenOdd(); break;
case 4: largestOfThree(); break;
case 5: calculator(); break;
case 6: multiplicationTable(); break;
case 7: factorial(); break;
case 8: fibonacci(); break;
case 9: reverseNumber(); break;
case 10: primeNumber(); break;
case 11: palindromeNumber(); break;
case 12: sumArray(); break;
case 13: maxArray(); break;
case 14: reverseString(); break;
case 15: countVowels(); break;
case 16: swapNumbers(); break;
case 17: simpleOOP(); break;
case 18: countDigits(); break;
case 19: sumNatural(); break;
case 20: multiplesOfFive(); break;
case 21: armstrongNumber(); break;
case 22: gcdTwoNumbers(); break;
case 23: lcmTwoNumbers(); break;
case 24: perfectNumber(); break;
case 25: fibonacciRecursion(); break;
case 26: countWords(); break;
case 27: reverseArray(); break;
case 28: minArray(); break;
case 29: palindromeString(); break;
case 30: swapWithoutTemp(); break;
case 0: [Link]("Exiting..."); return;
default: [Link]("Invalid choice!");
}

7
}
}

Common questions

Powered by AI

The program calculates the greatest common divisor (GCD) by iteratively checking each number from 1 to the minimum of the two numbers to see if it divides both numbers without a remainder, maintaining the largest such divisor. While this method is straightforward, its O(n) complexity is not as efficient as the Euclidean algorithm, which is often preferred for its logarithmic efficiency .

The program evaluates if a number is prime by first checking if the number is less than or equal to 1, in which case it is not prime. Then, it loops from 2 up to the square root of the number to check divisibility. If any divisor is found (i.e., num % i == 0), the number is not prime. It uses a boolean flag 'isPrime', initially set to true, which is changed to false if a divisor is found during the loop. The result is printed indicating whether the number is prime or not .

The program initializes a variable 'max' with the first element of the array. It then iteratively compares each element of the array with 'max'. If a larger element is found, 'max' is updated. This single pass through the array ensures an O(n) time complexity, making it efficient for finding the maximum value .

The method swaps two numbers without a temporary variable by utilizing arithmetic operations: it first adds both numbers and stores the result in the first variable, then subtracts the second variable from the first to derive the original value of the first variable, now stored in the second. Lastly, it subtracts the new value of the second from the first to restore the original value of the second into the first. This process utilizes the commutative properties of addition and subtraction .

The program determines if a number is odd or even by using the modulus operator (%) to check the remainder of the division of the number by 2. If the remainder is 0, the number is even; otherwise, it is odd. This logic is implemented in the 'evenOdd' method, where it prints the result based on the condition (num % 2 == 0) ? " is even" : " is odd" .

The program uses a recursive method 'fibRec' to calculate the Fibonacci series, which calls itself with the parameters n-1 and n-2 and sums their results until the base cases are reached (n == 0 or n == 1). This differs from the iterative method, which uses a loop to build the series by maintaining two previous results and updating them incrementally. The recursive approach can be less efficient due to repeated calculations, contrasting with the iterative method's linear progression in computing the series .

The simple calculator program performs division by checking if the divisor (second number) is not zero before executing the division operation. If the divisor is zero, it prints a message saying "Division by zero is not allowed" instead of attempting to divide. This precaution avoids division by zero errors, which would normally throw an exception .

The program reverses a given string by utilizing the StringBuilder class, which has a 'reverse' method. The method takes the input string, creates a StringBuilder object with it, reverses the sequence of characters, and converts it back to a string using the 'toString' method, which is then printed as the reversed string .

The program checks if a string is a palindrome by reversing the string using the StringBuilder's reverse method, then comparing it with the original string. If the reversed string matches the original, it is identified as a palindrome, otherwise it is not. This straightforward approach directly evaluates the equality of the strings .

The program uses a series of conditional (ternary) operators to compare three integers. It checks if the first number is greater than both the second and third numbers to assign it as the largest. If this condition is false, it checks if the second number is greater than the third one. The largest number is then printed. This process is implemented in the 'largestOfThree' method .

You might also like