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

OOP With Java Lab Manual

Uploaded by

thebabadrive
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)
8 views53 pages

OOP With Java Lab Manual

Uploaded by

thebabadrive
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/ 53

SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-1

Aim:

Programs on Basic programming constructs like branching and looping

Theory:

1. Simple If statement:
The general form of single if statement is :
if ( test expression)
{
statement-Block;
}
statement-Blocks;

Example:
int x = 20;
int y = 18;
if (x > y)
{
System.out.println("x is greater than y");
}

2. If- Else statement:


The general form of if-else statement is

if ( test expression)
{
statement-block1;
}
else
{
statement-block2
}

Example:
int time = 20;
if (time < 18)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."

3. Else-if statement:
general form of else-if statement is:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 1


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

if ( test condition)
{
statement-block1;
}
else if(test expression2)
{
statement-block2;
}
else
{
statement block3;
}

Example:
int time = 22;
if (time < 10)
{
System.out.println("Good morning.");
}
else if (time < 20)
{
System.out.println("Good day.");
}
else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."

4. Nested if – else statement:


The general form of nested if-else statement is:
if ( test condition)
{
if ( test condition)
{
statement block1;
}
else
{
statement block2;
}
}
else
{
statement block 3
}

Example:
percentage=65;
if (percentage>=60)
{

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 2


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

if (percentage>=70)
{
System.out.println(“Distinction");
}
else
{
System.out.println(“First Class");
}
}
else
{
System.out.println(“Second Class");
}

5. The switch statements:


The general form of switch statement is:

switch ( expression)
{
case value-1: block-1;
break;
case value-2: block-2;
break;
......
default: default block;
break;
}

Example:
int day = 4;
switch (day)
{
case 1: System.out.println("Monday");
break;
case 2: System.out.println("Tuesday");
break;
case 3: System.out.println("Wednesday");
break;
case 4: System.out.println("Thursday");
break;
case 5: System.out.println("Friday");
break;
case 6: System.out.println("Saturday");
break;
case 7: System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 3


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Loops In Java:
▪ In looping a sequence of statements are executed until a number of time or until some condition
for the loop is being satisfied.
▪ Any looping process includes following four steps:
(1) Setting an initialization for the counter.
(2) Execution of the statement in the loop
(3) Test the specified condition for the loop.
(4) Incrementing the counter.
Java includes three loops. They are:
1. while loop
2. do loop
3. for loop

1) while loop:
The general structure of a while loop is:
Initialization
while (test condition)
{
body of the loop
}

Example:
int i = 0;
while (i < 5)
{
System.out.println(i);
i++;
}

2) do loop:
The general structure of a do loop is :
Initialization
do
{
Body of the loop;
}
while ( test condition);

Example:
int i = 0;
do
{
System.out.println(i);
i++;
} while (i < 5);

3) for loop :
The general structure of for loop is:
for ( Initialization ; Test condition ; Increment)
{
body of the loop;

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 4


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Example:
for (int i = 0; i < 5; i++)
{
System.out.println(i);
}

Program 1. Write a Java Program to demonstrate Basic programming constructs like branching
and looping.

import java.util.*;
public class DemoBranchingLooping
{
public static void main(String[] args)
{
int i,b,n,j;
String c;
int fact=1;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number:");
n=sc.nextInt();
do
{
System.out.println("\n**Menu...**");
System.out.println("1. Factorial\n2. Print Pattern\n");
System.out.println("Enter the operation to be performed:");
b=sc.nextInt();

switch(b)
{
case 1:
for(i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("\nFactorial of entered number is:"+fact);
break;
case 2:
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("*");
}
System.out.print("\n");
}
break;
default:
System.out.println("\nPlease enter the correct option");
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 5


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

System.out.println("\nDo you want to continue?y/n:");


c=sc.next();
}while(c.equals("y"));
}
}

Sample Output:

Conclusion: Implemented and demonstrated program on Basic programming constructs like branching
and looping in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 6


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-2

Aim:

Program on accepting input through keyboard.

Theory:

Scanner Class
▪ Added by JDK 5, Scanner reads formatted input and converts it into its binary form.
▪ Because of the addition of Scanner, it is now easy to read all types of numeric values, strings,
and other types of data, whether it comes from a disk file, the keyboard, or another source.
▪ Scanner can be used to read input from the console, a file, a string, or any source that
implements the Readable interface or ReadableByteChannel.
▪ For example, you can use Scanner to read a number from the keyboard and assign its value to a
variable.

The Scanner Constructors

Program 2. Write a Java Program to demonstrate accepting input through keyboard.

import java.util.*;
public class UnsignedRightShift
{
public static void main(String[] args)
{
int a;
int b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a positive value for x:");
a=sc.nextInt();
System.out.println("Enter a negative value for y:");
b=sc.nextInt();

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 7


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

System.out.println(a >>> 2);


System.out.println(b >>> 24);
}
}

Sample Output:

Conclusion: Implemented and demonstrated Program to demonstrate accepting input through


keyboard in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 8


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-3

Aim:

Programs on class and objects

Theory:

Class:
▪ A class is a template for an object, and defines the data fields and methods of the object.
▪ The class methods provide access to manipulate the data fields.
▪ The “Data fields” of an object are often called “Instance variables”.

The General Form of a Class


▪ The data, or variables, defined within a class are called instance variables.
▪ The code is contained within methods.
▪ Collectively, the methods and variables defined within a class are called members of the class.
▪ Thus the methods that determine how a class’ data can be used.
▪ each object of the class contains its own copy of these variables.
▪ Thus, the data for one object is separate and unique from the data for another.

class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method
}
}

Creating Objects:
▪ when a class is created , we are creating a new data type.
▪ We can use this type to declare objects of that type.
▪ However, obtaining objects of a class is a two-step process.
▪ First, we must declare a variable of the class type. This variable does not define an object.
Instead, it is simply a variable that can refer to an object.
Rectangle rect1;

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 9


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

▪ Second, we must acquire an actual, physical copy of the object and assign it to that variable by
using the new operator.
rect1=new Rectangle();
▪ The new operator dynamically allocates (that is, allocates at run time) memory for an object
and returns a reference to it.
▪ Following statement combines the two steps just described.
Rectangle rect1 =new Rectangle();

Program 3. Write a Java Program to define a class, define instance methods for setting and
Retrieving values of instance variables and instantiate its object.

import java.lang.*;
class Emp
{
String name;
int id;
String address;
void getdata(String name,int id,String address)
{
this.name=name;
this.id=id;
this.address=address;
}
void putdata()
{
System.out.println("Employee details are :");
System.out.println("Name :" +name);
System.out.println("ID :" +id);
System.out.println("Address :" +address);
}
}
class EmpDemo
{
public static void main(String args[])
{
Emp e=new Emp();
e.getdata("Smith",76859,"London");
e.putdata();
}
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 10


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Sample Output:

Conclusion: Implemented and demonstrated Program to define a class, define instance methods for
setting and Retrieving values of instance variables and instantiate its object in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 11


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-4

Aim:

Program on method and constructor overloading.

Theory:

Method Overloading:
▪ Two or more methods have the same names but different argument lists.
▪ The arguments may differ in type or number, or both.
▪ However, the return types of overloaded methods can be the same or different is called method
overloading.

Example:
class MethodOverloading
{
int add( int a, int b)
{
return(a+b);
}
float add(float a, float b)
{
return(a+b);
}
double add( int a, double b, double c)
{
return(a+b+c);
}
}

Constructors:
▪ It can be tedious to initialize all of the variables in a class each time an instance is created.
▪ Thus automatic initialization is performed through the use of a constructor.
▪ A constructor initializes an object immediately upon creation.
▪ It has the same name as the class in which it resides and is syntactically similar to a method.
▪ the constructor is automatically called immediately after the object is created, before the new
operator completes.
▪ Constructors have no return type, not even void.
▪ This is because the implicit return type of a class’ constructor is the class type itself.

Example:
class Student
{
String name,location;
int postid;
Student()
{
name="Shreya";
location="Mumbai";
postid=400020;

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 12


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

}
Student(String name,String location,int postid)
{
this.name=name;
this.location=location;
this.postid=postid;
}
void display()
{
System.out.println(name +"\t"+location +"\t" +postid);
}
}

Program 4.A. Write a Java Program to define a class, define instance methods and overload
them and use them for dynamic method invocation.

class MethodOverloading
{
void display(int a,int b)
{
int result=a+b;
System.out.println("The sum of 2 integers are:" +result);
}
void display(double a,double b)
{
double result=a+b;
System.out.println("The sum of 2 floating numbers are:" +result);
}
void display(int a,int b,int c)
{
int result=a+b+c;
System.out.println("The sum of 3 integers are:" +result);
}
void display(int a,double b)
{
double result=a+b;
System.out.println("The sum an integer with a floating number is:" +result);
}
}
class MethodOverloadingDemo
{
public static void main(String d[])
{
MethodOverloading obj=new MethodOverloading();
obj.display(5,8);
obj.display(5.11,8.43);
obj.display(5,8,4);
obj.display(5,8.0132);
}
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 13


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Sample Output:

Program 4.B. Write a Java Program to define a class, describe its constructor, overload the
Constructors and instantiate its object.

class Student
{
String name,location;
int postid;
Student()
{
name="Shreya";
location="Mumbai";
postid=400020;
}
Student(String name,String location,int postid)
{
this.name=name;
this.location=location;
this.postid=postid;
}
void display()
{
System.out.println(name +"\t"+location +"\t" +postid);
}
}
class ConstructorsDemo
{
public static void main(String args[])
{
Student s1= new Student();
Student s2=new Student("Aniket","Mumbai", 400080);
s1.display();
s2.display();
}
}

Sample Output:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 14


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Conclusion: Implemented and demonstrated Program on method and constructor overloading in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 15


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-5

Aim:

Program on Packages.

Theory:

Packages:
▪ Package is a mechanism for partitioning the class name-space into more manageable chunks.
▪ A java package is a group of similar types of classes, interfaces and sub-packages.
▪ The package is both a naming and a visibility control mechanism.
▪ It is possible to define classes inside a package that are not accessible by code outside that
package.
▪ We can define class members that are only exposed to other members of the same package.
▪ Package in java can be categorized in two form,
• Built-in package
• User-defined package.
▪ There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Defining a Package
▪ To create a package ,simply include a package command as the first statement in a Java source
file.
▪ Any classes declared within that file will belong to the specified package.
▪ The package statement defines a name space in which classes are stored.
▪ If we skip the package statement, the class names are put into the default package, which has
no name.
▪ The general form of the package statement:
package pkg;
▪ Here, pkg is the name of the package.
▪ For example, the following statement creates a package called MyPackage.
package MyPackage;
▪ The general form of a multileveled package statement is shown here:
package pkg1[.pkg2[.pkg3]];

Example:
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

How to access package from another package?


There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 16


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

1) Using packagename.*
▪ If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
▪ The import keyword is used to make the classes and interface of another package accessible to
the current package.

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

3) Using fully qualified name


▪ If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import.
▪ But you need to use fully qualified name every time when you are accessing the class or
interface.
▪ It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Program 5. Write a Java program to implement the concept of importing classes from user
defined package and creating packages.

package package1;
public class PackageStudent
{
int regno;
String name;
public void getdata(int r,String s)
{
regno=r;
name=s;
}
public void putdata()
{
System.out.println("Registration Number = " +regno);
System.out.println("Name = " + name);
}
}

import package1.*;
class PackageStudentDemo
{
public static void main(String arg[])
{
PackageStudent s=new PackageStudent();
s.getdata(111,"Saket Joshi");
s.putdata();
}
}

Sample Output:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 17


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Conclusion: Implemented and demonstrated program to implement the concept of importing classes
from user defined package and creating packages in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 18


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-6

Aim:

Program on 2D array, strings functions.

Theory:

Array:
▪ An array is a group of like-typed variables that are referred to by a common name.
▪ Arrays of any type can be created and may have one or more dimensions.
▪ A specific element in an array is accessed by its index.
▪ Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
▪ A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you
first must create an array variable of the desired type.
▪ The general form of a one-dimensional array declaration is
type var-name[ ];
▪ Here, type declares the base type of the array.
▪ The base type determines the data type of each element that comprises the array.
▪ Thus, the base type for the array determines what type of data the array will hold.
▪ For example,
int month_days[];
▪ Although this declaration establishes the fact that month_days is an array variable, no array
actually exists.
▪ In fact, the value of month_days is set to null, which represents an array with no value.
▪ To link month_days with an actual, physical array of integers, you must allocate one using new
and assign it to month_days.
▪ new is a special operator that allocates memory.
▪ The general form of new as it applies to one-dimensional arrays appears as follows:
array-var = new type[size];
▪ Here,
type specifies the type of data being allocated,
size specifies the number of elements in the array, and
array-var is the array variable that is linked to the array
▪ For example,
month_days = new int[12];
▪ This example,
allocates a 12-element array of integers and links them to month_days.
month_days will refer to an array of 12 integers.
all elements in the array will be initialized to zero.

Multidimensional Arrays
▪ In Java, multidimensional arrays are actually arrays of arrays.
▪ To declare a multidimensional array variable, specify each additional index using another set of
square brackets.
▪ For example, the following declares a two dimensional array variable called twoD
int twoD[][] = new int[4][5];
▪ This allocates a 4 by 5 array and assigns it to twoD.
▪ Internally this matrix is implemented as an array of arrays of int.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 19


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Strings:
▪ In Java a string is a sequence of characters.
▪ But, unlike many other languages that implement strings as character arrays, Java implements
strings as objects of type String.
String Constructors:
▪ The String class supports several constructors.
▪ To create an empty String, you call the default constructor.
▪ For example,
String s = new String();
will create an instance of String with no characters in it.
▪ To create a String initialized by an array of characters, use the constructor shown here:

String(char chars[ ])
▪ Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
▪ You can specify a subrange of a character array as an initializer using the following
constructor:

String(char chars[ ], int startIndex, int numChars)

▪ Here, startIndex specifies the index at which the subrange begins, and numChars specifies the
number of characters to use.
▪ Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
▪ This initializes s with the characters cde.
▪ You can construct a String object that contains the same character sequence as another String
object using this constructor:
String(String strObj)
▪ Here, strObj is a String object.

Commonly used String Methods

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 20


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Program 6.A. Write a Java program to implement the concept of 2D array.

import java.util.*;
class MatrixMultiDemo
{
public static void main(String args[])
{
int m, n, p, q, sum=0, i, j, k;
Scanner sc=new Scanner(System.in);
System.out.println("Enter no. of rows and columns of 1st matrix:");
m=sc.nextInt();
n=sc.nextInt();

int first[][]=new int[m][n];


System.out.println("Enter first matrix elements:\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
first[i][j]=sc.nextInt();
}
}

System.out.println("Enter no. of rows and columns of 2nd matrix:");


p=sc.nextInt();
q=sc.nextInt();

int second[][]=new int[p][q];


System.out.println("Enter second matrix elements:");

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 21


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
second[i][j]=sc.nextInt();
}
}

System.out.println("Elements of first Matrix:\n");


for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
System.out.print(first[i][j]+"\t");
}
System.out.println("\n");
}
System.out.println("Elements of Second Matrix:\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
System.out.print(second[i][j]+"\t");
}
System.out.println("\n");
}

int mult[][]=new int[m][q];

System.out.println("Multiplication of the matrices:");


for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
for(k=0;k<p;k++)
{
sum=sum+first[i][k]*second[k][j];
}
mult[i][j]=sum;
sum=0;
}
}

for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
System.out.print(mult[i][j]+"\t");
}
System.out.println("\n");
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 22


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

}
}

Sample Output:

Program 6.B. Write a Java program to practice using String class and its methods.

import java.lang.String;
class StringDemo
{
public static void main(String arg[])
{
String s1=new String("mumbai maharashtra");
String s2="MUMBAI MAHARASHTRA";
System.out.println(" The string s1 is : " +s1);
System.out.println(" The string s1 is : " +s2);
System.out.println(" Length of the string s1 is : " +s1.length());
System.out.println(" The first accurence of r is at the position : " +s1.indexOf('r'));
System.out.println(" The String in Upper Case : " +s1.toUpperCase());
System.out.println(" The String in Lower Case : " +s1.toLowerCase());
System.out.println(" s1 equals to s2 : " +s1.equals(s2));
System.out.println(" s1 equals ignore case to s2 : " +s1.equalsIgnoreCase(s2));
int result=s1.compareTo(s2);
System.out.println("After compareTo()");
if(result==0)
System.out.println( s1 + " is equal to "+s2);
else if(result>0)
System.out.println( s1 + " is greather than to "+s2);
else
System.out.println( s1 + " is smaller than to "+s2);
System.out.println(" Character at an index of 4 is :" +s1.charAt(4));
String s3=s1.substring(4,12);

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 23


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

System.out.println(" Extracted substring is :"+s3);


System.out.println(" After Replacing m with 3 in s1 : " + s1.replace('m','3'));
String s4=" This is a book ";
System.out.println(" The string s4 is :"+s4);
System.out.println(" After trim() :"+s4.trim());
}
}

Sample Output:

Conclusion: Implemented and demonstrated Program on 2D array, strings functions in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 24


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-7

Aim:

Program on String Buffer and Vectors.

Theory:

String Buffer:

▪ StringBuffer is a peer class of String that provides much of the functionality of strings.
▪ String represents fixed-length, immutable character sequences.
▪ In contrast, StringBuffer represents growable and writeable character sequences.
▪ StringBuffer may have characters and substrings inserted in the middle or appended to the end.
▪ StringBuffer will automatically grow to make room for such additions and often has more
characters preallocated than are actually needed, to allow room for growth.

StringBuffer Constructors
StringBuffer defines these four constructors:
• StringBuffer( )
• StringBuffer(int size)
• StringBuffer(String str)
• StringBuffer(CharSequence chars)

StringBuffer( )
▪ The default constructor (the one with no parameters) reserves room for 16 characters
without reallocation.

StringBuffer(int size)
▪ This version accepts an integer argument that explicitly sets the size of the buffer.

StringBuffer(String str)
▪ This version accepts a String argument that sets the initial contents of the StringBuffer
object and reserves room for 16 more characters without reallocation.
▪ StringBuffer allocates room for 16 additional characters when no specific buffer length
is requested, because reallocation is a costly process in terms of time.
▪ Also, frequent reallocations can fragment memory.
▪ By allocating room for a few extra characters, StringBuffer reduces the number of
reallocations that take place.

StringBuffer(CharSequence chars)
▪ This constructor creates an object that contains the character sequence contained in
chars.

Vectors:
▪ Vector implements a dynamic array.
▪ It is similar to ArrayList, but with two differences:
• Vector is synchronized
• Vector contains many legacy methods that are not part of the Collections Framework.
▪ With the advent of collections, Vector was reengineered to extend AbstractList and to
implement the List interface.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 25


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

▪ Vector is fully compatible with collections


▪ Vector can have its contents iterated by the enhanced for loop.
▪ Vector is declared like this:
class Vector <E>
▪ Here, E specifies the type of element that will be stored.

Advantages:
• It is convenient to use vectors to store objects.
• It can be used to store list of objects that may vary in size.
• We can add and delete objects from the list as and when required.

Here are the Vector constructors:


▪ Vector( )
This creates a default vector, which has an initial size of 10.

▪ Vector(int size)
This creates a vector whose initial capacity is specified by size.

▪ Vector(int size, int incr)


This creates a vector whose initial capacity is specified by size and whose increment is
specified by incr.
The increment specifies the number of elements to allocate each time that a vector is resized
upward.

▪ Vector(Collection c)
This creates a vector that contains the elements of collection c.

Program 7.A. Write a Java program to practice using String Buffer class and its methods.

import java.lang.String;
class StringBufferDemo
{
public static void main(String arg[])
{
StringBuffer sb=new StringBuffer("This is my college");
System.out.println("This string sb is : " +sb);
System.out.println("The length of the string sb is : " +sb.length());
System.out.println("The capacity of the string sb is : " +sb.capacity());
System.out.println("The character at an index of 6 is : " +sb.charAt(6));
sb.setCharAt(3,'x');
System.out.println("After setting char x at position 3 : " +sb);
System.out.println("After appending : " +sb.append(" in Mumbai"));
System.out.println("After inserting : " +sb.insert(19, "SAKEC "));
System.out.println("After deleting : " +sb.delete(19,24));
}
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 26


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Sample Output:

Program 7.B. Write a Java Program to implement Vector class and its methods.

import java.lang.*;
import java.util.Vector;
import java.util.Enumeration;
class VectorDemo
{
public static void main(String arg[])
{
Vector v=new Vector();
v.addElement("one");
v.addElement("two");
v.addElement("three");
v.insertElementAt("zero",0);
v.insertElementAt("oops",3);
v.insertElementAt("four",5);
System.out.println("Vector Size :"+v.size());
System.out.println("Vector apacity :"+v.capacity());
System.out.println(" The elements of a vector are :");
Enumeration e=v.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement() +" ");
System.out.println();
System.out.println("The first element is : " +v.firstElement());
System.out.println("The last element is : " +v.lastElement());
System.out.println("The object oops is found at position : "+v.indexOf("oops"));
v.removeElement("oops");
v.removeElementAt(1);
System.out.println("After removing 2 elements ");
System.out.println("Vector Size :"+v.size());
System.out.println("The elements of vector are :");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i)+" ");
}
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 27


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Sample Output:

Conclusion: Implemented and demonstrated Program on String Buffer and Vectors in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 28


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-8

Aim:
Program on types of inheritance

Theory:

Inheritance:
▪ One class can acquire the properties of another class.
▪ a class that is inherited is called a superclass.
▪ The class that does the inheriting is called a subclass.
▪ Therefore, a subclass is a specialized version of a superclass.
▪ It inherits all of the instance variables and methods defined by the superclass and adds its own,
unique elements.
▪ To inherit a class, simply incorporate the definition of one class into another by using the
extends keyword.

The syntax of Java Inheritance:


class Subclass-name extends Superclass-name
{
//methods and fields
}

Types of Inheritance:
▪ Single Inheritance
▪ Multilevel Inheritance
▪ Multiple Inheritance
▪ Hierarchical Inheritance
▪ Hybrid Inheritance

1. Single Inheritance
• When a subclass is derived simply from its parent class then this mechanism is known as
simple inheritance.
• In case of simple inheritance there is only a sub class and its parent class.
• It is also called single inheritance or one level inheritance

2. Multilevel Inheritance

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 29


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

• When a subclass is derived from a derived class then this mechanism is known as the
multilevel inheritance.
• The derived class is called the subclass or child class for it's parent class and this parent class
works as the child class for it's just above ( parent ) class.
• Multilevel inheritance can go up to any number of level.

3. Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as hierarchical inheritance.

Program 8. Write a Java Program to implement inheritance and demonstrate use of method
overriding.

import java.lang.*;
class College
{
College()
{
System.out.println("SAKEC ");
}
}

class Department extends College


{
Department ()
{
System.out.println("Department of AI & DS ");
}
}

class Employee extends Department


{
int empID;
String empName;
Employee(int empID, String empName)
{
this.empID=empID;
this.empName=empName;
System.out.println("Emp Id= "+empID);
System.out.println("Emp Name= "+empName);
}
}

class Student extends Department


{
int stdRoll;
String stdName;
Student(int stdRoll, String stdName)
{
this.stdRoll=stdRoll;
this.stdName=stdName;
System.out.println("Student Roll No.= "+stdRoll);

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 30


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

System.out.println("Student Name= "+stdName);


}
}

class InheritanceTypesDemo
{
public static void main(String arg[])
{
System.out.println("Single Inheritance ");
Department dept=new Department();

System.out.println("\nMultilevel Inheritance");
Employee emp=new Employee (123, "Prof. Ramana Shastri");

System.out.println("\nHirarchical Inheritance");
Student std=new Student (10, "Rakesh Jain");
}
}

Sample Output:

Conclusion: Implemented and demonstrated Program on types of inheritance in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 31


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-9

Aim:
Program on Multiple Inheritance

Theory:

Interfaces:
▪ An interface in Java is a blueprint of a class.
▪ Interfaces are syntactically similar to classes.
▪ It has static constants and abstract methods.
▪ 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.
▪ Once interface is defined, any number of classes can implement an interface.
▪ Also, one class can implement any number of interfaces.

Defining an Interface
▪ An interface is defined much like a class.
▪ This is the general form of an interface:

access interface name


{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

▪ No access specifier: interface is only available to other members of the package in which
it is declared.
▪ Public access specifier: the interface can be used by any other code.
▪ name is the name of the interface, and can be any valid identifier.

Implementing Interfaces

▪ Once an interface has been defined, one or more classes can implement that interface.
▪ To implement an interface, include the implements clause in a class definition, and then create
the methods defined by the interface.
▪ The general form of a class that includes the implements clause looks like this:

class classname [extends superclass] [implements interface [,interface...]]


{
// class-body
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 32


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

▪ If a class implements more than one interface, the interfaces are separated with a comma.
▪ If a class implements two interfaces that declare the same method, then the same method will
be used by clients of either interface.
▪ The methods that implement an interface must be declared public.
▪ Also, the type signature of the implementing method must match exactly the type signature
specified in the interface definition

Multiple inheritance using interface


• If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.
• Multiple inheritance is not supported in the case of class because of ambiguity.
• However, it is supported in case of an interface because there is no ambiguity.
• It is because its implementation is provided by the implementation class.

Program 9. Write a Java Program to implement multiple inheritance and demonstrate use of
interfaces.

interface Citizen
{
String name="Raman";
abstract void showCitizen();
}

interface Employee
{
int eno=75;
int salary=50000;
abstract void showEmployee();
}

class Professor implements Citizen,Employee


{
int publications=100;
public void showCitizen()
{
System.out.println("Name="+name);
}
public void showEmployee()
{
System.out.println("Employee number="+eno+"\nSalary="+salary);
}
public void showProfessor()
{

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 33


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

System.out.println("Publications="+publications);
}
}

class MultiInheriInterfaceDemo
{
public static void main(String args[])
{
Professor p=new Professor();
p.showCitizen();
p.showEmployee();
p.showProfessor();
}
}

Sample Output:

Conclusion: Implemented and demonstrated Program on Multiple Inheritance in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 34


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-10

Aim:
Program on Exception handling

Theory:

Exception-Handling Fundamentals

▪ A Java exception is an object that describes an exceptional (that is, error) condition that has
occurred in a piece of code.
▪ When an exceptional condition arises, an object representing that exception is created and
thrown in the method that caused the error.
▪ That method may choose to handle the exception itself, or pass it on.
▪ Either way, at some point, the exception is caught and processed.
▪ Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code.
▪ Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java
language or the constraints of the Java execution environment.
▪ The unexpected situations that may occur during program execution are:
• Running out of memory
• Resource allocation errors
• Inability to find files
• Problems in network connectivity

▪ Java exception handling is managed via five keywords:


➢try
➢catch
➢throw
➢throws
➢finally
▪ Program statements that you want to monitor for exceptions are contained within a try block.
▪ If an exception occurs within the try block, it is thrown.
▪ Your code can catch this exception (using catch) and handle it in some rational manner.
▪ System-generated exceptions are automatically thrown by the Java run-time system.
▪ To manually throw an exception, use the keyword throw.
▪ Any exception that is thrown out of a method must be specified as such by a throws clause.
Any code that absolutely must be executed after a try block completes is put in a finally block.

General form of an exception-handling block:

try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 35


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

// exception handler for ExceptionType2


}
// ...
finally
{
// block of code to be executed after try block ends
}

try Block:
▪ The java code that you think may produce an exception is placed within a try block for a
suitable catch block to handle the error.
▪ If no exception occurs the execution proceeds with the finally block else it will look for the
matching catch block to handle the error.
▪ Again if the matching catch handler is not found execution proceeds with the finally block and
the default exception handler throws an exception.
catch Block:
▪ Exceptions thrown during execution of the try block can be caught and handled in a catch
block.
▪ On exit from a catch block, normal execution continues and the finally block is executed
(Though the catch block throws an exception).
finally Block:
▪ A finally block is always executed, regardless of the cause of exit from the try block, or
whether any catch block was executed.
▪ Generally finally block is used for freeing resources, cleaning up, closing connections etc.

Program 10. Write a Java program to implement the concept of Exception Handling using
predefined exception.

import java.io.*;
import java.util.*;
class ExceptionHandlingDemo
{
public static void main(String ar[])throws IOException
{
int a,b,res;
Scanner sc=new Scanner(System.in);
System.out.println("Enter 2 numbers:");
a=sc.nextInt();
b=sc.nextInt();

try
{
res=a/b;
System.out.println("The Quotient="+res);
}
catch(ArithmeticException e)
{
System.out.println("\nException has occored,You have entered the Divisor as
Zero\n"+e);

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 36


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

}
finally
{
System.out.println("\nIn finally block..");
}
}
}

Sample Output 1:

Sample Output 2:

Conclusion: Implemented and demonstrated Program on Exception handling in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 37


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-11

Aim:
Program on user defined exception

Theory:

User defined exception


▪ Although Java’s built-in exceptions handle most common errors, you will probably want to
create your own exception types to handle situations specific to your applications.
▪ This is quite easy to do: just define a subclass of Exception class (which is, of course, a
subclass of Throwable).
▪ Your subclasses don’t need to actually implement anything—it is their existence in the type
system that allows you to use them as exceptions.
▪ The Exception class does not define any methods of its own.
▪ It does inherit methods provided by Throwable.
▪ Thus, all exceptions, including those that you create, have the methods defined by Throwable
available to them.

The Methods Defined by Throwable:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 38


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Program 11. Write a Java program to implement the concept of Exception Handling by creating
user defined exceptions.

import java.lang.Exception;
import java.lang.*;
import java.lang.Exception;
import java.io.DataInputStream;

class MyException extends Exception


{
MyException(String message)
{
super(message);
}
}

class UserDefinedExceptionDemo
{
public static void main(String a[])
{
int age;
DataInputStream ds=new DataInputStream(System.in);
try
{
System.out.println("Enter the age (above 15 and below 25) :");
age=Integer.parseInt(ds.readLine());
if(age<15 || age> 25)
{
throw new MyException("Number not in range");
}
System.out.println(" the number is :" +age);
}
catch(MyException e)
{
System.out.println("Caught MyException");
System.out.println(e.getMessage());
}
catch(Exception e)
{
System.out.println(e);
}
}
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 39


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Sample Output 1:

Sample Output 2:

Conclusion: Implemented and demonstrated Program on user defined exception in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 40


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-12

Aim:
Program on Multithreading.

Theory:

JAVA Threads
▪ 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 a thread, and each thread defines a separate path of
execution.
▪ Thus, multithreading is a specialized form of multitasking.
▪ Multithreading enables you to write very efficient programs that make maximum use of the
CPU, because idle time can be kept to a minimum.
▪ Multitasking threads require less overhead than multitasking processes.

Thread Life Cycle

In Java, a thread always exists in any one of the following states.


1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
1. New:
6. Whenever a new thread is created, it is always in the new state.
7. For a thread in the new state, the code has not been run yet and thus has not begun its
execution.
2. Active:
▪ When a thread invokes the start() method, it moves from the new state to the active state.
▪ The active state contains two states within it.
➢ runnable
➢ running
▪ Runnable:
▪ A thread, that is ready to run is then moved to the runnable state.
▪ In the runnable state, the thread may be running or may be ready to run at any given
instant of time.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 41


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

▪ It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the
thread the running state.
▪ A program implementing multithreading acquires a fixed slice of time to each individual
thread.
▪ Each and every thread runs for a short span of time and when that allocated time slice is
over, the thread voluntarily gives up the CPU to the other thread, so that the other
threads can also run for their slice of time.
▪ Whenever such a scenario occurs, all those threads that are willing to run, waiting for
their turn to run, lie in the runnable state.
▪ In the runnable state, there is a queue where the threads lie.
▪ Running:
▪ When the thread gets the CPU, it moves from the runnable to the running state.
▪ Generally, the most common change in the state of a thread is from runnable to running
and again back to runnable.

3. Blocked or Waiting:
▪ Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in
the blocked state or is in the waiting state.
▪ For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in
the blocked state.
▪ A thread in the blocked state is unable to perform any execution and thus never consume any
cycle of the Central Processing Unit (CPU).
▪ Hence, we can say that thread A remains idle until the thread scheduler reactivates thread A,
which is in the waiting or blocked state.
▪ When the main thread invokes the join() method then, it is said that the main thread is in the
waiting state.
▪ The main thread then waits for the child threads to complete their tasks. When the child threads
complete their job, a notification is sent to the main thread, which again moves the thread from
waiting to the active state.
▪ If there are a lot of threads in the waiting or blocked state, then it is the duty of the thread
scheduler to determine which thread to choose and which one to reject, and the chosen thread is
then given the opportunity to run.

4. Timed Waiting:
▪ Sometimes, waiting for leads to starvation.
▪ For example, a thread (its name is A) has entered the critical section of a code and is not
willing to leave that critical section. In such a scenario, another thread (its name is B)
has to wait forever, which leads to starvation.
▪ To avoid such scenario, a timed waiting state is given to thread B.
▪ Thus, thread lies in the waiting state for a specific span of time, and not forever.
▪ A real example of timed waiting is when we invoke the sleep() method on a specific
thread. The sleep() method puts the thread in the timed wait state. After the time runs
out, the thread wakes up and start its execution from when it has left earlier.
5. Terminated:
▪ A thread reaches the termination state because of the following reasons:
➢ When a thread has finished its job, then it exists or terminates normally.
➢ Abnormal termination: It occurs when some unusual events such as an
unhandled exception or segmentation fault.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 42


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

▪ A terminated thread means the thread is no more in the system. In other words, the thread
is dead, and there is no way one can respawn (active after kill) the dead thread.

Program. 12. Write a Java program to implement the concept of threading by extending Thread
Class.

import java.lang.Thread;
class A extends Thread
{
public void run()
{
System.out.println("thread A is sterted:");
for(int i=1;i<=5;i++)
{
System.out.println("\t from thread A:i="+i);
}
System.out.println("exit from thread A:");
}
}
class B extends Thread
{
public void run()
{
System.out.println("thread B is sterted:");
for(int j=1;j<=5;j++)
{
System.out.println("\t from thread B:j="+j);
}
System.out.println("exit from thread B:");
}
}
class C extends Thread
{
public void run()
{
System.out.println("thread C is sterted:");
for(int k=1;k<=5;k++)
{
System.out.println("\t from thread C:k="+k);
}
System.out.println("exit from thread C:");
}
}
class ThreadDemo
{
public static void main(String arg[])
{
new A().start();
new B().start();
new C().start();
}

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 43


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Sample Output 1:

Sample Output 2:

Conclusion: Implemented and demonstrated Program on Multithreading in Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 44


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

EXPERIMENT-13

Aim:
Program on Graphics class

Theory:

Graphics Class Functions


▪ The Graphics class defines a number of drawing functions.
▪ Each shape can be drawn edge-only or filled.
▪ Objects are drawn and filled in the currently selected graphics color, which is black by default.
▪ When a graphics object is drawn that exceeds the dimensions of the window, output is
automatically clipped.

Commonly used methods of Graphics class:


▪ public abstract void drawString(String str, int x, int y)
is used to draw the specified string.
▪ public void drawRect(int x, int y, int width, int height)
draws a rectangle with the specified width and height.
▪ public abstract void fillRect(int x, int y, int width, int height)
is used to fill rectangle with the default color and specified width and height.
▪ public abstract void drawOval(int x, int y, int width, int height)
is used to draw oval with the specified width and height.
▪ public abstract void fillOval(int x, int y, int width, int height)
is used to fill oval with the default color and specified width and height.
▪ public abstract void drawLine(int x1, int y1, int x2, int y2)
is used to draw line between the points(x1, y1) and (x2, y2).
▪ public abstract void drawLine(int x1, int y1, int x2, int y2)
is used to draw line between the points(x1, y1) and (x2, y2).
▪ public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
is used draw the specified image.
▪ public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
is used draw a circular or elliptical arc.
▪ public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
is used to fill a circular or elliptical arc.
▪ public abstract void setColor(Color c)
is used to set the graphics current color to the specified color.
▪ public abstract void setFont(Font font)
is used to set the graphics current font to the specified font.

Program. 13.A. Write a Java program using Applet to display a message in the Applet to
demonstrate Graphics class.

/* Java CODE: Appletdemo.java*/

import java.applet.Applet;
import java.awt.Graphics;

public class Appletdemo extends Applet

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 45


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

{
public void paint(Graphics g)
{
String msg="HELLO!, Welcome to my applet ";
g.drawString(msg,80,150);
}
}

/* HTML CODE: Appletdemo.html*/

<HTML>
<HEAD>
<TITLE>Welcome to JAVA Applet Demo</TITLE>
</HEAD>
<BODY>
<APPLET CODE="Appletdemo.class" width=300 height=300>
</APPLET>
</BODY>
</HTML>

Sample Output:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 46


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Program. 13.B. Write a Java program using Applet to draw a Smiley in the Applet to
demonstrate Graphics class.

/* Java CODE: GraphicsDemo.java*/

import java.awt.*;
import java.applet.*;

public class GraphicsDemo extends Applet


{
public void paint(Graphics g)
{
g.drawOval(80, 70, 150, 150);
g.setColor(Color.YELLOW);
g.fillOval(120, 120, 15, 15);
g.fillOval(170, 120, 15, 15);
g.setColor(Color.RED);
g.drawArc(130, 180, 50, 20, 180, 180);
}
}

Sample Output:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 47


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Conclusion: Implemented and demonstrated Program on Graphics class in Java.

EXPERIMENT-14

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 48


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Aim:
Program to create GUI application

Theory:

AWT Program in Java

AWT stands for Abstract window toolkit is an Application programming interface (API) for creating
Graphical User Interface (GUI) in Java. It allows Java programmers to develop window-based
applications.

AWT provides various components like button, label, checkbox, etc. used as objects inside
a Java Program. AWT components use the resources of the operating system, i.e., they are platform-
dependent, which means, component's view can be changed according to the view of the operating
system. The classes for AWT are provided by the Java.awt package for various AWT components.

The following image represents the hierarchy for Java AWT.

Program. 14. Write a Java program to create GUI application with event handling using AWT
controls.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 49


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

import java.awt.event.*;
import java.awt.*;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.awt.Button;
//import java.awt.Frame;
//import java.awt.Label;
//import java.awt.TextField;
//import java.awt.event.WindowAdapter;
//import java.awt.event.WindowEvent;

class AWTLogin implements ActionListener


{
Button b1;
TextField t1, t2;
Label lb1, lb2, lb3, lb4;
Frame f;
AWTLogin()
{
f = new Frame("Awt Login Window");

lb1 = new Label("Enter ID :");


lb1.setBounds(5, 50, 150, 30);
f.add(lb1);

t1 = new TextField();
t1.setBounds(200, 50, 150, 30);
f.add(t1);

t2 = new TextField();
t2.setBounds(200, 80, 150, 30);
f.add(t2);

lb2 = new Label("Enter Password :");


lb2.setBounds(5, 80, 150, 30);
f.add(lb2);

lb3 = new Label("Result :");


lb3.setBounds(90, 140, 150, 30);
f.add(lb3);

b1 = new Button("Login");
b1.setBounds(90, 200, 100, 30);
f.add(b1);

b1.addActionListener(this);

f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 50


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

System.exit(0);
}
}
);

f.setLayout(null);
f.setSize(600, 500);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int c = 0;
if (e.getSource().equals(b1))
{
if (t1.getText().equals("Admin") && (t2.getText().equals("123")))
{
lb3.setText(String.valueOf("Success login!"));
}
else
{
lb3.setText(String.valueOf("Invalid login!"));
}
}
}
public static void main(String args[])
{
AWTLogin t = new AWTLogin();
}
}

Sample Output:

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 51


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Conclusion: Implemented and demonstrated Program to create GUI application in Java.

EXPERIMENT-15

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 52


SKILL BASED LABORATORY: OBJECT ORIENTED PROGRAMMING WITH JAVA LAB MANUAL

Aim:
Mini Project using concepts of Java.

Conclusion: Implemented and demonstrated Mini Project based on concepts of Java.

DEPT. OF ARTIFICIAL INTELLIGENCE & DATA SCIENCE / SAKEC / 2021-2022 53

You might also like