0% found this document useful (0 votes)
44 views16 pages

Java Programming Exercises with Solutions

The document contains 8 programming problems or exercises related to Java concepts. The first problem asks the student to write a program to calculate the sum of even and odd numbered seats in an exam hall with 100 total seats. The second problem involves writing a program to perform arithmetic operations like addition, subtraction etc based on user input. The remaining problems involve writing classes and methods to calculate areas of shapes, perform object operations, accept command line arguments, print patterns, and display student details.

Uploaded by

Chandan S Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views16 pages

Java Programming Exercises with Solutions

The document contains 8 programming problems or exercises related to Java concepts. The first problem asks the student to write a program to calculate the sum of even and odd numbered seats in an exam hall with 100 total seats. The second problem involves writing a program to perform arithmetic operations like addition, subtraction etc based on user input. The remaining problems involve writing classes and methods to calculate areas of shapes, perform object operations, accept command line arguments, print patterns, and display student details.

Uploaded by

Chandan S Patil
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Programs for Module 1

1) In an Examination hall students of second year and third year students sits in
an odd and even number positions consecutively. Then a teacher asks one of
the students to find the sum of even and odd positions separately. The total
seating capacity of an exam hall is 100. Develop a software application to
perform the above operations.
class Odd_Even
{
public static void main(String args[])
{
int sumeven=0, sumodd=0;
for(i=0;i<=100;i++)
{
if(i%2==0)
{
sumeven = sumeven+i;
}
else
{
sumodd = sumodd+i;
}
}
[Link](“The sum of even positions
is”+sumeven);
[Link](“The sum of odd positions
is”+sumodd);

}
}
Output:
The sum of even positions is2550
The sum of odd positions is2500
2) A Teacher asks one of the students in a class to do the arithmetic operations
based on a choice. Here at a time student have to perform one arithmetic
operation only. Write a Java program to perform the above operations
Solution:
import [Link];

public class Calculator {


public static void main(String[] args) {
// TODO Auto-generated method stub
int a,b,c=0;
Scanner sc = new Scanner([Link]);
[Link]("enter the values of a,b");
a=[Link]();
b=[Link]();

[Link]("1:Addition\n2:Substraction\n3:Multiplication\n4:Divisio
n");
[Link]("enter choice");
int ch=[Link]();
switch(ch)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
case 3: c=a*b;
break;
case 4: if(b!=0)
{
c=a/b;
break;
}
else
{
[Link]("division is not
possible");
break;
}
default: [Link]("invalid choice");
break;
}
[Link]("the result is"+c);
}

}
Output:
enter the values of a,b
35
1:Addition
2:Substraction
3:Multiplication
4:Division
enter choice
1
the result is8
----------------------------------------
enter the values of a,b
84
1:Addition
2:Substraction
3:Multiplication
4:Division
enter choice
4
the result is2

3) Swiggy App is celebrating its birthday, so it wants to give 80% discount for
those customers who have order number which is prime and others will get
50% discount. Help the application to identify the discount rate for
customers.

import [Link];

public class Prime {

public static void main(String[] args) {


// TODO Auto-generated method stub
int n, i;
boolean flag=false;
Scanner sc = new Scanner([Link]);
[Link]("enter order number");
n = [Link]();
if(n==0 || n==1)
[Link]("the customer will get 50% discount");
else
{
for(i=2;i<n;i++)
{
if(n%i==0)
{
[Link]("the customer will get 80%
discount");
flag=true;
break;
}
}
if(flag==false)
[Link]("the customer will get 50%
discount");
}

4) Shyam has drawing competition in school, he has to draw the following


pattern. Suggest a solution to Shyam for winning the competition.
*
**
***
****
Solution:
public class Printpyramidtest {

public static void main(String[] args) {


// TODO Auto-generated method stub
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5 - i; j++)
{
[Link](" ");
}
for (int k = 0; k <= i; k++)
{
[Link]("* ");
}
[Link]();
}
}
}
Output:
*
**
***
****
*****
5) Define a class called CommandLine, develop a program in Java that accepts
two floats and integers as its command line arguments and perform addition,
multiplication, subtraction and division and display the result.

Solution:
class CommandLine{
public static void main(String args[]){
int a,b;
float c,d;
a=[Link](args[0]);
b=[Link](args[1]);
c=[Link](args[2]);
d=[Link](args[3]);
[Link](" Integer Arithmetic Operations\n");
[Link]("Addition:"+(a+b)+ "\nSubtraction:" + (a-b) +
"\nMultiplication:" + (a*b) + "\nDivision:" + (a/b));
[Link]("\n Float Arithmetic Operations\n");
[Link]("Addition:" + (c+d) + "\nSubtraction:" + (c-d) +
"\nMultiplication:" + (c*d) + "\nDivision:" + (c/d));
}
}

Output:
 Javac [Link]
 Java CommandLine 10 20 6.5 4.5
Integer Arithmetic Operations
Addition: 30
Subtraction: -10
Multiplication: 200
Division: 0

Float Arithmetic Operations


Addition: 11
Subtraction: 2.5
Multiplication: 29.25
Division: 1.444

6) A teacher gave a project to student in the classroom to find the area of


different shapes. A student has to find the area of different shapes based on
the choice of different parameters and display the results,

Solution:
public class Students
{
void area(int x)
{
[Link]("the area of the square is "+[Link](x, 2)+" sq
units");
}
void area(int x, int y)
{
[Link]("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
[Link]("the area of the circle is "+z+" sq units");
}
public static void main(String args[])
{
Students ob = new Students();
[Link](5);
[Link](11,12);
[Link](2.5);
}
}

Output:
the area of the square is 25.0 sq units
the area of the rectangle is 132 sq units
the area of the circle is 19.625 sq units

7) Create a class named 'Rectangle' with two data members- length and breadth
and a method to calculate the area which is 'length*breadth'. The class has
three constructors which are
i -having no parameter - values of both length and breadth are assigned zero.
ii - having two numbers as parameters - the two numbers are assigned as length
and breadth respectively.
iii - having one number as parameter - both length and breadth are assigned that
number.
Now, create objects of the 'Rectangle' class having none, one and two
parameters and print their areas.
class Rectangle
{
int length;
int breadth;
void area()
{
int area=length*breadth;
[Link](area)
}
Rectangle()
{
length=0;
breadth=0;
}
Rectangle(int len)
{
length=len;
breadth=len;}
}
Rectangle(int l,int b)
{
length=l;
breadth=b;
}
Rectangle(Rectangle r)
{
length=[Link];
breadth=[Link];
}
public static void main(String args[])
{
int len, br;
Rectangle r1= new Rectangle();
[Link]();
Scanner input= new Scanner([Link])
[Link](“Enter the length and breadth”);
len=[Link]();
br=[Link]();
Rectangle r2= new Rectangle(len, br);
[Link]();
Rectangle r3= new Rectangle(50);
[Link]();
Rectangle r4= new Rectangle(r2);
[Link]();}}

Output:
Area of this rectangle 40000
Area of second rectangle 140000

8) A teacher asked the class people leader to prepare the list of student details
of his classroom. By using various parameters display the details of the
students using java program. Hint: Parameterized and Copy constructors to
apply overloading.

Solution:

class Student
{
String name, rollno, branch;
Student()
{
name = "sachin";
rollno = "20181CSE0001";
branch = "CSE";
}
Student(String name, String rollno, String branch)
{
[Link]=name;
[Link]=rollno;
[Link]=branch;
}
Student(Student s)
{
[Link]=[Link];
[Link]=[Link];
[Link]=[Link];
}
void disp()
{

[Link]("name:"+name+"\nrollno:"+rollno+"\nbranch:"+branch);
}
}
public class ConOver {

public static void main(String[] args) {


// TODO Auto-generated method stub
Student s1=new Student();
Student s2=new Student("virat","2018CCE0001","CCE");
Student s3=new Student(s2);
[Link]();
[Link]();
[Link]();
}
}

Output:
name:sachin
rollno:20181CSE0001
branch:CSE
name:virat
rollno:2018CCE0001
branch:CCE
name:virat
rollno:2018CCE0001
branch:CCE
9) AVR apartments uses a common water tank to supply water for every house.
Each time the water level of the tank reduces based on the usage of each
house. The maintenance person filled the tank thrice with 50litres each time.
One of the houses used 20litres and another house used 40 liters. Display the
current water level in the tank.

Solution:
class Common1{
int total_water=0;
int cur_level=0;
int usage=0;
int amount_used=0;
int water_filled=0;

static void totallevel(int water_filled){


total_water=3*water_filled;
[Link]("Total water filled "+" "+total_water);
}
void usageA(int usage)
{
int total_water1=total_water-usage;
[Link]("Water level after usage of A is"+"
"+total_water1);
}

void usageB(int usage)


{
Common1.total_water=130;
amount_used=total_water-usage;
[Link]("Water level after usage of B is"+"
"+amount_used);
[Link]("Current water level of the tank
is"+""+amount_used);
}
}

public class Water {

public static void main(String[] args) {


// TODO Auto-generated method stub
Common1 c= new Common1();
[Link](50);
[Link](20);
[Link](40);
}

Output:
Total water filled 150
Water level after usage of A is 130
Water level after usage of B is 90
Current water level of the tank is90

10) Develop a program in Java which has a static method min2() that


takes two int arguments and returns the value of the smallest one. Add an
overloaded function that does the same thing with two double values and
display the output.

Solution:
import [Link];

public class Staticmin {

static int min2(int a, int b)


{
if(a<b)
return a;
else
return b;
}
static double min2(double a,double b)
{
if(a<b)
return a;
else
return b;
}

public static void main(String[] args) {


// TODO Auto-generated method stub
Staticmin sm=new Staticmin();
Scanner sc = new Scanner([Link]);
[Link]("enter two integers");
int a1 = [Link]();
int b1 = [Link]();
int im=Staticmin.min2(a1,b1);
[Link]("enter double values");
double a2= [Link]();
double b2 = [Link]();
double dm = Staticmin.min2(a2,b2);
[Link]("smallest of 2 integers :"+im);
[Link]("smallest of 2 double values:"+dm);
}

Output:
enter two integers
20 30
enter double values
3.5 4.5
smallest of 2 integers :20
smallest of 2 double values:3.5
11) Develop a java program with two classes an Outer and Inner class.
Each of the class have one data member, the inner class has member
function which displays the data members. Write a main function to access
both inner and outer inner members.
Solution:
class Outer
{
int outer_x =100;
void test(){
Inner in=new Inner();
[Link]();
}
class Inner
{
int p=25;
void display()
{
[Link]("display: outer_x=" + outer_x);
[Link]("from inner: p value ="+ p);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer otr = new Outer();
[Link](" outer var="+ otr.outer_x);
[Link]();
}
}

Output:
outer var=100
display: outer_x=100
from inner: p value =25

Common questions

Powered by AI

A Java program can use Scanner objects to read input values for two integers, offer a menu for operations like addition, subtraction, multiplication, and division, and execute the corresponding arithmetic operation based on user choice via a switch statement. The program caters to both valid operations and invalid entries by returning results or error messages as appropriate .

The program represents a water tank's level using a 'Common1' class with methods to simulate filling and consuming water. Initially, the tank is filled thrice with a fixed amount. Usage from each house decrements the tank level, showcasing how shared resources can be manipulated and tracked programmatically. Such simulation helps to understand resource allocation and management in distributed systems .

By creating a class 'Rectangle' with constructors overloaded to handle various initialization scenarios. The program includes constructors with no parameters (assigning zero to length and breadth), one parameter (assigning the same value to length and breadth), and two parameters (explicit values to length and breadth). Additionally, a copy constructor initializes an object with the values of another object. Each object's area is calculated and printed, illustrating the concept of constructor overloading .

Java's polymorphism is exhibited through method overloading in a class where multiple 'area' methods take different parameter types, handling squares with a single integer, rectangles with two integers, and circles with a double. This allows the same method name to perform different operations based on parameter types and is a core principle of Java's object-oriented programming .

The program iterates through each seat position from 1 to 100, using a loop. It checks if the position number is even or odd using the modulus operator (i%2==0). For even positions, the number is added to 'sumeven', and for odd positions, it is added to 'sumodd'. Finally, the sums are printed to the console: 'The sum of even positions is' followed by the calculated sum of even positions, and 'The sum of odd positions is' followed by the calculated sum of odd positions .

The solution involves checking if the given order number is a prime number. A number is treated as prime if it is greater than 1 and has no divisors other than 1 and itself. The program uses a loop to check divisibility from 2 to n-1. If the number is divisible by any of these, a flag is set, indicating that the number is not prime. Customers with prime order numbers receive a 50% discount, while others get an 80% discount .

By implementing parameterized and copy constructors, a student can set initial values during object creation, streamlining the initialization process. Parameterized constructors allow different values for attributes, while copy constructors duplicate state from another instance, promoting code reuse and reducing errors in dynamic object creation .

The program utilizes command line arguments to receive inputs as strings, which are then parsed to integers or floats using Integer.parseInt() and Float.parseFloat(). It performs and displays results for addition, subtraction, multiplication, and division on these numbers. Each operation is executed separately in the main method, showcasing both integer and float operations .

The student can calculate the area by overloading a method called 'area' within a class 'Students', where different implementations of the method handle specific shapes. For instance, a single integer parameter calculates the square's area using Math.pow(), two integer parameters calculate the rectangle's area through multiplication, and a double parameter calculates the circle's area using the formula π*r². This demonstrates polymorphism, allowing a single method name to operate with various parameters .

An inner class is defined within the 'Outer' class, with the 'Inner' class having access to 'Outer' class's private members. The 'display' method in the 'Inner' class accesses and prints values from both the inner and outer classes. This structure encapsulates functionality specific to the outer class, enhancing organization and allowing logical grouping of related classes, aiding in improved readability and maintainability .

You might also like