Extc Oop Using Java Labmanuala.y.2017-2018
Extc Oop Using Java Labmanuala.y.2017-2018
EXPERIMENT NO 1
THEORY:The command line argument is the argument passed to a program at the time when you
run it. To access the command-line argument inside a java program is quite easy, they are stored as
string in String array passed to the args parameter of main() method.
1.The Echo example displays each of its command-line arguments on a line by itself:
public class echo {
public static void main (String[] args) {
for (String s: args) {
System.out.println(s);
}
}
}
OutPut:student@ACPCE:~/Desktop$ javac echo.java
student@ACPCE:~/Desktop$ java echo java program
java
program
student@ACPCE:~/Desktop$
EXPERIMENT NO 2
AIM : To Study simple java programs
PROBLEM STATEMENT :
1. WAP to calculate area & circumference of circle
2.WAP to swap given two strings
3.WAP to separate out digits of a number
4.WAP to convert temperature from Fahrenheit to Celsius.
5.WAP to find a square , squarroot, and Cube of a given no.
THEORY:Understanding first java program see what is the meaning of class, public, static, void,
main, String[], System.out.println().
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible to all.
static is a keyword, if we declare any method as static, it is known as static method. The
core advantage of static method is that there is no need to create object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create object to
invoke the main method. So it saves memory.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used print statement. We will learn about the internal working of
System.out.println statement later.
Program: 1.WAP to calculate area & circumference of circle
public class Area
{
public static void main(String[] args)
{
int r;
double pi = 3.14, area;
r = 5;
area = pi * r * r;
System.out.println("Area of circle:"+area);
}
}
OutPut:
student@ACPCE:~/Desktop$ javac Area.java
student@ACPCE:~/Desktop$ java Area
Area of circle:78.5
student@ACPCE:~/Desktop$
class digit
{public static void main(String args[]){
int x = 1234, y, z;
y = x /1000 ;
System.out.println(" The digit in the Thousand's place = "+y);
z = x % 1000;
y = z /100;
System.out.println("\n The digit in the Hundred's place = "+y);
z = z % 100;
y = z / 10;
System.out.println("\n The digit in the Ten's place = "+y);
y = z % 10;
System.out.println("\n The digit in the Unit's place = "+y);
}
}
student@ACPCE:~/Desktop$
fahrenheit = 37.77;
celsius = (fahrenheit-32)*(0.5556);
System.out.println("Temperature in Celsius:"+celsius);
}
OutPut:
student@ACPCE:~/Desktop$ javac FTOC.java
student@ACPCE:~/Desktop$ java FTOC
Temperature in Celsius:3.2058120000000017
student@ACPCE:~/Desktop$
EXPERIMENT NO 3
THEORY:Java Operators
Java provides a rich set of operators enviroment. Java operators can be devided into following
categories
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in algebra.
operator description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
Relation operators
The following table shows all relation operators supported by Java.
operator description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;
operator description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise &, | and ^
Assignment Operators
Assignment operator supported by Java are as follows
Program 1:
public class compare {
public static void main(String[] args)
{
int num1 = 324;
int num2 = 234;
EXPERIMENT NO 4
AIM : To study various ways of accepting data through keyboard & display its content.
PROBLEM STATEMENT :
1.WAP to Read data through DataInputstream.
2. WAP to Read data through Scanner.
3. WAP to Read data through BufferedReader.
THEORY:Reading data from keyboard. There are many ways to read data from the keyboard. For
example:
DataInputStream
Scanner
Console etc.
Output:
J-A-V-A
Method Description
public String next() it returns the next token from the scanner.
it moves the scanner position to the next line and returns the value as a
public String nextLine()
string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double
it scans the next token as a double value.
nextDouble()
EXPERIMENT NO 5
THEORY:
Concept of Array in Java
An array is a collection of similar data types. Array is a container object that hold values of
homogenous type. It is also known as static data structure because size of an array must be
specified at the time of its declaration.
An array can be either primitive or reference type. It gets memory in heap area. Index of array
starts from zero to size-1.
Features of Array
It is always indexed. Index begins from 0.
It is a collection of similar data types.
It occupies a contiguous memory location.
Array Declaration
Syntax :
datatype[ ] identifier;
or
datatype identifier[ ];
Both are valid syntax for array declaration. But the former is more readable.
Example :
int[ ] arr;
char[ ] arr;
short[ ] arr;
long[ ] arr;
int[ ][ ] arr; // two dimensional array.
Initialization of Array
new operator is used to initialize an array.
Example :
int[ ] arr = new int[10]; //this creates an empty array named arr of integer type whose size is 10.
or
int[ ] arr = {10,20,30,40,50}; //this creates an array named arr whose elements are given.
The above code will print the 4th element of array arr on console.
Note: To find the length of an array, we can use the following syntax: array_name.length. There
are no braces infront of length. Its not length().
foreach or enhanced for loop
J2SE 5 introduces special type of for loop called foreach loop to access elements of array. Using
foreach loop you can access complete array sequentially without using index of array. Let us see an
example of foreach loop.
class Test
{
public static void main(String[] args)
{
int[] arr = {10, 20, 30, 40};
for(int x : arr)
{
System.out.println(x);
}
}
}
Output :
10
20
30
40
Multi-Dimensional Array
A multi-dimensional array is very much similar to a single dimensional array. It can have multiple
rows and multiple columns unlike single dimensional array, which can have only one full row or
one full column.
Array Declaration
Syntax:
datatype[ ][ ] identifier;
or
datatype identifier[ ][ ];
Example:
int arr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
System.out.println("Element at (2,3) place" + arr[1][2]);
Jagged Array
Jagged means to have an uneven edge or surface. In java, a jagged array means to have a multi-
dimensional array with uneven size of rows in it.
//addition of matrices.
int[][] resultMatix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
First matrix is :
72
53
Second matrix is :
21
31
*/
program for matrix subtraction
import java.util.Scanner;
//Subtraction of matrices.
int[][] resultMatix = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatix[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
First matrix is :
72
53
Second matrix is :
21
31
*/
//Multiply matrices
int[][] productMatrix = new int[rowsMatrix1][columnsMatrix2];
for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
for (int k = 0; k < columnsMatrix1RowsMatrix2; k++) { //columns in matrix1= rows in matrix2
productMatrix[i][j] = productMatrix[i][j] + matrix1[i][k] * matrix2[k][j];
}
}
}
/*OUTPUT
Enter number of rows in first matrix : 2
Enter number of columns in first matrix / rows in matrix2: 3
Enter number of columns in second matrix : 2
Enter the first matrix in elements :
1
2
3
4
5
6
Enter the second matrix elements:
7
8
9
10
11
12
First matrix is :
123
456
Second matrix is :
78
9 10
11 12
EXPERIMENT NO 6
Objects in Java
Let us now look deep into what are objects. If we consider the real-world, we can find many
objects around us, cars, dogs, humans, etc. All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking, wagging
the tail, running.
If you compare the software object with a real-world object, they have very similar characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields and
behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-to-
object communication is done via methods.
Classes in Java
A class is a blueprint from which individual objects are created.
Following is a sample of a class.
Example
public class Dog {
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
Constructors
When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class, the Java compiler
builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Following is an example of a constructor
Example
public class Puppy {
public Puppy() {
}
Java also supports Singleton Classes where you would be able to create only one instance of a
class.
Note We have two different types of constructors. We are going to discuss constructors in detail
in the subsequent chapters.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a class
Declaration A variable declaration with a variable name with an object type.
Instantiation The 'new' keyword is used to create the object.
Initialization The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Following is an example of creating an object
Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}
Output
Passed Name is :tommy
Example
This example explains how to access instance variables and methods of a class.
public class Puppy {
int puppyAge;
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
Java Package
In simple words, it is a way of categorizing the classes and interfaces. When developing
applications in Java, hundreds of classes and interfaces will be written, therefore categorizing these
classes is a must as well as makes life much easier.
Import Statements
In Java if a fully qualified name, which includes the package and the class name is given, then the
compiler can easily locate the source code or classes. Import statement is a way of giving the
proper location for the compiler to find that particular class.
For example, the following line would ask the compiler to load all the classes available in directory
java_installation/java/io
import java.io.*;
Example
import java.io.*;
public class Employee {
String name;
int age;
String designation;
double salary;
As mentioned previously in this tutorial, processing starts from the main method. Therefore, in
order for us to run this Employee class there should be a main method and objects should be
created. We will be creating a separate class for these tasks.
Following is the EmployeeTest class, which creates two instances of the class Employee and
invokes the methods for each object to assign values for each variable.
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Save the following code in EmployeeTest.java file.
import java.io.*;
public class EmployeeTest {
empTwo.empAge(21);
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
}
Now, compile both the classes and then run EmployeeTest to see the result as follows
Output
C:\> javac Employee.java
C:\> javac EmployeeTest.java
C:\> java EmployeeTest
Name:James Smith
Age:26
Designation:Senior Software Engineer
Salary:1000.0
Name:Mary Anne
Age:21
Designation:Software Engineer
Salary:500.0
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Program:Bank Account
import java.util.Scanner;
class bankInternal {
int acno;
float bal=0;
Scanner get = new Scanner(System.in);
bankInternal()
{
System.out.println("Enter Account Number:");
acno = get.nextInt();
System.out.println("Enter Initial Balance:");
bal = get.nextFloat();
}
void deposit()
{
float amount;
System.out.println("Enter Amount to be Deposited:");
amount = get.nextFloat();
bal = bal+amount;
System.out.println("Deposited! Account Balance is "+bal);
}
void withdraw()
{
float amount;
System.out.println("Enter Amount to be Withdrawn:");
amount = get.nextFloat();
if(amount<bal)
{
EXPERIMENT NO 7
1. convert to lowercase
2. convert to uppercase
3. Replace all appearance of one character by another
4.Compare two strings
5. Derive the substring of a string
6.Derive the position of a character in a string
7.Calculate the length of a string
8. Derive the nth character of a string
THEORY:
Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its
value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has 11 constructors that allow you to provide the initial value of the
string using different sources, such as an array of characters.
public class StringDemo {
Output
hello.
Note The String class is immutable, so that once it is created a String object cannot be changed.
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
If there is a necessity to make a lot of modifications to Strings of characters, then you should use
String Buffer & String Builder Classes.
String Length
Methods used to obtain information about an object are known as accessor methods. One accessor
method that you can use with strings is the length() method, which returns the number of characters
contained in the string object.
The following program is an example of length(), method String class.
Example
public class StringDemo {
Output
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in
"My name is ".concat("Zara");
which results in
"Hello, world!"
Example
public class StringDemo {
Output
Dot saw I was Tod
Example
System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
String Methods
Here is the list of methods supported by String class
int compareTo(Object o)
2
Compares this String to another Object.
6 Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.
byte getBytes()
12 Encodes this String into a sequence of bytes using the platform's default charset, storing
the result into a new byte array.
int hashCode()
15
Returns a hash code for this string.
17 Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.
19 Returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.
String intern()
20
Returns a canonical representation for the string object.
22 Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.
24 Returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.
int length()
25
Returns the length of this string.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
27
Tests if two string regions are equal.
29 Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.
30 Replaces each substring of this string that matches the given regular expression with the
given replacement.
31 Replaces the first substring of this string that matches the given regular expression with the
given replacement.
char[] toCharArray()
39
Converts this string to a new character array.
String toLowerCase()
40 Converts all of the characters in this String to lower case using the rules of the default
locale.
41 Converts all of the characters in this String to lower case using the rules of the given
Locale.
String toString()
42
This object (which is already a string!) is itself returned.
String toUpperCase()
43 Converts all of the characters in this String to upper case using the rules of the default
locale.
String trim()
45
Returns a copy of the string, with leading and trailing whitespace omitted.
import java.io.*;
public class T {
OutPut:
student@ACPCE:~/Desktop$ javac T.java
student@ACPCE:~/Desktop$ java T
Return Value :WELCOME TO TUTORIALSPOINT.COM
student@ACPCE:~/Desktop$
OutPut:
student@ACPCE:~/Desktop$ javac T.java
student@ACPCE:~/Desktop$ java T
Return Value :welcome to tutorialspoint.com
student@ACPCE:~/Desktop$
OutPut:
student@ACPCE:~/Desktop$ javac E.java
student@ACPCE:~/Desktop$ java E
Strings bre bn importbnt pbrt of the Jbvb progrbmming lbngubge
Strings br1 bn importbnt pbrt of th1 Jbvb progrbmming lbngubg1
STrings br1 bn imporTbnT pbrT of Th1 Jbvb progrbmming lbngubg1
STrings br1 bn imorTbnT brT of Th1 Jbvb rogrbmming lbngubg1
STrings br1 bn imorTbnT brT of Th1 Thatbvb rogrbmming lbngubg1
student@ACPCE:~/Desktop$
OutPut:
student@ACPCE:~/Desktop$ javac T.java
student@ACPCE:~/Desktop$ java T
true
true
false
student@ACPCE:~/Desktop$
EXPERIMENT NO 8
class Student3{
int id;
String name;
Student3(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1 = new Student3(111,"Karan");
Student3 s2 = new Student3(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
student@ACPCE:~/Desktop$ javac Student3.java
student@ACPCE:~/Desktop$ java Student3
111 Karan
222 Aryan
student@ACPCE:~/Desktop$
EXPERIMENT NO 9
AIM : To Study Interface in java.
PROBLEM STATEMENT :1.Create an interface Area & implement the same
in different classes Rectangle ,circle ,triangle.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface
Example
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears
in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal {
Output
Mammal eats
Mammal travels
When overriding methods defined in interfaces, there are several rules to be followed
Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so, interface methods need not be
implemented.
When implementation interfaces, there are several rules
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, in a similar way as a class can extend another
class.
Extending Interfaces
An interface can extend another interface in the same way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of
the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.
Example
// Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.
Example
public interface Hockey extends Sports, Event
interface area
{
double pi = 3.14;
double calc(double x,double y);
}
class A
{
public static void main(String arg[])
{
rect r = new rect();
cir c = new cir();
area a;
a = r;
System.out.println("\nArea of Rectangle is : " +a.calc(10,20));
a = c;
System.out.println("\nArea of Circle is : " +a.calc(15,15));
}
}
OutPut:
student@ACPCE:~/Desktop$ javac A.java
student@ACPCE:~/Desktop$ java A
Area of Rectangle is : 200.0
Area of Circle is : 706.5
EXPERIMENT NO 10
Output :
Child method
Parent method
String modelType;
public void showDetail()
{
vehicleType = "Car"; //accessing Vehicle class member
modelType = "sports";
System.out.println(modelType+" "+vehicleType);
}
public static void main(String[] args)
{
Car car =new Car();
car.showDetail();
}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
}
Output :
sports Car
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
super keyword
In Java, super keyword is used to refer to immediate parent class of a child class. In other words
super keyword is used by a subclass whenever it need to refer to its immediate super class.
}
public class Child extends Parent {
String name;
public void details()
{
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Output :
Parent and Child
Example of Child class refering Parent class methods using super keyword
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Output :
Parent
Child
public Parent(String n)
{
name = n;
}
}
public class Child extends Parent {
String name;
Output :
Parent and Child
Note: When calling the parent class constructor from the child class using super keyword, super
keyword should always be the first line in the method/constructor of the child class.
Super class reference pointing to Sub class object.
In context to above example where Class B extends class A.
A a=new B();
is legal syntax because of IS-A relationship is there between class A and Class B.
Program :
class staff
{
String code;
String name;
public staff(String c, String n)
{
code = c;
name = n;
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
}
/* set/get methods for the staff code. */
public void setCode(String c)
{
code = c;
}
public String getCode()
{
return code;
}
/* set/get methods for the staff name. */
public void setName(String n)
{
name = n;
}
public String getName()
{
return name;
}
}
/* This class represents all the teacher staff */
class teacher extends staff
{
private String subject;
private String publication;
String code;
/* Input parameters for the constructor are:
String c: staff code.
String n: staff name.
*/
public teacher(String c, String n)
{
super(c, n);
}
/* Input parameters for the constructor are:
String c: staff code.
String n: staff name.
String sub: teacher subject.
String pub: array of teacher publication
*/
public teacher(String c, String n, String sub, String pub)
{
super(c, n);
subject = sub;
publication = pub;
}
public void setCode(String s)
{
super.setCode(s);
}
/* set/get methods for subject */
public void setSubject(String s)
{
subject = s;
}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
public String[] getSubject()
{
return subject;
}
/* set/get methods for publications */
public void setPublication(String p)
{
publication = p;
}
public String getPublication()
{
return publication;
}
}
/* This class represents all typist staff */
class typist extends staff
{
int speed;
/* Input parameters for the constructor are:
String c: staff code.
String n: staff name.
int s: typist speed.
*/
public typist(String c, String n, int s)
{
super(c, n);
speed = s;
}
/* set/get methods for the typist speed. */
public void setSpeed(int s)
{
speed = s;
}
public int getSpeed()
{
return speed;
}
}
/* This class represents all the officer staff */
class officer extends staff
{
int grade;
/* Constructor input parameters are:
String c: staff code.
String n: staff name.
int g: officer's grade.
*/
public officer(String c, String n, int g)
{
super(c, n);
grade = g;
}
/* set and get methods for the officers' grade */
public void setGrade(int g)
{
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
grade = g;
}
public int getGrade()
{
return grade;
}
}
/* This class represents all the regular typist staff */
class regular extends typist
{
/* Input parameters for the constructor are:
String c: staff code.
String n: staff name.
int s: typist speed.
*/
public regular(String c, String n, int s)
{
super(c, n, s);
}
}
/* This class represents all casual typists */
class casual extends typist
{
float daily_wages;
/* Input parameters for the constructor are:
of a casual typist:
String c: staff code.
String n: staff name.
int s: typist speed.
float w: casual's daily wages.
*/
public casual(String c, String n, int s, float w)
{
super(c, n, s);
daily_wages = w;
}
/* This method set the daily wages for a casual staff */
public void setWages(float w)
{
daily_wages = w;
}
/* This method returns the amount of the daily wages */
public float getWages()
{
return daily_wages;
}
}
EXPERIMENT NO 11
These import statements bring the classes into the scope of our applet class
java.applet.Applet
java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the file through
an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example
that invokes the "Hello, World" applet
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code = "HelloWorldApplet.class" width = "320" height = "120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Note You can refer to HTML Applet Tag to understand more about calling applet from HTML.
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an applet runs. The applet
directive must be closed with an </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding <param> tags
between <applet> and </applet>. The browser ignores text and other tags between the applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To
specify otherwise, use the codebase attribute of the <applet> tag as shown
<applet codebase = "https://amrood.com/applets" code = "HelloWorldApplet.class"
width = "320" height = "120">
If an applet resides in a package other than the default, the holding package must be specified in the
code attribute using the period character (.) to separate package/class components. For example
<applet = "mypackage.subpackage.TestApplet.class"
width = "320" height = "120">
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
setBackground (Color.black);
setForeground (fg);
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the
library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt()
throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad
input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a
series of string comparisons to match the parameter value to the name of a predefined color. You
need to implement these methods to make this applet work.
Event Handling
Applets inherit a group of event-handling methods from the Container class. The Container class
defines several methods, such as processKeyEvent and processMouseEvent, for handling particular
types of events, and then one catch-all method called processEvent.
In order to react to an event, an applet must override the appropriate event-specific method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
Initially, the applet will display "initializing the applet. Starting the applet." Then once you click
inside the rectangle, "mouse clicked" will be displayed as well.
Displaying Images
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image
within the applet, you use the drawImage() method found in the java.awt.Graphics class.
Following is an example illustrating all the steps to show images
import java.applet.*;
import java.awt.*;
import java.net.*;
Playing Audio
An applet can play an audio file represented by the AudioClip interface in the java.applet package.
The AudioClip interface has three methods, including
public void play() Plays the audio clip one time, from the beginning.
public void loop() Causes the audio clip to replay continually.
public void stop() Stops playing the audio clip.
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class.
The getAudioClip() method returns immediately, whether or not the URL resolves to an actual
audio file. The audio file is not downloaded until an attempt is made to play the audio clip.
Following is an example illustrating all the steps to play an audio
import java.applet.*;
import java.awt.*;
import java.net.*;
program:
import java.awt.*;
import java.applet.*;
publicclass LineRect extends Applet {
publicvoid paint(Graphics g) {
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.setColor(Color.blue);
g.fillRect(60,10,30,80);
g.setColor(Color.green);
g.drawRoundRect(10,100,80,50,10,10);
g.setColor(Color.yellow);
g.fillRoundRect(20,110,60,30,5,5);
g.setColor(Color.red);
g.drawLine(100,10,230,140);
g.drawLine(100,140,230,10);
g.drawString("Line Rectangles Demo",65,180);
g.drawOval(230,10,200,150);
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
g.setColor(Color.blue);
g.fillOval(245,25,100,100); } }
;import java.awt.*;
import java.applet.*;
publicclass LineRect extends Applet {
publicvoid paint(Graphics g) {
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.setColor(Color.blue);
g.fillRect(60,10,30,80);
g.setColor(Color.green);
g.drawRoundRect(10,100,80,50,10,10);
g.setColor(Color.yellow);
g.fillRoundRect(20,110,60,30,5,5);
g.setColor(Color.red);
g.drawLine(100,10,230,140);
g.drawLine(100,140,230,10);
g.drawString("Line Rectangles Demo",65,180);
g.drawOval(230,10,200,150);
g.setColor(Color.blue);
g.fillOval(245,25,100,100); } };