[Go to site: main page, start]

0% found this document useful (0 votes)
8 views54 pages

Java Program

The document outlines various Java programming exercises conducted in a lab setting, including string extraction, sorting names, matrix addition, and calculating factorials using recursion. Each exercise includes an aim, algorithm, program code, and results indicating successful execution. The document emphasizes concepts such as classes, objects, exception handling, multithreading, and graphics.

Uploaded by

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

Java Program

The document outlines various Java programming exercises conducted in a lab setting, including string extraction, sorting names, matrix addition, and calculating factorials using recursion. Each exercise includes an aim, algorithm, program code, and results indicating successful execution. The document emphasizes concepts such as classes, objects, exception handling, multithreading, and graphics.

Uploaded by

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

Programming In JAVA Lab

EX NO:1 DATE : 07.09.23

EXTRACT A PORTION OF A CHARACTER STRING AND PRINT THE EXTRACTED STRING

AIM :

To create a java program extracting a portion of a character string and print the extracted
string.

ALGORITHM:

1. Start
2. Declare a string variable s1 to store a string received from keyboard.
3. Declare another string variable s2 to store a set of extracted characters from string
s1.
4. Declare 2 integer variables namely, a and b to store the Starting Position and Ending
Position for Extraction.
5. Save the Java code in the name of [Link]
6. Compile the Java code using javac
7. Run the Java code using java
8. Stop.

PROGRAM
1
Programming In JAVA Lab

import [Link];

import [Link].*;

import [Link].*;

public class A

public static void main(String args[])

Scanner in = new Scanner([Link]);

[Link]("Enter string : ");

String s = [Link]();

int len = [Link]();

[Link]("Enter start index : ");

int n = [Link]();

if(n < 0 || n >= len)

[Link]("Invalid index");

[Link](1);

[Link]("Enter no. of characters to extract : ");

int m = [Link]();

int substrlen = n + m;

if( m <= 0 || substrlen > len)

[Link]("Invalid no. of characters");

[Link](1);

2
Programming In JAVA Lab

String substr = [Link](n, substrlen);

[Link]("Substring = " + substr);

OUTPUT

3
Programming In JAVA Lab

RESULT:

Thus the JAVA program was executed successfully.

EX NO : 2 DATE:

4
Programming In JAVA Lab

SORTING THE GIVEN NAMES IN ALPHABETICAL ORDER

AIM :

To create a java program and to sort the given names in alphabetical order.

ALGORITHM :

1. Start the program.


2. Declare an Array.
3. Initialize the Array.
4. Use two for loops to sort the array in alphabetical order.
5. Use the first for loop to hold the elements.
6. Use the second for loop to compare with the remaining elements.
7. Use the compareTo() to compare.
8. Swap the array elements.
9. Print the updated array.
10. Stop the program.

PROGRAM :

import [Link];

import [Link];

public class AlexisPriceAssignment6

public static String input = " ";

public static String input2 = " ";

public static String input3 = "";

public static void Greet()

[Link]("Welcome to Alexis Price's Name Sorter.");

5
Programming In JAVA Lab

[Link]("All names must be unique.");

public static void Uinput()

Scanner keyboard = new Scanner([Link]);

[Link]("Enter the first name: ");

input = [Link]();

char >

[Link]("Enter the second name: ");

input2 = [Link]();

char two = [Link](0);

[Link]("Enter the third name: " );

input3 = [Link]();

char three = [Link](0);

[Link]();

if ([Link](input2) )

[Link](input + " is the same as "+ input2);

if ( [Link](input3))

6
Programming In JAVA Lab

[Link](input + " is the same as "+ input3);

if ([Link](input3))

[Link](input2 + " is the same as "+ input3);

if (input!=(input2))

sort();

public static void sort()

[Link]("Here are the sorted names.");

char charArray [] = [Link]();

[Link](charArray);

String sortedString = new String(charArray);

[Link](sortedString);

7
Programming In JAVA Lab

public static void main(String[] args)

Greet();

Uinput();

OUTPUT :

8
Programming In JAVA Lab

RESULT :

Thus the JAVA program was executed successfully by using the concept of sorting.

EX NO : 3 DATE:

ADD TWO MATRICES

AIM :

To create a java program and to add two matrices.

ALGORITHM :

1. Start the program


2. Add two matrices in java using binary + operator.

9
Programming In JAVA Lab

3. A matrix is also known as array of arrays.


4. Create an empty matrix.
5. At each position in the new matrix, assign the sum of the values in the same position from
the given two matrices i.e. if A[i][j] and B[i][j] are the two given matrices then, the value of
c[i][j] should be A[i][j] + B[i][j].
6. Stop the program.

PROGRAM :

public class MatrixAdditionExample{

public static void main(String args[]){

//creating two matrices

int a[][]={{1,3,4},{2,4,3},{3,4,5}};

int b[][]={{1,3,4},{2,4,3},{1,2,4}};

//creating another matrix to store the sum of two matrices

int c[][]=new int[3][3]; //3 rows and 3 columns

//adding and printing addition of 2 matrices

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

for(int j=0;j<3;j++){

c[i][j]=a[i][j]+b[i][j]; //use - for subtraction

[Link](c[i][j]+" ");

[Link]();//new line

10
Programming In JAVA Lab

OUTPUT :

RESULT :

Thus the JAVA program was executed successfully by using the concept of matrix
addition.

11
Programming In JAVA Lab

EX NO : 4 DATE:

PREPARE A MARSHEET USING CLASS AND OBJECTS

AIM :

To create a java program and to prepare a mark sheet using class and objects.

ALGORITHM :

1. Start the program


2. Enter student details, i.e., name, rollno, and marks for six subjects.
3. Calculate the percentage of the student based on the marks of those three subjects, and then
calculate the grade using this range.
4. 80 or above A grade
60 or above B grade
45 or above C grade
35 or above D grade
Less than 35 Fail
5. Print the grade.
6. Stop the program.

PROGRAM :

import [Link];

public class Cthird

public static void main(String args[])

/* This program assumes that the student has 6 subjects,

* thats why I have created the array of size 6. You can

* change this as per the requirement.


12
Programming In JAVA Lab

*/

int marks[] = new int[6];

int i;

float total=0, avg;

Scanner scanner = new Scanner([Link]);

for(i=0; i<6; i++) {

[Link]("Enter Marks of Subject"+(i+1)+":");

marks[i] = [Link]();

total = total + marks[i];

[Link]();

//Calculating average here

avg = total/6;

[Link]("The student Grade is: ");

if(avg>=80)

[Link]("A");

else if(avg>=60 && avg<80)

[Link]("B");

else if(avg>=40 && avg<60)

[Link]("C");

13
Programming In JAVA Lab

else

[Link]("D");

OUTPUT :

14
Programming In JAVA Lab

RESULT :

Thus the JAVA program was executed successfully by using the concept of class and
objects.

EX NO : 5 DATE:

AREA OF A RECTANGLE

AIM:
15
Programming In JAVA Lab

To create a JAVA program and to find the area of a rectangle using constructor

ALGORITHM :

1. Start the program.


2. Get the length of the rectangle form the user.
3. Get the breadth of the rectangle form the user.
4. Calculate their product.
5. Print the product.
6. Stop the program.

PROGRAM :

import [Link].*;

class Rectangle

int l,b,a;

Rectangle(int x, int y)

l = x;

b = y;

void GetArea()

a=l*b;

[Link]("Area of Rectangle is : "+a);

class RectangleParameterisedConstructor

16
Programming In JAVA Lab

public static void main(String args[])

throws IOException

BufferedReader Br = new BufferedReader(new


InputStreamReader([Link]));

String lb;

int Length,Breadth;

[Link]("Enter Length and Breadth");

lb=[Link]();

Length=[Link](lb);

lb=[Link]();

Breadth=[Link](lb);

Rectangle Rect = new Rectangle(Length,Breadth);

[Link]();

OUTPUT

17
Programming In JAVA Lab

RESULT :

Thus the JAVA program was executed successfully .

18
Programming In JAVA Lab

EX NO: 6 DATE :

FACTORIAL USING RECURSION

AIM :

To create a java program and to find out the Factorial of a given number using recursion.

ALGORITHM :

1. Start the program.


2. To find the factorial of a number 5 we can call a recursive function and pass the
number 5 within the factorial function.
3. We will make a recursive call for calculating the factorial of number 4 until the number
becomes 0, after the factorial of 4 is calculated we will simply return the value of 5×4!
5×4!.
4. To calculate the factorial of 4 we will again call the recursive function. This process will
continue until the number reaches 0.
5. So, when the number reaches zero we will simply return 1 as the factorial of 0 is 1.
6. Stop the program.

PROGRAM :

class Factorial {

static int factorial( int n ) {

if (n != 0) // termination condition

return n * factorial(n-1); // recursive call

else

return 1;

19
Programming In JAVA Lab

public static void main(String[] args) {

int number = 4, result;

result = factorial(number);

[Link](number + " factorial = " + result);

OUTPUT

20
Programming In JAVA Lab

RESULT

Thus the JAVA Factorial program was executed successfully by using the concept of
recursion.

EX NO : 7 DATE :

MULTIPLE INHERITANCE

Algorithm :

1. Start the program.


2. Declare three classes namely Server, connection and my_test
3. Relate the classes with each other using 'extends' keyword
4. Call the objects of each class from a main function.
5. Stop the program.

Program :

import [Link].*;

import [Link].*;

import [Link].*;

interface one {
21
Programming In JAVA Lab

public void print_geek();

interface two {

public void print_for();

interface three extends one, two {

public void print_geek();

class child implements three {

@Override public void print_geek()

[Link]("Geeks");

public void print_for() { [Link]("for"); }

// Drived class

public class Main {

public static void main(String[] args)

child c = new child();

c.print_geek();

c.print_for();

c.print_geek();

22
Programming In JAVA Lab

OUTPUT

23
Programming In JAVA Lab

RESULT :

Thus the JAVA program was executed successfully by using the concept of Packages
and Interfaces.

EX NO:8 DATE :
24
Programming In JAVA Lab

PACKAGES AND INTERFACES

AIM :

To create a java program to implement user defined packages and interfaces.

ALGORITHM :

1. Start the program.


2. Choose the name of the package
3. Include the package command as the first line of code in your Java Source File.
4. The Source file contains the classes, interfaces, etc you want to include in the package.
5. Compile to create the Java packages
6. Stop the program.

PROGRAM :

package testpkg;

public class A

int x = 1;

public int y = 2;

protected int z = 3;

int returnx ()

return x;

public int returny ()

return y;

protected int returnz ()

25
Programming In JAVA Lab

return z;

public interface StartStop

void start ();

void stop ();

class B

public static void hello ()

[Link] ("hello");

26
Programming In JAVA Lab

27
Programming In JAVA Lab

Output

RESULT :

Thus the JAVA program was executed successfully by using the concept of packages
and interfaces.

EX NO:9 DATE :

EXCEPTION HANDLING

AIM :

To create a java program and to implement the concept of Exception Handling.

ALGORITHM :

1. Start the program.

28
Programming In JAVA Lab

2. The try-catch block is used to handle exceptions in Java. Here's the


syntax of try...catch block:
3. Here, we have placed the code that might generate an exception inside
the try block. Every try block is followed by a catch block.
4. When an exception occurs, it is caught by the catch block.
The catch block cannot be used without the try block.
5. Stop the program.

PROGRAM :

29
Programming In JAVA Lab

class ExceptionHandling {

public static void main(String[] args) {

try {

// code that generate exception

int divideByZero = 5 / 0;

[Link]("Rest of code in try block");

catch (ArithmeticException e) {

[Link]("ArithmeticException => " + [Link]());

}
}

OUTPUT :

30
Programming In JAVA Lab

RESULT :

Thus the JAVA program was executed successfully by using the concept of Exception
Handling.

EX NO : 10 DATE :

MULTITHREADING
31
Programming In JAVA Lab

AIM :

To create a JAVA program to implement the concept of Multithreading.

ALGORITHM :

1. Start the program.


2. Override run( ) method available in Thread class.
3. Once the Thread object is created, the thread can be started by calling start() method,
which executes a call to run( ) method.
4. Stop the program.

PROGRAM :

import [Link].*;

import [Link].*;

class MultithreadingDemo extends Thread{

public void run(){

[Link]("My thread is in running state.");

public static void main(String args[]){

MultithreadingDemo obj=new MultithreadingDemo();

[Link]();

32
Programming In JAVA Lab

OUTPUT

RESULT :

Thus the JAVA program was executed successfully by using the concept of Multithreading.

EX NO : 11 DATE :

DRAW SEVERAL SHAPES USING GRAPHICS

33
Programming In JAVA Lab

AIM :

To create a JAVA Applet program to draw several shapes using graphics.

ALGORITHM :

1. Start the program.


2. Graphics class methods ShapeTest extends JFrame that are frequently use
3. DrawString(String strg, int a, int b):Its purpose is to draw a string within the
coordinates.
4. DrawRect(int a, int b, int width, int height): It's used to create a rectangle with a
specific width and height.
5. DrawLine(int a1, int b1, int a2, int b2):It's used to draw a line with the points a1, b1,
and a2, b2.
6. Stop the program.

PROGRAM :

import [Link].*;

import [Link].*;

public class ShapeTest extends JFrame{

public ShapeTest(){

setSize(400,400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

setVisible(true);

public static void main(String a[]){

new ShapeTest();

public void paint(Graphics g){

[Link](40, 40, 60, 60); //FOR CIRCLE

[Link](80, 30, 200, 200); // FOR SQUARE

34
Programming In JAVA Lab

[Link](200, 100, 100, 200); // FOR RECT

OUTPUT

RESULT :

Thus the JAVA Applet program was executed successfully using graphics.

35
Programming In JAVA Lab

36
Programming In JAVA Lab

37
Programming In JAVA Lab

EX NO : 12 DATE:

EVENT HANDLING

AIM :

To create a java applet program and to implement Event Handling.

ALGORITHM :

1. Start the program.


2. Image 1 shows the output of our code when the state of the button was unclicked.
Image 2 shows the output after the button is pressed.
3. Let’s us continue with event handling in java article and look at the logic behind the
code and understand ActionListener in detail.
4. First of all, we imported all the important packages required to implement the
functionalities required. After importing packages we implemented ActionListener
interface to our class EventHandle.
5. Now, look at the code I’ve divided it into 2 important parts. Int the first part we are
registering our button object with the ActionListener.
6. This is done by calling the addActionListener( ) method and passing current instance
using ‘this’ keyword.
7. Stop the program.

PROGRAM :

import [Link].*;

import [Link].*;

class EventHandle extends Frame implements ActionListener{

TextField textField;

EventHandle()

38
Programming In JAVA Lab

textField = new TextField();

[Link](60,50,170,20);

Button button = new Button("Quote");

[Link](90,140,75,40);

//1

[Link](this);

add(button);

add(textField);

setSize(250,250);

setLayout(null);

setVisible(true);

//2

public void actionPerformed(ActionEvent e){

[Link]("Keep Learning");

public static void main(String args[]){

new EventHandle();

OUTPUT :

39
Programming In JAVA Lab

RESULT :

40
Programming In JAVA Lab

Thus the JAVA program was executed successfully by using the concept of Event
Handling.

EX NO : 13 DATE:

DISPLAY A MESSAGE WITH DIFFERENT COLORS, SIZE AND FONTS

AIM :

To create a Applet program and to display a message with different colors, size and fonts.

ALGORITHM :

1. Start the program.


2. This Java example displays the message "Hello" in different colours in applet.
The [Link] class is used to get pre-defined colors in Java.
3. We have created an array of objects of Color class which contains the pre-defined
colours in Java.
4. Stop the program.

PROGRAM :

import [Link].*;

import [Link];

public class DisplayGraphics extends Canvas{

public void paint(Graphics g) {

[Link]("Hello",40,40);

setBackground([Link]);

[Link](130, 30,100, 80);

[Link](30,130,50, 60);

setForeground([Link]);

41
Programming In JAVA Lab

[Link](130,130,50, 60);

[Link](30, 200, 40,50,90,60);

[Link](30, 130, 40,50,180,40);

public static void main(String[] args) {

DisplayGraphics m=new DisplayGraphics();

JFrame f=new JFrame();

[Link](m);

[Link](400,400);

//[Link](null);

[Link](true);

42
Programming In JAVA Lab

OUTPUT :

RESULT :

Thus the Applet program was executed successfully.

EX NO : 14 DATE:

CALCULATOR USING AWT CONTROLS

AIM :

To create a java program and to implement a calculator using AWT controls.

43
Programming In JAVA Lab

ALGORITHM :

1. Start the program.


2. User enters the character for which operation wants to perform like “+”, “-”, “*”, “/”,
“%”, “^” etc.
3. Within the switch case, we have implemented logic for each character.
4. Based on character operation performed like addition, subtraction, multiplication,
division, modulus (finds remainder) and power of the number.
5. Stop the program.

PROGRAM :

import [Link];

class Calculator {

public static void main(String[] args) {

char operator;

Double number1, number2, result;

// create an object of Scanner class

Scanner input = new Scanner([Link]);

// ask users to enter operator

[Link]("Choose an operator: +, -, *, or /");

operator = [Link]().charAt(0);

// ask users to enter numbers

[Link]("Enter first number");

44
Programming In JAVA Lab

number1 = [Link]();

[Link]("Enter second number");

number2 = [Link]();

switch (operator) {

// performs addition between numbers

case '+':

result = number1 + number2;

[Link](number1 + " + " + number2 + " = " + result);

break;

// performs subtraction between numbers

case '-':

result = number1 - number2;

[Link](number1 + " - " + number2 + " = " + result);

break;

// performs multiplication between numbers

case '*':

result = number1 * number2;

[Link](number1 + " * " + number2 + " = " + result);

break;

45
Programming In JAVA Lab

// performs division between numbers

case '/':

result = number1 / number2;

[Link](number1 + " / " + number2 + " = " + result);

break;

default:

[Link]("Invalid operator!");

break;

[Link]();

OUTPUT :

46
Programming In JAVA Lab

RESULT :

Thus the JAVA program was executed successfully by using the AWT controls.

EX NO : 15 DATE:

ANALOG CLOCK USING GRAPHICS

AIM :

To create a java program and to display an analog clock using graphics.

ALGORITHM :

1. Start the program.


2. Import the necessary packages.
3. Define a variable and make the object of the SimpleDate format class.
4. We are creating a structured method for the design of the analog clock.

47
Programming In JAVA Lab

5. Calculate the seconds, minutes and hours coordinates from the current time by getting
the system time. And convert the value into an integer form.
6. For moving needle logics. Actually in the following line we define some general condition
that is found in all types of clocks such as when the seconds hand reaches 12 then the
minutes hand moves 1 step and then after moving 5 steps of the minutes hand then 1-
stepmoves a hours needle.
7. For moving needle minute and hours. this code for set the color of needle and moving
forward rest of if conditions.
8. Stop the program.

PROGRAM :

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class Clock extends [Link] {

public int hour;

public int min;

public int sec;

ClockDial cd;

48
Programming In JAVA Lab

public Clock() {

setSize(510,530);

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

cd=new ClockDial(this);

getContentPane().add(cd);

Date curr=new Date();

String time=[Link]();

hour=[Link]([Link](11,13));

min=[Link]([Link](14,16));

sec=[Link]([Link](17,19));

[Link]([Link]()+3);

[Link]();

public static void main(String args[]) {

new Clock().setVisible(true);

Thread ClockEngine=new Thread()

int newsec,newmin;

public void run()

49
Programming In JAVA Lab

while(true)

newsec=(sec+1)%60;

newmin=(min+(sec+1)/60)%60;

hour=(hour+(min+(sec+1)/60)/60)%12;

sec=newsec;

min=newmin;

try {

[Link](1000);

} catch (InterruptedException ex) {}

[Link]();

};

class ClockDial extends JPanel{

Clock parent;

public ClockDial(Clock pt){

50
Programming In JAVA Lab

setSize(520,530);

parent=pt;

@Override

public void paintComponent(Graphics g) {

[Link]([Link]);

[Link](0, 0, getWidth(), getHeight());

[Link]([Link]);

[Link](5, 5,480,480);

[Link]([Link]);

[Link](10, 10,470,470);

[Link]([Link]);

[Link](237,237,15,15);

[Link]([Link]().deriveFont([Link],32));

for(int i=1;i<=12;i++)

[Link]([Link](i),240-(i/12)*11+(int)(210*[Link](i*[Link]/
6)),253-(int)(210*[Link](i*[Link]/6)));

double minsecdeg=(double)[Link]/30;

double hrdeg=(double)[Link]/6;

int tx,ty;

int xpoints[]=new int[3];

51
Programming In JAVA Lab

int ypoints[]=new int[3];

//second hand

tx=245+(int)(210*[Link]([Link]*minsecdeg));

ty=245-(int)(210*[Link]([Link]*minsecdeg));

[Link](245,245,tx,ty);

//minute hand

tx=245+(int)(190*[Link]([Link]*minsecdeg));

ty=245-(int)(190*[Link]([Link]*minsecdeg));

xpoints[0]=245;

xpoints[1]=tx+2;

xpoints[2]=tx-2;

ypoints[0]=245;

ypoints[1]=ty+2;

ypoints[2]=ty-2;

[Link](xpoints, ypoints,3);

//hour hand

tx=245+(int)(160*[Link]([Link]*hrdeg+[Link]*[Link]/360));

ty=245-(int)(160*[Link]([Link]*hrdeg+[Link]*[Link]/360));

xpoints[1]=tx+4;

xpoints[2]=tx-4;

ypoints[1]=ty-4;

ypoints[2]=ty+4;

52
Programming In JAVA Lab

[Link](xpoints, ypoints, 3);

OUTPUT :

RESULT :

Thus the program was executed successfully by using the concept of Analog clock using
graphics.

53
Programming In JAVA Lab

54

You might also like