0% found this document useful (0 votes)
3 views65 pages

Program Computer Application

The document contains multiple Java programs that solve various problems related to string and array manipulations. Key functionalities include finding the longest word, counting word frequencies, checking for palindromes, and converting strings to toggle case. Each program includes user input and outputs relevant results based on the specified tasks.

Uploaded by

Tanmoy Banerjee
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)
3 views65 pages

Program Computer Application

The document contains multiple Java programs that solve various problems related to string and array manipulations. Key functionalities include finding the longest word, counting word frequencies, checking for palindromes, and converting strings to toggle case. Each program includes user input and outputs relevant results based on the specified tasks.

Uploaded by

Tanmoy Banerjee
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

1.

Longest Word in a String Array


The Question: Write a program in Java to input 10 words into a String array of size 10. Find and
display the longest word and its length.

The Program:

Java

import [Link];​

public class LongestWord {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
String a[] = new String[10];​
String maxWord = "";​

[Link]("Enter 10 words:");​
for (int i = 0; i < 10; i++) {​
a[i] = [Link]();​
// Checking for the longest word​
if (a[i].length() > [Link]()) {​
maxWord = a[i];​
}​
}​

[Link]("Longest Word: " + maxWord);​
[Link]("Length: " + [Link]());​
}​
}​

2. Word Frequency in a String Array


The Question: Write a program to input 10 words into a String array. Then, input a new word
and find its frequency (how many times it occurs) in the array.
The Program:

Java

import [Link];​

public class Frequency {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
String a[] = new String[10];​

[Link]("Enter 10 words:");​
for (int i = 0; i < 10; i++) {​
a[i] = [Link]();​
}​

[Link]("Enter word to search frequency: ");​
String searchWord = [Link]();​
int count = 0;​

for (int i = 0; i < 10; i++) {​
// Using equals() for exact match comparison​
if (a[i].equalsIgnoreCase(searchWord)) {​
count++;​
}​
}​
[Link]("Frequency of " + searchWord + " = " + count);​
}​
}​

3. Special Word Frequency


The Question: Write a program to input 10 words into a String array. A word is called a Special
Word if its first and last characters are the same. Count and display the special words.

The Program:
Java

import [Link];​

public class SpecialWord {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
String a[] = new String[10];​

[Link]("Enter 10 words:");​
for (int i = 0; i < 10; i++) {​
a[i] = [Link]();​
}​

[Link]("Special words are:");​
int count = 0;​
for (int i = 0; i < 10; i++) {​
String w = a[i].toUpperCase();​
char first = [Link](0);​
char last = [Link]([Link]() - 1);​

if (first == last) {​
[Link](a[i]);​
count++;​
}​
}​
[Link]("Total Special Words: " + count);​
}​
}​

4. Frequency of a Specific Character


The Question: Write a program to input a sentence and a single character. Find and display the
frequency of that character in the sentence.

The Program:

Java
import [Link];​

public class CharFrequency {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a sentence: ");​
String s = [Link]();​
[Link]("Enter character to count: ");​
char ch = [Link]().charAt(0);​

int count = 0;​
for (int i = 0; i < [Link](); i++) {​
if ([Link](i) == ch) {​
count++;​
}​
}​
[Link]("Frequency of '" + ch + "' is: " + count);​
}​
}​

5. Toggle Case Conversion


The Question: Write a program to input a sentence and convert it into Toggle Case
(Uppercase characters to Lowercase and vice-versa).

The Program:

Java

import [Link];​

public class ToggleCase {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a sentence: ");​
String s = [Link]();​
String toggled = "";​

for (int i = 0; i < [Link](); i++) {​
char ch = [Link](i);​
if ([Link](ch)) {​
toggled += [Link](ch);​
} else if ([Link](ch)) {​
toggled += [Link](ch);​
} else {​
toggled += ch;​
}​
}​
[Link]("Toggled String: " + toggled);​
}​
}​

6. PigLatin Conversion
The Question: Write a program to input a word and convert it to PigLatin form.

(Logic: Find the first vowel. Move everything before the first vowel to the end and add "AY".)

The Program:

Java

import [Link];​

public class PigLatin {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a word: ");​
String w = [Link]().toUpperCase();​
int pos = -1;​

for (int i = 0; i < [Link](); i++) {​
char ch = [Link](i);​
if ("AEIOU".indexOf(ch) != -1) {​
pos = i;​
break;​
}​
}​

if (pos != -1) {​
String pigLatin = [Link](pos) + [Link](0, pos) + "AY";​
[Link]("PigLatin Form: " + pigLatin);​
} else {​
[Link]("No vowels found.");​
}​
}​
}​

7. Word Count and Character Statistics


The Question: Write a program to input a sentence and count the number of:
1.​ Vowels
2.​ Upper case letters
3.​ Lower case letters
4.​ Digits
5.​ White spaces

The Program:

Java

import [Link];​

public class CharStats {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter sentence: ");​
String s = [Link]();​

int v = 0, uc = 0, lc = 0, d = 0, ws = 0;​
for (int i = 0; i < [Link](); i++) {​
char ch = [Link](i);​
if ("AEIOUaeiou".indexOf(ch) != -1) v++;​
if ([Link](ch)) uc++;​
else if ([Link](ch)) lc++;​
if ([Link](ch)) d++;​
if ([Link](ch)) ws++;​
}​

[Link]("Vowels: " + v);​
[Link]("Uppercase: " + uc);​
[Link]("Lowercase: " + lc);​
[Link]("Digits: " + d);​
[Link]("Spaces: " + ws);​
}​
}​
1. Character Array Frequency Analysis
The Question: Write a program in Java to create a character array of size $n$ and find the
frequency of:
1.​ Vowels
2.​ Upper case letters
3.​ Lower case letters
4.​ Digits
5.​ White spaces

The Program:

Java

import [Link];​

public class CharArrayStats {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter array size: ");​
int n = [Link]();​
char a[] = new char[n];​

int v = 0, uc = 0, lc = 0, d = 0, ws = 0;​

[Link]("Enter " + n + " characters:");​
for (int i = 0; i < n; i++) {​
a[i] = [Link]().charAt(0);​

// Checking logic​
char ch = a[i];​
if ("AEIOUaeiou".indexOf(ch) != -1) v++;​
if ([Link](ch)) uc++;​
else if ([Link](ch)) lc++;​
if ([Link](ch)) d++;​
if ([Link](ch)) ws++;​
}​

[Link]("Vowels: " + v);​
[Link]("Uppercase: " + uc);​
[Link]("Lowercase: " + lc);​
[Link]("Digits: " + d);​
[Link]("Spaces: " + ws);​
}​
}​

2. Vowel Count in a String Array


The Question: Write a program in Java to count the number of vowels in each word of a String
array of size 5. Display the word along with its vowel count.

The Program:

Java

import [Link];​

public class WordVowels {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
String arr[] = new String[5];​

[Link]("Enter 5 words:");​
for (int i = 0; i < 5; i++) {​
arr[i] = [Link]();​
}​

[Link]("Word\tVowels");​
for (int i = 0; i < 5; i++) {​
int count = 0;​
String word = arr[i].toUpperCase();​
for (int j = 0; j < [Link](); j++) {​
char ch = [Link](j);​
if ("AEIOU".indexOf(ch) != -1) {​
count++;​
}​
}​
[Link](arr[i] + "\t" + count);​
}​
}​
}​

3. Count Words Starting with a Vowel


The Question: Write a program in Java to count the number of words starting with a vowel in a
given sentence.

The Program:

Java

import [Link];​

public class VowelWords {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a sentence: ");​
String s = [Link]();​

// Split sentence into words using split() or a loop​
String words[] = [Link](" ");​
int count = 0;​

[Link]("Words starting with vowels:");​
for (String w : words) {​
char first = [Link]().charAt(0);​
if ("AEIOU".indexOf(first) != -1) {​
[Link](w + " ");​
count++;​
}​
}​
[Link]("\nTotal frequency: " + count);​
}​
}​
4. Palindrome Word Check
The Question: Write a program in Java to input a word and check if it is a Palindrome or not.
Convert the word to uppercase before checking.

The Program:

Java

import [Link];​

public class PalindromeCheck {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a word: ");​
String word = [Link]().toUpperCase();​
String rev = "";​

for (int i = [Link]() - 1; i >= 0; i--) {​
rev += [Link](i);​
}​

if ([Link](rev)) {​
[Link]("Palindrome");​
} else {​
[Link]("Not a Palindrome");​
}​
}​
}​

5. Toggle Case Conversion


The Question: Write a program to input a sentence and convert each character into its
opposite case (Toggle Case).
The Program:

Java

import [Link];​

public class ToggleCase {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a sentence: ");​
String s = [Link]();​
String result = "";​

for (int i = 0; i < [Link](); i++) {​
char ch = [Link](i);​
if ([Link](ch)) {​
result += [Link](ch);​
} else if ([Link](ch)) {​
result += [Link](ch);​
} else {​
result += ch;​
}​
}​
[Link]("Toggled string: " + result);​
}​
}​

6. Double Letter Pair Count


The Question: Input a word and check for "Double Pair" letters (consecutive letters that are
identical).

(Example: "GOOD" has 'O' and 'O' as a double pair).

The Program:

Java
import [Link];​

public class DoubleLetter {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a word: ");​
String word = [Link]().toUpperCase();​
int count = 0;​

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

if (count > 0) {​
[Link]("Double pair letters found: " + count);​
} else {​
[Link]("No double pair letters.");​
}​
}​
}​

7. Word Lengths in a String Array


The Question: Write a program in Java to input 5 words into a String array and print the length
of each word.

The Program:

Java

import [Link];​

public class WordLengthArray {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
String arr[] = new String[5];​

[Link]("Enter 5 words:");​
for (int i = 0; i < 5; i++) {​
arr[i] = [Link]();​
}​

[Link]("Word\tLength");​
for (int i = 0; i < 5; i++) {​
[Link](arr[i] + "\t" + arr[i].length());​
}​
}​
}​
1. Largest, Smallest, and Sum of Array Elements
The Question: Write a program to input 20 integer elements into an array. Find and display the
Largest number, the Smallest number, and the Sum of all elements.

The Program:

Java

import [Link];​

public class ArrayStats {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
int a[] = new int[20];​
int sum = 0;​

[Link]("Enter 20 elements:");​
for (int i = 0; i < 20; i++) {​
a[i] = [Link]();​
}​

int max = a[0];​
int min = a[0];​

for (int i = 0; i < 20; i++) {​
if (a[i] > max) max = a[i];​
if (a[i] < min) min = a[i];​
sum += a[i];​
}​

[Link]("Largest Number: " + max);​
[Link]("Smallest Number: " + min);​
[Link]("Sum of All Elements: " + sum);​
}​
}​
2. Character Array Frequency (Vowels, Case, Digits)
The Question: Create a character array of size $n$. Input characters and count the frequency
of Vowels, Upper Case letters, Lower Case letters, Digits, and White Spaces.

The Program:

Java

import [Link];​

public class CharFreq {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter size of array: ");​
int n = [Link]();​
char a[] = new char[n];​

int v = 0, uc = 0, lc = 0, d = 0, ws = 0;​

[Link]("Enter " + n + " characters:");​
for (int i = 0; i < n; i++) {​
a[i] = [Link]().charAt(0);​
char ch = a[i];​

if ("AEIOUaeiou".indexOf(ch) != -1) v++;​
if ([Link](ch)) uc++;​
else if ([Link](ch)) lc++;​
if ([Link](ch)) d++;​
if ([Link](ch)) ws++;​
}​

[Link]("Vowels: " + v);​
[Link]("Uppercase: " + uc);​
[Link]("Lowercase: " + lc);​
[Link]("Digits: " + d);​
[Link]("Spaces: " + ws);​
}​
}​
3. Linear Search (Name Search)
The Question: Input the names of 10 students in an array. Accept a name to be searched and
check for its existence using Linear Search. If found, display its position; otherwise, print
"Name not found."

The Program:

Java

import [Link];​

public class LinearSearchNames {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
String names[] = new String[10];​

[Link]("Enter 10 names:");​
for (int i = 0; i < 10; i++) names[i] = [Link]();​

[Link]("Enter name to search: ");​
String searchName = [Link]();​
int pos = -1;​

for (int i = 0; i < 10; i++) {​
if (names[i].equalsIgnoreCase(searchName)) {​
pos = i;​
break;​
}​
}​

if (pos != -1) {​
[Link]("Found at position: " + (pos + 1));​
} else {​
[Link]("Name not found.");​
}​
}​
}​
4. Binary Search (Integer Array)
The Question: Search for an integer element in a sorted array using the Binary Search
technique.

The Program:

Java

import [Link];​

public class BinarySearch {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; // Pre-sorted array​

[Link]("Enter number to search: ");​
int x = [Link]();​

int low = 0, high = [Link] - 1, mid, pos = -1;​
while (low <= high) {​
mid = (low + high) / 2;​
if (a[mid] == x) {​
pos = mid;​
break;​
} else if (x > a[mid]) {​
low = mid + 1;​
} else {​
high = mid - 1;​
}​
}​

if (pos != -1) [Link]("Element found at index: " + pos);​
else [Link]("Element not present.");​
}​
}​
5. Bubble Sort (Ascending Order)
The Question: Write a program to sort an array of 10 integers in ascending order using the
Bubble Sort technique.

The Program:

Java

import [Link];​

public class BubbleSort {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
int a[] = new int[10];​
[Link]("Enter 10 integers:");​
for (int i = 0; i < 10; i++) a[i] = [Link]();​

// Bubble Sort Logic​
for (int i = 0; i < 9; i++) {​
for (int j = 0; j < 9 - i; j++) {​
if (a[j] > a[j + 1]) {​
int temp = a[j];​
a[j] = a[j + 1];​
a[j + 1] = temp;​
}​
}​
}​

[Link]("Sorted Array:");​
for (int x : a) [Link](x + " ");​
}​
}​

6. Selection Sort (Descending Order)


The Question: Write a program to sort an array of 10 integers in descending order using the
Selection Sort technique.

The Program:

Java

import [Link];​

public class SelectionSort {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
int a[] = new int[10];​
[Link]("Enter 10 integers:");​
for (int i = 0; i < 10; i++) a[i] = [Link]();​

// Selection Sort Logic​
for (int i = 0; i < 9; i++) {​
int maxIdx = i;​
for (int j = i + 1; j < 10; j++) {​
if (a[j] > a[maxIdx]) {​
maxIdx = j;​
}​
}​
int temp = a[i];​
a[i] = a[maxIdx];​
a[maxIdx] = temp;​
}​

[Link]("Sorted Array (Descending):");​
for (int x : a) [Link](x + " ");​
}​
}​
1. Rules for Naming Identifiers (Variables)
The Question: What is an identifier? What are the rules for naming variables in Java? Write a
program to show valid and invalid declarations.

The Program:

Java

public class IdentifierDemo {​


public static void main(String[] args) {​
// Valid Identifiers​
int age = 25; // Simple letters​
double _salary = 50000; // Starts with underscore​
int $value = 100; // Starts with dollar sign​
int student1 = 1; // Letters followed by digits​

// Invalid Identifiers (Examples commented out as they cause errors)​
// int 1student = 1; // Error: Cannot start with a digit​
// int class = 5; // Error: Cannot use keywords​
// int my age = 20; // Error: Cannot contain spaces​
// int total-sum = 10; // Error: Cannot contain hyphens​

[Link]("Identifier rules: Start with letter/$/_, no digits at start, no keywords.");​
}​
}​

2. Escape Sequences in Java


The Question: What are escape sequences? Write a program to demonstrate the use of \n, \t,
and \b.

The Program:

Java
public class EscapeSequenceDemo {​
public static void main(String[] args) {​
// \n for new line, \t for tab space, \b for backspace​
[Link]("Hello\nWorld"); // Prints on two lines​
[Link]("Name:\tTarun"); // Inserts a tab space​
[Link]("Java\b Programming"); // Deletes the 'a' in Java​
[Link]("He said, \"Hello!\""); // To print double quotes​
}​
}​

3. Evaluation of Increment and Decrement Expressions


The Question: Find the value of $x$ after evaluating the following expression:

x += x++ - --x + x when the initial value of $x = 3$.

The Program:

Java

public class ExpressionEvaluation {​


public static void main(String[] args) {​
int x = 3;​

// Evaluation logic:​
// x = x + (x++ - --x + x)​
// x = 3 + (3 - 3 + 3) ​
// Note: x++ uses 3 then x becomes 4. ​
// --x then makes x 3 again and uses 3.​
// The last x is now 3.​

x += x++ - --x + x;​

[Link]("The final value of x is: " + x); // Output: 6​
}​
}​
4. Conditional (Ternary) Operator
The Question: What is the conditional operator? Write a program to find the maximum of two
numbers using the ternary operator.

The Program:

Java

import [Link];​

public class TernaryDemo {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter two numbers: ");​
int a = [Link]();​
int b = [Link]();​

// condition ? expression1 : expression2​
int max = (a > b) ? a : b;​

[Link]("Maximum value is: " + max);​
}​
}​

5. Equivalent Java Expressions for Math Formulas


The Question: Write equivalent Java expressions for the following mathematical formulas:
1.​ $z = \sqrt{a^2 + b^2}$
2.​ $d = |x - y|$
3.​ $v = \sqrt[3]{s}$

The Program:

Java
public class MathExpressions {​
public static void main(String[] args) {​
double a = 3, b = 4;​
double x = 10, y = 25;​
double s = 27;​

// (i) Square root of sum of squares​
double z = [Link]([Link](a, 2) + [Link](b, 2));​

// (ii) Absolute difference​
double d = [Link](x - y);​

// (iii) Cube root​
double v = [Link](s);​

[Link]("z: " + z); // 5.0​
[Link]("d: " + d); // 15.0​
[Link]("v: " + v); // 3.0​
}​
}​

6. Difference between [Link]() and [Link]()


The Question: Explain the difference between [Link]() and [Link]() with a program
example.

The Program:

Java

public class CeilFloorDemo {​


public static void main(String[] args) {​
double val = 12.45;​

// ceil: smallest double value >= argument (Rounds UP)​
[Link]("Ceil of 12.45: " + [Link](val)); // 13.0​

// floor: largest double value <= argument (Rounds DOWN)​
[Link]("Floor of 12.45: " + [Link](val)); // 12.0​

// Negative example​
double negVal = -12.45;​
[Link]("Ceil of -12.45: " + [Link](negVal)); // -12.0​
[Link]("Floor of -12.45: " + [Link](negVal)); // -13.0​
}​
}​

7. Type Casting (Explicit Conversion)


The Question: What is type casting? Write a program to convert a double to an int.

The Program:

Java

public class TypeCastingDemo {​


public static void main(String[] args) {​
double price = 99.99;​

// Explicit conversion using (int)​
int roundedPrice = (int) price; ​

[Link]("Original double: " + price); // 99.99​
[Link]("Casted int: " + roundedPrice); // 99 (Loss of precision)​
}​
}​
.

1. Basic Method Structure (User-Defined Function)


The Question: What is a method? Write a program to create a user-defined function sum()
that takes two integers as parameters and returns their sum.

The Program:

Java

public class Calculator {​


// User-defined function to add two numbers​
public int sum(int a, int b) {​
return a + b; ​
}​

public static void main(String[] args) {​
Calculator obj = new Calculator();​
// Calling the method with parameters (Actual Arguments)​
int result = [Link](10, 20); ​
[Link]("The sum is: " + result);​
}​
}​

2. Function Overloading
The Question: Explain function overloading with an example. Write a program with multiple
methods named area() to calculate the area of a square, a rectangle, and a circle.

The Program:

Java

public class OverloadDemo {​


// Overloaded method for Square​
void area(int side) {​
[Link]("Area of Square: " + (side * side));​
}​

// Overloaded method for Rectangle​
void area(int length, int breadth) {​
[Link]("Area of Rectangle: " + (length * breadth));​
}​

// Overloaded method for Circle​
void area(double radius) {​
[Link]("Area of Circle: " + (3.14 * radius * radius));​
}​

public static void main(String[] args) {​
OverloadDemo obj = new OverloadDemo();​
[Link](5); // Calls Square method​
[Link](10, 20); // Calls Rectangle method​
[Link](7.5); // Calls Circle method​
}​
}​

3. Recursive Function (Recursion)


The Question: What is a recursive function? Write a program to find the factorial of a number
using recursion.

The Program:

Java

public class RecursionExample {​


// Recursive method to calculate factorial​
int factorial(int n) {​
if (n == 0 || n == 1) {​
return 1; // Base case​
} else {​
return n * factorial(n - 1); // Recursive call​
}​
}​

public static void main(String[] args) {​
RecursionExample obj = new RecursionExample();​
int num = 5;​
[Link]("Factorial of " + num + " is: " + [Link](num));​
}​
}​

4. Call by Value vs. Call by Reference


The Question: Demonstrate "Call by Value" using a Java program where values are passed to a
method but do not affect the original variables.

The Program:

Java

public class CallByValue {​


void change(int x) {​
x = x + 10; // Only local copy is changed​
}​

public static void main(String[] args) {​
CallByValue obj = new CallByValue();​
int n = 50;​
[Link]("Before method call: " + n);​
[Link](n);​
[Link]("After method call: " + n); // Value remains 50​
}​
}​

5. Pure vs. Impure Functions


The Question: Explain the difference between Pure and Impure functions with a program
example.

The Program:

Java

public class FunctionTypes {​


// Pure Function: Does not modify state, only returns a value based on arguments​
int pureAdd(int a, int b) {​
return a + b;​
}​

int total = 0;​
// Impure Function: Modifies the state of an object (instance variable)​
void impureAdd(int a) {​
total += a; ​
}​

public static void main(String[] args) {​
FunctionTypes obj = new FunctionTypes();​
[Link]("Pure Result: " + [Link](5, 5));​

[Link](10);​
[Link]("State after Impure call: " + [Link]);​
}​
}​
1. Basic Loop (Printing a Series)
The Question: Write a program in Java to print a series of numbers from 1 to 10 using a for
loop.

The Program:

Java

public class SeriesPrint {​


public static void main(String[] args) {​
// Loop structure: initialization; condition; increment​
for (int i = 1; i <= 10; i++) {​
[Link](i + " ");​
}​
}​
}​

2. Nested Loop Pattern (Star Triangle)


The Question: What is a nested loop? Write a program using nested loops to print a triangle
pattern of stars (*).

The Program:

Java

public class StarPattern {​


public static void main(String[] args) {​
// Outer loop for rows​
for (int i = 1; i <= 4; i++) {​
// Inner loop for columns (stars in each row)​
for (int j = 1; j <= i; j++) {​
[Link]("* ");​
}​
// Move to next line after each row​
[Link]();​
}​
}​
}​

3. Number Pattern (Increasing Triangle)


The Question: Write a program to print the following number pattern using nested loops:

Plaintext

1​
12​
123​
1 2 3 4​

The Program:

Java

public class NumberPattern {​


public static void main(String[] args) {​
for (int i = 1; i <= 4; i++) {​
for (int j = 1; j <= i; j++) {​
[Link](j + " ");​
}​
[Link]();​
}​
}​
}​
4. Factorial of a Number
The Question: What is factorial? Write a program to calculate and display the factorial of a
number input by the user (e.g., 5! = 120).

The Program:

Java

import [Link];​

public class Factorial {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a number: ");​
int n = [Link]();​
long fact = 1;​

for (int i = 1; i <= n; i++) {​
fact = fact * i;​
}​
[Link]("Factorial of " + n + " is: " + fact);​
}​
}​

5. Prime Number Check


The Question: A number is set to be prime if it is divisible only by 1 and itself. Write a program
to check if an input number is prime.

The Program:

Java

import [Link];​

public class PrimeCheck {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a number: ");​
int num = [Link]();​
int count = 0;​

for (int i = 1; i <= num; i++) {​
if (num % i == 0) {​
count++;​
}​
}​

if (count == 2) {​
[Link](num + " is a Prime Number.");​
} else {​
[Link](num + " is not a Prime Number.");​
}​
}​
}​

6. Sum of Series
The Question: Write a program to compute and display the sum of a mathematical series (e.g.,
$1 + 2 + 3 + ... + n$).

The Program:

Java

import [Link];​

public class SeriesSum {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter number of terms (n): ");​
int n = [Link]();​
int sum = 0;​

for (int i = 1; i <= n; i++) {​
sum += i;​
}​
[Link]("The sum of the series is: " + sum);​
}​
}​
1. Square Star Pattern
The Question: Write a program to print a 4x4 square pattern of stars using nested loops.

Plaintext

* * * *​
* * * *​
* * * *​
* * * *​

The Program:

Java

public class SquarePattern {​


public static void main(String[] args) {​
// controls rows​
for (int i = 1; i <= 4; i++) {​
// controls columns​
for (int j = 1; j <= 4; j++) {​
[Link]("* ");​
}​
// line break after each row​
[Link]();​
}​
}​
}​

2. Right-Angled Triangle Star Pattern


The Question: Write a program using nested loops to print a right-angled triangle pattern of
stars where the number of stars in each row equals the row number.
Plaintext

*​
* *​
* * *​
* * * *​

The Program:

Java

public class TrianglePattern {​


public static void main(String[] args) {​
for (int i = 1; i <= 4; i++) {​
// Inner loop runs until it reaches the current row index 'i'​
for (int j = 1; j <= i; j++) {​
[Link]("* ");​
}​
[Link]();​
}​
}​
}​

3. Left-to-Right Piramid (User Input Driven)


The Question: Write a program that asks the user how many lines they want to print and
generates a triangle pattern accordingly using a Scanner object.

The Program:

Java
import [Link];​

public class PyramidNum {​
public static void main(String[] args) {​
Scanner input = new Scanner([Link]);​
[Link]("Enter how many lines: ");​
int n = [Link]();​

for (int i = 1; i <= n; i++) {​
for (int j = 1; j <= i; j++) {​
[Link]("* ");​
}​
[Link]();​
}​
}​
}​

4. Diamond Shape Pattern (Upper half only example)


The Question: Discuss the logic for a diamond shape. How do you manage spaces and stars to
create a centered triangle?

The Program (Upper Pyramid):

Java

import [Link];​

public class CenteredPyramid {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter number of rows: ");​
int r = [Link]();​

for (int i = 1; i <= r; i++) {​
// Loop for spaces to shift stars to the right​
for (int k = 1; k <= r - i; k++) {​
[Link](" ");​
}​
// Loop for stars​
for (int j = 1; j <= i; j++) {​
[Link]("* ");​
}​
[Link]();​
}​
}​
}​

5. Decreasing Number Pattern


The Question: Write a program to print a decreasing number pattern based on a specific
starting string like "APPLE".

Plaintext

A P P L E​
A P P L​
A P P​
A P​
A​

The Program:

Java

public class StringPattern {​


public static void main(String[] args) {​
String s = "APPLE";​
int len = [Link]();​

for (int i = 1; i <= len; i++) {​
// Inner loop decreases range based on row index 'i'​
for (int j = 1; j <= len - i + 1; j++) {​
[Link]([Link](j - 1) + " ");​
}​
[Link]();​
}​
}​
}​
1. Iterative Process (Basic Loop)
The Question: What is an iterative process? How can it be resolved using a loop? Write a
program to print a sequence of numbers from 1 to 10 using a for loop to demonstrate this
process.

The Program:

Java

public class IterationDemo {​


public static void main(String[] args) {​
// Initialization (i=1), Condition (i<=10), Increment (i++)​
for (int i = 1; i <= 10; i++) {​
[Link](i); // Repeats until condition is false​
}​
}​
}​

2. Entry-Controlled Loop (While Loop)


The Question: Explain an entry-controlled loop. Write a program to print numbers from 1 to 5
using a while loop, showing that the condition is checked at the beginning.

The Program:

Java

public class WhileLoopDemo {​


public static void main(String[] args) {​
int i = 1; // Initial value​

// Condition checked at the entry point​
while (i <= 5) {​
[Link](i + " ");​
i++; // Update value​
}​
}​
}​

3. Exit-Controlled Loop (Do-While Loop)


The Question: What is an exit-controlled loop? Provide a program that prints a message at
least once using a do-while loop, even if the condition is false.

The Program:

Java

public class DoWhileDemo {​


public static void main(String[] args) {​
int i = 10;​

// Body executes first, then condition is checked​
do {​
[Link]("Execution starts: i is " + i);​
i++;​
} while (i < 5); // Condition is false, but body ran once​
}​
}​

4. Jump Statement (Break)


The Question: How can you terminate a loop prematurely? Write a program using a break
statement to stop a loop when a specific value is reached (e.g., stop when i is 5).

The Program:

Java
public class BreakDemo {​
public static void main(String[] args) {​
for (int i = 1; i <= 10; i++) {​
if (i == 5) {​
break; // Terminates the loop immediately​
}​
[Link](i + " ");​
}​
// Output: 1 2 3 4​
}​
}​

5. Jump Statement (Continue)


The Question: Explain the use of the continue statement. Write a program to print numbers
from 1 to 5 but skip the number 3.

The Program:

Java

public class ContinueDemo {​


public static void main(String[] args) {​
for (int i = 1; i <= 5; i++) {​
if (i == 3) {​
continue; // Skips current iteration and moves to next​
}​
[Link](i + " ");​
}​
// Output: 1 2 4 5​
}​
}​

6. Odd and Even Check using Modulo


The Question: Write a program to check if a number input by the user is even or odd using
conditional constructs.

The Program:

Java

import [Link];​

public class OddEvenCheck {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a number: ");​
int num = [Link]();​

// Modulo operator (%) returns the remainder​
if (num % 2 == 0) {​
[Link](num + " is Even.");​
} else {​
[Link](num + " is Odd.");​
}​
}​
}​
1. Basic Constructor (Default Constructor)
The Question: What is a constructor? Write a program to demonstrate a default constructor
that initializes a variable x to a specific value when an object is created.

The Program:

Java

public class MyClass {​


int x;​

// Default Constructor (no parameters)​
public MyClass() {​
x = 5; // Initializing instance variable​
}​

public static void main(String[] args) {​
// Constructor is called automatically when 'new' is used​
MyClass myObj = new MyClass();​
[Link]("Value of x: " + myObj.x); // Output: 5​
}​
}​

2. Parameterized Constructor
The Question: Explain parameterized constructors. Write a program to initialize an object's
state (like student marks or roll number) using values passed during object creation.

The Program:

Java

public class Result {​


int marks;​

// Parameterized Constructor​
public Result(int m) {​
marks = m; // Initializing marks with the value passed​
}​

public static void main(String[] args) {​
// Passing value '85' to the constructor​
Result student1 = new Result(85);​
[Link]("Student Marks: " + [Link]);​
}​
}​

3. Constructor Overloading
The Question: What is constructor overloading? Write a program for a Student class that has
one constructor to initialize only the roll number and another to initialize both the roll number
and marks.

The Program:

Java

public class Student {​


int roll;​
double marks;​

// Overload 1: Constructor with one argument​
public Student(int r) {​
roll = r;​
marks = 0.0;​
}​

// Overload 2: Constructor with two arguments​
public Student(int r, double m) {​
roll = r;​
marks = m;​
}​

void display() {​
[Link]("Roll: " + roll + ", Marks: " + marks);​
}​

public static void main(String[] args) {​
Student s1 = new Student(101);​
Student s2 = new Student(102, 92.5);​

[Link]();​
[Link]();​
}​
}​

4. Swapping Values Using a Constructor


The Question: Write a program to initialize two variables a and b using a constructor and then
swap their values in the main method.

The Program:

Java

public class Swap {​


int a, b;​

// Initializing variables through a constructor​
public Swap(int x, int y) {​
a = x;​
b = y;​
}​

public static void main(String[] args) {​
Swap obj = new Swap(10, 20);​
[Link]("Before Swapping: a=" + obj.a + ", b=" + obj.b);​

// Swapping logic​
int t = obj.a;​
obj.a = obj.b;​
obj.b = t;​

[Link]("After Swapping: a=" + obj.a + ", b=" + obj.b);​
}​
}​

5. Copy Constructor
The Question: What is a copy constructor? Write a program where one object is initialized
using the values of another existing object of the same class.

The Program:

Java

public class Point {​


int x, y;​

// Original Parameterized Constructor​
public Point(int a, int b) {​
x = a;​
y = b;​
}​

// Copy Constructor (takes an object of the same class)​
public Point(Point p) {​
x = p.x;​
y = p.y;​
}​

public static void main(String[] args) {​
Point p1 = new Point(10, 15);​
// Initializing p2 with values of p1​
Point p2 = new Point(p1); ​

[Link]("Object 2 values: x=" + p2.x + ", y=" + p2.y);​
}​
}​
1. Basic Class and Object Creation
The Question: What is an object? What is a class? Write a program to define a class Bike,
create objects for different bike brands (like Honda, Hero, TVS), and explain the relationship
using the new keyword.

The Program:

Java

public class Bike {​


// Attributes (State/Character)​
String brand;​
String color;​

public static void main(String[] args) {​
// Creating objects using the 'new' keyword​
Bike honda = new Bike(); ​
[Link] = "Honda";​
[Link] = "Red";​

Bike hero = new Bike();​
[Link] = "Hero";​
[Link] = "Black";​

[Link]("Brand: " + [Link] + ", Color: " + [Link]);​
[Link]("Brand: " + [Link] + ", Color: " + [Link]);​
}​
}​

2. Implementing Behavior with Methods


The Question: How do you define behavior in a class? Create a program with three distinct
methods: accept() to take input, calculate() to perform an operation (addition), and display() to
show the result.
The Program:

Java

import [Link];​

public class MathOperations {​
int a, b, sum;​

// Method to accept input​
void accept() {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter value for a: ");​
a = [Link]();​
[Link]("Enter value for b: ");​
b = [Link]();​
}​

// Method for processing​
void calculate() {​
sum = a + b;​
}​

// Method for output​
void display() {​
[Link]("The total sum is: " + sum);​
}​

public static void main(String[] args) {​
MathOperations obj = new MathOperations();​
[Link](); // Step 1: Input​
[Link](); // Step 2: Process​
[Link](); // Step 3: Output​
}​
}​

3. Working with Multiple Methods in One Function


The Question: Write a program that performs a subtraction logic within a single method and
demonstrates object instantiation within the main method.

The Program:

Java

import [Link];​

public class SimpleMath {​
// Single method to handle input, process, and output​
public void subtract() {​
Scanner sc = new Scanner([Link]);​
int n1, n2, result;​

[Link]("Enter first number: ");​
n1 = [Link]();​
[Link]("Enter second number: ");​
n2 = [Link]();​

result = n1 - n2;​
[Link]("The result of subtraction is: " + result);​
}​

public static void main(String[] args) {​
// Creating the object​
SimpleMath sm = new SimpleMath();​
// Calling the method​
[Link]();​
}​
}​
1. Basic User-Defined Method (Addition/Subtraction)
The Question: What is a user-defined method? Write a program to create a method named
subtraction() that takes two integers as parameters and returns their difference.

The Program:

Java

public class MathOps {​


// User-defined method to subtract two numbers​
public int subtraction(int x, int y) {​
return x - y; ​
}​

public static void main(String[] args) {​
MathOps obj = new MathOps();​
// Passing arguments 25 and 15​
int result = [Link](25, 15); ​
[Link]("The result of subtraction is: " + result); // Output: 10​
}​
}​

2. Method Overloading
The Question: Demonstrate method overloading. Create a class with multiple methods named
result() that have different parameter lists (e.g., one taking two integers and another taking
three integers).

The Program:

Java

public class OverloadingDemo {​


int sum;​

// Overload 1: Two integer parameters​
void result(int a, int b) {​
sum = a + b;​
[Link]("Sum of two numbers: " + sum);​
}​

// Overload 2: Three integer parameters​
void result(int a, int b, int c) {​
sum = a + b + c;​
[Link]("Sum of three numbers: " + sum);​
}​

// Overload 3: Mixed types (int and double)​
void result(double x, int y) {​
double res = x + y;​
[Link]("Sum of double and int: " + res);​
}​

public static void main(String[] args) {​
OverloadingDemo obj = new OverloadingDemo();​
[Link](10, 20); // Calls Overload 1​
[Link](10, 20, 30); // Calls Overload 2​
[Link](15.5, 5); // Calls Overload 3​
}​
}​

3. Call by Value
The Question: Explain "Call by Value" with a program. Show how changes made to a parameter
inside a method do not affect the original variable passed from the main method.

The Program:

Java

public class CallByValue {​


int n = 100;​

void myData(int n) {​
n = n + 50; // Change is only in the local copy​
[Link]("Inside method: " + n); // Output: 150​
}​

public static void main(String[] args) {​
CallByValue obj = new CallByValue();​
[Link]("Before calling method: " + obj.n); // Output: 100​
[Link](obj.n);​
[Link]("After calling method: " + obj.n); // Output: 100​
}​
}​

4. Call by Reference
The Question: Explain "Call by Reference" using a program. Show how passing an object as an
argument allows the method to modify the original object's state.

The Program:

Java

public class CallByRef {​


int n = 100;​

// Method takes an object as a reference​
void myData(CallByRef obj) {​
obj.n = obj.n + 50; // Modifies the actual object's instance variable​
}​

public static void main(String[] args) {​
CallByRef obj = new CallByRef();​
[Link]("Before calling method: " + obj.n); // Output: 100​
[Link](obj); // Passing the object reference​
[Link]("After calling method: " + obj.n); // Output: 150​
}​
}​

5. Polymorphism via Method Overloading


The Question: How is polymorphism implemented in Java using methods? Provide a program
example with different behaviors for the same method name.

The Program:

Java

public class PolyDemo {​


// Polymorphism: Same name 'add', different behaviors based on parameters​
void add(int a, int b) {​
[Link]("Integer Sum: " + (a + b));​
}​

void add(String s1, String s2) {​
[Link]("Concatenated Strings: " + s1 + s2);​
}​

public static void main(String[] args) {​
PolyDemo obj = new PolyDemo();​
[Link](5, 10); // behavior 1: addition​
[Link]("Hello ", "World"); // behavior 2: concatenation​
}​
}​
The Question: Showroom Discount Program
Design a class named Showroom with the following description:
●​ Instance Variables/Data Members:
○​ String name: To store the name of the customer.
○​ long mobno: To store the customer's mobile number.
○​ double cost: To store the cost of the items purchased.
○​ double dis: To store the discount amount.
○​ double amount: To store the net amount to be paid after discount.
●​ Member Methods:
○​ Showroom(): Default constructor to initialize data members with default values.
○​ void input(): To input customer name, mobile number, and cost.
○​ void calculate(): To calculate discount based on the following criteria:
■​ Cost $\le$ ₹10,000: 5% discount.
■​ Cost > ₹10,000 and $\le$ ₹20,000: 10% discount.
■​ Cost > ₹20,000 and $\le$ ₹35,000: 15% discount.
■​ Cost > ₹35,000: 20% discount.
■​ Also calculate amount = cost - dis.
○​ void display(): To display Customer Name, Mobile Number, and Net Amount to be paid.
○​ void main(): Create an object of the class and call the above methods.

The Complete Program

Java

import [Link].*; // Importing for Scanner class​



class Showroom {​
// Instance Variables​
String name;​
long mobno;​
double cost;​
double dis;​
double amount;​

// Default Constructor​
Showroom() {​
name = "";​
mobno = 0L;​
cost = 0.0;​
dis = 0.0;​
amount = 0.0;​
}​

// Method to take input​
void input() {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter Customer Name: ");​
name = [Link]();​
[Link]("Enter Mobile Number: ");​
mobno = [Link]();​
[Link]("Enter Cost of Items: ");​
cost = [Link]();​
}​

// Method to calculate discount and net amount​
void calculate() {​
if (cost <= 10000) {​
dis = cost * 5 / 100.0;​
} else if (cost > 10000 && cost <= 20000) {​
dis = cost * 10 / 100.0;​
} else if (cost > 20000 && cost <= 35000) {​
dis = cost * 15 / 100.0;​
} else {​
dis = cost * 20 / 100.0;​
}​
amount = cost - dis;​
}​

// Method to display results​
void display() {​
[Link]("Customer Name: " + name);​
[Link]("Mobile Number: " + mobno);​
[Link]("Amount to be paid after discount: " + amount);​
}​

// Main method to run the program​
public static void main(String[] args) {​
Showroom obj = new Showroom(); // Creating object​
[Link](); // Calling input​
[Link](); // Calling calculate​
[Link](); // Calling display​
}​
}​
The Question: Electric Bill Calculation Program
Define a class named ElectricBill with the following specifications:
●​ Instance Variables/Data Members:
○​ String n: To store the name of the customer.
○​ int units: To store the number of units consumed.
○​ double bill: To store the bill amount to be paid.
●​ Member Methods:
○​ void accept(): To accept the name of the customer and the number of units
consumed.
○​ void calculate(): To calculate the bill based on the following tariff:
■​ First 100 units: ₹2.00 per unit.
■​ Next 200 units: ₹3.00 per unit.
■​ Above 300 units: ₹5.00 per unit.
■​ Note: A surcharge of 2.5% is charged if the number of units consumed is above
300.
○​ void print(): To print the Customer Name, Units Consumed, and Bill Amount.
○​ void main(): Create an object of the class and call the above member methods.

The Complete Program

Java

import [Link].*; // Importing for Scanner class​



class ElectricBill {​
// Instance Variables​
String n;​
int units;​
double bill;​

// Method to take input​
void accept() {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter Customer Name: ");​
n = [Link]();​
[Link]("Enter Units Consumed: ");​
units = [Link]();​
}​

// Method to calculate the bill based on slabs​
void calculate() {​
if (units <= 100) {​
bill = units * 2.0;​
} else if (units <= 300) {​
// First 100 @ 2.0, remaining @ 3.0​
bill = (100 * 2.0) + ((units - 100) * 3.0);​
} else {​
// First 100 @ 2.0, next 200 @ 3.0, remaining @ 5.0​
bill = (100 * 2.0) + (200 * 3.0) + ((units - 300) * 5.0);​

// Adding 2.5% surcharge for consumption above 300 units​
double surcharge = bill * 2.5 / 100.0;​
bill = bill + surcharge;​
}​
}​

// Method to display the results​
void print() {​
[Link]("Customer Name: " + n);​
[Link]("Units Consumed: " + units);​
[Link]("Total Bill Amount: Rs. " + bill);​
}​

// Main method to run the program​
public static void main(String[] args) {​
ElectricBill obj = new ElectricBill(); // Object creation​
[Link](); // Calling accept method​
[Link](); // Calling calculate method​
[Link](); // Calling print method​
}​
}​
1. Palindrome Number Program
The Question: Write a program to input a number and check whether it is a Palindrome
Number or not. A number is called a palindrome if it remains the same when its digits are
reversed (e.g., 121, 4554).

The Program:

Java

import [Link].*;​

class PalindromeNumber {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter the number: ");​
int num = [Link]();​

// Save a copy because num will become 0 during processing​
int copy = num;​
int rv = 0; // To store reversed number​

while (num > 0) {​
int digit = num % 10; // Extract last digit​
rv = (rv * 10) + digit; // Build reverse​
num = num / 10; // Remove last digit​
}​

if (copy == rv) {​
[Link]("Given number is a Palindrome Number.");​
} else {​
[Link]("Given number is NOT a Palindrome Number.");​
}​
}​
}​
2. Even-Pal Number Program (2024 Board Question)
The Question: Write a program to accept a number and check whether it is an Even-Pal
Number or not.
An Even-Pal number must satisfy two conditions:
1.​ It must be a Palindrome Number (equal to its reverse).
2.​ The sum of its digits must be an Even Number.​
(Example: 121 is a Palindrome and its digit sum $1+2+1=4$ is even. So, 121 is an
Even-Pal number).

The Program:

Java

import [Link].*;​

class EvenPalNumber {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter the number: ");​
int num = [Link]();​

int copy = num;​
int sum = 0; // To store sum of digits​
int rv = 0; // To store reverse of number​

while (num > 0) {​
int digit = num % 10;​
sum = sum + digit; // Calculating sum of digits​
rv = (rv * 10) + digit; // Calculating reverse​
num = num / 10;​
}​

// Checking both conditions: Palindrome AND sum of digits is even​
if (copy == rv && sum % 2 == 0) {​
[Link]("It is an Even-Pal Number.");​
} else {​
[Link]("It is NOT an Even-Pal Number.");​
}​
}​
}​
The Question: Pronic Number Check
Write a program to input a number and check whether it is a Pronic Number or not.
●​ Definition: A Pronic Number is a number which is the product of two consecutive integers.
●​ Examples:
○​ $12 = 3 \times 4$ (Product of consecutive integers 3 and 4)
○​ $20 = 4 \times 5$ (Product of consecutive integers 4 and 5)
○​ $42 = 6 \times 7$ (Product of consecutive integers 6 and 7)

The Java Program

Java

import [Link]; // Importing Scanner for user input​



public class PronicNumber {​
public static void main(String[] args) {​
Scanner sc = new Scanner([Link]);​
[Link]("Enter a number: ");​
int num = [Link](); // Accepting the number to check​

boolean isPronic = false;​

// Loop to check the product of consecutive integers​
// We start from 1 and go up to num (though num/2 is logically sufficient)​
for (int i = 1; i < num; i++) {​
// Check if product of consecutive integers equals the input number​
if (i * (i + 1) == num) {​
isPronic = true;​
break; // Stop once a match is found​
}​
}​

// Output based on the check result​
if (isPronic) {​
[Link](num + " is a Pronic Number.");​
} else {​
[Link](num + " is not a Pronic Number.");​
}​
}​
}​

You might also like