0% found this document useful (0 votes)
34 views13 pages

Smallpdf - 2021 11 25 Edited Edited Edited

Java lab manual

Uploaded by

mohdtabcs
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)
34 views13 pages

Smallpdf - 2021 11 25 Edited Edited Edited

Java lab manual

Uploaded by

mohdtabcs
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
You are on page 1/ 13

RADARAMAN INSTITUTE OF

TECHNOLOGY AND SCIENCE

SESSION – 2021-22

SUBJECT :- COMPUTER WORKSHOP


SUBJECT CODE :- 306

SUBMITTED TO SUBMITTED BY
submitted by:Avinash Kumar
Bhavna B.Tech 2nd Year 3rd Sem(CS)
YOGENDRA BHAMMARKAR
B.TECH 2nd YEAR 3rd Sem(CS)
Enrollment No:0132CS201026
RITS BHOPAL Enrollment No.: 0132CS20116
0132CS201026

Lab Experiment of Java programming

S.No JAVA PROGRAMS


1. Write a sample program that print Hello world on the screen ?
2. Write a program that Accept two numbers from the user and print Sum of them?
3. Write a program to calculate addition of two number using prototyping of methods.
4. Find largest and smallest no.in Array ?
5. write a program that converts the original String to lowercase and uppercase.
6. Write a program demonstrate function overloading to calculate average of 3 or 4 or 5
numbers passed as parameters. The data type of numbers is double.
7. Program to demonstrating overloaded constructor for calculating box volume.
8. Program to show the detail of students using concept of inheritance.
9. Write a program to demonstrate multithreading using Java.
10. Program to demonstrate implementation of an Drawable interface which contains a
method declaration draw. And Its implementation is provided by Rectangle and Circle
classes.
11. Program to demonstrate exception handling in case of division by zero error.
12. Write a program that draw Circle on Applet

Page - 1
0132CS201026

1-> Simple program to print Helloworld on the Screen ?

Program: Assuming that Java is properly installed on your system there are three steps to
creating a Java program.
1. Open notepad and writing the code

class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Note: 1.Save Same as the Class name.java
2. Allprogram/Run/ type cmd

2. Compiling the code

C:> javac HelloWorld.java

3.running the code

C:> java HelloWorld

Output: Hello World

. I/O standard:
To take quick input from keyboard.we used scanner class. This class comes from
java.util package.
To call Scanner in your program:

import java.util.Scanner;

To Associated Scanner to Keyboard:

Scanner in=new Scanner(System.in);

For int type: a=in.nextInt();

For float type b=in.nextFloat();

Page - 2
0132CS201026

2-> Write a program that Accept two number from the user and print Sum of them ?

program:
import java.util.Scanner;
public class Addition{
// main method begins execution of Java application
public static void main( String args[] ){
Scanner input = new Scanner( System.in );
int number1;
int number2;
int sum;
System.out.print( "Enter first integer: " );
number1 = input.nextInt(); // read first number from user
System.out.print( "Enter second integer: " );
number2 = input.nextInt(); // read second number from user
sum = number1 + number2;
System.out.println( "Sum is %d\n", sum );
}
}

3-> Write a program to calculate addition of two number using prototyping of methods.

program:
class Add{
int c;
void addition(int x,int y){
c=x+y;
}
public static void main(String[] arg){
int a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter first number");
a=sc.nextInt();
System.out.println("Enter second number");
b=sc.nextInt();
Add r=new Add();
r.addition(a,b);
System.out.println("Addition of two numbers is : "+r.c);
}
}
output:
Enter first number
5
Enter second number
1
Addition of two numbers is : 6

Page - 3
0132CS201026

4-> Find largest and smallest no.in Array ?

Program:

public class FindLargestSmallestNumber{


public static void main(String[] args){
//array of 10 numbers
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largest = numbers[0];
for(int i=1; i< numbers.length; i++){
if(numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}
System.out.println("Largest Number is : " + largetst);
System.out.println("Smallest Number is : " + smallest);
}
}
output:
Largest Number is : 98
Smallest Number is : 23

5-> write a program that converts the original String to lowercase and uppercase.

Program:
class ChangeCase{
public static void main(String args[]){
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}

output :
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.

Page - 4
0132CS201026

6-> Write a program demonstrate function overloading to calculate average of 3 or 4 or 5


numbers passed as parameters. The data type of numbers is double.

program:

class FindAverages{
public static void main(String s[]){
Average av = new Average();
System.out.println("Average of 7.2, 4.7 and 3.1 is " + av.average(7.2, 4.7, 3.1));
System.out.println("Average of 2.5, 40.4, 3.3 and 2.0 is " + av.averag(2.5, 40.4, 3.3, 2.0));
System.out.println("Average of 5, 10, 15, 20 and 25 is " + av.average(5, 10, 15, 20, 25));
}
}
class Average{
double average(double a, double b, double c){
return (a+b+c)/3;
}
double average(double a, double b, double c, double d){
return (a+b+c+d)/4;
}
double average(double a, double b, double c, double d, double e){
return (a+b+c+d+e)/5;
}
}

output: Average of 7.2, 4.7 and 3.1 is 5.0


Average of 2.5, 40.4, 3.3 and 2.0 is 12.05
Average of 5, 10, 15, 20 and 25 is 15.0

7-> Program to demonstrating overloaded constructor for calculating box volume.

program:
class Box{
int l,b,h;
Box(int x) // Constructor for Cube
{
l=x;
b=x;
h=x;
}
Box(int x,int y,int z) //Constructor for Rectangle
{
l=x;
b=y;
h=z;
}
void volume()

Page - 5
0132CS201026

{
System.out.println("Volume of the box is "+(l*b*h));
}
public static void main(String args[])
{
Box cube= new Box(10); //Calling cube constructor
Box b=new Box(10,4,7); //Calling box constructor
cube.volume();
b.volume();
}
}

8-> Program to show the details of students using the concept of inheritance.

program:

/*This program is used for multilevel inheritance example.*/


class Student {
String name = "jai";
}

class CollegeStudent extends Student {


String className = "Engineering";
}

class EngineeringStudent extends CollegeStudent{


String semester = "3rd sem.";

/**
* This method is used to show details of a student.
*/
public void showDetail(){
System.out.println("Student name = " + name);
System.out.println("Student class name = " + className);
System.out.println("Student semester = " + semester);
}
}

public class StudentTest {


public static void main(String args[]){
//creating subclass object
EngineeringStudent obj = new McaStudent();
//method call
obj.showDetail();
}
}

Page - 6
0132CS201026

output: Student name = jai


Student class name = Engineering
Student semester = 3rd sem.

9-> Write a program to demonstrate multithreading using Java.


What are Threads in Java?
A thread is actually a lightweight process. Unlike many other computer languages, Java
provides built-in support for multithreaded programming. A multithreaded program
contains two or more parts that can run concurrently. Each part of such a program is
called thread and each thread defines a separate path of execution. Thus, multithreading
is a specialized form of multitasking.

Threads exist in several states. Following are those states:


● New – When we create an instance of Thread class, a thread is in a new state.
● Runnable – The Java thread is in running state.
● Suspended – A running thread can be suspended, which temporarily suspends its
activity. A suspended thread can then be resumed, allowing it to pick up where it
left off.
● Blocked – A java thread can be blocked when waiting for a resource.
● Terminated – A thread can be terminated, which halts its execution immediately
at any given time. Once a thread is terminated, it cannot be resumed.

How to Create a Java Thread?


Java lets you create thread in following two ways:-

● By implementing the Runnable interface.


● By extending the Thread

Method 1: Thread creation by extending Thread class

program:
class MultithreadingDemo extends Thread{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output: My thread is in running state.

Page - 7
0132CS201026

Method 2: Thread creation by implementing Runnable Interface

program:
class MultithreadingDemo implements Runnable{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Output: My thread is in running state.

10-> Program to demonstrate implementation of an Drawable interface which contains a method


declaration draw. And Its implementation is provided by Rectangle and Circle classes.

Interface: The interface in Java is a mechanism to achieve abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Page - 8
0132CS201026

program:
//Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
//In real scenario, object is provided by method e.g. getDrawable()
Drawable d=new Circle();
d.draw();
}
}
Output: drawing circle

11-> Program to demonstrate exception handling in case of division by zero error.

Exception:
● Exception is an abnormal condition.
● An exception is an unwanted or unexpected event, which occurs during the execution of a
program i.e at run time, that disrupts the normal flow of the program’s instructions.

Exception Handling
If an exception occurs, which has not been handled by programmer then program
execution gets terminated and a system generated error message is shown to the user.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by
two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below:

Page - 9
0132CS201026

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error is considered
as the unchecked exception. According to Oracle, there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Page - 10
0132CS201026

Difference between Checked and Unchecked Exceptions

1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.

3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

program:

// Java Program to Handle Divide By Zero Exception


import java.io.*;
class GFG {
public static void main(String[] args){
int a = 5;
int b = 0;
try {
System.out.println(a / b); // throw Exception
}
catch (ArithmeticException e) {
// Exception handler
System.out.println(“Divided by zero operation cannot possible");
}
}
}
Output: Divided by zero operation cannot possible

Page - 11
0132CS201026

12-> Write a program that draw Circle on Applet.

program:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Circles extends Applet implements ActionListener{
TextField value;
Button draw;
public void init(){
resize(400, 400);
draw = new Button("Draw");
value = new TextField();
draw.addActionListener(this);
add(value);
add(draw);
}
public void actionPerformed(ActionEvent e){
Graphics g = getGraphics();
int diameter = Integer.parseInt(value.getText()) * 2;
g.drawOval(0, 0, diameter, diameter);
}
}

Output:

Page - 12

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy