[Go to site: main page, start]

0% found this document useful (0 votes)
11 views29 pages

Java Program

The document contains a series of Java programming exercises, each demonstrating a different concept such as printing even numbers, calculating factorials, checking for palindromes, and implementing various algorithms like finding the largest element in an array and checking for anagrams. Each exercise includes a class definition with a main method that executes the specific task. The document serves as a practical guide for learning Java programming through hands-on examples.

Uploaded by

Dhawal Nagar
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)
11 views29 pages

Java Program

The document contains a series of Java programming exercises, each demonstrating a different concept such as printing even numbers, calculating factorials, checking for palindromes, and implementing various algorithms like finding the largest element in an array and checking for anagrams. Each exercise includes a class definition with a main method that executes the specific task. The document serves as a practical guide for learning Java programming through hands-on examples.

Uploaded by

Dhawal Nagar
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

1.

Print Even Numbers (1–50)

class EvenNumbers {

public static void main(String[] args) {

for(int i = 1; i <= 50; i++) {

if(i % 2 == 0) {

[Link](i + " ");

2. Multiplication Table

class MultiplicationTable {

public static void main(String[] args) {

int num = 5;

for(int i = 1; i <= 10; i++) {

[Link](num + " x " + i + " = " + (num * i));

3. Factorial

class Factorial {

public static void main(String[] args) {

int num = 5;
int fact = 1;

for(int i = 1; i <= num; i++) {

fact *= i;

[Link]("Factorial = " + fact);

4. Sum of Digits

class SumOfDigits {

public static void main(String[] args) {

int num = 1234;

int sum = 0;

while(num > 0) {

sum += num % 10;

num /= 10;

[Link]("Sum of digits = " + sum);

}
5. Palindrome Number

class PalindromeNumber {

public static void main(String[] args) {

int num = 121;

int original = num;

int reverse = 0;

while(num > 0) {

reverse = reverse * 10 + (num % 10);

num /= 10;

if(original == reverse)

[Link]("Palindrome");

else

[Link]("Not Palindrome");

6. Star Triangle

class StarTriangle {

public static void main(String[] args) {

for(int i = 1; i <= 5; i++) {

for(int j = 1; j <= i; j++) {

[Link]("*");

}
[Link]();

7. Inverted Star Triangle

class InvertedTriangle {

public static void main(String[] args) {

for(int i = 5; i >= 1; i--) {

for(int j = 1; j <= i; j++) {

[Link]("*");

[Link]();

8. Number Pyramid

class NumberPyramid {

public static void main(String[] args) {

for(int i = 1; i <= 5; i++) {

for(int j = 1; j <= i; j++) {

[Link](j);

[Link]();
}

9. Positive, Negative or Zero

class CheckNumberType {

public static void main(String[] args) {

int num = -10;

if(num > 0)

[Link]("Positive");

else if(num < 0)

[Link]("Negative");

else

[Link]("Zero");

10. Prime Number

class PrimeNumber {

public static void main(String[] args) {

int num = 7;

boolean isPrime = true;

if(num <= 1)
isPrime = false;

for(int i = 2; i <= num/2; i++) {

if(num % i == 0) {

isPrime = false;

break;

if(isPrime)

[Link]("Prime");

else

[Link]("Not Prime");

11. Leap Year

class LeapYear {

public static void main(String[] args) {

int year = 2024;

if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

[Link]("Leap Year");

else

[Link]("Not Leap Year");

}
}

12. Vowel or Consonant

class VowelOrConsonant {

public static void main(String[] args) {

char ch = 'a';

if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'||

ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')

[Link]("Vowel");

else

[Link]("Consonant");

13. Simple Calculator (Switch)

class SimpleCalculator {

public static void main(String[] args) {

int a = 10, b = 5;

char op = '+';

switch(op) {

case '+': [Link](a + b); break;

case '-': [Link](a - b); break;

case '*': [Link](a * b); break;

case '/': [Link](a / b); break;


default: [Link]("Invalid Operator");

14. Armstrong Number

class ArmstrongNumber {

public static void main(String[] args) {

int num = 153;

int original = num;

int sum = 0;

while(num > 0) {

int digit = num % 10;

sum += digit * digit * digit;

num /= 10;

if(original == sum)

[Link]("Armstrong Number");

else

[Link]("Not Armstrong Number");

}
15. Fibonacci Series

class FibonacciSeries {

public static void main(String[] args) {

int a = 0, b = 1;

for(int i = 1; i <= 10; i++) {

[Link](a + " ");

int next = a + b;

a = b;

b = next;

16️⃣ Find the Largest Element in an Array

class LargestElement {

public static void main(String[] args) {

int arr[] = {10, 25, 5, 40, 15};

int max = arr[0];

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

if(arr[i] > max) {

max = arr[i];

[Link]("Largest element = " + max);


}

17️⃣ Find Sum and Average of Array Elements

class SumAndAverage {

public static void main(String[] args) {

int arr[] = {10, 20, 30, 40};

int sum = 0;

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

sum += arr[i];

double average = (double) sum / [Link];

[Link]("Sum = " + sum);

[Link]("Average = " + average);

18️⃣ Reverse an Array Without Using Another Array

class ReverseArray {

public static void main(String[] args) {

int arr[] = {1, 2, 3, 4, 5};


int start = 0;

int end = [Link] - 1;

while(start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

[Link]("Reversed Array:");

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

[Link](arr[i] + " ");

19️⃣ Count Even and Odd Numbers in an Array

class CountEvenOdd {

public static void main(String[] args) {

int arr[] = {1, 2, 3, 4, 5, 6};

int even = 0, odd = 0;

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


if(arr[i] % 2 == 0)

even++;

else

odd++;

[Link]("Even count = " + even);

[Link]("Odd count = " + odd);

20️⃣ Check if Array is Sorted

class CheckSorted {

public static void main(String[] args) {

int arr[] = {1, 2, 3, 4, 5};

boolean sorted = true;

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

if(arr[i] > arr[i + 1]) {

sorted = false;

break;

if(sorted)

[Link]("Array is Sorted");
else

[Link]("Array is Not Sorted");

21️⃣ Move All Zeroes to End (Without Changing Order)

class MoveZeroes {

public static void main(String[] args) {

int arr[] = {0, 1, 0, 3, 12};

int index = 0;

// Move non-zero elements forward

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

if(arr[i] != 0) {

arr[index++] = arr[i];

// Fill remaining positions with zero

while(index < [Link]) {

arr[index++] = 0;

[Link]("After moving zeroes:");

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

[Link](arr[i] + " ");


}

22️⃣ Find Missing Number (1 to n+1)

class MissingNumber {

public static void main(String[] args) {

int arr[] = {1, 2, 4, 5}; // Missing 3

int n = [Link] + 1;

int expectedSum = n * (n + 1) / 2;

int actualSum = 0;

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

actualSum += arr[i];

int missing = expectedSum - actualSum;

[Link]("Missing number = " + missing);

23️⃣ Find Second Largest Number in an Array

class SecondLargest {

public static void main(String[] args) {


int arr[] = {10, 25, 40, 5, 30};

int largest = arr[0];

int secondLargest = arr[0];

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

if(arr[i] > largest) {

secondLargest = largest;

largest = arr[i];

} else if(arr[i] > secondLargest && arr[i] != largest) {

secondLargest = arr[i];

[Link]("Second Largest = " + secondLargest);

24️⃣ Check Palindrome (String)

class StringPalindrome {

public static void main(String[] args) {

String str = "madam";

String reverse = "";

for(int i = [Link]() - 1; i >= 0; i--) {

reverse += [Link](i);
}

if([Link](reverse))

[Link]("Palindrome");

else

[Link]("Not Palindrome");

25️⃣ Convert to Uppercase Without Inbuilt Function

class ToUpperCaseManual {

public static void main(String[] args) {

String str = "hello world";

String result = "";

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

char ch = [Link](i);

if(ch >= 'a' && ch <= 'z') {

ch = (char)(ch - 32);

result += ch;

[Link]("Uppercase: " + result);


}

26️⃣ Frequency of a Character in a String

class CharFrequency {

public static void main(String[] args) {

String str = "programming";

char ch = 'g';

int count = 0;

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

if([Link](i) == ch) {

count++;

[Link]("Frequency of " + ch + " = " + count);

27️⃣ Count Number of Words in a String

class WordCount {

public static void main(String[] args) {

String str = "Java is very easy";

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

if([Link](i) == ' ') {

count++;

[Link]("Number of words = " + count);

28️⃣ Remove Duplicates from a String

class RemoveDuplicates {

public static void main(String[] args) {

String str = "programming";

String result = "";

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

char ch = [Link](i);

if([Link](ch) == -1) {

result += ch;

[Link]("After removing duplicates: " + result);


}

29️⃣ First Non-Repeating Character

class FirstNonRepeating {

public static void main(String[] args) {

String str = "swiss";

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

char ch = [Link](i);

int count = 0;

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

if([Link](j) == ch) {

count++;

if(count == 1) {

[Link]("First non-repeating character: " + ch);

break;

}
30️⃣ Print ASCII Value of Each Character

class ASCIIValues {

public static void main(String[] args) {

String str = "Java";

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

char ch = [Link](i);

[Link](ch + " = " + (int)ch);

31️⃣ Check for Anagram String

class AnagramCheck {

public static void main(String[] args) {

String str1 = "listen";

String str2 = "silent";

// Convert to lowercase

str1 = [Link]();

str2 = [Link]();

if([Link]() != [Link]()) {

[Link]("Not Anagram");

return;

}
char[] arr1 = [Link]();

char[] arr2 = [Link]();

// Sort both arrays

[Link](arr1);

[Link](arr2);

if([Link](arr1, arr2))

[Link]("Anagram");

else

[Link]("Not Anagram");

32️⃣ Encapsulation Example

class Student {

private String name;

private int age;

// Setter methods

public void setName(String name) {

[Link] = name;

public void setAge(int age) {


[Link] = age;

// Getter methods

public String getName() {

return name;

public int getAge() {

return age;

class EncapsulationDemo {

public static void main(String[] args) {

Student s = new Student();

[Link]("Dhawal");

[Link](22);

[Link]("Name: " + [Link]());

[Link]("Age: " + [Link]());

👉 Encapsulation = Data hiding using private variables + public


getter/setter methods.
33️⃣ Inheritance Examples

(Single, Multilevel, Hierarchical)

// Parent class

class Animal {

void eat() {

[Link]("Animal eats food");

// Single Inheritance

class Dog extends Animal {

void bark() {

[Link]("Dog barks");

// Multilevel Inheritance

class Puppy extends Dog {

void weep() {

[Link]("Puppy weeps");

// Hierarchical Inheritance

class Cat extends Animal {

void meow() {
[Link]("Cat meows");

class InheritanceDemo {

public static void main(String[] args) {

// Single

Dog d = new Dog();

[Link]();

[Link]();

// Multilevel

Puppy p = new Puppy();

[Link]();

[Link]();

[Link]();

// Hierarchical

Cat c = new Cat();

[Link]();

[Link]();

34️⃣ Runtime Polymorphism (Method Overriding)


class Vehicle {

void run() {

[Link]("Vehicle is running");

class Bike extends Vehicle {

@Override

void run() {

[Link]("Bike is running safely");

class RuntimePolymorphismDemo {

public static void main(String[] args) {

Vehicle v = new Bike(); // Parent reference, child object

[Link](); // Calls overridden method

1️⃣ LeetCode 1480 – Running Sum of 1d Array

✅ Logic:

class Solution {

public int[] runningSum(int[] nums) {

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

nums[i] = nums[i] + nums[i - 1];


}

return nums;

2️⃣ LeetCode 724 – Find Pivot Index

✅ Logic:

Pivot index = left sum == right sum

class Solution {

public int pivotIndex(int[] nums) {

int totalSum = 0;

for(int num : nums)

totalSum += num;

int leftSum = 0;

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

if(leftSum == totalSum - leftSum - nums[i])

return i;

leftSum += nums[i];

return -1;

}
Time Complexity: O(n)
Space Complexity: O(1)

3️⃣ LeetCode 121 – Best Time to Buy and Sell Stock

✅ Logic:

Track minimum price & maximum profit.

class Solution {

public int maxProfit(int[] prices) {

int minPrice = Integer.MAX_VALUE;

int maxProfit = 0;

for(int price : prices) {

if(price < minPrice) {

minPrice = price;

} else {

maxProfit = [Link](maxProfit, price - minPrice);

return maxProfit;

Time Complexity: O(n)


Space Complexity: O(1)
4️⃣ LeetCode 283 – Move Zeroes

✅ Logic:

Move non-zero elements forward, fill remaining with zero.

class Solution {

public void moveZeroes(int[] nums) {

int index = 0;

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

if(nums[i] != 0) {

nums[index++] = nums[i];

while(index < [Link]) {

nums[index++] = 0;

Time Complexity: O(n)


Space Complexity: O(1)

5️⃣ LeetCode 303 – Range Sum Query - Immutable

✅ Logic:

Use Prefix Sum array

class NumArray {
private int[] prefix;

public NumArray(int[] nums) {

prefix = new int[[Link]];

if([Link] > 0) {

prefix[0] = nums[0];

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

prefix[i] = prefix[i - 1] + nums[i];

public int sumRange(int left, int right) {

if(left == 0)

return prefix[right];

return prefix[right] - prefix[left - 1];

Time Complexity: O(n)


Space Complexity: O(1)

You might also like