0% found this document useful (0 votes)
2 views63 pages

Core Java

The document contains a series of Java programming exercises for a BBA(CA) course, including programs for checking palindromes, finding maximum and minimum values, generating multiplication tables, displaying Fibonacci series, and more. Each exercise includes code snippets demonstrating the implementation of the respective functionality. The document serves as a practical guide for students to enhance their Java programming skills.

Uploaded by

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

Core Java

The document contains a series of Java programming exercises for a BBA(CA) course, including programs for checking palindromes, finding maximum and minimum values, generating multiplication tables, displaying Fibonacci series, and more. Each exercise includes code snippets demonstrating the implementation of the respective functionality. The document serves as a practical guide for students to enhance their Java programming skills.

Uploaded by

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

TY BBA(CA) SEM 5 Core java P.P.

Kulkarni

Practice Set:
1. Write a java Program to check whether given String is Palindrome or not.
import [Link].*;

// Driver Class
class palindrome {
// main function
public static boolean isPalindrome(String str)
{
// Initializing an empty string to store the reverse
// of the original str
String rev = "";

// Initializing a new boolean variable for the


// answer
boolean ans = false;

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


rev = rev + [Link](i);
}

// Checking if both the strings are equal


if ([Link](rev)) {
ans = true;
}
return ans;
}
public static void main(String[] args)
{
// Input string
String str = "abc";

// Convert the string to lowercase


str = [Link]();
boolean A = isPalindrome(str);
[Link](A);
}
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 1


TY BBA(CA) SEM 5 Core java [Link]

2. Write a Java program which accepts three integer values and prints the maximum and
Minimum.

import [Link];
public class Example {

public static void main(String[] args) {


Scanner in = new Scanner([Link]);

[Link]("Input the 1st number: ");


int num1 = [Link]();

[Link]("Input the 2nd number: ");


int num2 = [Link]();

[Link]("Input the 3rd number: ");


int num3 = [Link]();

if (num1 > num2)


if (num1 > num3)
[Link]("The greatest: " + num1);

if (num2 > num1)


if (num2 > num3)
[Link]("The greatest: " + num2);

if (num3 > num1)


if (num3 > num2)
[Link]("The greatest: " + num3);
}
}
3. Write a Java program to accept a number from command prompt and generate
multiplication table of a number.
import [Link];
public class MultiplicationTable {
public static void main(String args[]) {
[Link]("Enter an integer variable :: ");
Scanner sc = new Scanner([Link]);
int num = [Link]();
for(int i=1; i<= 20; i++) {

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 2


TY BBA(CA) SEM 5 Core java [Link]

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


}
}
}

4. Write a Java program to display Fibonacci series.


class Main {
public static void main(String[] args) {

int n = 10, firstTerm = 0, secondTerm = 1;


[Link]("Fibonacci Series till " + n + " terms:");

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


[Link](firstTerm + ", ");

// compute the next term


int nextTerm = firstTerm + secondTerm;
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
}

5. Write a Java program to calculate the sum of digits of a number.


import [Link];
class SumOfDigits
{
public static void main(String arg[])
{
long n,sum;
Scanner sc=new Scanner([Link]);
[Link]("Enter a number ");
n=[Link]();
for(sum=0 ;n!=0 ;n/=10)
{
sum+=n%10;
}
[Link]("Sum of digits of a number is "+sum);
}
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 3


TY BBA(CA) SEM 5 Core java [Link]

6. Write a Java program to accept a year and check if it is a leap year or not.
import [Link];
class Leapyear
{
public static void main(String arg[])
{
long a,y,c;
Scanner sc=new Scanner([Link]);
[Link]("enter any calendar year :");
y=[Link]();
if(y!=0)
{
a=(y%400==0)?(c=1):((y%100==0)?(c=0):((y%4==0)?(c=1):(c=0)));
if(a==1)
[Link](y+" is a leap year");
else
[Link](y+" is not a leap year");
}
else
[Link]("year zero does not exist ");
}
}

7. Write a Java program to display characters from A to Z using loop.


Public class DisplayCharacters { // Step 1: Define a class named DisplayCharacters

public static void main(String[] args) { // Main method

// Step 3: Initialize i to 65 and Step 4: Continue as long as i is less than or equal to 90


for (int i = 65; i <= 90; i++) {
// Step 5: Cast i to char and print the character
[Link]((char) i + " ");
}
}
}

8. Write a Java program to accept two numbers using command line argument and
calculate
addition, subtraction, multiplication and division

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 4


TY BBA(CA) SEM 5 Core java [Link]

import [Link];

public class JavaProgram


{
public static void main(String args[])
{
int first, second, add, subtract, multiply;
float devide;
Scanner scanner = new Scanner([Link]);

[Link]("Enter Two Numbers : ");


first = [Link]();
second = [Link]();

add = first + second;


subtract = first - second;
multiply = first * second;
divide = (float) first / second;

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


[Link]("Difference = " + subtract);
[Link]("Multiplication = " + multiply);
[Link]("Division = " + divide);
}
}.
9. Write a java Program to calculate the sum of first and last digit of a number.
public class Main
{
public static void main(String args[])
{
//a number declared
int number = 63365;
//storing the number value in a temporary variable say 'temp'
int temp=number;
//declaring two integer variable firstDigit and lastDigit
//and initializing both with value as 0
int firstDigit=0;
int lastDigit=0;

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 5


TY BBA(CA) SEM 5 Core java [Link]

//find last digit of number


lastDigit=number%10;

//countinue the loop till the number becomes 0


//inside loop variable 'firstDigit' will give the first digit at the end of while loop
while(number!=0)
{
int rem = number%10;
firstDigit=rem;
number= number/10;
}
[Link]("Number is: "+temp);
[Link]("First digit of number: "+ firstDigit );
[Link]("Last digit of number: "+ lastDigit);
[Link]("Sum of first and last digit of number: "+ (firstDigit+lastDigit));
}
}

10. Write a java program to calculate the sum of even numbers from an array.
// Main method
public static void main(String[] args) {

// Declare and Initialize an integer array


int arr[] = { 2, 4, 3, 8, 11, 50, 7, 15, 5 };

// To calculate sum of even numbers


int evenSum = 0;

[Link]("The sum of all Even numbers:");

// Iterate the array


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

// Check whether the No. is an Even


// if reminder is 0, it is an Even number
if (arr[i] % 2 == 0) {

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 6


TY BBA(CA) SEM 5 Core java [Link]

if (evenSum > 0) {
[Link](" + " + arr[i]);
} else {
[Link](arr[i]);
}

// Calculate the even sum


evenSum = evenSum + arr[i];
}
}

// Print the final result


[Link](" = " + evenSum);

Set A:
1. Write a java Program to check whether given number is Prime or Not.
public class Main {

public static void main(String[] args) {

int num = 29;


boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}

if (!flag)
[Link](num + " is a prime number.");
else
[Link](num + " is not a prime number.");
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 7


TY BBA(CA) SEM 5 Core java [Link]

2. Write a java Program to display all the perfect numbers between 1 to n.


import [Link];
public class Perfect
{
static boolean perfect(int num)
{
int sum = 0;
for(int i=1; i<num; i++)
{
if(num%i==0)
{
sum = sum+i;
}
}
if(sum==num)
return true;
else
return false;
}
public static void main(String[] args)
{
Scanner obj = new Scanner ([Link]);
[Link]("enter the value for n");
int n = [Link]();
for(int i=1; i<=n; i++)
{
if(perfect(i))
[Link](i);
}
}

3. Write a java Program to accept employee name from a user and display it in reverse
order.
public class Main {
public static void main(String[] args) {
String originalStr = "Hello";
String reversedStr = "";

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 8


TY BBA(CA) SEM 5 Core java [Link]

[Link]("Original string: " + originalStr);

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


reversedStr = [Link](i) + reversedStr;
}

[Link]("Reversed string: "+ reversedStr);


}
}

4. Write a java program to display all the even numbers from an array. (Use Command
Line arguments)
import [Link];

public class DisplayEvenNumbersExample3

public static void main(String[] args)

int number, i;

Scanner sc=new Scanner([Link]);

[Link]("Enter the limit: ");

number = [Link]();

i=2;

[Link]("Lit of even numbers: ");

//the while loop executes until the condition become false

while(i<=number)

//prints the even number

[Link](i +" ");

//increments the variable i by 2

i=i+2;

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 9


TY BBA(CA) SEM 5 Core java [Link]

5. Write a java program to display the vowels from a given string


import [Link];

.
class Main {
private static boolean isVowel(char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'
|| c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U';
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter a string: ");


String str = [Link]();

[Link]("Vowels found: ");


for (char c : [Link]()) {
if (isVowel(c)) {
[Link](c + " ");
}
}
}

Set B:
1. Write a java program to accept n city names and display them in ascending order.
import [Link];

class SortStrings
{
public static void main(String args[])
{
String temp;
Scanner SC = new Scanner([Link]);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 10


TY BBA(CA) SEM 5 Core java [Link]

[Link]("Enter the value of N: ");


int N= [Link]();
[Link](); //ignore next line character

String names[] = new String[N];

[Link]("Enter names: ");


for(int i=0; i<N; i++)
{
[Link]("Enter name [ " + (i+1) +" ]: ");
names[i] = [Link]();
}

//sorting strings

for(int i=0; i<5; i++)


{
for(int j=1; j<5; j++)
{
if(names[j-1].compareTo(names[j])>0)
{
temp=names[j-1];
names[j-1]=names[j];
names[j]=temp;
}
}
}

[Link]("\nSorted names are in Ascending Order: ");


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

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 11


TY BBA(CA) SEM 5 Core java [Link]

2. Write a java program to accept n numbers from a user store only Armstrong numbers in
an array
and display it.
class ArmstrongWhile
{
public static void main(String[] arg)
{
int i=100,arm;
[Link]("Armstrong numbers between 100 to 999");
while(i<1000)
{
arm=armstrongOrNot(i);
if(arm==i)
[Link](i);
i++;
}
}
static int armstrongOrNot(int num)
{
int x,a=0;
while(num!=0)
{
x=num%10;
a=a+(x*x*x);
num/=10 ;
}
return a;
}
}

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

import [Link];

class SortStrings
{
public static void main(String args[])
{
String temp;

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 12


TY BBA(CA) SEM 5 Core java [Link]

Scanner SC = new Scanner([Link]);

[Link]("Enter the value of N: ");


int N= [Link]();
[Link](); //ignore next line character

String names[] = new String[N];

[Link]("Enter names: ");


for(int i=0; i<N; i++)
{
[Link]("Enter name [ " + (i+1) +" ]: ");
names[i] = [Link]();
}

//sorting strings

for(int i=0; i<5; i++)


{
for(int j=1; j<5; j++)
{
if(names[j-1].compareTo(names[j])>0)
{
temp=names[j-1];
names[j-1]=names[j];
names[j]=temp;
}
}
}

[Link]("\nSorted names are in Ascending Order: ");


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

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 13


TY BBA(CA) SEM 5 Core java [Link]

4. Write a java program to display following pattern:


5
45
345
2345
12345
import [Link].*;

public class GeeksForGeeks {


// Function to demonstrate pattern
public static void printPattern(int n)
{
int i, j;

// outer loop to handle rows


for (i = n; i >= 1; i--) {

// inner loop to print spaces.


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

// inner loop to print stars.


for (j = 0; j <= n - i; j++) {
[Link]("*");
}

// printing new line for each row


[Link]();
}
}

// Driver Function
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 14


TY BBA(CA) SEM 5 Core java [Link]

5. Write a java program to display following pattern:


1
01
010
1010
import [Link].*;

public class GeeksForGeeks {


// Function to demonstrate pattern
public static void printPattern(int n)
{
int i, j;
//outer loop to handle number of rows
for (i = 1; i <= n; i++) {
//inner loop to handle number of columns
for (j = 1; j <= i; j++) {
// if the sum of (i+j) is even then print 1
if ((i + j) % 2 == 0) {
[Link](1 + " ");
}
// otherwise print 0
else {
[Link](0 + " ");
}
}

//printing new line for each row


[Link]();
}
}

// Driver Function
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 15


TY BBA(CA) SEM 5 Core java [Link]

Assignment 2
Set A:
1. Write a Java program to calculate power of a number using recursion.
class xyz{

// Function to calculate N raised to the power P


static int power(int N, int P)
{
if (P == 0)
return 1;
else
return N * power(N, P - 1);
}

// Driver code
public static void main(String[] args)
{
int N = 2;
int P = 3;

[Link](power(N, P));
}
}

2. Write a Java program to display Fibonacci series using function.


class FibonacciExample2{

static int n1=0,n2=1,n3=0;

static void printFibonacci(int count){

if(count>0){

n3 = n1 + n2;

n1 = n2;

n2 = n3;

[Link](" "+n3);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 16


TY BBA(CA) SEM 5 Core java [Link]

printFibonacci(count-1);

public static void main(String args[]){

int count=10;

[Link](n1+" "+n2);//printing 0 and 1

printFibonacci(count-2);//n-2 because 2 numbers are already printed

3. Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method
Overloading)
public class Main
{
//Driver Code
public static void main(String[] args)
{
Rectangle obj = new Rectangle();
// Calling function
[Link](30, 20);
[Link](12.5, 4.5);
Circle obj1 = new Circle();
// Calling function
[Link](3);
[Link](5.5);
Square obj2 = new Square();
// Calling function
[Link](20);
[Link](5.2);

}
}
class Square
{
// Overloaded function to
// calculate the area of the square

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 17


TY BBA(CA) SEM 5 Core java [Link]

// It takes one double parameter


void Area(double side)
{
[Link]("Area of the Square: "+ side * side);
}
// Overloaded function to
// calculate the area of the square
// It takes one float parameter
void Area(float side)
{
[Link]("Area of the Square: "+ side * side);
}
}
class Circle
{
static final double PI = [Link];

// Overloaded function to
// calculate the area of the circle.
// It takes one double parameter
void Area(double r)
{
double A = PI * r * r;

[Link]("The area of the circle is :" + A);


}

// Overloaded function to
// calculate the area of the circle.
// It takes one float parameter
void Area(float r)
{
double A = PI * r * r;

[Link]("The area of the circle is :" + A);


}
}
class Rectangle
{
// Overloaded function to

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 18


TY BBA(CA) SEM 5 Core java [Link]

// calculate the area of the rectangle


// It takes two double parameters
void Area(double l, double b)
{
[Link]("Area of the rectangle: " + l * b);
}
// Overloaded function to
// calculate the area of the rectangle.
// It takes two float parameters
void Area(int l, int b)
{
[Link]("Area of the rectangle: " + l * b);
}

4. Write a Java program to Copy data of one object to another Object.


import [Link].*;

// A test class whose objects are cloned


class Test {
int x, y;
Test()
{
x = 10;
y = 20;
}
}

// Driver Class
class Main {
public static void main(String[] args)
{
Test ob1 = new Test();

[Link](ob1.x + " " + ob1.y);

// Creating a new reference variable ob2

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 19


TY BBA(CA) SEM 5 Core java [Link]

// pointing to same address as ob1


Test ob2 = ob1;

// Any change made in ob2 will


// be reflected in ob1
ob2.x = 100;

[Link](ob1.x + " " + ob1.y);


[Link](ob2.x + " " + ob2.y);
}
}

5. Write a Java program to calculate factorial of a number using recursion.


Public class Factorial {

public static void main(String[] args) {


int num = 6;
long factorial = multiplyNumbers(num);
[Link]("Factorial of " + num + " = " + factorial);
}
public static long multiplyNumbers(int num)
{
if (num >= 1)
return num * multiplyNumbers(num - 1);
else
return 1;
}
}

Set B:
1. Define a class person(pid,pname,age,gender). Define Default and parameterised
constructor. Overload the constructor. Accept the 5 person details and display it.(use this
keyword).
import [Link].*;
class person
{

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 20


TY BBA(CA) SEM 5 Core java [Link]

int pid,age;
String pname,gender;
person()
{

}
person(int p,int a,String pname,String gen)
{
[Link]=p;
[Link]=a;
[Link]=pname;
[Link]=gen;
}
public String toString()
{
[Link]("Person id is :"+pid);
[Link]("Person Age is :"+age);
[Link]("Person Name is :"+pname);
[Link]("Person gender is :"+gender);
return "true";
}
public static void main(String args[])
{
Scanner sc=new Scanner([Link]);
[Link]("Enter How many Person details you want to store ?");
int n=[Link]();
person p[]=new person[n];
for(int i=0;i<n;i++)
{
[Link]("Enter Person Id :");
int pid=[Link]();
[Link]("Enter Person Age :");
int age=[Link]();
[Link]("Enter Person Name :");
String name=[Link]();
[Link]("Enter Person gender :");
String gender=[Link]();

p[i]=new person(pid,age,name,gender);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 21


TY BBA(CA) SEM 5 Core java [Link]

}
for(int i=0;i<n;i++)
{
[Link]("**********Person Details are ***********");

p[i].toString();
}

2. Define a class product(pid,pname,price). Write a function to accept the product details,


to
display product details and to calculate total amount. (use array of Objects)

3. Define a class Student(rollno,name,per). Create n objects of the student class and Display
it using toString().(Use parameterized constructor)
import [Link].*;
class Student {
int rollNumber;
String name;
float per;
static int count=0;
public Student(){
rollNumber=0;
name=null;
per=0.0f;
}
public Student(int rollNumber,String name,float per){
[Link]=rollNumber;
[Link]=name;
[Link]=per;
count++;
}
public static void count(){
[Link]("Object "+(count)+" Created");
}
public void display(){
[Link]("Roll Number: "+rollNumber);
[Link]("Name: "+name);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 22


TY BBA(CA) SEM 5 Core java [Link]

[Link]("Percentage: "+per);
[Link]("------------------------------");
}
}
public class StudentMain {
public static void main(String [] args)throws IOException{
Student s1=new Student(1,"Rusher",56.76f);
[Link]();
Student s2=new Student(2,"Naren",89.67f);
[Link]();
Student s3=new Student(3,"Adi",99.54f);
[Link]();
[Link]();
[Link]();
[Link]();
}
}

4. Define a class MyNumber having one private integer data member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value. Write
methods isNegative, isPositive. Use command line argument to pass a value to the object
and perform the above tests.
public class MyNumber {
private int x;
public MyNumber(){
x=0;
}
public MyNumber(int x){
this.x=x;
}
public boolean isNegative(){
if(x<0)
return true;
else return false;
}
public boolean isPositive(){
if(x>0)
return true;
else return false;
}
public boolean isZero(){
if(x==0)

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 23


TY BBA(CA) SEM 5 Core java [Link]

return true;
else return false;
}
public boolean isOdd(){
if(x%2!=0)
return true;
else return false;
}
public boolean isEven(){
if(x%2==0)
return true;
else return false;
}
public static void main(String [] args) throws ArrayIndexOutOfBoundsException
{
int x=[Link](args[0]);
MyNumber m=new MyNumber(x);
if([Link]())
[Link]("Number is Negative");
if([Link]())
[Link]("Number is Positive");
if([Link]())
[Link]("Number is Even");
if([Link]())
[Link]("Number is Odd");
if([Link]())
[Link]("Number is Zero");
}
}

Assignment 3

Set A:
1. Write a java program to calculate area of Cylinder and Circle.(Use super keyword)
import [Link].*;

class Shape {
double radius;

Shape(double r) {
radius = r;

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 24


TY BBA(CA) SEM 5 Core java [Link]

double area() {
return 0.0;
}
}

class Circle extends Shape {


Circle(double r) {
super(r);
}

double area() {
return [Link] * radius * radius;
}
}

class Cylinder extends Shape {


double height;

Cylinder(double r, double h) {
super(r);
height = h;
}

double area() {
return 2 * [Link] * radius * height + 2 * [Link] * radius * radius;
}
}

class Test {
public static void main(String args[]) {
Circle c = new Circle(10);
[Link]("Area of circle is: " + [Link]());

Cylinder cy = new Cylinder(10, 20);


[Link]("Area of cylinder is: " + [Link]());
}
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 25


TY BBA(CA) SEM 5 Core java [Link]

2. 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
{
void input();
void area();
}
class Circle implements Shape
{
int r = 0;
double pi = 3.14, ar = 0;
@Override
public void input()
{
r = 5;
}
@Override
public void area()
{
ar = pi * r * r;
[Link]("Area of circle:"+ar);
}
}
class Rectangle extends Circle
{int l = 0, b = 0;
double ar;
public void input()
{
[Link]();
l = 6;
b = 4;
}
public void area()
{
[Link]();
ar = l * b;
[Link]("Area of rectangle:"+ar);
}

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 26


TY BBA(CA) SEM 5 Core java [Link]

}
public class Demo
{
public static void main(String[] args)
{
{
Rectangle obj = new Rectangle();
[Link]();
[Link]();
}
}

3. Define an Interface “Integer” with a abstract method check().Write a Java program to


check whether a given number is Positive or Negative.
public class CheckPositiveOrNegativeExample1

public static void main(String[] args)

//number to be check

int num=912;

//checks the number is greater than 0 or not

if(num>0)

[Link]("The number is positive.");

//checks the number is less than 0 or not

else if(num<0)

[Link]("The number is negative.");

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 27


TY BBA(CA) SEM 5 Core java [Link]

//executes when the above two conditions return false

else

[Link]("The number is zero.");

4. Define a class Student with attributes rollno and name. Define default and
parameterized
constructor. Override the toString() method. Keep the count of Objects created. Create
objects using parameterized constructor and Display the object count after each object is
Created.

import [Link].*;
class Student {
int rollNumber;
String name;
float per;
static int count=0;
public Student(){
rollNumber=0;
name=null;
per=0.0f;
}
public Student(int rollNumber,String name,float per){
[Link]=rollNumber;
[Link]=name;
[Link]=per;
count++;
}
public static void count(){
[Link]("Object "+(count)+" Created");
}
public void display(){
[Link]("Roll Number: "+rollNumber);
[Link]("Name: "+name);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 28


TY BBA(CA) SEM 5 Core java [Link]

[Link]("Percentage: "+per);
[Link]("------------------------------");
}
}
public class StudentMain {
public static void main(String [] args)throws IOException{
Student s1=new Student(1,"Rusher",56.76f);
[Link]();
Student s2=new Student(2,"Naren",89.67f);
[Link]();
Student s3=new Student(3,"Adi",99.54f);
[Link]();
[Link]();
[Link]();
[Link]();
}

}
5. Write a java program to accept ‘n’ integers from the user & store them in an ArrayList
collection. Display the elements of ArrayList collection in reverse order.

import [Link].*;

class array

public static void main(String a[])

Scanner sc=new Scanner([Link]);

[Link]("Enter Limit of ArrayList :");

int n=[Link]();

ArrayList alist=new ArrayList();

[Link]("Enter Elements of ArrayList :");

for(int i=0;i<n;i++)

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 29


TY BBA(CA) SEM 5 Core java [Link]

String elmt=[Link]();

[Link](elmt);

[Link]("Original ArrayList is :"+alist);

[Link](alist);

[Link]("Reverse of a ArrayList is :"+alist);

Set B:
1. Create an abstract class Shape with methods calc_area() & calc_volume(). Derive two
classes Sphere(radius)& Cone(radius, height) from it. Calculate area and volume of both.
(Use Method Overriding)

import [Link].*;

class array

public static void main(String a[])

Scanner sc=new Scanner([Link]);

[Link]("Enter Limit of ArrayList :");

int n=[Link]();

ArrayList alist=new ArrayList();

[Link]("Enter Elements of ArrayList :");

for(int i=0;i<n;i++)

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 30


TY BBA(CA) SEM 5 Core java [Link]

String elmt=[Link]();

[Link](elmt);

[Link]("Original ArrayList is :"+alist);

[Link](alist);

[Link]("Reverse of a ArrayList is :"+alist);

2. Define a class Employee having private members-id, name, department, salary. Define
default & parameterized constructors. Create a subclass called Manager with private
member bonus. Define methods accept & display in both the classes. Create n objects of
the manager class & display the details of the manager having the maximum total
salary(salary+bonus).

import [Link].*;
import [Link].*;
class Employee
{
String nm;
int id;
float sal;
void accept()
{
[Link]("Enter id & name");
Scanner s=new Scanner([Link]);
id=[Link]();
nm=[Link]();
}
float getsalary()
{
[Link]("Enter salary");
Scanner s=new Scanner([Link]);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 31


TY BBA(CA) SEM 5 Core java [Link]

sal=[Link]();
return sal;
}
}
class Manager extends Employee
{
int ta,hr;
float s1;
float getsalary()
{
[Link]();
s1=[Link]();
[Link]("Enter travelling allownces & house rent");
Scanner s=new Scanner([Link]);
ta=[Link]();
hr=[Link]();
[Link]("Salary after adding="+(s1+ta+hr));
return s1+ta+hr;
}
void display()
{
float a=getsalary();
}
}
class Slip25
{
public static void main(String a[])
{
Manager ob=new Manager();
[Link]();
}
}

3. Construct a Linked List containg name: CPP, Java, Python and PHP. Then extend your
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.
4. Create a hashtable containing employee name & salary. Display the details of the
hashtable. Also search for a specific Employee and display salary of that employee.

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 32


TY BBA(CA) SEM 5 Core java [Link]

import [Link].*;

class Hashtable1{

public static void main(String args[]){

Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

[Link](100,"Amit");

[Link](102,"Ravi");

[Link](101,"Vijay");

[Link](103,"Rahul");

for([Link] m:[Link]()){

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

5. Write a package game which will have 2 classes Indoor & Outdoor. Use a function
display() to generate the list of player for the specific game. Use default & parameterized
Constructor.
import games.*;
import [Link].*;
class Slip20
{
public static void main(String args[])
{
int n,m,i;
Scanner s=new Scanner([Link]);
[Link]("How many indoor player you want ");
n=[Link]();
[Link]("How many outdoor player you want ");
m=[Link]();
Indoor in[]=new Indoor[n];

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 33


TY BBA(CA) SEM 5 Core java [Link]

Outdoor out[]=new Outdoor[m];


for(i=0;i {
[Link]("Enter indoor player name ");
String name=[Link]();
in[i]=new Indoor(name);
}
for(i=0;i {
[Link]("Enter outdoor player name ");
String name=[Link]();
out[i]=new Outdoor(name);
}
[Link]("Indoor Player are ");
for(i=0;i {
in[i].display();
}
[Link]("Outdoor Player are ");
for(i=0;i {
out[i].display();
}
}
protected void finalize()
{

[Link]("Finalize is called");
}
}

Assignment No 4
Set A:
1. Write a java program to count the number of integers from a given list.(Use command
line arguments).
import [Link];
public class CountingDigitsInInteger {
public static void main(String args[]){
Scanner sc = new Scanner([Link]);
int count = 0;
[Link]("Enter a number ::");
int num = [Link]();
while(num!=0){

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 34


TY BBA(CA) SEM 5 Core java [Link]

num = num/10;
count++;
}
[Link]("Number of digits in the entered integer are :: "+count);
}
}

2. Write a java program to check whether given candidate is eligible for voting or not.
Handle user defined as well as system defined Exception.
import [Link];
public class Vote_Eligible
{
public static void main(String[] args)
{
Scanner input = new Scanner([Link]);
int age = 0;
[Link]("Enter the Age : ");
age = [Link]();
int res = age >= 18?1:0;
switch (res)
{
case 0:
[Link]("You are Not Eligible for Voting...");
break;

case 1:
[Link]("You are Eligible for Voting...");
break;
}
}
}

3. Write a java program to calculate the size of a file.

class MyClass {
//Storing path file in a String
static final String PATH = "C:\\Users\\Dhanush\\[Link]";
public static void main(String args[])
{

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 35


TY BBA(CA) SEM 5 Core java [Link]

//specifying the file path to the File constructor


File file = new File(PATH);

//checking if the file exists or the file specified is of the type file
if (([Link]()) && ([Link]()))
{

//displays the file size in KB


[Link]("The File Size in KiloBytes : "+convertToKilobytes(file)+"kb");

//displays the file size in MB


[Link]("The File Size in MegaBytes : "+convertToMegabytes(file)+"mb");
}
else {
[Link]("OOPs! The Specified File not found.");
}
}
// Function which calculates the file size in megabytes
private static long convertToMegabytes(File file)
{
return [Link]() / (1024 * 1024);
}

// Function which calculates the file size in kilobytes


private static long convertToKilobytes(File file)
{
return [Link]() / 1024;
}

//Function which calculates the file size in bytes


private static long convertToBytes(File file)
{
return [Link]();

4. Write a java program to accept a number from a user, if it is zero then throw user
defined

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 36


TY BBA(CA) SEM 5 Core java [Link]

Exception “Number is Zero”. If it is non-numeric then generate an error “Number is


Invalid” otherwise check whether it is palindrome or not.
import [Link].*;
import [Link];
class abc extends Exception{}

class slip{

public static void main( String args[]){

int r,sum=0,temp;

int n;
Scanner dr=new Scanner([Link]);

try {

[Link]("Enter Number : ");

n = [Link]();

if(n==0){

throw new abc();

}else{

temp=n;

while(n>0){

r=n%10;

sum=(sum*10)+r;

n=n/10;

if(temp==sum){

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 37


TY BBA(CA) SEM 5 Core java [Link]

[Link]("It is Palindrome Number ");

}else{

[Link]("Not Palindrome");

} catch (abc nz) {

[Link]("Number is 0");

catch (NumberFormatException e){

[Link]("Invalid Number ");

catch (Exception e){}

5. Write a java program to accept a number from user, If it is greater than 100 then throw
user defined exception “Number is out of Range” otherwise do the addition of digits of
that number. (Use static keyword)
import [Link].*;
import [Link];
class abc extends Exception{}

class slip{

public static void main( String args[]){

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 38


TY BBA(CA) SEM 5 Core java [Link]

int r,sum=0,temp;

int n;
Scanner dr=new Scanner([Link]);

try {

[Link]("Enter Number : ");

n = [Link]();

if(n==0){

throw new abc();

}else{

temp=n;

while(n>0){

r=n%10;

sum=(sum*10)+r;

n=n/10;

if(temp==sum){

[Link]("It is Palindrome Number ");

}else{

[Link]("Not Palindrome");

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 39


TY BBA(CA) SEM 5 Core java [Link]

} catch (abc nz) {

[Link]("Number is 0");

catch (NumberFormatException e){

[Link]("Invalid Number ");

catch (Exception e){}

Set B:
1. Write a java program to copy the data from one file into another file, while copying
change the case of characters in target file and replaces all digits by ‘*’ symbol.

import [Link].*;

Import [Link].*;

// create FileExample class to copy data of one file into another

publicclassFileExample {

// create coptData() method that copy data of file1 into file2

publicstaticvoidcopyData(File file1, File file2) throws Exception

// create instances of FileInputStream and FileOutputStream classes for file1 and file2

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 40


TY BBA(CA) SEM 5 Core java [Link]

FileInputStreaminputStream = newFileInputStream(file1);

FileOutputStreamoutputStream = newFileOutputStream(file2);

// use try-catch-finally block to read and write bytes data into file

try {

// declare variable for indexing

inti;

// use while loop with read() method of FileInputStream class to read bytes data from
file1

while ((i = [Link]()) != -1) {

// use write() method of FileOutputStream class to write the byte data into file2

[Link](i);

// catch block to handle exceptions

catch(Exception e) {

[Link]("Error Found: "+[Link]());

// use finally to close instance of the FileInputStream and FileOutputStream classes

finally {

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 41


TY BBA(CA) SEM 5 Core java [Link]

if (inputStream != null) {

// use close() method of FileInputStream class to close the stream

[Link]();

// use close() method of FileOutputStream class to close the stream

if (outputStream != null) {

[Link]();

[Link]("File Copied");

// main() method start

Public static void main(String[] args) throws Exception

// create scanner class object to take file name from user

Scanner sc = new Scanner([Link]);

// get the file from which the data would be copied.

[Link]("Enter the name of the file from where the data would be copied :");

String file1 = [Link]();

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 42


TY BBA(CA) SEM 5 Core java [Link]

// create instance of the File class for the source file

File a = newFile("C:\\Users\\pc\\OneDrive\\Desktop\\"+file1);

// get the file in which the data would be written.

[Link]("Enter the name of the file from where the data would be written :");

String file2 = [Link]();

// create instance of the File class for the destination file

File b = newFile("C:\\Users\\pc\\OneDrive\\Desktop\\"+file2);

[Link]();

// method called to copy the data from file a to file b

copyData(a, b);

2. Write a java program to accept string from a user. Write ASCII values of the characters
from a string into the file.
public class xyz {

// Main driver method


public static void main(String[] args)
{
// Character whose ASCII is to be computed
char ch = '}';

// Creating a new variable of type int

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 43


TY BBA(CA) SEM 5 Core java [Link]

// and assigning the character value.


int ascii = ch;

/* Java stores the ascii value there itself*/

// Printing the ASCII value of above character


[Link]("The ASCII value of " + ch
+ " is: " + ascii);
}
}

3. Write a java program to accept a number from a user, if it less than 5 then throw user
defined Exception “Number is small”, if it is greater than 10 then throw user defined
exception “Number is Greater”, otherwise calculate its factorial.
import [Link].*;
class NumberZero extends Exception{
public NumberZero(){
super("Zero Number Exception");
}
}
class ZeroNumberException{
static void addDigit(int num){
if(num<10)
[Link]("Addition of first and last digit = "+num);
else{
int lastDigit=0,firstDigit=0;
lastDigit=num%10;
while(num >= 10){
num = num / 10;
}
firstDigit = num;

[Link]("Addition of first and last digit = "+ (firstDigit + lastDigit));


}

}
public static void main(String a[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter Number=");
int number=[Link]([Link]());
try{

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 44


TY BBA(CA) SEM 5 Core java [Link]

if(number==0)
throw new NumberZero();

else
addDigit(number);
}
catch(NumberZero e){
[Link]("Number is 0");
[Link]([Link]());
}
}
}

4. Write a java program to display contents of a file in reverse order.


import [Link];
import [Link];
import [Link];

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// The file reading process may sometimes give


// IOException

// Try block to check for exceptions


try {

// Creating a FileReader object and


// file to be read is passed as in parameters
// from the local directory of computer
FileReader fr = new FileReader("[Link]");

// FileReader will open that file from that


// directory, if there is no file found it will

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 45


TY BBA(CA) SEM 5 Core java [Link]

// through an IOException

// Creating a FileWriter object


FileWriter fw = new FileWriter("[Link]");

// It will create a new file with name


// "[Link]", if it is already available,
// then it will open that instead

// Declaring a blank string in which


// whole content of file is to be stored
String str = "";

int i;

// read() method will read the file character by


// character and print it until it end the end
// of the file

// Condition check
// Reading the file using read() method which
// returns -1 at EOF while reading
while ((i = [Link]()) != -1) {

// Storing every character in the string


str += (char)i;
}}

// Print and display the string that


// contains file data
[Link](str);

// Writing above string data to


// FileWriter object
[Link](str);

// Closing the file using close() method


// of Reader class which closes the stream &
// release resources that were busy in stream

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 46


TY BBA(CA) SEM 5 Core java [Link]

[Link]();
[Link]();

// Display message
[Link](
"File reading and writing both done");
}

// Catch block to handle the exception


catch (IOException e) {

// If there is no file in specified path or


// any other error occurred during runtime
// then it will print IOException

// Display message
[Link](
"There are some IOException");
}
}
}

5. Write a java program to display each word from a file in reverse order.

import [Link];
public class Exp {

// Method to reverse words of a String


static String reverseWords(String str)
{

// Specifying the pattern to be searched


Pattern pattern = [Link]("\\s");

// splitting String str with a pattern


// (i.e )splitting the string whenever their
// is whitespace and store in temp array.

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 47


TY BBA(CA) SEM 5 Core java [Link]

String[] temp = [Link](str);


String result = "";

// Iterate over the temp array and store


// the string in reverse order.
for (int i = 0; i < [Link]; i++) {
if (i == [Link] - 1)
result = temp[i] + result;
else
result = " " + temp[i] + result;
}
return result;
}

// Driver methods to test above method


public static void main(String[] args)
{
String s1 = "Welcome to geeksforgeeks";
[Link](reverseWords(s1));

String s2 = "I love Java Programming";


[Link](reverseWords(s2));
}
}
Assignment 5
Set A:
1. Write a program that asks the user's name, and then greets the user by name. Before
outputting the user's name, convert it to upper case letters. For example, if the user's
name is Raj, then the program should respond "Hello, RAJ, nice to meet you!".
import [Link];

class Slip13B {

public static void main(String args[]){

String str;

Scanner dr=new Scanner([Link]);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 48


TY BBA(CA) SEM 5 Core java [Link]

try {

[Link]("Enter Username : ");

str = [Link]();

[Link]("\"Hello, " + [Link]() + ", nice to meet you!\"");

} catch (Exception e) {}

2. Write a program that reads one line of input text and breaks it up into words. The
words should be output one per line. A word is defined to be a sequence of letters.
Any characters in the input that are not letters should be discarded. For example, if
the user inputs the line He said, "That's not a good idea." then the output of the
program should be
He
said
thats
not

a
good
Idea
import [Link];

/**
* This program will read one line of input typed by the user.
* It will print the words from the input, one word to a line.
* A word is defined to be a sequence of letters. All non-letters
* in the input are discarded.
*/

public class ListWordsInString {

public static void main(String[] args) {

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 49


TY BBA(CA) SEM 5 Core java [Link]

String line; // A line of text, typed in by the user.


int i; // Position in line, from 0 to [Link]() - 1.
char ch; // One of the characters in line.
boolean didCR; // Set to true if the previous output was a carriage return.

[Link]("Enter a line of text.");


[Link]("? ");
line = [Link]();

[Link]();
didCR = true;

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


ch = [Link](i);
if ( [Link](ch) ) {
[Link](ch);
didCR = false;
}
else {
if ( didCR == false ) {
[Link]();
didCR = true;
}
}
}

[Link](); // Make sure there's at least one carriage return at the end.

} // end main()

} // end class ListWordsInString

3. Write a program that will read a sequence of positive real numbers entered by the
user and will print the same numbers in sorted order from smallest to largest. The
user will input a zero to mark the end of the input. Assume that at most 100 positive
numbers will be entered.
import [Link];

/**
* This program reads up to 100 positive integers from the user and

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 50


TY BBA(CA) SEM 5 Core java [Link]

* prints them in sorted order. Input ends when the user enters a
* non-positive integer. The numbers are read and stored in an array.
* That array is sorted using selection sort, and then the array is
* printed.
*/

public class SortInputNumbers {

public static void main(String[] args) {

double[] numbers; // An array for storing the input values.


int numCt; // The number of numbers saved in the array.
double num; // One of the numbers input by the user.

numbers = new double[100]; // Space for 100 numbers.


numCt = 0; // No numbers have been saved yet.

[Link]("Enter up to 100 positive numbers; Enter 0 to end");

while (true) { // Get the numbers and put them in the array.
[Link]("? ");
num = [Link]();
if (num <= 0)
break;
numbers[numCt] = num;
numCt++;
}

selectionSort(numbers, numCt); // Sort the numbers.

[Link]("\nYour numbers in sorted order are:\n");

for (int i = 0; i < numCt; i++) {


[Link]( numbers[i] );
}

} // end main();

/**
* Sort the numbers in A[0], A[1], ..., A[count-1] into

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 51


TY BBA(CA) SEM 5 Core java [Link]

* increasing order using Selection Sort.


*/
static void selectionSort(double[] A, int count) {
for ( int lastPlace = count - 1; lastPlace > 0; lastPlace-- ) {
int maxLoc = 0;
for (int j = 1; j <= lastPlace; j++) {
if (A[j] > A[maxLoc]) {
maxLoc = j;
}
}
double temp = A[maxLoc];
A[maxLoc] = A[lastPlace];
A[lastPlace] = temp;
}
} // end selectionSort

} // end class SortInputNumbers

4. Create an Applet that displays the x and y position of the cursor movement using
Mouse and Keyboard. (Use appropriate listener).
import [Link].*;

import [Link];

import [Link];

public class Paint extends Frame implements MouseMotionListener{

Label l;

Color c=[Link];

Paint(){

l=new Label();

[Link](20,40,100,20);

add(l);

addMouseMotionListener(this);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 52


TY BBA(CA) SEM 5 Core java [Link]

setSize(400,400);

setLayout(null);

setVisible(true);

public void mouseDragged(MouseEvent e) {

[Link]("X="+[Link]()+", Y="+[Link]());

Graphics g=getGraphics();

[Link]([Link]);

[Link]([Link](),[Link](),20,20);

public void mouseMoved(MouseEvent e) {

[Link]("X="+[Link]()+", Y="+[Link]());

public static void main(String[] args) {

new Paint();

5. Create the following GUI screen using appropriate layout managers.


//Usually you will require both swing and awt packages
// even if you are working with just swings.
import [Link].*;
import [Link].*;
class gui {
public static void main(String args[]) {

//Creating the Frame


JFrame frame = new JFrame("Chat Frame");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](400, 400);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 53


TY BBA(CA) SEM 5 Core java [Link]

//Creating the MenuBar and adding components


JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
[Link](m1);
[Link](m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
[Link](m11);
[Link](m22);

//Creating the panel at bottom and adding components


JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
[Link](label); // Components Added using Flow Layout
[Link](tf);
[Link](send);
[Link](reset);

// Text Area at the Center


JTextArea ta = new JTextArea();

//Adding Components to the frame.


[Link]().add([Link], panel);
[Link]().add([Link], mb);
[Link]().add([Link], ta);
[Link](true);
}
}

Set B:
1. Write a java program to implement a simple arithmetic calculator. Perform appropriate
Validations.
import [Link].*;
import [Link].*;
import [Link].*;

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 54


TY BBA(CA) SEM 5 Core java [Link]

public class Calculator extends Applet implements ActionListener {


TextField inp;

public void init() {


setBackground([Link]);
setLayout(null);

inp = new TextField();


[Link](150, 100, 270, 50);
[Link](inp);

Button[] button = new Button[10];


for (int i = 0; i < 10; i++) {
button[i] = new Button([Link](9 - i));
button[i].setBounds(150 + ((i % 3) * 50), 150 + ((i / 3) * 50), 50, 50);
[Link](button[i]);
button[i].addActionListener(this);
}

Button dec = new Button(".");


[Link](200, 300, 50, 50);
[Link](dec);
[Link](this);

Button clr = new Button("C");


[Link](250, 300, 50, 50);
[Link](clr);
[Link](this);

String[] operators = { "/", "*", "-", "+", "=" };


for (int i = 0; i < 4; i++) {
Button operatorButton = new Button(operators[i]);
[Link](300, 150 + (i * 50), 50, 50);
[Link](operatorButton);
[Link](this);
}
}

public void actionPerformed(ActionEvent e) {

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 55


TY BBA(CA) SEM 5 Core java [Link]

// Handle button clicks and perform calculations here


// You can use [Link]() to get the input from the text field
// Display the result back in the text field
}
}

2. Write a java program to implement following. Program should handle appropriate


events.
// Java program to handle MouseListener events
import [Link].*;
import [Link].*;
import [Link].*;
class Mouse extends Frame implements MouseListener {

// Jlabels to display the actions of events of mouseListener


// static JLabel label1, label2, label3;

// default constructor
Mouse()
{
}

// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");

// set the size of the frame


[Link](600, 100);

// close the frame when close button is pressed


[Link](JFrame.EXIT_ON_CLOSE);

// create a new panel


JPanel p = new JPanel();

// set the layout of the panel

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 56


TY BBA(CA) SEM 5 Core java [Link]

[Link](new FlowLayout());

// initialize the labels


label1 = new JLabel("no event ");

label2 = new JLabel("no event ");

label3 = new JLabel("no event ");

// create an object of mouse class


Mouse m = new Mouse();

// add mouseListener to the frame


[Link](m);

// add labels to the panel


[Link](label1);
[Link](label2);
[Link](label3);

// add panel to the frame


[Link](p);

[Link]();
}

// getX() and getY() functions return the


// x and y coordinates of the current
// mouse position
// getClickCount() returns the number of
// quick consecutive clicks made by the user

// this function is invoked when the mouse is pressed


public void mousePressed(MouseEvent e)
{

// show the point where the user pressed the mouse


[Link]("mouse pressed at point:"
+ [Link]() + " " + [Link]());

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 57


TY BBA(CA) SEM 5 Core java [Link]

// this function is invoked when the mouse is released


public void mouseReleased(MouseEvent e)
{

// show the point where the user released the mouse click
[Link]("mouse released at point:"
+ [Link]() + " " + [Link]());
}

// this function is invoked when the mouse exits the component


public void mouseExited(MouseEvent e)
{

// show the point through which the mouse exited the frame
[Link]("mouse exited through point:"
+ [Link]() + " " + [Link]());
}

// this function is invoked when the mouse enters the component


public void mouseEntered(MouseEvent e)
{

// show the point through which the mouse entered the frame
[Link]("mouse entered at point:"
+ [Link]() + " " + [Link]());
}

// this function is invoked when the mouse is pressed or released


public void mouseClicked(MouseEvent e)
{

// getClickCount gives the number of quick,


// consecutive clicks made by the user
// show the point where the mouse is i.e
// the x and y coordinates
[Link]("mouse clicked at point:"
+ [Link]() + " "

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 58


TY BBA(CA) SEM 5 Core java [Link]

+ [Link]() + "mouse clicked :" + [Link]());


}
}

3. Write an applet application to draw Temple.


import [Link];

import [Link];

import [Link];

public class Slip26B extends Applet{

public void init() {

setBackground([Link]);

public void paint(Graphics g){

[Link]([Link]);

[Link](100, 150, 90, 120);

[Link](130, 230, 20, 40);

[Link](150, 100, 100, 150);

[Link](150, 100, 190, 150);

[Link](150, 50, 150, 100);

[Link]([Link]);

[Link](150, 50, 20, 20);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 59


TY BBA(CA) SEM 5 Core java [Link]

/*

<applet code="[Link]" width="300" height="300">

</applet>

*/

4. Write an applet application to display Table lamp. The color of lamp should get
change in random color.

import [Link].*;

import [Link].*;

public class tablelamp extends Applet{

public float R,G,B;

Graphics gl;

public void init(){

repaint();

public void paint(Graphics g){

R = (float)[Link]();

G = (float)[Link]();

B = (float)[Link]();

Color cl = new Color(R,G,B);

[Link](0,250,290,290);

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 60


TY BBA(CA) SEM 5 Core java [Link]

[Link](125,250,125,160);

[Link](175,250,175,160);

[Link](85,157,130,50,-65,312);

[Link](85,87,130,50,62,58);

[Link](85,177,119,89);

[Link](215,177,181,89);

[Link](cl);

[Link](78,120,40,40,63,-174);

[Link](120,96,40,40);

[Link](173,100,40,40,110,180);

/*

<applet code="[Link]" width="300" height="300">

</applet>

*/

5. Write a java program to design email registration form.( Use maximum Swing
component in form).
import [Link].*;
import [Link].*;
import [Link].*;

public class EmailRegistrationForm extends JFrame implements ActionListener {


private JLabel nameLabel, emailLabel;
private JTextField nameField, emailField;
private JButton submitButton;

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 61


TY BBA(CA) SEM 5 Core java [Link]

public EmailRegistrationForm() {
nameLabel = new JLabel("Name:");
emailLabel = new JLabel("Email:");

nameField = new JTextField(20);


emailField = new JTextField(20);

submitButton = new JButton("Submit");


[Link](this);

// Set layout
setLayout(new FlowLayout());

// Add components to the frame


add(nameLabel);
add(nameField);
add(emailLabel);
add(emailField);
add(submitButton);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Email Registration Form");
setSize(300, 150);
setLocationRelativeTo(null); // Center the window
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String name = [Link]();
String email = [Link]();
[Link](this, "Registration successful!\nName: " + name +
"\nEmail: " + email);
}

public static void main(String[] args) {


new EmailRegistrationForm();
}
}

Haribhai [Link] College

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 62


TY BBA(CA) SEM 5 Core java [Link]

BBACA Dept 1

1
Java Solutions

Haribhai [Link] College of Arts, Science and Commerce, BBA(CA) Department 63

You might also like