[Go to site: main page, start]

0% found this document useful (0 votes)
14 views33 pages

Java Programming Practical Exercises

The document is a practical file containing various Java programming assignments, including programs for printing messages, calculating areas, implementing control statements, and object-oriented programming concepts. Each program is accompanied by its source code and expected output. The file serves as a guide for students to practice and understand Java programming fundamentals.

Uploaded by

NARENDER
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)
14 views33 pages

Java Programming Practical Exercises

The document is a practical file containing various Java programming assignments, including programs for printing messages, calculating areas, implementing control statements, and object-oriented programming concepts. Each program is accompanied by its source code and expected output. The file serves as a guide for students to practice and understand Java programming fundamentals.

Uploaded by

NARENDER
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

Practical file of

Submitted to: Submitted by:


Mrs. Name :
(Asstt. Prof. in C.S. Dept) Class :
Roll no: ………………
Index
[Link]. Program Page Sign.
no.
1. WAP To Print Hello In Java WAP.

2. WAP To Calculate Area.

3. WAP To Implement Else If Ladder.

4. WAP To Implement Switch Statement.

5. WAP To Implement Nested For Loop.

6. WAP To Draw Pattern On Screen.

7. WAP To Implement Classes And Object.

8. WAP To Implement Constructor.

9. WAP To Implement Copy Constructor.

10. WAP To Implement Constructor Overloading.

11. WAP To Implement Abstract Class.

12. WAP To Implement Interface.

13. WAP To Implement Exception Handling.

14. WAP To Implement Package.

15. WAP To Implement Simple Applet.


SIMPLE JAVA PROGRAM

class SampleOne

public static void main(String args[])

[Link]("Java is better than c++");

OUTPUT
PROGRAM TO CALCULATE AREA
class Room

float length;

float breadth;

void getdata(float a, float b)

length=a;

breadth=b;

class RoomArea

public static void main(String args[])

float area;

Room room1 = new Room();

[Link](14, 10);

area = [Link] * [Link];

[Link]("Area =" + area);

}
OUTPUT
PROGRAM OF ELSE IF LADDER

class ElseIfLadder

public static void main(String args[])

int rollNumber[] = { 111, 222, 333, 444 };

int marks[] = { 81, 75, 43, 58 };

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

if (marks[i] > 79)

[Link](rollNumber[i] + " Honours");

else if (marks[i] >59)

[Link](rollNumber[i] + " 1st Division");

else if (marks[i] > 49)

[Link](rollNumber[i] + " 2nd Division");

else

[Link](rollNumber[i] + " Fail");

}
OUTPUT
PROGRAM OF SWITCH STATEMENT

class CityGuide

public static void main(String args[])

char choice;

[Link]("Select your choice");

[Link](" M -> Madras");

[Link](" B -> Bombay");

[Link](" C -> Calcutta");

[Link]("choice--->");

[Link]();

try

switch (choice = (char) [Link]())

case 'M':

case 'm': [Link]("Madras : Booklet 5");

break;

case 'B':

case 'b':[Link]("Bombay : Booklet 9");


break;

case 'C':

case'c': [Link]("Calcutta: Booklet15");

break;

default:[Link]("Invalid Choice (IC)");

catch (Exception e)

[Link]("I/O Error");

}
OUTPUT
PROGRAM OF NESTED FOR LOOP

class NestedLoop

public static void main(String args[])

int p,q;

[Link]("The right angle triangle of @ is shown below:\n");

for (p = 1; p <= 9; p++)

for(q = 1; q <= p; q++)

[Link]("@");

[Link](" ");

}
OUTPUT
PROGRAM TO DRAW PATTERN ON SCREEN
class Displaying

public static void main(String args[])

[Link]("Screen Display");

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

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

[Link](" ");

[Link](i);

[Link]("\n");

[Link]("Screen Display Done");

}
OUTPUT
PROGRAM OF CLASSES AND OBJECTS

class Rectangle

int length, width;

void getdata (int x, int y)

length = x;

width = y;

int rectArea ()

int area = length * width;

return (area);

class RectArea

public static void main (String args[])

int area1, area2;


Rectangle rect1 = new Rectangle();

Rectangle rect2 = new Rectangle();

[Link] = 15;

[Link] = 10;

area1 = [Link] * [Link];

[Link] (20, 12);

area2 = [Link]();

[Link]("Area1 = " + area1);

[Link]("Area2 = " + area2);

OUTPUT
PROGRAM OF CONSTRUCTOR
class Rectangle

int length, width;

Rectangle (int x, int y)

length = x;

width = y;

int rectArea ()

return (length * width);

class RectangleArea

public static void main(String args[])

Rectangle rect1 = new Rectangle(15, 10);

int area1 = [Link]();


[Link]("Area1 = " + area1);

OUTPUT
PROGRAM OF COPY CONSTRUCTOR
class Student6

int id;

String name;

int age;

Student6 (int i, String n)

id = i;

name = n;

Student6(Student6 s)

id = [Link];

name = [Link];

void display()

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

public static void main(String args[])


{

Student6 s1 = new Student6(111, "karan");

Student6 s2 = new Student6(s1);

[Link]();

[Link]();

OUTPUT
PROGRAM OF CONSTRUCTOR OVERLOADING

class Student5

int id;

String name;

int age;

Student5 (int i, String n)

id = i;

name = n;

Student5 (int i, String n, int a)

id = i;

name = n;

age = a;

void display()

[Link](id + " " + name + " " + age);

}
public static void main(String args[])

Student5 s1 = new Student5(111, "karan");

Student5 s2 = new Student5(222, "Aryan", 25);

[Link]();

[Link]();

OUTPUT
PROGRAM TO IMPLEMENT ABSTRACT CLASS
abstract class Sum

public abstract int SumOfTwo (int n1, int n2);

public abstract int SumOfThree (int n1, int n2, int n3);

public void disp()

[Link]("Method of class Sum");

class AbstractDemo extends Sum

public int SumOfTwo (int num1, int num2)

return num1 + num2;

public int SumOfThree (int num1, int num2, int num3)

return num1 + num2 + num3;

public static void main(String args[])


{

AbstractDemo obj = new AbstractDemo();

[Link]([Link](3, 7));

[Link]([Link](4, 3, 19));

[Link]();

OUTPUT
PROGRAM OF INTERFACE: MULTIPLE INHERITENCE
interface Area

final static float pi = 3.14F;

float compute (float x, float y);

class Rectangle implements Area

public float compute (float x, float y)

return(x * y);

class Circle implements Area

public float compute (float x, float y)

return(pi * x * x);

class InterfaceTest

{
public static void main(String args[])

Rectangle rect = new Rectangle();

Circle cir = new Circle();

Area area;

area = rect;

[Link]("Area of Rectangle = " + [Link](10, 20));

area = cir;

[Link]("Area of Circle = " + [Link](10, 12));

OUTPUT
PROGRAM WITHOUT EXCEPTION HANDLING
class Error2

public static void main(String args[])

int a = 10;

int b = 5;

int c = 5;

int x = a/(b-c);

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

int y = a/(b+c);

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

}
OUTPUT
PROGRAM FOR IMPLEMENTING PACKAGE

import [Link];

import package2.*;

class PackageTest2

public static void main(String args[])

ClassA objectA = new ClassA();

ClassB objectB = new ClassB();

[Link]();

[Link]();

//[Link]

package package1;

public class ClassA

public void displayA()

[Link]("Class A");
}

} //[Link]

package package2;

public class ClassB

protected int m = 10;

public void displayB()

[Link]("Class B");

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

OUTPUT
PROGRAM TO IMPLEMENT SIMPLE APPLET

import [Link].*;

import [Link].*;

public class HelloJavaParam extends Applet

String str;

public void init( )

str = getParameter( "string" );

if (str == null)

str = "Java";

str = "Hello" + str;

public void paint (Graphics g)

[Link](str, 10, 100);

}
//[Link]

<HTML>

<! Parametrized HTML File>

<Head>

<TITLE> Welcome to Java Applets </TITLE>

</HEAD>

<BODY>

<APPLET CODE = [Link]

WIDTH = 400

HEIGHT = 200>

</APPLET>

</BODY>

</HTML>
OUTPUT

Common questions

Powered by AI

Implementation of classes and objects in Java allows for encapsulation, where the object data (attributes) is separated from methods (functions), enhancing modularity . For instance, the 'Rectangle' class encapsulates data such as length and width, along with operations like 'rectArea' that compute area, thereby allowing the same 'Rectangle' class to be reused with different data in separate instances, promoting code reusability .

Exception handling in Java is crucial for developing robust applications as it enables a program to handle runtime errors gracefully, maintaining normal flow rather than crashing. The mechanism is implemented using try-catch blocks, as seen in the 'CityGuide' program where input-output exceptions are caught when invalid input is given . In another example, lack of exception handling in 'Error2' results in a runtime error when division by zero occurs .

Java interfaces enable polymorphism by allowing classes to implement multiple interfaces, handling different types under a common interface. In the document, both 'Rectangle' and 'Circle' classes implement the 'Area' interface, allowing them to be treated uniformly when calculating the area, despite differing implementations in 'compute' method . Here, an 'Area' type reference can hold objects of both 'Rectangle' and 'Circle', demonstrating polymorphic behavior .

Copy constructors in Java are used to create new objects as copies of existing objects, ensuring a new instance with the same state. The 'Student6' class demonstrates this by defining a copy constructor that initializes a new object with the fields of an existing 'Student6' object, useful in situations where an identical but independent object is needed, preserving original object encapsulation . This design pattern is particularly significant for cloning objects without exposing the direct copy process to client code.

Applets differ from standalone Java applications in that they are designed to be embedded in web pages and run in a Java-enabled browser, rather than being executed independently. The 'HelloJavaParam' applet example shows it using the Applet class and executing within an HTML framework, requiring an 'init' and 'paint' method for display, unlike standalone applications that have a main method and execute directly from the command line .

Nested control structures, such as loops, enhance functionality by allowing repetitive operations to be performed within larger repetitive operations, thus handling complex iterations. In the document, the 'NestedLoop' class uses nested 'for' loops to print a right-angle triangle pattern, demonstrating how two-level iteration can be implemented to handle repeating tasks efficiently .

Packages in Java help in organizing large projects by grouping related classes under namespaces, reducing naming conflicts and providing controlled access to classes. The document illustrates this by using packages 'package1' and 'package2' to separate 'ClassA' and 'ClassB', allowing structured project organization where classes with similar functions can reside in their respective directories, fostering maintainable project development .

Constructor overloading in Java allows a class to have more than one constructor with different parameters. In the document, the 'Student5' class demonstrates constructor overloading. It defines two constructors: one taking an 'id' and a 'name', and the other taking an 'id', 'name', and 'age'. This allows creating 'Student5' objects with different initial data, showing flexibility in object creation .

The 'switch' statement simplifies condition checks by allowing branching based on the value of a variable, removing the need for multiple 'if-else' checks that can make the code bulky. As demonstrated in the 'CityGuide' program, 'switch' branches based on a character input to provide a selection of guides, making the code cleaner and more readable compared to handling each choice with individual 'else-if' statements .

Abstract classes in Java provide flexibility by allowing both abstract methods (to be implemented by subclasses) and fully implemented methods, unlike interfaces which cannot contain implementation prior to Java 8. The document shows 'Sum' as an abstract class with abstract methods 'SumOfTwo' and 'SumOfThree', along with a concrete method 'disp' that subclasses can directly use, offering a mix of defined and abstract behavior . In contrast, interfaces require all implementing classes to define method behavior unless default methods are used .

You might also like