0% found this document useful (0 votes)
10 views43 pages

Java Programming Exercises and Solutions

The document contains various Java programming exercises, including tasks such as displaying alphabets, copying non-numeric data from files, checking Armstrong numbers, and implementing mouse event handling. It also includes examples of using abstract classes, interfaces, and exception handling in Java. Additionally, there are exercises related to file operations, matrix transposition, and creating graphical user interfaces using AWT and applets.
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)
10 views43 pages

Java Programming Exercises and Solutions

The document contains various Java programming exercises, including tasks such as displaying alphabets, copying non-numeric data from files, checking Armstrong numbers, and implementing mouse event handling. It also includes examples of using abstract classes, interfaces, and exception handling in Java. Additionally, there are exercises related to file operations, matrix transposition, and creating graphical user interfaces using AWT and applets.
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

SLIP SOLUTIONS

Slip1

Java que1:
Slip1 Q.1. Core Java: A) Write a ‘java’ program to display characters
from ‘A’ to ‘Z’
import [Link].*; class slip1 {
public static void main(String[] args) { char ch;
for(ch = 'A'; ch <= 'Z';ch++)

[Link]("the alphabets are :"+ch);

}
Output:
C:\Program Files\Java\jdk1.8.0_144\bin>javac [Link]
C:\Program Files

Slip 1 .B)Write a ‘java’ program to copy only non-numeric data from one file to
another file
import [Link].*;
import [Link].*;
class Copyfile {
public static void main(String arg[]) throws Exception {
Scanner sc = new Scanner([Link]);
[Link]("source file name :");
String sfile = [Link]();
[Link]("destination file name:");
String dfile = [Link]();
FileReader fin = new FileReader(sfile);
FileWriter fout = new FileWriter(dfile, true);
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
[Link]("copy finish...");
[Link]();
[Link]();
}
}

Slip2
Que1: Write a java program to display all the vowels from a given string.
import [Link].*;
class Vowel {
public static void main(String args[]) {
String str = new String("HI Sakshi!");
for(int i=0; i<[Link](); i++) {
if([Link](i) == 'a'|| [Link](i) == 'e'||
[Link](i) == 'i' || [Link](i) == 'o' ||
[Link](i) == 'u'||[Link](i) == 'A'|| [Link](i) == 'E'||
[Link](i) == 'I' || [Link](i) == 'O' ||
[Link](i) == 'U')
[Link]("Given string contains " +
[Link](i)+" at the index " + i);
}
}
}

Que2: Design a screen in Java to handle the Mouse Events such as


MOUSE_MOVED
and MOUSE_CLICK and display the position of the Mouse_Click in a
TextField

import [Link].*;
import [Link].*;
class Slip4 extends Frame
{
TextField statusBar;
Slip4()
{
addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
[Link]("Clicked at (" +[Link]() + "," + [Link]() + ")");
repaint();
}
public void mouseEntered(MouseEvent e)
{
[Link]("Entered at (" + [Link]() + "," +[Link]() + ")");
repaint();
}
});
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
[Link](0);
}
});
setLayout(new FlowLayout());
setSize(275,300);
setTitle("Mouse Click Position");
statusBar = new TextField(20);
add(statusBar);
setVisible(true);
}
public static void main(String []args)
{
new Slip4();
}
}
Slip3
Que1: write a ‘java’ program to check whether given number is Armstrong or
not.(Use static keyword)

import [Link];
public class ArmstsrongNumber
{
static int num, temp, res=0, rem;
public static void main(String[] args)
{
Scanner scan = new Scanner([Link]);
[Link]("Enter the Number: ");
num = [Link]();
temp = num;
while(temp!=0)
{
rem = temp%10;
res = res + (rem*rem*rem);
temp = temp/10;
}
if(num==res)
[Link]("\nArmstrong Number.");
else
[Link]("\nNot an Armstrong Number.");
}
}

Que2: define abstract class shape with abstract method area()and


volume().derive abstract class shape into twoclasses cone and cylinder write
a java
Program to calculate area and volume of Cone and Cylinder.(Use Super
Keyword.)

import [Link].*;
abstract class Shape
{
abstract public void area();
abstract public void vol();
}
class Cone extends Shape
{
int r,s,h;
Cone(int r,int s,int h)
{
super();
this.r=r;
this.s=s;
this.h=h;
}
public void area()
{
[Link]("Area of Cone = "+(3.14*r*s));
}
public void vol()
{
[Link]("volume of Cone = "+(3.14*r*r*h)/3);
}
}
class Cylinder extends Shape
{
int r,h;
Cylinder(int r,int h)
{
this.r=r;
this.h=h;
}
public void area()
{[Link]("Area of cylinder= "+(2*3.14*r*h));
}
public void vol()
{
[Link]("volume of Cylinder = "+(3.14*r*r*h));
}
}
class Slip15
{
public static void main(String a[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter radius, side and height for cone");
int r =[Link]();
int s1 =[Link]();
int h =[Link]();
Shape s;
s=new Cone(r,s1,h);
[Link]();
[Link]();
[Link]("Enter radius, height for cylinder");
r =[Link]();
h =[Link]();
s=new Cylinder(r,h);
[Link]();
[Link]();
}
}

Slip5
Que1: Write a java program to display following pattern:
5
45
345
2345
12345

import [Link].*;
public class pattern {
public static void main(String[] args) {
int n=5; for (int i=n;i>0;i—)
{
for (int j=i;j<=n;j++)
{
[Link](j+" ");
}
[Link]();
}
}
}
QUE:2 Write a java program to accept list of file names through command
line and delete the files having extension “.txt”. Display the details of
remaining files such as FileName and size.

import [Link].*;
class Slip12
{
public static void main(String args[]) throws Exception
{
for(int i=0;i<[Link];i++)
{
File file=new File(args[i]);
if([Link]())
{
String name = [Link]();
if([Link](".txt"))
{
[Link]();
[Link]("file is deleted " + file);
}
else
{
[Link](name + " "+[Link]()+" bytes");
}
}
else
{
[Link](args[i]+ "is not a file");
}
}
}
}
Slip6: que1

Write a java program to accept a number from the user, if number is zero
then throw
user defined Exception “Number is 0” otherwise calculate the sum of first
and last digit of a given number (Use static keyword).

import [Link].*;
class ZeroException extends Exception
{
ZeroException()
{
super("Number is 0");
}
}
class Slip19
{
static int n;
public static void main(String args[])
{
int i,rem,sum=0;
try
{
Scanner sr=new Scanner([Link]);
n=[Link]();
if(n==0)
{
throw new ZeroException();
}
else
{
rem=n%10;
sum=sum+rem;
if(n>9)
{
while(n>0)
{
rem=n%10;
n=n/10;
}
sum=sum+rem;
}
[Link]("Sum is: "+sum);
}
}
catch(ZeroException e)
{
[Link](e);
}
}
}

Que2
Write a java program to display transpose of a given matrix.- Java

import [Link].*;
public class Matrix{
public static void main(String args[]){
//creating a matrix
int original[][]={{10,30,40},{20,40,30},{30,40,50}};
//creating another matrix to store transpose of a matrix
int transpose[][]=new int[3][3]; //3 rows and 3 columns
//Code to transpose a matrix
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
[Link]("Printing Matrix without transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](original[i][j]+" ");

}
[Link]();//new line
}
[Link]("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](transpose[i][j]+" ");
}
[Link]();//new line
}
}
}

Slip8:
Que1 :Define an Interface Shape with abstract method area(). Write a java
program to
calculate an area of Circle and Sphere.(use final keyword)

interface shape
{
final static float pi=3.14f;
float area(float r);
}
class Circle implements shape
{
public float area(float r)
{
return(3.14f*r*r);
}
}
class sphere implements shape
{
public float area(float r)
{
return(2*3.14f*r*r);
}
}
class Main
{
public static void main(String args[])
{
Circle cir=new Circle();
sphere sp=new sphere();
shape s;
s=cir;
[Link]("Area of circle:"+[Link](3));
s=sp;
[Link]("Area of Sphere:"+[Link](5));
}
}
QUE:2
Write a java program to display the files having extension .txt from a given
directory.

import [Link];
public class ListTxtFiles {
public static void main(String[] args) {
String directoryPath = "";
File directory = new File(directoryPath);
if ([Link]() && [Link]()) {
File[] files = [Link]();
if (files != null) {
[Link]("List of .txt files in the directory:");
for (File file : files) {
if ([Link]() && [Link]().toLowerCase().endsWith(".txt")) {
[Link]([Link]());
}
}
} else {
[Link]("No files found in the directory.");
}
}else{
[Link]("The specified directory does not exist or is not a
directory.");
}
}
}
Slip11
Que:1Write a menu dri e a menu driven java program using command line ar
am using command line arguments f guments for the following:
1. Addition
2. Subtraction
3. Multiplication
4. Division.

import [Link].*;
public class CommandLineCalculator {
public static void main(String[] args) {
if ([Link] != 3) {
[Link]("CommandLine Argument");
return;
}
String operation = args[0];
double num1 = [Link](args[1]);
double num2 = [Link](args[2]);

double result=0;

switch (operation) {
case "1":
result = num1 + num2;
[Link]("Addition Result: " + result);
break;
case "2":
result = num1 - num2;
[Link]("Subtraction Result: " + result);
break;
case "3":
result = num1 * num2;
[Link]("Multiplication Result: " + result);
break;
case "4":
if (num2 == 0) {
[Link]("Error: Division by zero is not allowed.");
} else {
result = num1 / num2;
[Link]("Division Result: " + result);
}
break;
default:
[Link]("Invalid [Link] choose 1 for Addition, 2 for
Subtraction, 3 for Multiplication, or 4 for Division.");
}
}
}

QUE2:write a applet application to display table lamp .the colour of lamp


should get change randomely.

import [Link].*;
import [Link].*;
public class Lamp extends [Link] {
public void init() {
resize(300,300);
}
public void paint(Graphics g) {
// the platform
[Link](0,250,290,290);
// the base of the lamp
[Link](125,250,125,160);
[Link](175,250,175,160);
// the lamp shade; two arcs
[Link](215,177,181,89);
// pattern on the shade
[Link](78,120,40,40,63,-174);
[Link](120,96,40,40);
[Link](173,100,40,40,110,180);
}
}

SLIP13:
QUE:1write a java program to accept ‘n’ integers from the user & store thm
in an array list collection Display the elements of arraylist collection in
reverse order.

import [Link].*;
import [Link];
import [Link];
public class ReverseArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
ArrayList<Integer> numberList = new ArrayList<Integer>();
[Link]("Enter the number of integers (n): ");
int n = [Link]();
[Link]("Enter " + n + " integers:");
for(int i=0;i<n;i++){
int num=[Link]();
[Link](num);
}
[Link]("Elements in reverse order:");
for (int i = [Link]() - 1; i >= 0; i--) {
[Link]([Link](i));
}
[Link]();
}
}
QUE2: write a java program that ask user , name and then greet the user by
name before out putting the user name convert it to uppercase letter.

import [Link];
import [Link].*;
public class GreetUser {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter your name: ");
String userName = [Link]();
// Convert the user's name to uppercase
String upperCaseName = [Link]();
[Link]("Hello, " + upperCaseName + ", nice to meet you!");
[Link]();
}
}

Slip 15: Slip 15 A) Write a java program to search given name into the array, if
it is found then display its index otherwise display appropriate message.

QUE1:

public class NameSearch {


public static void main(String[]args) {
String[] names ={"Asha", "Babita ", "Babita", "Chmpa ", "Chmpa", "David",
"Eina vid", "Eina"};
String searchName = "Charlie";
int index = -1;
for (int i = 0; i < [Link]; i++){
if (names[i].equals(searchName)) {
index=i;
break;
}
}
if(index != -1) {
[Link]("Name '" + searchName +"' found at index "+ index);
} else {
[Link]("Name '" + searchName + "'not found in the array.");
} }}

QUE2: Write an applet application to display smiley face.

import [Link];
import [Link].*;
public class Slip30 extends Applet
{
public void paint(Graphics g)
{
[Link](50,15,200,200);
[Link](80,90,30,15);
[Link](190,90,30,15);
[Link](17,90,30,50);
[Link](250,90,30,50);
[Link](150,110,150,150);
//[Link](80,160,10,35);
[Link](100,160,100,30,170,200);
}
}
/*<applet code="[Link]" width="300" height="300"> </applet> */
Slip20

QUE1: A) Write a java program using AWT to create a Frame with title
“TYBBACA”, background color RED. If user clicks on close button then frame
should close.

import [Link].*;
import ja import [Link];
import ja import [Link];
public class RedFrame {
public static void main(String[] args) {
Frame frame = new Frame("TYBB ame("TYBBACA");
[Link]([Link]);
[Link](new WindowAdapter() {
public void windowClosing(WindowEvent e) {
[Link](0);
}
}};
[Link](400, 400);
[Link](true);
}
}

QUE2: SLIP 20.B) Construct a Linked List containing name: CPP, Java, Python
and PHP. Then extend your java program to do the following:
i. Display the contents of the List using an Iterator ii. Display the
contents of the List in reverse order using a ListIterator

import [Link];
import [Link];
import [Link];
import [Link];
public class LinkedListDemo {
public static void main(String[] args) {
List<String> names = new LinkedList<>();
[Link]("CPP");
[Link]("JAVA");
[Link]("PYTHON");
[Link]("PHP");
[Link]("Contents of the List using an It ents of the List using an
Iterator:");
Iterator<String>iterator =[Link]();
while([Link]()) {
[Link]([Link]());
}
[Link]("\nContents of the List in Reverse Order using a
ListIterator:");
ListIterator<String>listIterator = [Link]([Link]());
while([Link]()) {
[Link]([Link]());
}
}
}
PYTHON SLIP SOLUTION

Slip 1

QUE1:A-WriteaPythonprogramtoacceptnnumbersinlistandremove
duplicatesfromalist.

First-Solution marks=[]

n=int(input('Enternumberofelements:'))
foriinrange(n): value=int(input())
[Link](value)
print(marks) new_marks=[]
forxinmarks:
ifxnotinnew_marks:

new_marks.append(x)

print(new_marks)

Enternumberofelements:5

[1,2,3,5,2]

[1,2,3,5]
B)WritePythonGUIprogramtotakeacceptyourbirthdateandoutput
youragewhenabuttonispressed. #importallfunctionsfromthetkinter

fromtkinterimport*
fromtkinterimportmessagebox

[Link](0,END)
[Link](0,END)
[Link](0,END)
[Link](0,END)
[Link](0,END)
[Link](0,END)
[Link](0,END)
[Link](0,END)
[Link](0,END)

#functionforcheckingerror defcheckError():

#ifanyoftheentryfieldisempty
#thenshowanerrormessageandclear
#alltheentries
if([Link]()==""[Link]()==""
[Link]()==""[Link]()==""
[Link]()==""[Link]()==""):

#showtheerrormessage
[Link]("InputError")

#clearAllfunctioncalling
clearAll()

return-1

#functiontocalculateAge defcalculateAge():

#checkforerror
value=checkError()
#iferrorisoccurthenreturn ifvalue== -1:

return
else:

#takeavaluefromtherespectiveentryboxes
#getmethodreturnscurrenttextasstring
birth_day=int([Link]())
birth_month=int([Link]())
birth_year=int([Link]())

given_day=int([Link]())
given_month=int([Link]())
given_year=int([Link]())

#ifbirthdateisgreaterthengivenbirth_month
#thendonotcountthismonthandadd30tothedateso
#astosubtractthedateandgettheremainingdays
month=[31,28,31,30,31,30,31,31,30,31,30,31]

if(birth_day>given_day):
given_month=given_month-1
given_day=given_day+month[birth_month-1]

#ifbirthmonthexceedsgivenmonth,then
#donotcountthisyearandadd12tothe
#monthsothatwecansubtractandfindout
#thedifference
if(birth_month>given_month):
given_year=given_year-1
given_month=given_month+12

#calculateday,month,year
calculated_day=given_day-birth_day;
calculated_month=given_month-birth_month;
calculated_year=given_year-birth_year;
#calculatedday,month,yearwriteback #totherespectiveentryboxes
#insertmethodinsertingthe #valueinthetextentrybox.

[Link](10,str(calculated_day))
[Link](10,str(calculated_month))
[Link](10,str(calculated_year))

#DriverCode if__name__=="__main__":

#CreateaGUIwindow
gui=Tk()

#SetthebackgroundcolourofGUIwindow
[Link](background="lightgreen")

#setthenameoftkinterGUIwindow
[Link]("AgeCalculator")

#SettheconfigurationofGUIwindow
[Link]("525x260")

#CreateaDateOfBirth:label
dob=Label(gui,text="DateOfBirth",bg="blue")

#CreateaGivenDate:label
givenDate=Label(gui,text="GivenDate",bg="blue")

#CreateaDay:label
day=Label(gui,text="Day",bg="lightgreen")

#CreateaMonth:label
month=Label(gui,text="Month",bg="lightgreen")

#CreateaYear:label
year=Label(gui,text="Year",bg="lightgreen")

#CreateaGivenDay:label
givenDay=Label(gui,text="GivenDay",bg="lightgreen")
#CreateaGivenMonth:label
givenMonth=Label(gui,text="GivenMonth",bg="lightgreen")

#CreateaGivenYear:label
givenYear=Label(gui,text="GivenYear",bg="lightgreen")

#CreateaYears:label
rsltYear=Label(gui,text="Years",bg="lightgreen")

#CreateaMonths:label
rsltMonth=Label(gui,text="Months",bg="lightgreen")

#CreateaDays:label
rsltDay=Label(gui,text="Days",bg="lightgreen")

#CreateaResultantAgeButtonandattachedtocalculateAge function
resultantAge=Button(gui,text="ResultantAge",fg="Black",bg=
"Red",command=calculateAge)

#CreateaClearAllButtonandattachedtoclearAllfunction
clearAllEntry=Button(gui,text="ClearAll",fg="Black",bg="Red",
command=clearAll)

#Createatextentryboxforfillingortypingtheinformation.
dayField=Entry(gui)
monthField=Entry(gui)
yearField=Entry(gui)

givenDayField=Entry(gui)
givenMonthField=Entry(gui)
givenYearField=Entry(gui)

rsltYearField=Entry(gui)
rsltMonthField=Entry(gui)
rsltDayField=Entry(gui)
#gridmethodisusedforplacing #thewidgetsatrespectivepositions
#intablelikestructure.
[Link](row=0,column=1)

[Link](row=1,column=0)
[Link](row=1,column=1)

[Link](row=2,column=0)
[Link](row=2,column=1)

[Link](row=3,column=0)
[Link](row=3,column=1)

[Link](row=0,column=4)

[Link](row=1,column=3)
[Link](row=1,column=4)

[Link](row=2,column=3)
[Link](row=2,column=4)

[Link](row=3,column=3)
[Link](row=3,column=4)

[Link](row=4,column=2)

[Link](row=5,column=2)
[Link](row=6,column=2)

[Link](row=7,column=2)
[Link](row=8,column=2)

[Link](row=9,column=2)
[Link](row=10,column=2)

[Link](row=12,column=2)

#StarttheGUI
[Link]()
SLIP2:QUE1

[Link]
numberofuppercaselettersandlowercaseletters.

SampleString:'ThequickBrownFox'

ExpectedOutput:[Link]:3No.
ofLowercasecharacters:13 string=input('enterastring:')
up=low=ele=0 forxinstring:
[Link](): up+=1
[Link]():
low+=1
else:

ele+=1

print('[Link]:',up)
print('[Link]:',low)
print('otherspecialsymbols',ele)print(count1)
print("Thenumberofuppercasecharactersis:") print(count2)

enterastring:Abcdefg
[Link]
[Link]
otherspecialsymbols0

B)WritePythonGUIprogramtocreateadigitalclockwithTkinterto
displaythetime.

importtime fromtkinterimport*
canvas=Tk()
[Link]("DigitalClock")
[Link]("350x200") [Link](1,1)
label=Label(canvas,font=("Courier",30,'bold'),bg="blue",fg="white",bd

=30)
[Link](row=0,column=1) defdigitalclock():
text_input=[Link]("%H:%M:%S")
[Link](text=text_input)
[Link](200,digitalclock)
digitalclock() [Link]()
Output
Runningtheabovecodegivesusthefollowingresult−

SLIP3 :QUE1

A-WriteaPythonprogramtocheckifagivenkeyalreadyexistsina
[Link]/valuepair.

Dict={} n=int(input('enternumberofkeys:'))
forxinrange(0,n): key=input('enterthekey:')
ifkeyinDict: print('thegivenkeyexists!')
[Link]():

print(key,end='')

print('\n^usedifferntkeysfromabovelist')
key=input('enterthekey:')
value=input('enterthevalue:')

Dict[key]=value print(Dict)

enternumberofkeys:2
enterthekey:abc
enterthevalue:200
enterthekey:pqr
enterthevalue:300

{'abc':'200','pqr':'300'}

B)Write a python script to define a class student having members roll


no,name,age,[Link] a subclass called test with member marks of 3
[Link] three objects of theTest class and display all the details of the
student with to total marks.

cl
assSt
udent
():

def__init__(self,roll_no,name,age,gender):
self.roll_no=roll_no
[Link]=name [Link]=age
[Link]=gender

classTest(Student): def
__init__(self,roll_no,name,age,gender,sub1mark,sub2mark,sub3mark,):
super().__init__(roll_no,name,age,gender)
self.mark1=sub1mark self.mark2=sub2mark
self.mark3=sub3mark

defget_marks(self):
[Link]=self.mark1+self.mark2+self.mark3 print([Link],"\
b'smarks:",[Link]) print("sub1marks:",self.mark1)
print("sub2marks:",self.mark2) print("sub3marks:",self.mark3)

p1=Test(1,"amar",19,'male',82,89,76)
p2=Test(2,'priya',20,'female',94,91,84)
p1.get_marks() p2.get_marks()

abc'smarks:247
sub1marks:82
sub2marks:89
sub3marks:76
pqr'smarks:269
sub1marks:94
sub2marks:91
sub3marks:84
SLIP5: QUE1

Que 1: A)WriteaPythonscriptusingclass,whichhastwomethods
get_Stringandprint_String.get_Stringacceptastringfromthe
userandprint_Stringprintthestringinuppercase.

class Str1():
def __init__(self,demo=0):

[Link]=demo

def set_String(self,demo):

[Link]=demo

def print_streing(self):

str=[Link]

print([Link]())

A=Str1()

rowinput=input('enter a string :')

A.set_String(rowinput)

A.print_streing()

Que 2) Write a python script to generate Fibonacci term using generator


function.
def generator(r):

a=0;b=1

for i in range (1,r):

print(b)

a,b=b,a+b

n=int(input('Enter a number :'))

if n==0:

print('0')

else:

print(0)

generator(n)

slip 6

que 1) write a python program script using packages to calculate area and
volume of cube and sphere.

#impotr math package to use [Link] for the value of PI

import math

#take radius from user

r=float(input("Enter the r of a sphere:"))

#calculate the surface area of sphere


s_area=4*[Link]*pow(r,2)

print("surface area of the sphere wll be %.2f" %s_area)

#calculate the volume of sphere

volume=(4/3)*[Link]*pow(r,3)

print("volume of the sphere will be %.2f" %volume)

#calculate the area of cube

av=6*pow(r,2)

print("area of cube %.2f" %av)

#calculate the volume of cube

vc=pow(r,3)

print("volume of cube %.2f" %vc)

que 2) write python program GUI program to create a lable and change
the lable font style.(font name .bold,sixe) specify seprate check button for
each style.

from tkinter import *

win= Tk()

[Link]("650x250")

def size_1():
[Link](font=('Arial',20))

[Link](bg= "gray51", fg= "white")

def size_2():

[Link](font=('Helvetica bold',40))

[Link](bg= "white", fg= "red")

text=Label(win, text="Hello World!")

[Link]()

frame= Frame(win)

#Create a label

Label(frame, text="Select the Font-Size").pack()

#Create Buttons for styling the label

button1= Checkbutton(frame, text="Arial - 20", command= size_1)

[Link](pady=10)

button2= Checkbutton(frame, text="Helvetica - 40", command=size_2)

[Link](pady=10)

[Link]()
[Link]()

Slip 8

Que 1) write a slip to find the repeated items of a tuple.

#create a tuple

tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7

print(tuplex)

count = [Link](4)

print(count)

que 2)write a python class which has two methods get string from the user
ad print string print the string in upper case further modify the program to
reverse a string word by word and print it in lower case.

class Str1():

def __init__(self,demo=0):

[Link]=demo

def set_String(self,demo):

demo=[Link]()

[Link]=demo
def print_streing(self):

return [Link]

A=Str1()

str1=input('enter a string to display :')

A.set_String(str1)

print('Upper string :',A.print_streing())

Slip11

Que 1) write a python program to compute elements -wise sum of given


tuple.

Original list (1,2,3,4) (3,5,2,1)(2,2,3,1) element wise totle of a given tuple is


(6,9,8,6)

x = (1,2,3,4)

y = (3,5,2,1)

z = (2,2,3,1)

print("Original lists:")
print(x)

print(y)

print(z)

print("\nElement-wise sum of the said tuples:")

result = tuple(map(sum, zip(x, y, z)))

print(result)

que 2) write a python GUI program to add menu bar with name of colors
as option to change the background color as per selection from menu
option.

from tkinter import Menu, Tk, mainloop

def redcolor():

[Link](background = 'red')

def greencolor():

[Link](background = 'green')

def yellowcolor():

[Link](background = 'yellow')
def violetcolor():

[Link](background = 'violet')

def bluecolor():

[Link](background = 'blue')

def cyancolor():

[Link](background = 'cyan')

root = Tk()

[Link]('COLOR MENU')

menubar = Menu(root)

color = Menu(menubar, tearoff = 0)

menubar.add_cascade(label ='color', menu = color)

color.add_command(label ='Red', command = redcolor,activebackground='red',

activeforeground='cyan')

color.add_command(label ='Green',command =
greencolor,activebackground='green',

activeforeground='blue')

color.add_command(label ='Blue',command =
bluecolor,activebackground='blue',

activeforeground='yellow')
color.add_command(label ='Yellow',command =
yellowcolor,activebackground='yellow',

activeforeground='blue')

color.add_command(label ='Cyan',command =
cyancolor,activebackground='cyan',

activeforeground='red')

color.add_command(label ='Violet',command =
violetcolor,activebackground='violet',

activeforeground='green')

color.add_separator()

color.add_command(label ='Exit',command = [Link])

[Link](menu = menubar)

mainloop()

Slip13

Que 1) write a python program to input a positive integer Display correct


massage for correct and incorrect input.(use exception handelling)

try:

num=int(input('Enter a number :'))

except ValueError:

print("\nThis is negative number!")


else:

print('\nnumber is positive : ',num)

que 2) write a program to implement the concept of queue using list

q=[]

[Link](10)

[Link](100)

[Link](1000)

[Link](10000)

print("Initial Queue is:",q)

print([Link](0))

print([Link](0))

print([Link](0))

print("After Removing elements:",q)

Slip15

Que 1) write a python class named student with two attributes


studentname , and marks modify the attribute values of the said class and
print the original and modified values of said attributes.

class StudentDetails:

def AcceptDetails(self):

[Link]=input("Enter Student Name:")

[Link]=int(input("Enter Student Total Marks:"))

def ModifyDetails(self):
[Link]=[Link]

[Link]=int(input("Enter Student New Total Marks:"))

print("Student Name:",[Link])

print("Old Total Mark:",[Link])

print("New Total Mark:",[Link])

S=StudentDetails()

[Link]()

[Link]()

Que 2) write a python program to accept the string and remove the
characters which have odd index values of given string using user defined
function.

def removeodd(string):

str2=''

for x in range(len(string)):

if x%2==0:

str2=str2+string[x]

return str2

str1=input('enter a string : ')

print('String after removing char : ',removeodd(str1))


Slip 20

Que 1) write a python program to create a classs circle and computes the
area of circumference of a circle (use parameterized constructor.)..

from math import pi

class Circle():

def __init__(self,Radius):

[Link]=Radius

def area(self):

a=pi*[Link]*[Link]

return round(a,2)

def circumference(self):

c=2*[Link]*pi

return round(c,2)

r= int(input('enter radius of circle : '))

a=Circle(r)

print('Area of circle is : ',[Link]())

print('Circumference of circle is : ',[Link]())

que 2) write a python script to generate and print a dictionary which


contain a number between 1 to n in the form of (x,x*x) sample dictionary
(n=5)

expected output :{1:1,2:4,3:9,4:16,5:25}

n=int(input("Input a number : "))

d =dict()
for x in range(1,n+1):

d[x]=x*x

print(d)

method 2:

n=int (input(“enter a number:”))

d={x:x*x for x in range (1,n+1)}

print(d)

Common questions

Powered by AI

The command-line calculator in the Java program handles division by zero explicitly by checking if the second number is zero before performing the division, thus avoiding an ArithmeticException. However, improvements could include handling potential NumberFormatException when parsing command-line arguments to double and ensuring valid operation codes, further improving robustness against user input errors by displaying more descriptive error messages .

Iterators in Java, such as ListIterator, provide methods for bidirectional traversal over lists like LinkedLists, including operations like insertion, removal, and replacement of elements. They allow developers to iterate through collections with more granularity and control, supporting forward and backward traversal. This utility is demonstrated in examples where iterators are used to display elements in reverse, which would be cumbersome with basic loop constructs .

The Scanner class in Java is a versatile tool for input handling, parsing user entries from the console for various data types including int, double, and String. It simplifies extracting and converting input data by offering methods like nextInt(), nextDouble(), and nextLine(), each tailored to efficiently capture and convert input without needing extensive validation logic. This makes it integral for designing user-interactive applications where data type accuracy is critical .

Java's ArrayList and LinkedList, part of the Collections Framework, offer dynamic size and performance-optimized list management. ArrayLists provide fast random access and are suitable for iterate-through tasks, while LinkedLists allow efficient insertions and deletions. The ListIterator enables functionalities like reverse iteration, demonstrated in the program where elements are traversed in reverse, showcasing Java's robust capabilities for managing data collections .

The applet application uses Java's AWT library to draw shapes and colors that form a smiley face by overriding the 'paint' method, which includes drawing ovals and arcs for facial features within a defined window. Despite its straightforward illustration of GUI design, using AWT and applets can pose challenges such as compatibility issues with modern browsers that no longer support Java applets, the security risks associated with enabling them, and generally limited functionalities for building complex user interfaces .

In Java, using the 'final' keyword for a static variable within an interface indicates that the value cannot be changed, ensuring that π, a mathematical constant, remains immutable and secure from accidental modification. This guarantees the consistency needed for precise calculations in classes implementing the 'shape' interface, as seen in the provided solutions .

The Java program uses inheritance and polymorphism to ensure each shape, like a cone or cylinder, calculates its area and volume using its specific formulas. The 'Shape' class is extended by classes like 'Cone' and 'Cylinder', each overriding the 'area' and 'vol' methods to provide their specific implementations based on their geometric properties. This structure adheres to the object-oriented programming principles of encapsulation, hierarchy, and polymorphism, allowing for each shape to maintain its unique behavior .

The matrix transposition in Java involves iterating through the original matrix's rows and columns, swapping indices to populate a new matrix such that each row element becomes a column element. This process is implemented with nested loops to ensure each element is relocated according to the transpose logic. Computational considerations include ensuring the matrix dimensions align for correct data placement and optimizing loops to handle larger datasets efficiently .

Using a user-defined exception in Java, such as 'ZeroException' for handling zero input, enhances program reliability by allowing developers to define precise error handling strategies tailored to specific application needs. This approach provides clearer, context-specific error messages and maintains control over the program flow, thus preventing unexpected crashes or undefined behaviors arising from invalid inputs .

The WindowAdapter class in Java's AWT framework is pivotal for handling window events. It serves as an abstract adapter class with empty methods that can be overridden to provide specific event handling logic. In applications, such as when managing a window's close operation, developers override the 'windowClosing' method to execute custom actions like terminating the application, which facilitates precise control over UI interactions and enhances user experience .

You might also like