Computer
Computer
Computer
import java.util.*;
class Employee
{
static double basic;
OUTPUT 1:
Enter Basic Pay
10000
Gross Pay : 13167.0
OUTPUT 2:
Enter Basic Pay
15000
Gross Pay : 19750.5
class MyString
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
import java.util.*;
class MyString2
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
ch = Character.toLowerCase(ch);
OUTPUT:
Enter a String
TigEr
The total number of characters : 5
The total number of vowels : 2
The reversed string : rEgiT
import java.util.*;
class FindArea
{
switch(choice)
{
case 1 : System.out.println(" Enter Radius ");
double r = sc.nextDouble( );
System.out.println(" Area of Circle = " + obj.area(r) );
break;
My Menu
1.Circle
2.Square
3.Rectangle
Enter your choice to find area : 0
Wrong choice !
My Menu
1.Circle
2.Square
3.Rectangle
Enter your choice to find area : 3
Enter Length and Breadth
12
8
Area of Rectangle = 96.0
switch(choice)
{
case 1 : System.out.println(" Enter Radius ");
double r = sc.nextDouble( );
System.out.println(" Area of Circle = " + area(r) );
break;
Write a program to bubble sort the following set of values in ascending order.
5, 3, 8, 4, 9, 2, 1, 12, 98, 16
Output: 1, 2, 3, 4, 5, 8, 9, 12, 16, 98
class BubbleSort
{
public static void main( String args[ ] )
{
int A[ ] = {5,3,8,4,9,2,1,12,98,16};
int n = A.length;
int temp;
for (int i=1; i<n; i++) for (int i=0; i<n; i++)
{ {
for (int j=0; j<n-i; j++) for (int j=0; j<n-i-1; j++)
if ( A[ j ] > A[ j+1] ) OR if ( A[ j ] > A[ j+1] )
{ {
temp = A[ j ]; temp = A[ j ];
A[ j ] = A[ j+1 ]; A[ j ] = A[ j+1 ];
A[ j+1 ] = temp; A[ j+1 ] = temp;
} }
} }
OUTPUT:
Sorted values are below
1
2
3
4
5
8
9
12
16
98
import java.util.*;
class Summation
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n,sumNeg=0,sumPosEven=0,sumPosOdd=0;
do
{
System.out.print(" Enter a number : ");
n = sc.nextInt();
if ( n < 0 )
sumNeg += n;
if (n>0 && n%2== 0)
sumPosEven += n;
if (n>0 && n%2== 1)
sumPosOdd += n;
}
while(n !=0 );
OUTPUT:
Enter a number : -9
Enter a number : 6
Enter a number : -4
Enter a number : 7
Enter a number : 4
Enter a number : 11
Enter a number : 0
Sum of Negative Number : -13
Sum of Positive Even Number : 10
Sum of Positive Odd Number : 18
import java.util.*;
class Summation2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n=1, sumNeg=0,sumPosEven=0,sumPosOdd=0;
while(n != 0)
{
System.out.print(" Enter a number : ");
n = sc.nextInt( );
if (n < 0)
sumNeg += n;
else if (n%2==0)
sumPosEven += n;
else
sumPosOdd += n;
}
OUTPUT:
Enter a number : -22
Enter a number : 10
Enter a number : -7
Enter a number : 35
Enter a number : 22
Enter a number : 89
Enter a number : -46
Enter a number : 0
Sum of Negative Number : -75
Sum of Positive Even Number : 32
Sum of Positive Odd Number : 124
import java.util.*;
class Search
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
if (pos >= 0)
{
System.out.println("Search Successful");
System.out.println( names[pos]+" telephone number is "+telephone[pos] );
}
else
System.out.println("Search unsuccessful. Name not enlisted");
}
}
OUTPUT:
Enter a name
bhagat
Search Successful
Bhagat telephone number is 1907
/* Program print the sum of odd numbers and the sum of even numbers
for the first n natural numbers. */
import java.util.*;
class Summation
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT:
Enter value of N :
10
Sum of even numbers = 30
Sum of odd numbers = 25
Alternate Logic:
Write a program to input the total cost and to compute and display the amount to be paid by the customer after
availing the discount.
class ShowRoom
{ public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT:
Enter total cost : 9540
The amount to be paid after discount = 6201.0
class MyString
{
String s1;
MyString(String x)
{
s1 = x ;
}
void display( )
{
System.out.println(s1);
}
if ( ch == ' ' )
{
if ( eword.equalsIgnoreCase(fword))
s2 = s2 + " " + rword;
else
s2 = s2 + " " + eword;
eword = "";
}
else
eword = eword + ch;
}
s1 = s2.trim( );
}
class FindReplace
{
public static void main(String args[ ])
{
String s1="January 26 is celebrated as the Republic Day of India";
s1 = s1 + " ";
String s2 = "";
String w = "";
if ( ch != ' ' )
w += ch;
else
{
if ( w.equals("26") )
w = "15";
else if ( w.equals("January") )
w = "August";
else if ( w.equals("Republic") )
w = "Independence";
s2 = s2 + " " + w;
w = "";
}
}
s2 = s2.substring(1);
System.out.println( s2 );
}
}
OUTPUT:
August 15 is celebrated as the Independence Day of India
Note: s1 = string1, s2 = string2, w = word and s2.substring(1) is used to copy all characters of the string except
first character because it contains space.
class Evaluation
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch(choice)
{ case 1: System.out.println(" Math.log(x) = "+Math.log(x));
break;
case 2: System.out.println(" Math.abs(x) = "+Math.abs(x));
break;
case 3: System.out.println(" Math.sqrt(x) = "+Math.sqrt(x));
break;
case 4: System.out.println(" Math.random() = "+Math.random( ) );
}
}
}
OUTPUT:
Enter the value of x : 36
1. Natural logarithm of the number
2. Absolute value of the number
3. Square root of the number
4. Random numbers between 0 and 1
. .
. .
. .
Write a program to input the names and marks of the students in the subject.
Calculate and display:
𝑠𝑢𝑏𝑗𝑒𝑐𝑡𝑡𝑜𝑡𝑎𝑙
(i) The subject average marks (𝑠𝑢𝑏𝑗𝑒𝑐𝑡𝑎𝑣𝑒𝑟𝑎𝑔𝑒𝑚𝑎𝑟𝑘𝑠 = 50
)
(ii) The highest mark in the subject and the name of the student.
(The maximum marks in the subject are 100)
class Student
{ public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
int n = 5;
int total=0;
int max=0;
String name="";
total += marks[i];
}
}
OUTPUT:
Enter name of student1 : Dharsheel
Enter Dharsheel marks : 97
Note: In the above program change the value of n to 50(int n = 50), as per question asked in the exam.
class SelectionSort
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n = 15;
int A[ ] = new int[n];
int i=0;
while (i<n)
{
int x = sc.nextInt( );
if (x==0)
System.out.println(" Don't enter zero ! ");
else
A[i++] = x;
}
temp = A[i];
A[i] = A[pos];
A[pos] = temp;
}
OUTPUT:
Enter 15 numbers
97
32
51
0
Don't enter zero !
64
-69
512
-10
48
1000
123
899
-1024
786
10
203
Member methods:
(a) To accept the details of a teacher including the monthly salary.
(b) To display the details of the teacher.
(c) To compute the annual Income Tax as 5% of the annual salary above ₹ 1,75,000/-.
Write a main method to create object of a class and call the above member method.
// Program to calculate teachers income tax based on monthly salary...
import java.util.*;
class Salary
{
String name,addr,ph,sub;
double sal,total,IT;
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter Name,Address,Phone,Subject & Monthly salary");
name = sc.nextLine( );
addr = sc.nextLine( );
ph = sc.nextLine( );
sub = sc.nextLine( );
sal = sc.nextDouble( );
}
void compute( )
{
total = sal * 12;
void display( )
{
System.out.println(" Teacher Details ");
System.out.println(" Name : " + name );
System.out.println(" Address : " + addr );
System.out.println(" Phone No : " + ph );
System.out.println(" Subject : " + sub );
System.out.println(" Annual Salary : " + total );
System.out.println(" Income Tax : " + IT );
}
OUTPUT 1:
Enter Name,Address,Phone,Subject & Monthly salary
Suresh
Nehru Circle
273649
Physics
20000
Teacher Details
Name : Suresh
Address : Nehru Circle
Phone No : 273649
Subject : Physics
Annual Salary : 240000.0
Income Tax : 3250.0
OUTPUT 2:
Enter Name,Address,Phone,Subject & Monthly salary
Ramesh
Gandhi Nagar
278125
Social
12000
Teacher Details
Name : Ramesh
Address : Gandhi Nagar
Phone No : 278125
Subject : Social
Annual Salary : 144000.0
Income Tax : 0.0
import java.util.*;
class Series1
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT:
Enter n value
5
Total = 3.04166
import java.util.*;
class Series2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT 1:
Enter n value
4
Total = 2.9166
OUTPUT 2:
Enter n value
5
Total = 3.04166
Output:
Minimum value: 1
Maximum value: 5
Sum of the elements: 15
// Program to find largest, smallest and sum of all elements of the array...
import java.util.*;
class Array
{
public static void main(String args[ ])
{
int A[ ] = {2,5,4,1,3};
OUTPUT:
Minimum value : 1
Maximum value : 5
Sum of the elements : 15
class SearchWord1
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
if ( ch == ' ' )
{
if ( sword.equalsIgnoreCase(eword) )
count++;
eword = "" ;
}
if ( Character.isLetter(ch) )
eword = eword + ch;
}
System.out.println(" Search word occurs : "+ count + " times ");
}
}
OUTPUT:
Enter a sentence :
the? quick brown fox jumps over The lazy dog.
Enter a word to be searched :
the
Search word occurs : 2 times
class SearchWord2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int count = 0 ;
int sl = s.length( );
int wl = w.length( );
if ( j == wl )
count++;
}
System.out.println(" Search word occurs : "+ count + " times ");
}
}
OUTPUT 1: OUTPUT 2:
Enter a sentence : Enter a sentence :
TOMATOMATOMATOMATOMATO MATHEMATICS
Enter a word to be searched : Enter a word to be searched :
TOMATO MAT
Search word occurs : 5 times Search word occurs : 2 times
class Temperature
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
double C,F;
switch (choice)
{
case 1 : System.out.println(" Enter Celsius ");
C = sc.nextDouble( );
F = (C*9/5) + 32;
System.out.println(" Fahrenheit = " + F );
break;
class Palindrome1
{
public static boolean Palin(String word)
{
word = word.toUpperCase( );
boolean flag = true;
int size = word.length()-1;
if ( Palin(word) )
System.out.println(word + " is Palindrome ");
else
System.out.println(word + " is Not palindrome ");
}
}
import java.util.*;
class Palindrome2
{
public static boolean Palin( String w )
{
String rev = "" ;
return w.equalsIgnoreCase(rev);
}
if ( Palin(word) )
System.out.println(word + " is Palindrome ");
else
System.out.println(word + " is Not palindrome ");
}
}
Member functions:
input( ) Store the PAN number, name, taxableincome
calc( ) Calculate tax for an employee
display( ) Output details of an employee
Write a program to compute the tax according to the given conditions and display the output as per given
format.
Total Annual Taxable Income Tax Rate
Up to ₹ 1,00,000 No Tax
From ₹ 1,00,001 to 10% of the income exceeding
₹ 1,50,000 ₹ 1,00,000
From ₹ 1,50,001 to ₹ 5000 + 20% of the income
₹ 2,50,000 exceeding ₹ 1,50,000
Above ₹ 2,50,000 ₹ 25,000 + 30% of the income
exceeding ₹ 2,50,000
Output:
PAN Number Name Tax-Income Tax
_ _ _ _
_ _ _ _
_ _ _ _
_ _ _ _
class Employee
{
int PAN;
String name;
double taxIncome, tax;
void input( )
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter Employee Name, PAN number and Taxable Income");
name = sc.nextLine( );
PAN = sc.nextInt( );
taxIncome = sc.nextDouble( );
}
void calc( )
{
if ( taxIncome <= 100000 )
tax = 0 ;
else if ( taxIncome <= 150000 )
tax = ( taxIncome - 100000 ) * 0.1;
else if ( taxIncome <= 250000 )
tax = ( taxIncome - 150000 ) * 0.2 + 5000;
else
tax = (taxIncome - 250000 ) * 0.3 + 25000;
}
void display( )
{
System.out.println(" PAN No. \t Name \t Tax-Income \t Tax ");
System.out.println(PAN + "\t" + name + "\t" + taxIncome + "\t" + tax);
}
OUTPUT:
Enter Employee Name, PAN number and Taxable Income
Neha 1234 100000
Brahmini 3456 135000
Hithashri 5678 196000
Hunar 7890 384500
import java.util.*;
class Convert1
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String s2 = "" ;
System.out.println( s2 );
}
}
OUTPUT:
Enter a string
aCTIVATE 5g aIRtEL *123#
Activate 5G AirTel *123#
Note: In the above program we used ASCII values, A=65, Z=90, a=97 and z=122
String s2 = "" ;
class Convert3
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String s2 = "";
if ( Character.isUpperCase(ch) )
s2 += Character.toLowerCase(ch);
else if ( Character.isLowerCase(ch) )
s2 += Character.toUpperCase(ch);
else
s2 += ch;
}
System.out.println( s2 );
}
}
import java.util.*;
class BubbleSort
{
public static void main(String args[ ])
{
String A[ ] = {"Delhi","Hyderabad","Bengaluru","Agra","Mumbai","Calcutta"};
String temp;
int i, j;
OUTPUT:
Agra
Bengaluru
Calcutta
Delhi
Hyderabad
Mumbai
import java.util.*;
class PerfectPalindrome1
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : perfect(n); break;
if ( sum == n )
System.out.println(" It is Perfect number ");
else
System.out.println(" Not Perfect number ");
}
while (n>=1)
{
d = n % 10;
rev = rev * 10 + d;
n = n / 10;
}
if ( rev == x )
System.out.println(" It is Palindrome ");
else
System.out.println(" Not Palindrome ");
}
}
OUTPUT 1:
Enter a number
28
1.Check Perfect or Not
2.Check Palindrome or Not
Enter your choice
1
It is Perfect number
OUTPUT 2:
Enter a number
2882
1.Check Perfect or Not
2.Check Palindrome or Not
Enter your choice
2
It is Palindrome
OUTPUT 3:
Enter a number
6
1.Check Perfect or Not
2.Check Palindrome or Not
Enter your choice
-1
Wrong choice
class PerfectPalindrome2
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : if ( IsPerfect(n) )
System.out.println(" It is Perfect number ");
else
System.out.println(" Not Perfect number ");
break;
case 2 : if ( IsPalindrome(n) )
System.out.println("It is Palindrome ");
else
System.out.println("Not Palindrome ");
break;
} // End of class
import java.util.*;
class VOLUME
{
OUTPUT:
Volume of a cuboid (vcd) = 432.0
Volume of a sphere (vs) = 4188.7902
Volume of a cube (vc) = 1728.0
import java.util.*;
class VOLUME
{
OUTPUT:
Volume of a cuboid = 432.0
Volume of a sphere = 4188.7902
Volume of a cube = 1728
Write a program to calculate and print the sum of each of the following series:
(a) Sum (S) = 2 - 4 + 6 – 8 + … -20
𝑥 𝑥 𝑥 𝑥 𝑥
(b) Sum (S) = 2 + 5 + 8 + 11 +. . . . . . + 20
(Value of x is to be input by the user)
import java.util.*;
class Series
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner( System.in );
}
}
OUTPUT:
Sum of Series1 = -10.0
Enter x value : 12
Sum of Series2 = 13.153934300993125
Write a program based on the above criteria, to input name, address, amount of purchase and the type of
purchase (L for Laptop and D for Desktop) by a customer. Compute and print the net amount to be paid by a
customer along with his name and address.
(Hint: discount = ( discount rate / 100 ) * amount of purchase
Net amount = amount of purchase – discount)
class ElectronicShop
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter Type of Purchase L for Laptop and D for Desktop ");
char ch = Character.toUpperCase( sc.next( ).charAt(0) );
double r = 0;
switch ( ch )
{
case 'L' : if ( amt <=25000 )
r=0;
else if ( amt <= 57000 )
r=5;
else if ( amt <= 100000 )
r = 7.5 ;
else
r = 10 ;
break ;
OUTPUT:
Enter Customer Name, Address
Mayukh
Srinagar
Note: where amt = amount, ch = choice, r = rate, dis = discount & net = net amount
import java.util.*;
class Triangles
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
int i, j;
switch ( choice )
{
case 1 : for (i=1; i<=n; i++)
{
for (j=1; j<=i; j++)
System.out.print( i );
System.out.println( );
}
break;
System.out.print("\n");
}
break;
OUTPUT 1:
1. for a Triangle
2. for an Inverted triangle
Enter your choice : 2
OUTPUT 2:
1. for a Triangle
2. for an Inverted triangle
Enter your choice : 1
import java.util.*;
class LongestWord
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
s += " ";
int big=0;
String lword="", eword="";
if ( ch == ' ' )
{
if ( eword.length( ) > big )
{
big = eword.length( );
lword = eword;
}
eword = "";
}
if ( Character.isLetter(ch) )
eword += ch;
}
OUTPUT:
Enter a Sentence
India is my country, My motherland is great!!!!!!!!!!
Longest word is motherland
Its Length is 10
(a)void num_calc(int num, char ch) with one integer argument and one character argument, computes the square
of integer argument if choice ch is ‘s’ otherwise finds its cube.
(b) void num_calc(int a, int b, char ch) with two integer arguments and one character argument. It computes the
product of integer arguments if ch is ‘p’ else adds the integers.
(c) void num_calc(String s1, String s2) with two string arguments, which prints whether the strings are equal or
not.
class Overload
{
public static void num_calc(int num, char ch)
{
if (ch == 's' || ch == 'S')
System.out.println(" The Square = " + (num * num) );
else
System.out.println(" The Cube = " + (num * num * num) );
}
class Menu
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
switch (choice)
{
case 1 : System.out.println(" Enter a number ");
int n = sc.nextInt( );
if ( n%7==0 || n%10==7 )
System.out.println(" It is Buzz number ");
else
System.out.println(" Not a Buzz number ");
break;
OUTPUT 1: OUTPUT 2:
Press 1 to Check Buzz number or not Press 1 to Check Buzz number or not
Press 2 to Find GCD of two numbers Press 2 to Find GCD of two numbers
GCD = 1
LCM = 3649
OUTPUT 3: OUTPUT 4:
Press 1 to Check Buzz number or not Press 1 to Check Buzz number or not
Press 2 to Find GCD of two numbers Press 2 to Find GCD of two numbers
GCD = 24
LCM = 6840
OUTPUT 5: OUTPUT 6:
Press 1 to Check Buzz number or not Press 1 to Check Buzz number or not
Press 2 to Find GCD of two numbers Press 2 to Find GCD of two numbers
GCD = 10
LCM = 10
class Examination
{ public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
import java.util.*;
class Student
{
String name;
int rollno;
int sub1,sub2,sub3,total;
double avg;
void input( )
{
System.out.println(" Enter Student name, rollno and 3 subjects marks ");
name = sc.next( );
rollno = sc.nextInt( );
sub1 = sc.nextInt( );
sub2 = sc.nextInt( );
sub3 = sc.nextInt( );
}
void compute( )
{
total = sub1 + sub2 + sub3;
avg = total / 3.0;
}
void output( )
{
System.out.println(rollno+"\t"+name+"\t"+sub1+"\t"+sub2+"\t"+sub3+"\t"+total+"\t"+avg);
}
OUTPUT:
Enter Students strength : 5
Enter Student name, rollno and 3 subjects marks
Tharun 101 64 71 55
Enter Student name, rollno and 3 subjects marks
Jack 102 81 79 83
Enter Student name, rollno and 3 subjects marks
Peter 103 38 25 19
Enter Student name, rollno and 3 subjects marks
Zafreen 104 99 87 92
Enter Student name, rollno and 3 subjects marks
Rakesh 105 41 40 37
import java.util.*;
class BinarySearch
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner( System.in );
int A[ ] = {5,7,9,11,15,20,30,45,89,97,100};
if ( x == A[mid] )
{
pos = mid;
break;
}
if ( x > A[mid] )
start = mid + 1;
else
end = mid - 1;
}
if ( pos >= 0 )
System.out.println(" Element found at position : "+(pos+1) );
else
System.out.println(" Search element not found ");
}
}
OUTPUT:
Enter an element to search : 20
Element found at position : 6
Member methods:
(a) A parameterized constructor to initialize the data members.
(b) To accept the details of a student.
(c) To compute the average and the maximum out of three marks.
(d) To display the name, age, marks in three subjects, maximum and average.
Write a main method to create an object of a class and call the above member methods.
import java.util.*;
class Student
{
String name;
int age,m1,m2,m3,max;
double avg;
Student( ) { }
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter Student name, age and 3 subject marks ");
name = sc.nextLine( );
age = sc.nextInt( );
m1 = sc.nextInt( );
m2 = sc.nextInt( );
m3 = sc.nextInt( );
}
void compute( )
{
avg = (m1+m2+m3) / 3.0;
void display( )
{
System.out.println(name+"\t"+age+"\t"+m1+"\t"+m2+"\t"+m3+"\t"+max+"\t"+avg);
}
OUTPUT:
name age m1 m2 m3 max avg
Vishal 15 67 94 50 94 70.33
class ShashaTravels
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
int n=5, r ;
OUTPUT:
Enter name of the customer 1 : Jagadish
Enter ticket charge : 54000
import java.util.*;
class AutoPrime
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch ( choice )
{
case 1 : for (int i=2; i<=Math.sqrt(num); i++)
{
if (num%i == 0)
{
flag = false;
break;
}
}
if ( flag )
System.out.println(num + " is Prime ");
else
System.out.println(num + " is Composite ");
break;
if ( flag )
System.out.println(" Automorphic ");
else
System.out.println(" Not automorphic ");
break;
OUTPUT 1:
Enter a number
215
Press 1 to check Prime or not
Press 2 to check Automorphic or not
Which is your choice?
2
Not automorphic
OUTPUT 2:
Enter a number
49
Press 1 to check Prime or not
Press 2 to check Automorphic or not
Which is your choice?
1
49 is Composite
class AutoPrime2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch( choice )
{
case 1 : int factors=0;
for(int i=1; i<=n; i++)
{
if (n%i == 0)
factors++;
}
if (factors > 2)
System.out.println(n+" is Composite ");
else
System.out.println(n+" is Prime ");
break;
Example:
P[]= 4 6 1 2 3 10
Input
Q[ ] = 19 23 7 8
Output R[ ] = 4 6 1 2 3 10 19 23 7 8
import java.util.*;
class Merge
{
public static void main(String args[ ])
{
int P[ ] = {4,6,1,2,3,10};
int Q[ ] = {19,23,7,8};
int i, j;
OUTPUT:
4 6 1 2 3 10 19 23 7 8
Alternate Logic:
for (j=0; j<Q.length; j++) for (j=0; j<Q.length; j++,i++) for (j=0; j<Q.length; j++)
R[i+j] = Q[j]; R[i] = Q[j]; R[i++] = Q[j];
Characters: A C D E H M O P R T U W
Frequency: 2 1 1 2 1 1 1 1 3 1 1 1
class Frequency
{
public static void main( String args[ ] )
{
Scanner sc = new Scanner(System.in);
if (count > 0)
System.out.println(ch + "\t" + count);
}
}
}
OUTPUT:
Enter a string
Computer Hardware
A 2
C 1
D 1
E 2
H 1
M 1
O 1
P 1
R 3
T 1
U 1
W 1
class Frequency2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
if ( Character.isLetter(ch) )
alpha[ch - 'A'] ++;
}
OUTPUT:
Enter a string
an apple a day keeps the doctor away
A 6
C 1
D 2
E 4
H 1
K 1
L 1
N 1
O 2
P 3
R 1
S 1
T 2
W 1
Y 2
Member methods/functions:
void input( ) - to input and store the detail of the customer.
void compute( ) - to compute the rental charge.
class Mobike
{
String name;
int bno,phno,days,charge;
void input( )
{
Scanner sc = new Scanner(System.in);
void compute( )
{
if ( days <= 5 )
charge = days * 500;
else if ( days <= 10 )
charge = 2500 + (days-5)*400;
else
charge = 2500 + 2000 + (days-10)*200;
}
void display( )
{
System.out.println(" Bike No. \t Phone No. \t Name \t No.of days \t Charge ");
System.out.println(bno+"\t"+phno+"\t"+name+"\t"+days+"\t"+charge);
}
obj.input( );
obj.compute( );
obj.display( );
}
}
OUTPUT 1:
Enter Bike number : 1234
Enter Customer name and phone number : Chavi
9876543210
Enter number of days bike is taken on rent : 9
Bike No. Phone No. Name No.of days Charge
1234 9876543210 Chavi 9 4100
OUTPUT 2:
Enter Bike number : 5678
Enter Customer name and phone number : Gouri
9876543210
Enter number of days bike is taken on rent : 14
Bike No. Phone No. Name No.of days Charge
5678 9876543210 Gouri 14 5300
import java.util.*;
class SelectionSort
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT:
How many people are there? 5
Enter weight of 5 people
19 34 82 100 67
Weight of people in descending order
100 82 67 34 19
Example:
145 is a special number, because 1! + 4! + 5! = 1 + 24 + 120 = 145
(Where ! stands for factorial of the number and the factorial value of a number is the product of all integers
from 1 to that number, example 5! = 1*2*3*4*5 = 120).
class Special
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
while( n>=1 )
{
d = n%10;
n = n/10;
fact = 1;
for(int i=1; i<=d; i++)
fact = fact * i;
if ( sum == x )
System.out.println(" Special number ");
else
System.out.println(" Not special number ");
}
}
class ReplaceVowels
{
public static void main( String args[] )
{
Scanner sc = new Scanner(System.in);
OUTPUT:
Enter a word
Covid19
cpvjd19
class ReplaceVowels2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String nw = "";
nw += ch;
}
OUTPUT 1:
Enter a word
computer
Encoded word is: cpmpvtfr
OUTPUT 2:
Enter a word
emu
Encoded word is: fmv
Note:
where nw = new word
import java.util.*;
class Overload
{
public static void compare(int x, int y)
{
if (x>y)
System.out.println(x);
else
System.out.println(y);
}
OUTPUT:
54
a
Vishweshwaraiah
Solution 2
import java.util.*;
class Overload
{
public static void compare(int x, int y)
{
int big = (x>y)? x : y ;
System.out.println(big);
}
Solution 3
import java.util.*;
class Overload
{
public static void compare(int x, int y)
{
System.out.println( Math.max(x,y) );
}
class Series
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : System.out.print(" Enter value of n : ");
int n = sc.nextInt( );
for(int i=1; i<=n; i++)
System.out.println( i*i-1 );
break;
OUTPUT 1: OUTPUT 2:
Press 1 to print 0,3,8,15,24...n terms Press 1 to print 0,3,8,15,24...n terms
Press 2 to find sum of 1/2+3/4+...+19/20 Press 2 to find sum of 1/2+3/4+...+19/20
Enter your choice : 1 Enter your choice : 2
Enter value of n : 10 8.5355
0 3 8 15 24 35 48 63 80 99
Member methods:
void input( ) To input and store the accession number, title and author.
void compute( ) To accept the number of days late, calculate and display
the fine charged at the rate of Rs. 2 per day.
void display( ) To display the details in the following format:
Accession Number Title Author
Write a main method to create an object of the class and call the above member methods.
// Program to calculate fine charged on the book…
import java.util.*;
class Library
{ int acc_num, days;
String title, author;
Scanner sc = new Scanner(System.in);
void input( )
{
System.out.println(" Enter accession number, title and author of the book");
acc_num = Integer.parseInt(sc.nextLine( ));
title = sc.nextLine( );
author = sc.nextLine( );
}
void compute( )
{
System.out.print(" Enter number of days late : ");
days = sc.nextInt( );
System.out.println(" Fine amount = "+ days*2);
}
void display( )
{
System.out.println(" Accession number \t Title \t Author ");
System.out.println(acc_num + "\t" + title + "\t" + author );
}
OUTPUT
public static void main(String args[ ]) Enter accession number, title and author
{ 2001
Library obj = new Library( ); Harry Potter
J K Rowling
obj.input( );
obj.compute( ); Enter number of days late : 12
obj.display( ); Fine amount = 24
}
} Accession number Title Author
2001 Harry Potter J K Rowling
Is greater than ₹ 5,00,000 & less than or [(TI - 5,00,000) x 20%] + 34,000
equal to ₹ 8,00,000
class IncomeTax
{ public static void main(String args[ ])
{ Scanner sc = new Scanner(System.in);
int age;
char gender;
double TI, tax;
if ( age>65 || gender=='F' )
{
System.out.print(" Wrong category ");
System.exit(0);
}
import java.util.*;
class DoubleLetter
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(s);
int count=0;
if (x == y)
{
count++;
System.out.println(x+""+y);
}
}
System.out.println(" Total double letter sequences are = "+count);
}
}
OUTPUT 1:
Enter a string
she was feeding the little rabbit with an apple
SHE WAS FEEDING THE LITTLE RABBIT WITH AN APPLE
EE
TT
BB
PP
Total double letter sequences are = 4
OUTPUT 2:
Enter a string
Google pizza
GOOGLE PIZZA
OO
ZZ
Total double letter sequences are = 2
(i) void polygon(int n,char ch) – with one integer argument and one character type argument that draws a
filled square of side n using the character stored in ch.
(ii) void polygon(int x, int y) – with two integer arguments that draws a filled rectangle of length x and breadth
y, using the symbol ‘@’.
(iii) void polygon( ) - with no arguments that draws a filled triangle shown below.
Example:
(i) Input value of n=2, ch=’O’ (ii) Input value of x=2, y=5 (iii) No Input Value
Output: Output: Outptut:
OO @@@@@ *
OO @@@@@ **
***
@@@@@@@@
public static void polygon(int x, int y) @@@@@@@@
{ @@@@@@@@
for(int i=1; i<=x; i++) @@@@@@@@
{
for(int j=1; j<=y; j++)
System.out.print("@"); $$$$$
System.out.println( ); $$$$$
} $$$$$
} $$$$$
$$$$$
public static void polygon( )
{
for(int i=1; i<=3; i++)
{
for(int j=1; j<=i; j++)
System.out.print("*");
System.out.println( );
}
}
class MenuDriven
{ public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : int c,a=0,b=1;
System.out.println(" Fibonacci series upto 10 ");
System.out.print(a + ",");
System.out.print(b + ",");
for(int i=3; i<=10; i++) OUTPUT:
{ 1.Fibonacci series upto 10
c = a + b; 2.Sum of the digits
System.out.print(c+",");
a = b; Enter your choice : 1
b = c; Fibonacci series upto 10
} 0,1,1,2,3,5,8,13,21,34,
break;
// Program to search a city in the array and display its STD code…
import java.util.*;
class StdCode
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n=10;
String city[ ] = new String[n];
int std[ ] = new int[n];
if (pos == -1)
System.out.println("Search Unsuccessful, No such city in the list");
else
{
System.out.println("Search Successful");
System.out.println(city[pos]+" STD Code is "+std[pos]);
}
}
}
OUTPUT:
Enter name of city 1
Tawang
Enter Tawang STD code
03794
Member methods:
(i) FruitJuice( ) - Default constructor to initialize integer data members to 0 and string
data members to “”(NULL)
(ii) void input( ) - To input and store the product code, flavor, pack type, pack size and
product price.
(iii) void discount( ) - To reduce the product price by 10
(iv) void display( ) - To display the product code, flavor, pack type, pack size and product price.
// Program to input fruit juice price and reduce the price by 10 Rs.
import java.util.*;
class FruitJuice
{
int product_code;
String flavour;
String pack_type;
int pack_size;
int product_price;
FruitJuice( )
{
product_code = pack_size = product_price = 0;
flavour = pack_type = "";
}
void input( )
{
Scanner sc = new Scanner(System.in);
void discount( )
{
product_price -= 10;
}
void display( )
{
System.out.println(" Product Code : "+ product_code );
System.out.println(" Flavour : "+ flavour );
System.out.println(" Pack Type : "+ pack_type );
System.out.println(" Pack Size : "+ pack_size);
System.out.println(" Product Price: "+ product_price);
}
OUTPUT 1:
Enter product code : 101
Enter flavour : Strawberry milkshake
Enter pack type : Tetra pack
Enter pack size : 250
Enter product price : 50
OUTPUT 2:
Enter product code : 102
Enter flavour : Pine Apple
Enter pack type : PET bottle
Enter pack size : 500
Enter product price : 90
The ISBN is legal if: 1XDigit1 + 2XDigit2 + 3XDigit3 + 4XDigit4 + 5XDigit5 + 6XDigit6 + 7XDigit7 + 8XDigit8 +
9XDigit9 + 10XDigit10 is divisible by 11.
class ISBN
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
long n = isbn;
int count=0;
while( n>0 )
{
count++;
n=n/10;
}
if ( count != 10 )
{
System.out.println(" ISBN is wrong! ");
return;
}
n = isbn;
long d, sum=0;
if ( sum%11 == 0 )
System.out.println(" Legal ISBN ");
else
System.out.println(" Illegal ISBN ");
}
}
Alternate Logic:
long d, sum=0; long sum = 0;
for (int i=10; i>=1; i--) int i=10;
{ while (n>0)
d = n % 10; {
sum = sum + d * i; sum += n%10 * i;
n = n/10; n/=10;
} i--;
}
class ISBN
{
public static void main(String args[ ])
{ Scanner sc = new Scanner(System.in);
if ( isbn.length() != 10 )
{
System.out.println(" ISBN is wrong! ");
System.exit(0);
}
int sum = 0;
if ( sum%11 == 0 )
System.out.println(" Legal ISBN ");
else
System.out.println(" Illegal ISBN ");
}
}
OUTPUT 1: OUTPUT 2: OUTPUT 3:
Enter an ISBN code : Enter an ISBN code : Enter an ISBN code :
8750942123 123 8750942163
sum = 176 ISBN is wrong! sum = 212
Legal ISBN Illegal ISBN
Alternate Logic:
for (int i=0; i<isbn.length( ); i++) for (int i=0; i<isbn.length( ); i++)
{ {
char ch = isbn.charAt(i); int d = Integer.parseInt( isbn.charAt(i)+"" );
int d = ch - 48; sum = sum + d * (i+1);
sum = sum + d * (i+1); }
}
Note: The ASCII values of character ‘0’, ‘1’, ‘2’, ‘3’ … ‘9’ are 48, 49, 50 ...57. If we convert character ‘0’ to
Integer we get 48 but to get numeric 0 we have to subtract 48.
Example1: ‘0’ - 48 = 0 Example2: ‘9’ - 48 = 9
import java.util.*;
class Piglatin
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String a = "" ;
String b = "" ;
if (vowelFound)
b = b + ch;
else if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
b = b + ch;
vowelFound = true;
}
else
a = a + ch;
}
import java.util.*;
class Piglatin
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i;
String a = s.substring(0,i);
String b = s.substring(i);
class Piglatin
{
public static void main(String[ ] args)
{
Scanner sc = new Scanner(System.in);
sb.append(ch);
sb.deleteCharAt(0);
}
sb.append("AY");
System.out.println("Piglatin = " + sb);
}
}
import java.util.*;
class BubbleSort
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT:
Enter 10 elements
-11 26 40 52 65 77 -10 98 50 13
(ii) double series(double a, double n) with two double arguments and returns
the sum of the series.
1 4 7 10
sum = 2 + 5 + 8 + 11 +. . . . . . + to n terms
𝑎 𝑎 𝑎 𝑎
import java.util.*;
class Overload
{
public static double series(double n)
{
double sum = 0;
return sum;
}
return sum;
}
OUTPUT:
2.2833333333
0.4072265625
import java.util.*;
class Menu
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch ( choice )
{
case 1 : boolean flag = true;
for (int i=2; i<=n/2; i++)
{
if ( n%i == 0 )
{
flag = false;
break;
}
}
if ( flag )
System.out.println(n + " is Prime ");
else
System.out.println(n + " is Composite ");
break;
small = n%10;
n = n/10; int small=9, d;
while( n >= 1)
while(n >= 1) {
{ d = n%10;
d = n%10; OR n = n/10;
n = n/10;
if (small > d)
if (small > d) small = d;
small = d; }
}
OUTPUT 1: OUTPUT 2:
Enter a number Enter a number
1947 13
Enter 1 to check composite number or not Enter 1 to check composite number or not
Enter 2 to find the smallest digit Enter 2 to find the smallest digit
Which is your choice? 2 Which is your choice? 1
Smallest digit is 1 13 is Prime
OUTPUT 3: OUTPUT 3:
Enter a number Enter a number
15 2658
Enter 1 to check composite number or not Enter 1 to check composite number or not
Enter 2 to find the smallest digit Enter 2 to find the smallest digit
Which is your choice? 1 Which is your choice? 2
15 is Composite Smallest digit is 2
Member methods:
MovieMagic( ) Default constructor to initialize numeric data
members to 0 and String data member to “”(NULL).
void accept( ) To input and store year, title and rating.
void display( ) To display the title of a movie and a message based on the rating as per the table below.
Write a main method to create an object of the class and call the above member methods.
class MovieMagic
{
int year;
String title;
float rating;
MovieMagic( )
{
year = 0;
title = "";
rating = 0.0F;
}
void accept( )
{
Scanner sc = new Scanner(System.in);
void display( )
{
if ( rating <= 2.0 )
System.out.println(title + " is Flop ");
else if ( rating <= 3.4 )
System.out.println(title + " is Semi-Hit ");
else if ( rating <= 4.5 )
System.out.println(title + " is Hit ");
else if ( rating <= 5.0 )
System.out.println(title + " is Super Hit ");
else
System.out.println(" You entered wrong rating ");
}
OUTPUT 1: OUTPUT 2:
Enter the year of release of a movie Enter the year of release of a movie
2016 2018
Enter rating of the movie between 0.0 to 5.0 Enter rating of the movie between 0.0 to 5.0
5.0 5.1
Write a program to accept a two-digit number. Add the sum of its digits to the product of its digits. If the value
is equal to the number input, output the message “Special 2-digit number” otherwise, output the message
“Not a special 2-digit number”.
class Special2Digit
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
if ( s.length() != 2 )
{
System.out.println(" Input is not a two-digit number! ");
System.exit(0);
}
int n = Integer.parseInt( s );
if ( n == (d1+d2) + (d1*d2) )
System.out.println(" Special 2-digit number ");
else
System.out.println(" Not a special 2-digit number ");
}
}
OUTPUT 1: OUTPUT 2: OUTPUT 3:
Enter a number Enter a number Enter a number
1234 69 96
Input is not a two-digit number! Special 2-digit number Not a special 2-digit number
Alternate Logic:
System.out.println(" Enter a number ");
int n = sc.nextInt( );
if ( n<10 || n>99 )
{
System.out.println(" Invalid Input! ");
return;
}
// Program to extract the file name and file extension from a full path…
import java.util.*;
class PathProcess
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT:
Enter a full path
D:\Songs\Hindi\SlumdogMillionaire\JaiHo.mp3
Path: D:\Songs\Hindi\SlumdogMillionaire\
File name: JaiHo
Extension: mp3
Note 1: In above program fp = full path, lsp = last slash position, dotp = dot position,
fn = file name and ext = extension.
Note 2: If we want to assign a full path in the program then include extra slash to distinguish escape sequence.
import java.util.*;
class Overload
{
public static double area(double a, double b, double c)
{
double s = (a+b+c) / 2;
double area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
return area;
}
OUTPUT:
1320.0
204.0
24.0
For option 1:
accept principal(p), rate of interest(r) and time period in years(n). Calculate and output the maturity
amount(A) receivable using the formula:
𝑟 𝑛
𝐴 = 𝑝 [1 + ]
100
For option 2:
accept monthly installment (p), rate of interest(r) and time period in months(n). Calculate and output the
maturity amount(A) receivable using the formula:
𝑛(𝑛+1) 𝑟 1
A = 𝑝𝑋𝑛 + 𝑝𝑋 2
𝑋 100 𝑋 12
import java.util.*;
class BankDeposit
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
double p, r, n, a;
switch(choice)
{
case 1 : System.out.print(" Enter Principal : ");
p = sc.nextDouble( );
System.out.print(" Enter Rate of Interest : ");
r = sc.nextDouble( );
System.out.print(" Enter Time period in years : ");
n = sc.nextDouble( );
a = p * Math.pow((1 + r/100),n);
System.out.println(" Maturity amount = "+ a);
break;
OUTPUT 1: OUTPUT 2:
1.Term Deposit 1.Term Deposit
2.Recurring Deposit 2.Recurring Deposit
Enter your choice : 1 Enter your choice : 2
import java.util.*;
class BinarySearch
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int A[ ] = {1982,1987,1993,1996,1999,2003,2006,2007,2009,2010};
if ( year == A[mid] )
{
pos = mid;
break;
}
if (pos == -1)
System.out.println("Record does not exist");
else
System.out.println("Record exists");
}
}
OUTPUT 1: OUTPUT 2:
Enter year of graduation Enter year of graduation
2000 1987
Record does not exist Record exists
Member methods:
void input( ) To input and store vehicle number and hours.
void calculate( ) To compute the parking charge at the rate of Rs.3 for the
first hour or part thereof, and Rs.1.50 for each additional hour or part thereof.
void display( ) To display the detail
Write a main method to create an object of the class and call the above methods.
class ParkingLot
{
int vno, hours;
double bill;
void input( )
{
Scanner sc = new Scanner(System.in);
void calculate( )
{
bill = 3 + (hours – 1) * 1.5;
}
void display( )
{
System.out.println(" Vehicle Number : "+ vno);
System.out.println(" No. of Hours Parked : "+ hours);
System.out.println(" Bill Amount : "+ bill);
}
(a) (b)
* 5 4 3 2 1
* # 5 4 3 2
* # * 5 4 3
* # * # 5 4
* # * # * 5
class Pattern1
{
public static void main( String args[ ] ) OUTPUT:
{ *
for (int i=1; i<=5; i++) * #
{ * # *
for (int j=1; j<=i; j++) * # * #
{ * # * # *
if ( j%2 == 0 )
System.out.print("#");
else
System.out.print("*");
}
System.out.println( );
}
}
}
𝑇𝑜𝑡𝑎𝑙𝑀𝑎𝑟𝑘𝑠
Average Marks =
3
85 – 100 Excellent
75 – 84 Distinction
60 – 74 First Class
40 – 59 Pass
class Student
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String remark;
if ( avg >= 85 )
remark = " Excellent ";
else if ( avg >= 75 )
remark = " Distinction ";
else if ( avg >= 60 )
remark = " First class ";
else if ( avg >= 40 )
remark = " Pass ";
else
remark = " Poor ";
Details of Student1
*******************
Name : Varun
Average : 79.0
Remark : Distinction
Details of Student2
*******************
Name : Mukund
Average : 90.66
Remark : Excellent
(ii) void Joystring(String s) with one string argument that prints the position
of the first space and the last space of the given string s.
Example:
Input value of s = “Cloud computing means Internet based computing”
Output:
First Index : 5
Last Index : 36
(iii) void Joystring(String s1, String s2) with two string arguments that
combines the two strings with a space between them and prints the
resultant string.
Example:
Input value of s1 = “COMMON WEALTH”
Input value of s2 = “GAMES”
Output: “COMMON WEALTH GAMES”
(use library functions)
class Overload
{
void joystring(String s, char ch1, char ch2)
{
s = s.replace(ch1,ch2);
System.out.println(s);
}
void joystring(String s)
{
System.out.println(" First Space Position = " + s.indexOf(" "));
System.out.println(" Last Space Position = " + s.lastIndexOf(' '));
}
void joystring(String s1, String s2) void joystring(String s1, String s2)
{ OR {
String s3 = s1 + " " + s2; String s3;
System.out.println(s3); s3 = s1.concat(" ");
} s3 = s3.concat(s2);
System.out.println(s3);
}
}
Write a program to input twenty names in an array. Arrange these names in descending order of alphabets,
using the bubble sort technique.
import java.util.*;
class BubbleSort
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String temp;
int i,j;
OUTPUT:
How many names you want to enter? 19
Enter 19 names
Shreyans
VadiRaj
Aneesh
Inchara
Keerthana
Suraj
Yojith
Shourya
Madhumithra
Rishika
Shrishanth
Harshit
Nehitha
Shreyas
Nikhil
Shwethadri
Sunaina
Yashasree
Anshuman
class Menu
{
public static void main(String args[ ])
{ Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : for(int i=1; i<=n/2; i++)
{
if ( n%i == 0 )
System.out.print(i+", ");
}
break;
case 2 : int fact=1; int f=1;
for(int i=1; i<=n; i++) OR while(n>1)
fact = fact * i; {
System.out.println(fact); f = f * n;
break; n--;
}
System.out.println( f );
default : System.out.println(" Incorrect choice! ");
}
}
}
OUTPUT 1: OUTPUT 2: OUTPUT 3:
Enter a number : 18 Enter a number : 75 Enter a number : 6
Press 1 to display Factors of 18 Press 1 to display Factors of 75 Press 1 to display Factors of 6
Press 2 to display Factorial of 18 Press 2 to display Factorial of 75 Press 2 to display Factorial of 6
Enter your choice : 1 Enter your choice : 1 Enter your choice : 2
1, 2, 3, 6, 9 1, 3, 5, 15, 25 720
Member Methods:
(i) BookFair( ) Default constructor to initialize data members.
(ii) void input( ) To input and store the name and the price of the book.
(iii) void calculate( ) To calculate the price after discount. Discount is calculated based on the following
criteria.
Price Discount
Less than or equal to ₹1000 2% of price
More than ₹1000 and less than or equal to ₹3000 10% of price
More than ₹3000 15% of price
(iv) void display( ) To display the name and price of the book after discount.
Write a main method to create an object of the class and call the above member methods.
import java.util.*;
class BookFair
{
String bname;
double price;
BookFair( )
{
bname = "";
price = 0.0;
}
obj.input( );
obj.calculate( );
obj.display( );
}
}
OUTPUT 1:
Enter book name : Wings of Fire
Enter book price : 800
Book Name : Wings of Fire
Price after discount : 784.0
OUTPUT 2:
Enter book name : My Experiments with Truth
Enter book price : 3000
Book Name : My Experiments with Truth
Price after discount : 2700.0
OUTPUT 3:
Enter book name : Gitanjali
Enter book price : 3500
Book Name : Gitanjali
Price after discount : 2975.0
Using the switch-case statement, write a menu-driven program for the following.
(i) To print the Floyd’s triangle. (ii) To display the following pattern.
1 I
I C
2 3
I C S
4 5 6
I C S E
7 8 9 10
11 12 13 14 15
import java.util.*;
class Menu
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : System.out.println(" Enter value of n ");
int n = sc.nextInt( );
int x = 1;
for (int i=1; i<=n; i++)
{
for (int j=1; j<=i; j++)
System.out.print( x++ );
System.out.println( );
}
break;
System.out.println( );
}
break;
OUTPUT 1: OUTPUT 2:
Input 1 to display Floyds triangle Input 1 to display Floyds triangle
Input 2 to display String Pattern Input 2 to display String Pattern
1 L
23 LI
456 LIN
7 8 9 10 LINU
11 12 13 14 15 LINUX
All Palindromes are special words, but all Special words are not palindromes.
Write a program to accept a word check and print whether the word is a palindrome or only special word.
class PalindromeSpecial
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in); OUTPUT 1:
Enter a word : Amma
System.out.print(" Enter a word : "); AMMA is Palindrome and Special
String s = sc.nextLine( ).toUpperCase( );
OUTPUT 2:
boolean flag = true; Enter a word : Australia
int n = s.length()-1; AUSTRALIA is Special word
(i) void SumSeries(int n, double x) – With one integer argument and one
double argument to find and display the sum of the series given below:
𝑥 𝑥 𝑥 𝑥 𝑥
𝑠 = 1 − 2 + 3 − 4 + 5 . . . . . .to 𝑛 𝑡𝑒𝑟𝑚𝑠
(ii) void SumSeries( ) - To find and display the sum of the following series:
s = 1 + (1X2) + (1X2X3) + …… + (1X2X3X4…...X20)
import java.util.*;
class OverLoad
{
public static void SumSeries(int n, double x)
{
double sum = 0;
OUTPUT
Sum of fractions = 6.1666
Sum of factorials = 153
Write a program to accept a number and check and display whether it is a Niven number or not.
(Niven number is that number which is divisible by it sum of digits).
Example:
Consider the number 126
Sum of its digits is 1+2+6 = 9 and 126 is divisible by 9.
import java.util.*;
class Niven
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
while( n >= 1 )
{
d = n % 10;
sum = sum + d;
n = n/10;
}
if ( x % sum == 0 )
System.out.println(" It is Niven number ");
else
System.out.println(" Not Niven number ");
}
}
OUTPUT 1
Enter a number : 126
It is Niven number
OUTPUT 2
Enter a number : 678
Not Niven number
If found, display the name of the country along with its Wonder, otherwise display “Sorry Not Found!”.
Seven wonders – Chichen Itza, Christ the Redeemer, Taj Mahal, Great Wall of
China, Machu Picchu, Petra, Colosseum.
Locations – Mexico, Brazil, India, China, Peru, Jordan, Italy
Example:
Country Name: India Output: INDIA – TAJ MAHAL
Country Name: USA Output: Sorry Not Found!
import java.util.*;
class WorldWonders
{
public static void main(String args[ ])
{
String wonders[ ] = {"Chichen Itza","Christ the Redeemer","Taj Mahal", "Great Wall of China",
"Machu Picchu","Petra","Colosseum"};
if ( pos == -1)
System.out.println("Sorry Not Found!");
else
System.out.println(locations[pos]+" - "+wonders[pos]);
}
}
OUTPUT 1: OUTPUT 2:
Enter a country to search... Enter a country to search...
PERU Russia
Peru - Machu Picchu Sorry Not Found!
Members methods:
void accept( ) - to accept the name of the customer and number of units consumed.
void calculate( ) - to calculate the bill as per the following tariff:
A surcharge of 2.5% charged if the number of units consumed is above 300 units.
Write a main method to create an object of the class and call the above member methods.
class ElectricBill
{
String n;
int units;
double bill;
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter customer name : ");
n = sc.nextLine( );
System.out.println(" Enter units consumed : ");
units = sc.nextInt( );
}
void calculate( )
{
if (units <= 100)
bill = units * 2;
else if (units <= 300)
bill = 200 + (units-100) * 3;
else
{
bill = 800 + (units-300) * 5;
bill = bill + bill * 0.025;
}
}
void print( )
{
System.out.println(" Name of the customer : " + n);
System.out.println(" Number of units consumed : "+ units);
System.out.println(" Bill amount : " + bill);
}
obj.accept( );
obj.calculate( );
obj.print( );
}
OUTPUT
Enter the customer name : Enter the customer name : Enter the customer name :
Amruth Adil Alex
Enter units consumed : Enter units consumed : Enter units consumed :
81 290 500
Name of the customer : Amruth Name of the customer : Adil Name of the customer : Alex
Number of units consumed : 81 Number of units consumed : 290 Number of units consumed : 500
Bill amount : 162.0 Bill amount : 770.0 Bill amount : 1845.0
import java.util.*;
class Spy
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
while(n >= 1)
{
d = n % 10;
sum = sum + d;
product = product * d;
n = n / 10;
}
if ( sum == product )
System.out.println(" It is Spy number ");
else
System.out.println(" Not a spy number ");
}
}
OUTPUT 1:
Enter a number :
1124
It is Spy number
OUTPUT 2:
Enter a number :
1729
Not a spy number
class MenuDriven
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : int sum=0,x=2,term;
for(int i=1; i<=20; i++)
{
term = (int) Math.pow(x,i);
if ( i%2 == 1)
sum = sum + term;
else
sum = sum - term;
}
System.out.println(" Sum = "+sum);
break;
System.out.print(" ");
}
break;
default : System.out.println(" Incorrect option ");
}
}
}
OUTPUT
1. To find sum of the series
2. To display series 1 11 111 1111 11111
Enter your choice : 1
Sum = - 699050
class MenuDriven
{
public static void main(String args[ ])
{ Scanner sc = new Scanner(System.in);
switch(choice)
{
case 1 : int sum=0, sign=1;
for(int i=1; i<=20; i++)
{
sum += sign * (int)Math.pow(2,i);
sign *= -1;
}
System.out.println(" Sum = "+sum);
break;
Alternate Logic
int x=1; for(int i = 1; i <= 5; i++)
for(int i=1; i<=5; i++) {
{ int x = (int) (Math.pow( 10 , i ) – 1) / 9;
System.out.print(x + " "); System.out.print( x + " ");
x = x * 10 + 1; }
}
// Program to find largest, smallest and sum of all elements of the array...
import java.util.*;
class Array
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int max,min,sum;
max = min = sum = A[0];
OUTPUT
How many elements you want to enter?
5
Enter 5 elements
50
80
30
90
70
Minimum value : 30
Maximum value : 90
Sum of the elements : 320
(ii) void check(String s1) – to display only vowels from string s1, after converting it to
lower case.
Example:
Input:
s1 = “computer” Output: o u e
class Overload
{
public static void check(String str, char ch)
{
int count=0;
import java.util.*;
class SelectionSort
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int pos;
String temp;
temp = A[i];
A[i] = A[pos];
A[pos] = temp;
}
OUTPUT
How many words you want to enter?
6
Enter 6 words
Orange Apple Watermelon Papaya Banana Mango
Member methods:
void accept( ) - To take input for name, coach, mobile number and amount.
void update( ) - To update the amount as per the coach selected
(extra amount to be added in the amount as follows)
Type of Coaches Amount
First_AC 700
Second_AC 500
Third_AC 250
Sleeper None
void display( ) - To display all details of a customer such as name, coach, total amount and mobile number.
Write a main method to create an object of the class and call the above member methods.
// Program to update railway ticket amount as per the coach selected…
import java.util.*;
class RailwayTicket
{ String name, coach;
long mobno;
int amt, totalamt;
void accept( )
{ Scanner sc = new Scanner(System.in);
System.out.print(" Enter customer name : ");
name = sc.nextLine( );
System.out.print(" Enter type of coach : ");
coach = sc.nextLine( );
System.out.print(" Enter mobile number : ");
mobno = sc.nextLong( );
System.out.print(" Enter basic amount of ticket : ");
amt = sc.nextInt( );
}
void update( )
{
if (coach.equalsIgnoreCase("First_AC"))
totalamt = amt + 700;
else if (coach.equalsIgnoreCase("Second_AC"))
totalamt = amt + 500;
else if (coach.equalsIgnoreCase("Third_AC"))
totalamt = amt + 250;
else if (coach.equalsIgnoreCase("Sleeper"))
totalamt = amt;
}
void display( )
{
System.out.println(" Details of Customer ");
System.out.println(" **************** ");
System.out.println(" Name : " + name );
System.out.println(" Coach : " + coach );
System.out.println(" Mobile : " + mobno );
System.out.println(" Total amount : " + totalamt );
}
OUTPUT 1:
Enter customer name : Shravya
Enter type of coach : first_ac
Enter mobile number : 9876543210
Enter basic amount of ticket :
150
Details of Customer
*****************
Name : Shravya
Coach : first_ac
Mobile : 9876543210
Total amount : 850
OUTPUT 2:
Enter customer name : Sahasra
Enter type of coach : Sleeper
Enter mobile number : 9876543210
Enter basic amount of ticket :
150
Details of Customer
*****************
Name : Sahasra
Coach : Sleeper
Mobile : 9876543210
Total amount : 150
class Pronic
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
if ( flag )
System.out.println(" It is pronic number ");
else
System.out.println(" Not a pronic number ");
}
}
OUTPUT
Enter a number : 12
It is pronic number
Enter a number : 15
Not a pronic number
Enter a number : 20
It is pronic number
Enter a number : 32
Not a pronic number
Enter a number : 42
It is pronic number
import java.util.*;
class Pronic2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
if ( a*(a+1) == n )
System.out.println(" It is pronic number ");
else
System.out.println(" Not a pronic number ");
}
}
OUTPUT
Enter a number : 12
It is pronic number
Enter a number : 15
Not a pronic number
Enter a number : 20
It is pronic number
Enter a number : 32
Not a pronic number
Enter a number : 42
It is pronic number
Enter a number : 50
Not a pronic number
Enter a number : 90
It is pronic number
import java.util.*;
class FirstLetterUpper
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
s = ' ' + s;
String ns = "";
if ( ch == ' ' )
{
if ( i != 0 )
ns += ch;
ns += Character.toUpperCase( s.charAt(++i) );
}
else
ns = ns + ch;
}
System.out.println( ns );
}
}
OUTPUT:
Enter a string
tHeRE'S nO enEmy oUTsIDe OuR souL. ThE reAl EnemIEs live insIdE Us: AnGeR, EGO, gReeD AnD haTE.
There's No Enemy Outside Our Soul. The Real Enemies Live Inside Us: Anger, Ego, Greed And Hate.
import java.util.*;
class FirstLetterUpper2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
s = ' ' + s;
String ns = "";
OUTPUT
Enter a string
all ReliGions leAds to onE goD...
All Religions Leads To One God...
(ii) double volume(double H, double R) – with height(H) and radius (R) as the arguments,
returns the volume of a cylinder using the formula.
V = 22/7 X R2 X H
import java.util.*;
class Overload
{
double volume(double R)
{
double V = 4/3.0 * 22/7.0 * R * R * R;
return V;
}
System.out.println(obj.volume(5));
System.out.println(obj.volume(8,3));
System.out.println(obj.volume(12,10,6));
}
}
OUTPUT
523.80
226.28
720.0
Pattern 1 Pattern 2
ABCDE B
ABCD LL
ABC UUU
AB EEEE
A
class MenuPatterns
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String s;
switch(choice)
{
case 1 : s = "ABCDE";
for(int i=s.length()-1; i>=0; i--)
{
for(int j=0; j<=i; j++)
System.out.print( s.charAt(j) );
System.out.println( );
}
break;
case 2 : s = "BLUE";
for(int i=0; i<s.length(); i++)
{
for(int j=0; j<=i; j++)
System.out.print( s.charAt(i) );
System.out.println( );
}
break;
OUTPUT 1:
Enter 1: To display ABCD pattern
Enter 2: To display BLUE pattern
1
ABCDE
ABCD
ABC
AB
A
OUTPUT 2:
Enter 1: To display ABCD pattern
Enter 2: To display BLUE pattern
2
B
LL
UUU
EEEE
OUTPUT 3:
Enter 1: To display ABCD pattern
Enter 2: To display BLUE pattern
3
Wrong option!
class Deviation
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
avg = sum / n ;
System.out.println(" The average of total marks = "+avg);
OUTPUT
Enter students strength : 5
Member methods:
ShowRoom( ) - default constructor to initialize data members
void input( ) - To input customer name, mobile number, cost
void calculate( ) - To calculate discount on the cost of purchased items, based on
following criteria
Cost Discount
(in percentage)
void display( ) - To display customer name, mobile number, amount to be paid after
discount.
Write a main method to create an object of the class and call the above member methods.
import java.util.*;
class ShowRoom
{
String name;
long mobno;
double cost,dis,amount;
ShowRoom( )
{
name = "";
mobno = 0;
cost = dis = amount = 0.0;
}
void input( )
{
Scanner sc = new Scanner(System.in);
System.out.print(" Enter customer name : ");
name = sc.next( );
System.out.print(" Enter mobile number : ");
mobno = sc.nextLong( );
System.out.print(" Enter cost of the items : ");
cost = sc.nextDouble( );
}
void calculate( )
{
if ( cost <= 10000 )
dis = cost * 0.05;
else if ( cost <= 20000 )
dis = cost * 0.1;
else if ( cost <= 35000 )
dis = cost * 0.15;
else
dis = cost * 0.2;
void display( )
{
System.out.println(" Customer name : "+ name );
System.out.println(" Mobile number : "+ mobno );
System.out.println(" Amount to be paid : "+ amount);
}
obj.input( );
obj.calculate( );
obj.display( );
}
}
OUTPUT
Enter customer name : Swapnil
Enter mobile number : 9876543210
Enter cost of the items : 30000
import java.util.*;
class MenuDriven
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch(n)
{
case 1 : for(char ch='A'; ch<='Z'; ch++)
System.out.println( ch + "\t" + (int) ch );
break; OUTPUT
Enter 1 to display Unicode
case 2 : for(int i=1; i<=5; i++) Enter 2 to display Pattern
{ 1
for(int j=1; j<=i; j++) 12
System.out.print( j ); 123
System.out.println( ); 1234
} 12345
}
}
}
class BubbleSort
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n=15,temp;
int A[] = new int[n];
class overload
{
public static void series(int x, int n)
{
double sum=0;
Example:
Sample Input: ADVANCEMENT AND APPLICATION OF INFORMATION TECHNOLOGY ARE EVER CHANGING.
import java.util.*;
class LetterCount
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(s);
s = ' ' + s;
int count=0;
System.out.println(" Total number of words starting with letter 'A' = " + count);
}
}
OUTPUT
Enter a sentence
affordable apples available in america.
AFFORDABLE APPLES AVAILABLE IN AMERICA.
Total number of words starting with letter 'A' = 4
Example:
Consider the number 3025
Square of sum of the halves of 3025 = ( 30 + 25 )2
= ( 55 )2
= 3025 is a tech number.
class TechNumber
{
public static void main(String args[ ])
{
for(int i=1000; i<=9999; i++)
{
int sum = i/100 + i%100;
if ( sum * sum == i )
System.out.println( i );
}
}
}
OUTPUT
2025
3025
9801
Member methods:
CabService( ) - Default constructor to initialize data members.
String data members to “” and double data members to 0.0
void calculate( ) - To calculate the bill as per the rules given above.
class CabService
{
String car_type;
double km, bill;
CabService( )
{
car_type = "";
km = bill = 0.0;
}
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter car_type ");
car_type = sc.nextLine( ).toUpperCase( );
System.out.println(" Enter kilometer travelled ");
km = sc.nextDouble( );
}
void calculate( )
{
if ( car_type.equals("AC") )
{
bill = 150 ;
if ( km > 5 )
bill += (km-5) * 10 ;
}
if ( car_type.equals("NON AC") )
{
bill = 120 ;
if ( km > 5 )
bill += (km-5) * 8 ;
}
}
void display( )
{
System.out.println(" CAR TYPE: " + car_type);
System.out.println(" KILOMETER TRAVELLED: " + km);
System.out.println(" TOTAL BILL: " + bill);
}
OUTPUT 1: OUTPUT 2:
Enter car_type Enter car_type
ac AC
Enter kilometer travelled Enter kilometer travelled
2.5 13
class BinarySearch
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int A[ ] = {31,36,45,50,60,75,86,90};
if ( x == A[mid] )
{
pos = mid;
break;
}
if ( x > A[mid] )
start = mid + 1;
else
end = mid - 1;
}
if ( pos >= 0 )
{
System.out.println(" Search Successful ");
System.out.println(" The element found at position : "+(pos+1));
}
else
System.out.println(" Search Unsuccessful ");
}
}
OUTPUT 1: OUTPUT 2:
Enter an element to search : 60 Enter an element to search : 61
Search Successful Search Unsuccessful
The element found at position : 5
import java.util.*;
class MyString1
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
if ( ch == ' ' )
System.out.print("\n");
else
System.out.print(ch);
}
}
}
OUTPUT
Enter a sentence
Don'T say 2moRrow Do iT 2dAy!
DON'T
SAY
2MORROW
DO
IT
2DAY!
import java.util.*;
class MyString2
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
OUTPUT
Input a sentence
It is easy to see the faults of others, but difficult to see one's own faults.
IT
IS
EASY
TO
SEE
THE
FAULTS
OF
OTHERS,
BUT
DIFFICULT
TO
SEE
ONE'S
OWN
FAULTS.
(ii) void Number(int n1) – To find and display the sum of even digits of a number.
Example:
n1 = 29865
Sum of even digits = 16
Write a main method to create an object and invoke the above methods.
class Overload
{
void Number(int num, int d)
{
int c=0;
while(num > 0)
{
if (num%10 == d)
c++;
num /= 10;
}
System.out.println(" Frequency of digit "+d+" = "+c);
}
(i) To print the value of c = a2+2ab, where a varies from 1.0 to 20.0 with increment of 2.0
and b=3.0 is a constant.
class MenuDriven
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
switch(choice)
{ OUTPUT
case 1 : for(double a=1,b=3; a<=20; a+=2) Input 1 to print the value of c
{
Input 2 to display pattern
double c = a*a + 2*a*b;
System.out.println(c); 1
} 7.0
break; 27.0
55.0
case 2 : for(int i=1; i<=5; i++) 91.0
{ 135.0
for(int j=0; j<i; j++)
187.0
System.out.print( (char)('A'+j) );
System.out.print("\n"); 247.0
} 315.0
break; 391.0
475.0
default : System.out.println(" Invalid choice ");
}
}
}
Example:
1 3 5
4 6 8
9 2 4
class Matrix1
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter " + n*n + " elements for the matrix ");
Example:
1 3 5
4 6 8
9 2 4
class Matrix2
{
public static void main(String args[ ])
{
int A[ ] [ ] = { {1, 3, 5},
{4, 6, 8},
{9, 2, 4}
};
int sum = 0;
OUTPUT
Sum of the left diagonal elements = 11
Member methods:
void accept( ) - to accept customer’s name, mobile number and bill amount.
void calculate( ) - to calculate GST, service tax and total amount to be paid by
the customer.
gst = 18% on bill
st = 12.5% on bill
tamt = bill + gst + st
void display( ) - to display the customer’s name, mobile number, GST, service tax
and total amount.
Write a main method to create an object and invoke the above member methods.
// Program to calculate GST, Service tax and total amount paid by customer...
import java.util.*;
class Hotel
{
String name;
long mno;
double bill,gst,st,tamt;
void accept( )
{
Scanner sc = new Scanner(System.in);
System.out.println(" Enter customer name, mobile number & bill amount");
name = sc.next();
mno = sc.nextLong();
bill = sc.nextDouble();
}
void calculate( )
{
gst = bill * 0.18;
st = bill * 0.125;
tamt = bill + gst + st;
}
void display( )
{
System.out.println(" Customer Details ");
System.out.println(" Name : " +name);
System.out.println(" Mobile : " +mno);
System.out.println(" GST : " +gst);
System.out.println(" Service tax : "+st);
System.out.println(" Total amount : "+tamt);
}
OUTPUT 1:
Enter customer name, mobile number & bill amount
Achala
6655443322
2500
Customer Details
Name : Achala
Mobile : 6655443322
GST : 450.0
Service tax : 312.5
Total amount : 3262.5
OUTPUT 2:
Enter customer name, mobile number & bill amount
Praneetha
6622334455
5000
Customer Details
Name : Praneetha
Mobile : 6622334455
GST : 900.0
Service tax : 625.0
Total amount : 6525.0
OUTPUT 3:
Enter customer name, mobile number & bill amount
Sreeya
6644335522
7500
Customer Details
Name : Sreeya
Mobile : 6644335522
GST : 1350.0
Service tax : 937.5
Total amount : 9787.5
Write a main method to create an object of the class and call the above member methods.
// Program to overload a method called PattSeries() as follows...
class Overload
{
void PattSeries( )
{
for(int i=5; i>=1; i--)
{
for(int j=i; j>=1; j--)
System.out.print(j);
System.out.print("\n");
}
}
void PattSeries(int n)
{ double sum=0;
OUTPUT
54321
4321
321
21
1
The number is said to be an EvenPal number when the number is a palindrome number and the sum of its digits is
an even number.
Example:
Number 121 is a palindrome number and the sum of its digits is 1+2+1=4, which is an even number.
class EvenPal
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int sum=0,rev=0,d,x=n;
while(n>0)
{
d=n%10;
sum+=d;
rev=rev*10+d;
n/=10;
}
OUTPUT 1:
Enter a number
1331
It is EvenPal number
OUTPUT 2:
Enter a number
515
Not EvenPal
class Range
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int r1=0,r2=0,r3=0,r4=0,r5=0;
(i) The blueprint that define the variables and the methods common to all of a certain kind is termed as:
(a) class
(b) object
(c) package
(d) method
(ii) A data type which contains integer as well as fractional part and occupies 32 bits space is:
(a) float
(b) char
(c) double
(d) byte
(iv) Which of the following keyword is used to crate symbolic constants in Java?
(a) final
(b) Final
(c) Constant
(d) Const
Question 2.
Fill in the blanks with the correct options:
(i) The keyword to create an object of a class is ____________
(a) create
(b) new
(c) New
(d) NEW
Question 3.
Name the following:
(i) The concept of having more than one constructor with different types of parameters:
(a) Copy constructor
(b) Method overloading
(c) Constructor overloading
(d) Overloaded methods
(ii) The keyword which indicates that the method returns no value:
(a) public
(b) static
(c) void
(d) abstract
(iii) The process of binding the data and method together as one unit it called as:
(a) Encapsulation
(b) Inheritance
(c) Polymorphism
(d) Dynamic binding
(iv) The jump statement that is used inside a switch case construct to terminate a statement sequence:
(a) continue
(b) break
(c) return
(d) goto
(v) The program code written in any high-level language to solve a problem is:
(a) object code
(b) source code
(c) machine code
(d) bytecode
Question 4.
State whether the statement is True or False:
(i) char is a non-primitive data type.
(a) True
(b) False
(ii) Multi line comments in Java start with /* and end with */.
(a) True
(b) False
(iv) Java compiler automatically creates a default constructor in case no constructor is present in the java class.
(a) True
(b) False
Question 5.
Choose the odd one:
(i) (a) >= (ii) (a) double (iii) (a) if else (iv) (a) nextInt( ) (v) (a) Robust
(b) % (b) int (b) if (b) nextDouble( ) (b) Platform Independent
(c) / (c) char (c) switch case (c) nextString (c) Inheritance
(d) String (d) next( ) (d) Multithreading
(d) * (d) while( )
Question 6.
Give the output of the following:
(i) int x=2, y=4, z=1; (ii) int x; (iii) int f=10, m=9;
int result = (++z) + y + (++x) + (z++); for( x=1; x<=3; x++) ; String e = (m%f == 9)? “YES” : “No” ;
(a) 11 System.out.print(x); System.out.print(e);
(b) 12 (a) 1 2 3 (a) YES
(c) 10 (b) 1 2 3 4 (b) No
(d) 9 (c) 4 (c) YESNO
(d) 1 (d) NOYES
(iv) switch(x)
{ (v) int v=5;
case ‘M’ : System.out.print(“ Microsoft Teams “); while( --v >= 0 )
break; {
case ‘G’ : System.out.print(“ Google Meet “); System.out.print(v);
default : System.out.print(“ Any software “); }
break;
case ‘W’: System.out.print(“ Web Ex”);
break; (a) 43210
} (b) 54321
When x=’g’ (c) 543210
(d) 4321
(a) Google Meet
(b) Any software
(c) Google Meet
Any software
(d) WebEx
Question 7.
Given below is a class with following specifications:
class name : Number
void Display(int n ) - To extract and print each digit of given number from last digit of the first digit
on separate lines.
Example: n= 674
Output
4
7
6
void Display( ) – To print numbers from 0.5 to 5.0 with updation of 0.5.
Fill in the blanks of the given program with appropriate statements.
class (i) ___________
{
void Display(int n) {
while( (ii)__________)
{
int rem = (iii) _________
System.out.println(rem);
n = (iv) ___________
}
}
void Display( )
{
for(v)_______; x<=(vi)_______; x+=0.5)
System.out.println(x);
}
}
(i) (a) Number (ii) (a) n<0 (iii) (a) n%100; (iv) (a) n%10; (v) (a) double x=0.5 (vi) (a) x>=5.0
(b) number (b) n>0 (b) n/10; (b) n/10; (b) Double x=0.5 (b) x<=5.0
(c) NUMBER (c) n==0 (c) n%10; (c) n/100; (c) double x=0.0 (c) x==5.0
(d) NUM (d) n=0 (d) n/100 (d) n%100 (d) Double x=0.0 (d) x=5.0
Question 8.
A school is giving away merit certificates for the students who have scored 90 percentage and above in class 10.
The following program is based on the specification given below. Fill in the blanks with appropriate Java statements.
Class name: Student
Member variables:
String name : To enter name of a student
double per: To enter percentage obtained by the student
String cer: To store the message
Member method
void input( ) : To accept the detail
void merit( ): To check the percentage and award the merit
void display( ): To display the detail
void main( ): To create an object of the class and invoke the methods
import java.(i)________.*;
class Student
{
String name;
double per;
String cer;
void input( )
{
Scanner obj = new Scanner(System.in);
System.out.println(“ Enter name, Percentage”);
name = obj.next( );
per = (ii) ________
}
void merit( )
{
if ( (iii)_______ )
{
cer = “AWARDED”;
}
else
cer = (iv)__________
}
void (v)_________
{
System.out.println(name);
System.out.println(per);
System.out.println(cer);
}
void main( )
{
Student s = new (vi)______
s.input( );
s.merit( );
s.display( );
}}
(i) (a) utility
(b) Util
(c) util
(d) UTILITY
Question 9.
The following program segment checks whether number is an Abundant number or not. A number is said to be an Abundant
number when the sum of its factors (excluding the number itself) is greater than the number.
Example:
Factors of number 12 are 1,2,3,4,6
Sum of factors is 1+2+3+4+6 = 16
Fill in the blanks with appropriate java statements
void abundant(int n)
{
int s=0;
for( (i)_______; (ii)_________; i++)
{
if ( (iii) ________ )
s = s+i;
}
if ( (iv)______)
System.out.println(“ Abundant Number “);
else
System.out.println(“ Not Abundant Number “);
}
(i) (a) int i=1 (ii) (a) i<=n (iii) (a) n%i == 0 (iv) (a) s<n
(b) int i=0 (b) i<n (b) n%i == 1 (b) s>n
(c) int i=2 (c) i>n (c) n%2 == 0 (c) s==n
(d) Int i=1 (d) i>=n
(d) n/2 == 0 (d) s=n
Question 10.
Read the following case study and answer the questions given below by choosing the correct option:
Java compilation is different from the compilation of other high-level languages. Other high-level languages use interpreter or
compiler but in Java, the source code is first compiled to produce an intermediate code called the byte code, this byte code is
platform independent and is a highly optimized se of instructions designed to be executed by Java in the run time system
called JVM(Java Virtual Machine), JVM is a Java interpreter loaded in the computer memory as soon as java is loaded. JVM is
different for different platforms.
COMPUTER APPLICATIONS
SEMESTER 2 EXAMINATION (50 Marks)
SECTION A (10 Marks)
Question 1
Choose the correct answers to the questions from the given options.
(Do not copy the question. Write the correct answers only.)
(v) _______ class is used to convert a primitive data type to its corresponding object.
(a) String
(b) Wrapper
(c) System
(d) Math
(vii) A single dimensional array contains N elements. What will be the last subscript?
(a) N
(b) N-1
(c) N-2
(d) N+1
class ASCII
{
public static void main(String args[ ])
{ Scanner sc = new Scanner(System.in);
/* Program to print the product of all elements and square of each element of the array */
import java.util.*;
class MyArray
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n=5;
int product=1;
OUTPUT
Enter 5 elements
11
12
13
14
15
121
144
169
196
225
Product of all elements = 360360
class DisplayWords
{ public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
int n=10;
String A[ ] = new String[n];
boolean start,end;
System.out.println(" Words starts and ends with the letter 'A' or 'a' ");
OUTPUT: BWAOLRLD
class Neword
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.in);
String c = "";
System.out.println(c);
}
}
OUTPUT
Enter two strings of same length
BALL
WORD
BWAOLRLD
Member variables:
name – name of student
age – age of student
mks – marks obtained
stream – stream allocated
(Declare the variables using appropriate data types)
Member methods:
void accept( ) – Accept name, age and marks using methods of Scanner class.
void allocation( ) – Allocate the stream as per following criteria:
mks stream
>= 300 Science and Computer
>=200 and <300 Commerce and Computer
>=75 and 200 Arts and Animation
<75 Try Again
void print( ) – Display student name, age, mks and stream allocated.
// Program to input student marks and allocate the stream as per criteria...
import java.util.*;
class Student
{
String name,stream;
int age,mks;
void accept()
{
Scanner sc = new Scanner(System.in);
void allocation( )
{
if (mks >= 300)
stream = "Science and Computer";
else if (mks >= 200)
stream = "Commerce and Computer";
else if (mks >= 75)
stream = "Arts and Animation";
else
stream = "Try Again";
}
void print( )
{
System.out.println(" Student Details ");
System.out.println(" Name : " + name);
System.out.println(" Age : " + age);
System.out.println(" Marks : " + mks);
System.out.println(" Stream : " + stream);
}
OUTPUT 1:
Accept name, age and marks
Rohan
15
300
Student Details
Name : Rohan
Age : 15
Marks : 300
Stream : Science and Computer
OUTPUT 2:
Accept name, age and marks
Sohan
15
299
Student Details
Name : Sohan
Age : 15
Marks : 299
Stream : Commerce and Computer
void print(int n) To check whether the number is a lead number. A lead number is the one whose sum of even
digits are equals to sum of odd digits.
e.g. 3669 odd digits sum = 3 + 9 = 12
even digits sum = 6 + 6 = 12
3669 is a lead number.
class Overload
{
void print( )
{
for(int i=1; i<=5; i++)
{
for(int j=1; j<=5; j++)
System.out.print(i);
System.out.println();
}
}
import java.util.*;
class MyString
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int alpha=0,digits=0,special=0;
OUTPUT
Enter a string
[email protected]
Number of alphabets = 17
Number of digits = 3
Number of special = 2
// Program to find sum of one digit and two digit numbers separately...
import java.util.*;
class FindSum
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
for(int i=0;i<=9;i++)
{
A[i] = sc.nextInt( );
if (A[i]>=0 && A[i]<=9) sum1+=A[i];
if (A[i]>9 && A[i]<=99) sum2+=A[i];
}
OUTPUT
Enter 10 integer elements
2
12
4
9
18
25
3
32
20
1