100% found this document useful (5 votes)
9K views27 pages

Java Programming Lab Exercises

The document provides examples of Java programming lab exercises covering topics such as: 1. Printing a simple message 2. Displaying the month from an array of months 3. Handling a division by zero exception 4. Creating a custom exception 5. Overloading methods to add integers and float numbers 6. Using inheritance with mathematical operator classes 7. Using static variables in classes 8. Catching a NegativeArraySize exception 9. Using try, catch, and finally blocks 10. Creating and using packages and classes The document contains 10 programming challenges with sample code solutions to demonstrate Java programming concepts for students.

Uploaded by

shwetha
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
100% found this document useful (5 votes)
9K views27 pages

Java Programming Lab Exercises

The document provides examples of Java programming lab exercises covering topics such as: 1. Printing a simple message 2. Displaying the month from an array of months 3. Handling a division by zero exception 4. Creating a custom exception 5. Overloading methods to add integers and float numbers 6. Using inheritance with mathematical operator classes 7. Using static variables in classes 8. Catching a NegativeArraySize exception 9. Using try, catch, and finally blocks 10. Creating and using packages and classes The document contains 10 programming challenges with sample code solutions to demonstrate Java programming concepts for students.

Uploaded by

shwetha
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
  • Java Basics Program
  • Exception Handling
  • Function Overloading
  • Mathematical Operations
  • Static Variables
  • Handling Arrays and Exceptions
  • Package Creation
  • Class and Objects
  • Employee Management
  • Student Information
  • GUI Programming
  • Applet and Grid
  • Event Handling
  • Personal Applet
  • Dynamic Shapes and Events
  • Menu Bar Program

Java Programming Lab Manual

1. Write a simple java application to print the message “Welcome to java”.

class Hello{
public static void main(String args[]){
[Link]("Welcome to Java");
}
}

Output:

2. Write a program to display the month of a year. Months of the year should be held in an
array.

import [Link];
public class CalDemo {
public static void main(String[] args) {
Calendar calendar = [Link]();
String[] month = new String[] {"January", "February", "March", "April", "May", "June",
"July", "August","September", "October", "November", "December" };
[Link]("Current Month = " + month[[Link]([Link])]);
}
}

Output:
3. Write a program to demonstrate a division by zero exception

class Excep{
public static void main (String args[]) {
int num1 = 15, num2 = 0, result = 0;
try{
result = num1/num2;
[Link]("The result is" +result);
}
catch (ArithmeticException e) {
[Link] ("Can't be divided by Zero " + e);
}
}
}

Output:

4. Write a program to create a user defined exception say Pay Out of Bounds
import [Link].*;
class PayOutOfBounds extends Exception
{
public void showError()
{
[Link]("Invalid Pay");
}
}
class ErrorTest
{
public static void main(String []args) throws Exception
{
InputStreamReader isr=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(isr);
int m=0;
try
{
[Link]("Enter Pay:");
m=[Link]([Link]());
if(m>10000)
throw new PayOutOfBounds();
[Link]("Your Pay:"+m);
}
catch(PayOutOfBounds e)
{
[Link]();
}
}
}
5. Write a java program to add two integers and two float numbers. When no arguments are
supplied, give a default value to calculate the sum. Use function overloading.
public class OverloadingTest1
{

void addition(int a, int b)


{
int sum=a+b;
[Link]("Sum of two numbers is "+sum);
}
void addition(double a ,double b)
{
double sum=a+b;
[Link]("Sum of two numbers is "+sum);
}
public static void main(String args[])
{
OverloadingTest1 ovl=new OverloadingTest1();
[Link](5,10);
[Link](1.5,8.5);
}
}
6. Write a program to perform mathematical operations. Create a class called AddSub with
methods to add and subtract. Create another class called MulDiv that extends from AddSub class
to use the member data of the super class. MulDiv should have methods to multiply and divide A
main function should access the methods and perform the mathematical operations.

class addsub
{
int num1,num2;
addsub(int n1, int n2)
{
num1 = n1;
num2 = n2;
}
int add()
{
return num1+num2;
}
int sub()
{
return num1-num2;
}
}
class multdiv extends addsub
{
public multdiv(int n1, int n2)
{
super(n1, n2);
}
int mul()
{
return num1*num2;
}
float div()
{
return num2/num1;
}
}
public class inheritancedemo
{
public static void main(String arg[])
{
addsub r1=new addsub(50,20);
int ad = [Link]();
int sb = [Link]();
[Link]("Addition =" +ad);
[Link]("Subtraction =" +sb);
multdiv r2 =new multdiv(4,20);
int ml = [Link]();
float dv =[Link]();
[Link]("Multiply =" +ml);
[Link]("Division =" +dv);
}
}

7. Write a program with class variable that is available for all instances of a class. Use static variable
declaration. Observe the changes that occur in the object’s member variable values.

class Staticvar
{
public static int a,b;
public void display()
{
[Link](" A value ="+a+" B valu ="+b);
}
}
class Demo
{
public static void main(String args[])

{
Staticvar sv=new Staticvar();
sv.a=10;
sv.b=20;
[Link]();
Staticvar sv1=new Staticvar();
[Link]();
}
}
8. Write a small program to catch Negative Array Size Exception. This exception is caused when
the array is initialized to negative values.

public class NegativeArraySizeExceptionExample {


public static void main(String[] args) {
try {
int[] array = new int[-5];
} catch (NegativeArraySizeException nase) {
[Link]();
}
[Link]("Continuing execution...");
}
}

9. Write a program to handle Null Pointer Exception and use the “finally” method to display a
message to the user.
class TestFinallyBlock {
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){
[Link](e);
}
finally {
[Link]("finally block is always executed");
}

[Link]("rest of code...");
}
}

10. Create a package‘ [Link]‘ in your current working directory a. Create a default
class student in the above package with the following attributes: Name, age, sex. b. Have methods
for storing as well as displaying

a. package [Link];
public class Studentinfo
{
int age;
char gender;
String name;
public Studentinfo(String a,int e,char f)
{
name=a;
age=e;
gender=f;
}
public void display()
{
[Link]("STUDENT PERSONAL DETAILS");
[Link]("Name of the student is: "+name);
[Link]("Age="+age);
[Link]("Student is "+gender);
}
}

b. import [Link].*;
class PackDemo
{
public static void main(String args[])
{
[Link] a
= new [Link]("Rita",18,'F');
[Link]();
}
}

11. In a college first year class are having the following attributesName of the class (BCA, BCom,
BSc), Name of the staff No of the students in the class, Array of students in the class 10. Define a
class called first year with above attributes and define a suitable constructor. Also write a method
called best Student () which process a first-year object and return the student with the highest
total mark. In the main method define a first-year object and find the best student of this class
import [Link].*;
class FirstYear{
String classname;
String classteacher;
int stdcount;
int stdmarks[]= new int[50];
String stdnames[] = new String[50];
Scanner sc = new Scanner([Link]);

public FirstYear() {
getinfo();
}

public void getinfo() {


[Link]("Please Enter the class Name:");
classname = [Link]();
[Link]("Please Enter the class Teacher Name:");
classteacher = [Link]();
[Link]("Please Enter the Total number of students of the class:");
stdcount = [Link]([Link]());

[Link]("Please Enter the Names of all the students of the class:");


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

[Link]("Please Enter the marks of all the students of the class:");


for(int i=0;i<stdcount;i++)
stdmarks[i]=[Link]();
}

public void bestStudent(){


int best=0, k=-1;
for(int i=0;i<stdcount;i++) {
if(stdmarks[i] > best) {
best = stdmarks[i];
k=i;
}
}
[Link]("The Best Student is "+stdnames[k]);
}
}
public class FirstyearStudent{
public static void main(String args[]){
FirstYear fy = new FirstYear();
[Link]();
}
}

12. Write a Java program to define a class called employee with the name and date of appointment.
Create ten employee objects as an array and sort them as per their date of appointment. ie, print
them as per their seniority.

import [Link];
class Employee {
String name;
Date appdate;
public Employee(String nm, Date apdt){
name=nm;
appdate=apdt;
}
public void display(){
[Link]("employee name:"+name+"\t appointment date:\t"+[Link]()+
"/"+ [Link]()+"/"+[Link]());
}}
public class EmpDate{
public static void main(String args[]){
Employee emp[]=new Employee[10];
emp[0]=new Employee("Neeraja k", new Date(1999,05,22));
emp[1]=new Employee("roja D",new Date(2009,04,25));
emp[2]=new Employee("rana k",new Date (2005,02,19));
emp[3]=new Employee("jothika", new Date(2009,01,01));
emp[4]=new Employee("srikanth",new Date(1999,01,01));
emp[5]=new Employee("rajesh",new Date(2020,05,19));
emp[6]=new Employee("asha",new Date(2000,01,25));
emp[7]=new Employee("ammu",new Date(2022,04,22));
emp[8]=new Employee("gourav",new Date(2002,9,9));
emp[9]=new Employee("kuldeep",new Date(2000,01,19));
[Link]("list of employees");
for(int i=0;i<[Link];i++)
emp[i].display();
for(int i=0;i<[Link];i++){
for(int j=i+1;j<[Link];j++){
if(emp[i].[Link](emp[j].appdate)){
Employee t= emp[i];
emp[i]=emp[j];
emp[j]=t;
}}}
[Link]("\nList of employees seniority wise");
for(int i=0;i<[Link];i++)
emp[i].display();
}}

[Link] a java program to create a student class with following attributes: Enrollment_id:
Name, Mark of sub1, Mark of sub2, mark of sub3, Total Marks. Total of the three marks
must be calculated only when the student passes in all three subjects. The pass mark for
each subject is 50. If a candidate fails in any one of the subjects his total mark must be
declaredas zero. Using this condition write a constructor for this class. Write separate
functions for accepting and displaying student details. In the main method create an
array of three student objects and display the details.

import [Link].*;

class Student {
Scanner sc = new Scanner([Link]);
String Enrollment_id;
String Name;
int sub1, sub2, sub3, total;

Student(){
readStudentInfo();
}

public void readStudentInfo(){


[Link]("Enter Student Details");
[Link]("EnrolmentNo: ");
Enrollment_id = [Link]();
[Link]("Name: ");
Name = [Link]();
[Link](" Enter marks of 3 subjects:");
sub1 = [Link]();
sub2 = [Link]();
sub3 = [Link]();
if (sub1 >= 50 && sub2 >= 50 && sub3 >= 50)
total = sub1 + sub2 + sub3;
else
total = 0;
}
public void displayInfo() {
[Link](Enrollment_id+"\t\t"+Name+"\t"+total);
}
}
public class StudentInfo {
public static void main(String[] args) {
Student s[] = new Student[3];
for (int i = 0; i < 3; i++) {s
s[i] = new Student();
}
[Link]("\t\tStudent Details");
[Link]("EnrollmentNo\tName\tTotal");
for(int i = 0;i < 3; i++) {
s[i].displayInfo();
}
}
}
14. Write a program which create and displays a message on the window
import [Link].*;
public class FrameDemo{
FrameDemo(){
Frame fm = new Frame();
[Link]("My First Frame");
Label lb = new Label("Welcome to GUI Programming");
[Link](lb);
[Link](300,300);
[Link](true);
}

public static void main(String args[]) {


FrameDemo ta = new FrameDemo();
}
}

15. Write a program to draw several shapes in the created window


import [Link].*;
public class Drawings extends Canvas {
public void paint(Graphics g) {
[Link](50,75,100,50);
[Link](200,75,50,50);
[Link](50,150,100,50,15,15);
[Link](175,150,100,50,15,15);
[Link](50,275,100,50);
[Link](175,275,100,50);
[Link](20,350,100,50,25,75);
[Link](175,350,100,50,25,75);
}

public static void main(String args[]) {


Drawings m=new Drawings();
Frame f=new Frame("Shapes");
[Link](m);
[Link](300,450);
[Link](true);
}
}

16. Write a program to create an applet and draw grid lines

import [Link].*;
import [Link].*;
public class Grid extends Applet {
public void paint(Graphics g) {
int row, column,x,y=20;
//for every row
for(row=1;row<5;row++) {
x=20;
//for ever column
for(column=1;column<5;column++) {
[Link](x,y,40,40);
x=x+20;
}
y=y+20;
}
}
}

/*
*<applet code="[Link]" height =500 width =500> </applet>
*/

17. Write a program which creates a frame with two buttons father and mother. When
we click the father button the name of the father, his age and designation must appear.
When we click mother similar details of mother also appear.

import [Link].*;
import [Link].*;

public class ButtonClickActionEvents {

public static void main(String args[]) {


Frame f=new Frame("Button Event");
Label l=new Label("DETAILS OF PARENTS");
[Link](new Font("Calibri",[Link], 16));
Label nl=new Label();
Label dl=new Label();
Label al=new Label();
[Link](20,20,500,50);
[Link](20,110,500,30);
[Link](20,150,500,30);
[Link](20,190,500,30);
Button mb=new Button("Mother");
[Link](20,70,50,30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("NAME:"+" "+"Aishwarya");
[Link]("DESIGNATION:"+" "+"Professor");
[Link]("AGE:"+" "+"42");
}
});
Button fb=new Button("Father");
[Link](80,70,50,30);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]("NAME:"+" "+"Ram");
[Link]("DESIGNATION:"+" "+"Manager");
[Link]("AGE:"+" "+"44");
}
});
//adding elements to the frame
[Link](mb);
[Link](fb);
[Link](l);
[Link](nl);
[Link](dl);
[Link](al);
// setting size,layout, and visibility
[Link](250,250);
[Link](null);
[Link](true);
}
}
18. Create a frame which displays your personal details with respect to a button click

import [Link].*;
import [Link].*;
public class PersonalDetails
{
public static void main(String args[])
{
Frame f = new Frame("Button Example");
Label l = new Label("Welcome TO MY PAGE");
[Link](new Font("Calibri",[Link],16));
Label fnl= new Label();
Label mnl = new Label();
Label lnl = new Label();
Label rl = new Label();
Label al = new Label();
[Link](250,30,600,50);
[Link](20,120,600,30);
[Link](20,160,600,30);
[Link](20,200,600,30);
[Link](20,240,600,30);
[Link](20,280,600,30);
Button mb = new Button ("Click Here FOR MY PERSONAL DETAILS");
[Link](new Font ("Calibri",[Link],14));
[Link](210,70,320,30);
[Link](new ActionListener(){
public void actionPerformed(ActionEvent e){
[Link]("FULL NAME: Aishwarya Rao");
[Link]("Father Name: Ranjit Mother Name: Vijetha Age:19");
[Link]("Roll No: BNU35628 College Name: Jain Degree College");
[Link]("Nationality : Indian Contact No: 9999988888");
[Link]("Address : 7th Cross,Indira Nagar,Bangalore");
}
});
//adding elements to the frame
[Link](mb);
[Link](l);
[Link](fnl);
[Link](mnl);
[Link](lnl);
[Link](rl);
[Link](al);
[Link](400, 400);
[Link](null);
[Link](true);
}
}

[Link] a simple applet which reveals the personal information of yours.

import [Link].*;
import [Link].*;
import [Link].*;
public class personalDetailsApplet extends Applet implements ActionListener{
String s1= " ", s2=" ", s3=" ", s4=" ", s5=" ";
public void init(){
setLayout(null);
setSize(400,300);
Button btn= new Button("CLICK HERE FOR MY PERSONAL DETAILS");
add (btn);
[Link](20,50,300,30);
[Link](this);
}
public void actionPerformed(ActionEvent e){
s1="Full Name: Aishwaraya Rao";
s2="Father Name: Ranjit Mother Name: Vijetha Age: 19";
s3= "Roll No: BNU35628 College Name: Jain Degree College";
s4= "Nationality: Indian Contact No : 9999988888";
s5=" Address: 75th Cross,Indira Nagar,Bangalore";
repaint();
}
public void paint(Graphics g){
[Link](new Font("TimesRoman", [Link],14));
[Link](s1,20,110);
[Link](s2,20,140);
[Link](s3,20,180);
[Link](s4,20,220);
[Link](s5,20,260);
}
}

/*
*<applet code="[Link]"height=400 width=400> </applet>
*/
20. Write a program to move different shapes according to the arrow key pressed.

import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="ArrowKeys"Width=400 height=400>
</applet>
*/
public class ArrowKeys extends Applet implements KeyListener{

int x1=100,y1=50,x2=250,y2=200;
public void init(){
addKeyListener(this);
}

public void keyPressed(KeyEvent ke){


showStatus("KeyDown");
int key=[Link]();
switch(key){
case KeyEvent.VK_LEFT : x1=x1-10; x2=x2-10;
break;
case KeyEvent.VK_RIGHT : x1=x1+10; x2=x2+10;
break;
case KeyEvent.VK_UP : y1=y1-10; y2=y2-10;
break;
case KeyEvent.VK_DOWN : y1= y1+10; y2= y2+10;
break;
}
repaint();
}
public void keyReleased(KeyEvent ke){
}
public void keyTyped(KeyEvent ke){
repaint();
}
public void paint(Graphics g){
[Link](x1,y1,x2,y2);
[Link](x1,y1+160,100,50);
[Link](x1,y1+235,100,50);
}
}
21. Write a java Program to create a window when we press M or m the window displays
Good Morning, A or a the window displays Good After Noon E or e the window
displays Good Evening, N or n the window displays Good Night

import [Link].*;
import [Link].*;
public class KeysDemo extends Frame implements KeyListener{
Label lbl;
KeysDemo() {
addKeyListener(this);
requestFocus();
lbl=new Label();
[Link](100,100,200,40);
[Link](new Font("Calibri",[Link],16));
add(lbl);
setSize(400,300);
setLayout(null);
setVisible(true);
}
public void keyPressed(KeyEvent e){
if([Link]() == 'M' || [Link]() == 'm')
[Link]("Good morning");
else if([Link]() == 'A'||[Link]() == 'a')
[Link]("Good afternoon");
else if ([Link]() == 'N' || [Link]() =='n')
[Link]("Good night");
else if([Link]() == 'E' || [Link]() == 'e')
[Link]("good evening");
}
public void keyReleased(KeyEvent e){
}
public void keyTyped (KeyEvent e){
}
public static void main(String[] args){
new KeysDemo();
}}

22. Demonstrate the various mouse handling events using suitable example

import [Link].*;
import [Link];
import [Link];
public class MouseListenerExample implements MouseListener{
//create two labels lbl1 and lbl2
Label lbl1, lbl2;
//create a frame frame
Frame fr;
//create a string s
String s;
MouseListenerExample(){
fr = new Frame("Java Mouse Listener Example");
lbl1 = new Label("Demo for the Mouse Event",[Link]);
lbl2 = new Label();
//set the layout of frame as Flowlayout
[Link](new FlowLayout());
//add label 1 to frame
[Link](lbl1);
//add label 2 to frame
[Link](lbl2);
//Register the created class MouseListenerExample with MouseListener
[Link](this);
//set the size of the where width is 250 and height iss 250
[Link](250,250);
//set the visibility of frame as true
[Link](true);
}
//implementation of mouseClicked method
public void mouseClicked(MouseEvent ev){
[Link]("Mouse Button Clicked");
[Link](true);
}
//implementation of mouseEntered method
public void mouseEntered(MouseEvent ev){
[Link]("Mouse has entered the area of window");
[Link](true);
}
//implementation of mouseExited method
public void mouseExited(MouseEvent ev){
[Link]("Mouse has left the area of window");
[Link](true);
}
//implementation of mousePressed method
public void mousePressed(MouseEvent ev){
[Link]("Mouse button is being pressed");
[Link](true);
}
//implementation of mouseReleased method
public void mouseReleased(MouseEvent ev){
[Link]("Mouse released");
[Link](true);
}
//main method
public static void main(String args[]){
new MouseListenerExample();
}
}
23. Write a program to create menu bar and pull-down menus.

import [Link].*;
public class MenuDemo{
MenuDemo(){
Frame fr = new Frame("Menu Demo");
MenuBar mb = new MenuBar();
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu("View");
[Link](fileMenu);
[Link](editMenu);
[Link](viewMenu);
MenuItem a1 = new MenuItem("New");
MenuItem a2 = new MenuItem("Open");
MenuItem a3 = new MenuItem("Save");
MenuItem b1 = new MenuItem("Copy");
MenuItem b2 = new MenuItem("Find");
MenuItem c1 = new MenuItem("Show");
[Link](a1);
[Link](a2);
[Link](a3);
[Link](b1);
[Link](b2);
[Link](c1);
[Link](mb);
[Link](300,300);
[Link](null);
[Link](true);
}
public static void main(String args[]){
new MenuDemo();
}
}

Common questions

Powered by AI

Polymorphism allows methods to operate differently based on the context, which in Java is often implemented via function overloading—multiple methods with the same name but different parameters. The 'OverloadingTest1' example shows two 'addition' methods handling integers and floats, illustrating compile-time polymorphism where the appropriate method is determined based on input. Advantages include cleaner code and ease of extension for new data types .

Inheritance improves code reusability and organization by allowing a new class to acquire the properties and methods of an existing class. This allows for hierarchical class development, reducing redundancy. In the example, 'MulDiv' extends 'AddSub', inheriting its methods and fields (num1 and num2). 'MulDiv' can directly use 'add' and 'sub' methods from 'AddSub' and extend functionality by adding 'mul' and 'div'. This reuses 'AddSub's functionality without duplication and organizes functionalities related to arithmetic operations into a cohesive structure .

Function overloading enhances code flexibility by allowing multiple methods with the same name but different parameter lists. This lets developers create multiple methods that perform similar tasks with different input types. In the provided example, the program includes overloaded 'addition' methods for both integer and double parameters. This allows the program to handle addition of both integer and float numbers seamlessly, making the code more versatile .

User-defined exceptions in Java allow for more specific error handling by letting developers create custom exceptions that reflect the program's domain logic, as seen in 'PayOutOfBounds'. This facilitates debugging and clear error reporting. However, pitfalls include increased code complexity and the need for thorough documentation. In the example, the 'PayOutOfBounds' exception is thrown when a pay amount exceeds a set threshold, illustrating the specificity and clarity custom exceptions provide .

A menu bar with pull-down menus can enhance user interface design by providing an organized and easily navigable structure for users to access various application functionalities. The 'MenuDemo' example utilizes a menu bar to compartmentalize file, edit, and view functionalities, making the interface intuitive and efficient for users, thereby enhancing the overall user experience and minimizing clutter .

The 'finally' block in Java exception handling ensures that necessary cleanup code, such as resource release, executes irrespective of whether an exception occurs. This guarantees resource management and program stability by preventing resource leaks and maintaining predictable program execution. In the 'TestFinallyBlock' example, the 'finally' block displays a message regardless of exceptions, ensuring code post-exception handling is executed .

Handling exceptions like 'division by zero' is crucial in Java programs to ensure the program does not terminate abruptly and the user gets a meaningful error message instead. In the given example, the Java program uses a try-catch block to catch an ArithmeticException when attempting to divide a number by zero. The catch block then prints a user-friendly message indicating the error: "Can't be divided by Zero" .

Encapsulation involves bundling data and methods that operate on the data within one unit, often using access restrictions to prevent unauthorized access. It is vital for maintaining control over the data in an object and minimizing reliance on outside code. In the 'Studentinfo' class, attributes like 'age', 'gender', and 'name' are private to ensure they are accessed or modified only through specific, well-defined methods, thus protecting integrity and alignment with business rules .

Static variables in Java belong to the class rather than any individual instance, meaning they maintain a single, shared state across all instances. In the 'Staticvar' class example, the static variables 'a' and 'b' are shared by all instances of the class. When 'a' and 'b' are modified through one instance, the changes are reflected across other instances, demonstrating shared state management .

Inheritance and hierarchical class structures allow for efficient code organization and reuse. The 'FirstYear' class captures shared attributes and methods for different student types or related roles, facilitating DRY (Don't Repeat Yourself) principles. It reduces duplication, eases maintenance, and supports scalable designs by encapsulating shared logic and allowing subclass extensions. This approach simplifies evolving code without altering existing classes .

Java Programming Lab Manual 
 
1. Write a simple java application to print the message “Welcome to java”. 
 
class Hello{
3. Write a program to demonstrate a division by zero exception 
 
class Excep{ 
   public static void main (String args
import java.io.*; 
class PayOutOfBounds extends Exception 
{ 
public void showError() 
{ 
System.out.println("Invalid Pay")
5. Write a java program to add two integers and two float numbers. When no arguments are 
supplied, give a default value to c
6. Write a program to perform mathematical operations. Create a class called AddSub with 
methods to add and subtract. Crea
multdiv r2 =new multdiv(4,20);  
int ml = r2.mul();  
float dv =r2.div();  
System.out.println("Multiply =" +ml);  
System.ou
8. Write a small program to catch Negative Array Size Exception. This exception is caused when 
the array is initialize
class TestFinallyBlock {     
  public static void main(String args[]){     
  try{      
   int data=25/5;     
   System.
name=a;  
  age=e; 
  gender=f; 
 } 
public void display() 
 { 
   System.out.println("STUDENT PERSONAL DETAILS"); 
   Syst
class FirstYear{ 
String classname; 
String classteacher; 
int stdcount; 
int stdmarks[]= new int[50]; 
String stdnames[] =

You might also like