0% found this document useful (0 votes)
128 views71 pages

Extc Oop Using Java Labmanuala.y.2017-2018

The document discusses various operators in Java including arithmetic, relational, logical, and bitwise operators. It provides examples of using different operators and their behavior. It also discusses left and right shift operators and how they work with binary values.

Uploaded by

Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
128 views71 pages

Extc Oop Using Java Labmanuala.y.2017-2018

The document discusses various operators in Java including arithmetic, relational, logical, and bitwise operators. It provides examples of using different operators and their behavior. It also discusses left and right shift operators and how they work with binary values.

Uploaded by

Prakash
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 71

Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 1

AIM : To study command line argument in Java.


PROBLEM STATEMENT :
1.WAP To Implement Echoing Command-Line Arguments.
2. WAP To Implement Parsing Numeric Command-Line arguments.

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$

OutPut:student@ACPCE:~/Desktop$ javac echo.java


student@ACPCE:~/Desktop$ java echo "java program"
java program
student@ACPCE:~/Desktop$
2.Parsing Numeric Command-Line Arguments
public class add {
public static void main(String[] args) {
int sum = 0;
for (int i = 0; i < args.length; i++) {
sum = sum + Integer.parseInt(args[i]);
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
}
System.out.println("The sum of the arguments passed is " + sum);
}
}
OutPut:
student@ACPCE:~/Desktop$ javac add.java
student@ACPCE:~/Desktop$ java add 1 2 3 4 5
The sum of the arguments passed is 15
student@ACPCE:~/Desktop$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

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$

Program: 2.WAP to swap given two strings.


public class swapstring
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
{ public static void main(String[] input)
{ String str1, str2, strtemp;
str1 = "ABC"; str2 = "PQR";
System.out.println("\nStrings before Swapping are :");
System.out.print("String 1 = " +str1+ "\n");
System.out.print("String 2 = " +str2+ "\n");
strtemp = str1;
str1 = str2;
str2 = strtemp;
System.out.println("\nStrings after Swapping are :");
System.out.print("String 1 = " +str1+ "\n");
System.out.print("String 2 = " +str2+ "\n");
}
}
OutPut:
student@ACPCE:~/Desktop$ javac swapstring.java
student@ACPCE:~/Desktop$ java swapstring

Strings before Swapping are :


String 1 = ABC
String 2 = PQR

Strings after Swapping are :


String 1 = PQR
String 2 = ABC
student@ACPCE:~/Desktop$
Program: 3.WAP to separate out digits of a number

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);
}
}

OutPut::student@ACPCE:~/Desktop$ javac digit.java

student@ACPCE:~/Desktop$ java digit

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
The digit in the Thousand's place = 1

The digit in the Hundred's place = 2

The digit in the Ten's place = 3

The digit in the Unit's place = 4

student@ACPCE:~/Desktop$

Program: 4.WAP to convert temperature from Fahrenheit to Celsius


public class FTOC
{
public static void main(String[] args)
{

double celsius, fahrenheit;

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$

Program: 5.WAP to find a square , squarroot, and Cube of a given no.


public class j5 {
public static void main(String args[]){
int num;
num=5;
System.out.println("Square of "+ num + " is: "+ Math.pow(num, 2));
System.out.println("Cube of "+ num + " is: "+ Math.pow(num, 3));
System.out.println("Square Root of "+ num + " is: "+ Math.sqrt(num));
}
}
OutPut:student@ACPCE:~/Desktop$ javac j5.java
student@ACPCE:~/Desktop$ java j5
Square of 5 is: 25.0
Cube of 5 is: 125.0
Square Root of 5 is: 2.23606797749979
student@ACPCE:~/Desktop$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 3

AIM : To Study of different operators in java


PROBLEM STATEMENT :
1.WAP to compare two numbers.
2.WAP to print truth table for java logical operators
3. WAP to read the number & shift left & right by 3 bits.

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 example


&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false
Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short, char
and byte

operator description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
Now lets see truth table for bitwise &, | and ^

a b a&b a|b a^b


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
The bitwise shift operators shifts the bit value. The left operand specifies the value to be shifted
and the right operand specifies the number of positions that the bits in the value are to be shifted.
Both operands have the same precedence.
Example
a = 0001000
b= 2
a << b= 0100000
a >> b= 0000010

Assignment Operators
Assignment operator supported by Java are as follows

operator description example


= assigns values from right side operands to left side operand a=b
a+=b is same as
+= adds right operand to the left operand and assign the result to left
a=a+b
subtracts right operand from the left operand and assign the
-= a-=b is same as a=a-b
result to left operand
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
mutiply left operand with the right operand and assign the result a*=b is same as
*=
to left operand a=a*b
divides left operand with the right operand and assign the result
/= a/=b is same as a=a/b
to left operand
calculate modulus using two operands and assign the result to a%=b is same as
%=
left operand a=a%b
Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression
epr1 ? expr2 : expr3

If epr1Condition is true? Then value expr2 : Otherwise value expr3


instanceOf operator
This operator is used for object reference variables. The operator checks whether the object is of
particular type (class type or interface type)

Program 1:
public class compare {
public static void main(String[] args)
{
int num1 = 324;
int num2 = 234;

if(num1 > num2){


System.out.println(num1 + " is greater than " + num2); }
else if(num1 < num2){
System.out.println(num1 + " is less than " + num2);
}
else{
System.out.println(num1 + " is equal to " + num2);
}
}
}
OutPut:student@ACPCE:~/Desktop$ javac compare.java
student@ACPCE:~/Desktop$ java compare
324 is greater than 234
student@ACPCE:~/Desktop$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Program 2.WAP to print truth table for java logical operators
public class TT {
public static void main( String[] args ) {
boolean p, q;
System.out.println( "Part 1: Exercise conditional AND and OR operators");
System.out.println( "=========================================");
System.out.println( " p q (p ^ q) (p v q)" );
System.out.println( "=========================================");
p = true; q = true;
System.out.printf( "%8s %8s %11s %11s\n", p, q, p && q, p || q );
p = false; q = true;
System.out.printf( "%8s %8s %11s %11s\n", p, q, p && q, p || q );
p = true; q = false;
System.out.printf( "%8s %8s %11s %11s\n", p, q, p && q, p || q );
p = false; q = false;
System.out.printf( "%8s %8s %11s %11s\n", p, q, p && q, p || q );
System.out.println( "==========================================");
System.out.println( "");
System.out.println( "Part 2: Exercise logical negation operator");
System.out.println( "=========================================");
System.out.println( " p !p " );
System.out.println( "=========================================");
p = true;
System.out.printf( "%8s %8s \n", p, !p );
p = false;
System.out.printf( "%8s %8s \n", p, !p );
System.out.println( "=========================================");
}
}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
OutPut:
student@ACPCE:~/Desktop$ javac TT.java
student@ACPCE:~/Desktop$ java TT
Part 1: Exercise conditional AND and OR operators
=========================================
p q (p ^ q) (p v q)
=========================================
true true true true
false true false true
true false false true
false false false false
==========================================

Part 2: Exercise logical negation operator


=========================================
p !p
=========================================
true false
false true
=========================================
student@ACPCE:~/Desktop$
Program 3: WAP to read the number & shift left & right by 3 bits.
class Test {
public static void main(String args[]) {
//right shift
int x = -4;
System.out.println(x>>1);
int y = 4;
System.out.println(y>>1);
//left shift
byte a = 64, b;
int i;
i = a << 2;
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
b = (byte) (a << 2);
System.out.println("i and b: " + i + " " + b);
}
}
OutPut:
student@ACPCE:~/Desktop$ javac Test.java
student@ACPCE:~/Desktop$ java Test
-2
2
i and b: 256 0
student@ACPCE:~/Desktop$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

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.

1.Java DataInputStream Class


Java DataInputStream class allows an application to read primitive data from the input stream in a
machine-independent way.
Java application generally uses the data output stream to write data that can later be read by a data
input stream.

Java DataInputStream class declaration


Let's see the declaration for java.io.DataInputStream class:
public class DataInputStream extends FilterInputStream implements DataInput

Java DataInputStream class Methods


Method Description
int read(byte[] b) It is used to read the number of bytes from the input stream.
int read(byte[] b, int off, int len) It is used to read len bytes of data from the input stream.
int readInt() It is used to read input bytes and return an int value.
byte readByte() It is used to read and return the one input byte.
char readChar() It is used to read two input bytes and returns a char value.
double readDouble() It is used to read eight input bytes and returns a double value.
It is used to read one input byte and return true if byte is non zero,
boolean readBoolean()
false if byte is zero.
int skipBytes(int x) It is used to skip over x bytes of data from the input stream.
It is used to read a string that has been encoded using the UTF-8
String readUTF()
format.
It is used to read bytes from the input stream and store them into
void readFully(byte[] b)
the buffer array.
void readFully(byte[] b, int off,
It is used to read len bytes from the input stream.
int len)
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Program 1: DataInputStream class
In this example, we are reading the data from the file testout.txt file.
import java.io.*;
public class DataStreamExample {
public static void main(String[] args) throws IOException {
InputStream input = new FileInputStream("D:\\testout.txt");
DataInputStream inst = new DataInputStream(input);
int count = input.available();
byte[] ary = new byte[count];
inst.read(ary);
for (byte bt : ary) {
char k = (char) bt;
System.out.print(k+"-");
}
}
}
OutPut:
Here, we are assuming that you have following data in "testout.txt" file:
JAVA

Output:
J-A-V-A

2.Java Scanner class


There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is whitespace bydefault.
It provides many methods to read and parse various primitive values.
Java Scanner class is widely used to parse text for string and primitive types using regular
expression.
Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Commonly used methods of Scanner class
There is a list of commonly used Scanner class methods:

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()

Program 2.Java Scanner Example to get input from console


Let's see the simple example of the Java Scanner class which reads the int, string and double value
as an input:
import java.util.Scanner;
class ST{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("Enter your rollno");
int rollno=sc.nextInt();
System.out.println("Enter your name");
String name=sc.next();
System.out.println("Enter your fee");
double fee=sc.nextDouble();
System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);
}
}
OutPut:
Enter your rollno
111
Enter your name
Ratan
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Enter
450000
Rollno:111 name:Ratan fee:450000

Java Console Class


The Java Console class is be used to get input from console. It provides methods to read texts and
passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
Let's see a simple example to read text from console.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Java Console class declaration
Let's see the declaration for Java.io.Console class:
public final class Console extends Object implements Flushable

Java Console class methods


Method Description
It is used to retrieve the reader object associated with the
Reader reader()
console
String readLine() It is used to read a single line of text from the console.
String readLine(String fmt, It provides a formatted prompt then reads the single line of text
Object... args) from the console.
It is used to read password that is not being displayed on the
char[] readPassword()
console.
char[] readPassword(String fmt, It provides a formatted prompt then reads the password that is
Object... args) not being displayed on the console.
Console format(String fmt, It is used to write a formatted string to the console output
Object... args) stream.
Console printf(String format,
It is used to write a string to the console output stream.
Object... args)
It is used to retrieve the PrintWriter object associated with the
PrintWriter writer()
console.
void flush() It is used to flushes the console.
How to get the object of Console
System class provides a static method console() that returns the singleton instance of Console class.
public static Console console(){}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Let's see the code to get the instance of Console class.
Console c=System.console();
Java Console Example
import java.io.Console;
class ReadStringTest{
public static void main(String args[]){
Console c=System.console();
System.out.println("Enter your name: ");
String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output
Enter your name: Nakul Jain
Welcome Nakul Jain

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 5

AIM : To study Arrays in Java


PROBLEM STATEMENT : 1.Write a program for addition, subtraction and
multiplication of two matrices.

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.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Accessing array element
As mention ealier array index starts from 0. To access nth element of an array. Syntax
arrayname[n-1];

Example : To access 4th element of a given array


int[ ] arr = {10,20,30,40};
System.out.println("Element at 4th place" + arr[3]);

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[ ][ ];

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Initialization of Array
new operator is used to initialize an array.
Example:
int[ ][ ] arr = new int[10][10]; //10 by 10 is the size of array.
or
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
// 3 by 5 is the size of the array.

Accessing array element


For both, row and column, the index begins from 0.
Syntax:
array_name[m-1][n-1]

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.

Initialization of Jagged Array


new operator is used to initialize an array.
Example:
int[ ][ ] arr = new int[3][ ]; //there will be 10 arrays whose size is variable
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[5];

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Program Matrix Addition
import java.util.Scanner;

public class MatrixAddition {

public static void main(String...args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows in matrix : "); //rows and columns in matrix1 and matrix2 must be same
for addition.
int rows = scanner.nextInt();
System.out.print("Enter number of columns in matrix : ");
int columns = scanner.nextInt();
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];

System.out.println("Enter the elements in first matrix :");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("Enter the elements in second matrix :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

//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];
}
}

System.out.println("\nFirst matrix is : ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}

System.out.println("\nSecond matrix is : ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}

System.out.println("\nThe sum of the two matrices is : ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatix[i][j] + " ");
}
System.out.println();
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
}
}
}
/*OUTPUT

Enter number of rows in matrix : 2


Enter number of columns in matrix : 2
Enter the elements in first matrix :
7
2
5
3
Enter the elements in second matrix :
2
1
3
1

First matrix is :
72
53

Second matrix is :
21
31

The sum of the two matrices is :


93
84

*/
program for matrix subtraction
import java.util.Scanner;

public class MatrixSubtraction {

public static void main(String...args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows in matrix : "); //rows and columns in matrix1 and matrix2 must be same
for subtraction.
int rows = scanner.nextInt();
System.out.print("Enter number of columns in matrix : ");
int columns = scanner.nextInt();
int[][] matrix1 = new int[rows][columns];
int[][] matrix2 = new int[rows][columns];

System.out.println("Enter the elements in first matrix :");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("Enter the elements in second matrix :");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
matrix2[i][j] = scanner.nextInt();
}
}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

//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];
}
}

System.out.println("\nFirst matrix is : ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}

System.out.println("\nSecond matrix is : ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}

System.out.println("\nThe subtraction of the two matrices is : ");


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatix[i][j] + " ");
}
System.out.println();
}
}
}
/*OUTPUT
Enter number of rows in matrix : 2
Enter number of columns in matrix : 2
Enter the elements in first matrix :
7
2
5
3
Enter the elements in second matrix :
2
1
3
1

First matrix is :
72
53

Second matrix is :
21
31

The subtraction of the two matrices is :


Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
51
22

*/

program Matrix Multiplication


import java.util.Scanner;

public class MatrixMultiplication {

public static void main(String...args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter number of rows in first matrix : ");


int rowsMatrix1 = scanner.nextInt();
System.out.print("Enter number of columns in first matrix / rows in matrix2: ");
int columnsMatrix1RowsMatrix2 = scanner.nextInt(); //variable name used for understanding convenience,
because columns in matrix1 = rows in matrix2
System.out.print("Enter number of columns in second matrix : ");
int columnsMatrix2 = scanner.nextInt();

int[][] matrix1 = new int[rowsMatrix1][columnsMatrix1RowsMatrix2];


int[][] matrix2 = new int[columnsMatrix1RowsMatrix2][columnsMatrix2];
System.out.println("Enter the first matrix in elements :");
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

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


for (int i = 0; i < matrix2.length; i++) {
for (int j = 0; j < matrix2[0].length; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

//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];
}
}
}

System.out.println("\nFirst matrix is : ");


for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix1RowsMatrix2; j++) {
System.out.print(matrix1[i][j] + " ");
}
System.out.println();
}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

System.out.println("\nSecond matrix is : ");


for (int i = 0; i < columnsMatrix1RowsMatrix2; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
System.out.print(matrix2[i][j] + " ");
}
System.out.println();
}

System.out.println("\nProduct of matrix1 and matrix2 is");


for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < columnsMatrix2; j++) {
System.out.print(productMatrix[i][j] + " ");
}
System.out.println();
}
}

/*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

Product of matrix1 and matrix2 is:


58 64
139 154

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 6

AIM : To Study of Objects and Classes


PROBLEM STATEMENT 1.WAP To Implement Define a class to represent a bank
account. Include the following members:
Data:
1. name of the depositor
2. account number
3. type of account
4. balance amount in the account
Methods:
1.to assign initial values
2.to deposit an amount
3.to withdraw an amount after checking balance.
4.to display the name & balance
THEORY:
Classes and Objects.
Object Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors wagging the tail, barking, eating. An object is an instance of a class.
Class A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.

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() {
}
}

A class can contain any of the following variable types.


Local variables Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable
will be destroyed when the method has completed.
Instance variables Instance variables are variables within a class but outside any method.
These variables are initialized when the class is instantiated. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
Class variables Class variables are variables declared within a class, outside any method,
with the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the
above example, barking(), hungry() and sleeping() are methods.
Following are some of the important topics that need to be discussed when looking into classes of
the Java Language.

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() {
}

public Puppy(String name) {


Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
// This constructor has one parameter, name.
}
}

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 );
}

public static void main(String []args) {


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}
f we compile and run the above program, then it will produce the following result

Output
Passed Name is :tommy

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an instance variable,
following is the fully qualified path
/* First create an object */
ObjectReference = new Constructor();
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

Example
This example explains how to access instance variables and methods of a class.
public class Puppy {
int puppyAge;

public Puppy(String name) {


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

public int getAge( ) {


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}
If we compile and run the above program, then it will produce the following result

Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

Source File Declaration Rules


As the last part of this section, let's now look into the source file declaration rules. These rules are
essential when declaring classes, import statements and package statements in a source file.
There can be only one public class per source file.
A source file can have multiple non-public classes.
The public class name should be the name of the source file as well which should be
appended by .java at the end. For example: the class name is public class Employee{} then
the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should be the first
statement in the source file.
If import statements are present, then they must be written between the package statement
and the class declaration. If there are no package statements, then the import statement
should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It is
not possible to declare different import and/or package statements to different classes in the
source file.
Classes have several access levels and there are different types of classes; abstract classes, final
classes, etc. We will be explaining about all these in the access modifiers chapter.
Apart from the above mentioned types of classes, Java also has some special classes called Inner
classes and Anonymous classes.

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.*;

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

A Simple Case Study


For our case study, we will be creating two classes. They are Employee and EmployeeTest.
First open notepad and add the following code. Remember this is the Employee class and the class
is a public class. Now, save this source file with the name Employee.java.
The Employee class has four instance variables - name, age, designation and salary. The class has
one explicitly defined constructor, which takes a parameter.

Example
import java.io.*;
public class Employee {

String name;
int age;
String designation;
double salary;

// This is the constructor of the class Employee


public Employee(String name) {
this.name = name;
}

// Assign the age of the Employee to the variable age.


public void empAge(int empAge) {
age = empAge;
}

/* Assign the designation to the variable designation.*/


public void empDesignation(String empDesig) {
designation = empDesig;
}

/* Assign the salary to the variable salary.*/


public void empSalary(double empSalary) {
salary = empSalary;
}

/* Print the Employee details */


public void printEmployee() {
System.out.println("Name:"+ name );
System.out.println("Age:" + age );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + 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 {

public static void main(String args[]) {


/* Create two objects using constructor */
Employee empOne = new Employee("James Smith");
Employee empTwo = new Employee("Mary Anne");

// Invoking methods for each object created


empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();

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)
{

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
bal = bal-amount;
System.out.println("Amount Withdrawn!! Available Balance: "+bal);
}
else
{
System.out.println("Insufficient funds!!");
}
}
}

public class Bank {


public static void main(String[] args)
{
bankInternal myObj = new bankInternal();
myObj.deposit();
myObj.withdraw();
}
}
OutPut:
student@ACPCE:~/Desktop$ javac Bank.java
student@ACPCE:~/Desktop$ java Bank
Enter Account Number:
1234
Enter Initial Balance:
2000
Enter Amount to be Deposited:
400
Deposited! Account Balance is 2400.0
Enter Amount to be Withdrawn:
300
Amount Withdrawn!! Available Balance: 2100.0
student@ACPCE:~/Desktop$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 7

AIM : To Study of Strings in Java.


PROBLEM STATEMENT :Accept the two strings from user & do the following operations

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 {

public static void main(String args[]) {


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This will produce the following result

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 {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}

This will produce the following result

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");

Strings are more commonly concatenated with the + operator, as in


"Hello," + " world" + "!"

which results in
"Hello, world!"

Let us look at the following example

Example
public class StringDemo {

public static void main(String args[]) {


Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}

This will produce the following result

Output
Dot saw I was Tod

Creating Format Strings


You have printf() and format() methods to print output with formatted numbers. The String class
has an equivalent class method, format(), that returns a String object rather than a PrintStream
object.
Using String's static format() method allows you to create a formatted string that you can reuse, as
opposed to a one-time print statement. For example, instead of

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);

You can write


String fs;
fs = String.format("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);
System.out.println(fs);

String Methods
Here is the list of methods supported by String class

Sr.No. Method & Description


char charAt(int index)
1
Returns the character at the specified index.

int compareTo(Object o)
2
Compares this String to another Object.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
int compareTo(String anotherString)
3
Compares two strings lexicographically.

int compareToIgnoreCase(String str)


4
Compares two strings lexicographically, ignoring case differences.

String concat(String str)


5
Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb)

6 Returns true if and only if this String represents the same sequence of characters as the
specified StringBuffer.

static String copyValueOf(char[] data)


7
Returns a String that represents the character sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count)


8
Returns a String that represents the character sequence in the array specified.

boolean endsWith(String suffix)


9
Tests if this string ends with the specified suffix.

boolean equals(Object anObject)


10
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)


11
Compares this String to another String, ignoring case considerations.

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.

byte[] getBytes(String charsetName)


13
Encodes this String into a sequence of bytes using the named charset, storing the result into
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
a new byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


14
Copies characters from this string into the destination character array.

int hashCode()
15
Returns a hash code for this string.

int indexOf(int ch)


16
Returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)

17 Returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.

int indexOf(String str)


18
Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)

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.

int lastIndexOf(int ch)


21
Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(int ch, int fromIndex)

22 Returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.

int lastIndexOf(String str)


23
Returns the index within this string of the rightmost occurrence of the specified substring.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
int lastIndexOf(String str, int fromIndex)

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 matches(String regex)


26
Tells whether or not this string matches the given regular expression.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
27
Tests if two string regions are equal.

boolean regionMatches(int toffset, String other, int ooffset, int len)


28
Tests if two string regions are equal.

String replace(char oldChar, char newChar)

29 Returns a new string resulting from replacing all occurrences of oldChar in this string with
newChar.

String replaceAll(String regex, String replacement

30 Replaces each substring of this string that matches the given regular expression with the
given replacement.

String replaceFirst(String regex, String replacement)

31 Replaces the first substring of this string that matches the given regular expression with the
given replacement.

String[] split(String regex)


32
Splits this string around matches of the given regular expression.

String[] split(String regex, int limit)


33
Splits this string around matches of the given regular expression.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
boolean startsWith(String prefix)
34
Tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)


35
Tests if this string starts with the specified prefix beginning a specified index.

CharSequence subSequence(int beginIndex, int endIndex)


36
Returns a new character sequence that is a subsequence of this sequence.

String substring(int beginIndex)


37
Returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)


38
Returns a new string that is a substring of this string.

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.

String toLowerCase(Locale 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 toUpperCase(Locale locale)


44

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Converts all of the characters in this String to upper case using the rules of the given
Locale.

String trim()
45
Returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(primitive data type x)


46
Returns the string representation of the passed data type argument.

Program 1.String toUpperCase() Method

import java.io.*;
public class T {

public static void main(String args[]) {


String Str = new String("Welcome to Tutorialspoint.com");

System.out.print("Return Value :" );


System.out.println(Str.toUpperCase() );
}
}

OutPut:
student@ACPCE:~/Desktop$ javac T.java
student@ACPCE:~/Desktop$ java T
Return Value :WELCOME TO TUTORIALSPOINT.COM
student@ACPCE:~/Desktop$

Program 2.String toLowerCase() Method


import java.io.*;
public class Test {

public static void main(String args[]) {


String Str = new String("Welcome to Tutorialspoint.com");

System.out.print("Return Value :");


System.out.println(Str.toLowerCase());
}
}

OutPut:
student@ACPCE:~/Desktop$ javac T.java
student@ACPCE:~/Desktop$ java T
Return Value :welcome to tutorialspoint.com
student@ACPCE:~/Desktop$

Program 3:Replace all appearance of one character by another


import java.lang.String;
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
public class E {
public static void main(String[] args) {
String str = "Strings are an important part of the Java programming language";
String Str1 = str.replaceAll("a", "b");
System.out.println(Str1);
Str1 = Str1.replaceAll("e", "1");
System.out.println(Str1);
Str1 = Str1.replaceAll("t", "T");
System.out.println(Str1);
Str1 = Str1.replaceAll("p", "");
System.out.println(Str1);
Str1 = Str1.replaceAll("J", "That");
System.out.println(Str1);
}
}

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$

program 4:Compare two strings


class T{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}

OutPut:
student@ACPCE:~/Desktop$ javac T.java
student@ACPCE:~/Desktop$ java T
true
true
false
student@ACPCE:~/Desktop$

Program 5:Derive the substring of a string


public class substring{
public static void main(String args[]){
String s="SachinTendulkar";
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
OutPut:
student@ACPCE:~/Desktop$ javac substring.java
student@ACPCE:~/Desktop$ java substring
Tendulkar
Sachin
student@ACPCE:~/Desktop$

Program 6:Derive the position of a character in a string


public class Pos{
public static void main(String args[]){
String s1="this is index of example";
//passing substring
int index1=s1.indexOf("is");//returns the index of is substring
int index2=s1.indexOf("index");//returns the index of index substring
System.out.println(index1+" "+index2);//2 8
//passing substring with from index
int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index
System.out.println(index3);//5 i.e. the index of another is

//passing char value


int index4=s1.indexOf('s');//returns the index of s char value
System.out.println(index4);//3
}}
OutPut:

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
student@ACPCE:~/Desktop$ javac Pos.java
student@ACPCE:~/Desktop$ java Pos
2 8
5
3
student@ACPCE:~/Desktop$

Program 7:Calculate the length of a string


import java.io.*;
public class Test {
public static void main(String args[]) {
String Str1 = new String("Welcome to Tutorialspoint.com");
String Str2 = new String("Tutorials" );
System.out.print("String Length :" );
System.out.println(Str1.length());
System.out.print("String Length :" );
System.out.println(Str2.length());
}
}
OutPut:
student@ACPCE:~/Desktop$ javac Test.java
student@ACPCE:~/Desktop$ java Test
String Length :29
String Length :9
student@ACPCE:~/Desktop$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 8

AIM : To Study constructors in java.


PROBLEM STATEMENT :1.WAP Default constructor in java
2.WAP Parameterized constructor in java
THEORY:Constructor in Java
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default constructor.
Syntax of default constructor:
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Bike1 b=new Bike1();
}
}
OutPut:
student@ACPCE:~/Desktop$ javac Bike1.java
student@ACPCE:~/Desktop$ java Bike1
Bike is created
student@ACPCE:~/Desktop$

Example of default constructor that displays the default values


class Student3{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
OutPut:
student@ACPCE:~/Desktop$ javac Student3.java
student@ACPCE:~/Desktop$ java Student3
0 null
0 null
student@ACPCE:~/Desktop$

Java parameterized constructor


A constructor that have parameters is known as parameterized constructor.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Why use parameterized constructor?
Parameterized constructor is used to provide different values to the distinct objects.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters. We can
have any number of parameters in the constructor.

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$

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

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.

THEORY:An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
Along with abstract methods, an interface may also contain constants, default methods, static
methods, and nested types. Method bodies exist only for default methods and static methods.
Writing an interface is similar to writing a class. But a class describes the attributes and behaviors
of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.
An interface is similar to a class in the following ways
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
However, an interface is different from a class in several ways, including
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.

Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Example
Following is an example of an interface
/* File name : NameOfInterface.java */
import java.lang.*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}

Interfaces have the following properties


An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.

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 {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
public static void main(String args[]) {
MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This will produce the following result

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.

Extending Multiple Interfaces


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as

Example
public interface Hockey extends Sports, Event

Program:Area using Interface

interface area
{
double pi = 3.14;
double calc(double x,double y);
}

class rect implements area


{
public double calc(double x,double y)
{
return(x*y);
}
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
}

class cir implements area


{
public double calc(double x,double y)
{
return(pi*x*x);
}
}

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

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
student@ACPCE:~/Desktop$

EXPERIMENT NO 10

AIM : To Study of Inheritance


PROBLEM STATEMENT :1.Create an interface Area & implement the same
in different classes Rectangle ,circle ,triangle.

THEORY:Inheritance is one of the key features of Object Oriented Programming. Inheritance


provided mechanism that allowed a class to inherit property of another class. When a Class
extends another class it inherits all non-private members including fields and methods. Inheritance
in Java can be best understood in terms of Parent and Child relationship, also known as Super
class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub class. extends and
implements keywords are used to describe inheritance in Java.

Let us see how extends keyword is used to achieve Inheritance.


class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}

Now based on above example. In OOPs term we can say that,


Vehicle is super class of Car.
Car is sub class of Vehicle.
Car IS-A Vehicle.
Purpose of Inheritance
1. It promotes the code reusabilty i.e the same methods and variables which are defined in a
parent/super/base class can be used in the child/sub/derived class.
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
2. It promotes polymorphism by allowing method overriding.
Disadvantages of Inheritance
Main disadvantage of using inheritance is that the two classes (parent and child class) gets tightly
coupled.
This means that if we change code of parent class, it will affect to all the child classes which is
inheriting/deriving the parent class, and hence, it cannot be independent of each other.
Simple example of Inheritance
class Parent
{
public void p1()
{
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1()
{
System.out.println("Child method");
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}

Output :
Child method
Parent method

Another example of Inheritance


class Vehicle
{
String vehicleType;
}
public class Car extends Vehicle {

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

Why multiple inheritance is not supported in Java


To remove ambiguity.
To provide more maintainable and clear design.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

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.

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Example of Child class refering Parent class property using super keyword
class Parent
{
String name;

}
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

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Example of Child class calling Parent class constructor using super keyword
class Parent
{
String name;

public Parent(String n)
{
name = n;
}

}
public class Child extends Parent {
String name;

public Child(String n1, String n2)


{

super(n1); //passing argument to parent class constructor


this.name = n2;
}
public void details()
{
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child("Parent","Child");
cobj.details();
}
}

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;
}
}

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

EXPERIMENT NO 11

AIM : To Study graphics using applet.


PROBLEM STATEMENT :WAP to draw all geometric shapes and fill them with different
colors.
THEORY:An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following
An applet is a Java class that extends the java.applet.Applet class.
A main() method is not invoked on an applet, and an applet class will not define main().
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is
downloaded to the user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser
or a separate runtime environment.
The JVM on the user's machine creates an instance of the applet class and invokes various
methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an
applet is often referred to as sandbox security, comparing the applet to a child playing in a
sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any serious applet
init This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
start This method is automatically called after the browser calls the init method. It is also
called whenever the user returns to the page containing the applet after having gone off to
other pages.
stop This method is automatically called when the user moves off the page on which the
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
behind after a user leaves the page that contains the applet.
paint Invoked immediately after the start() method, and also any time the applet needs to
repaint itself in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet


Following is a simple applet named HelloWorldApplet.java
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}

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.

The Applet Class


Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the browser
context.
These include methods that do the following
Get applet parameters
Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
Print a status message in the browser
Fetch an image
Fetch an audio clip
Play an audio clip
Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may
Request information about the author, version, and copyright of the applet
Request a description of the parameters the applet recognizes
Initialize the applet
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
Destroy the applet
Start the applet's execution
Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.

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

Getting Applet Parameters


The following example demonstrates how to make an applet respond to setup parameters specified
in the document. This applet displays a checkerboard pattern of black and a second color.
The second color and the size of each square may be specified as parameters to the applet within
the document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the paint()
method. However, getting the values and saving the settings once at the start of the applet, instead
of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init()
once, immediately after loading the applet. (Applet.init() is implemented to do nothing.) Override
the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's name (the value of a
parameter is always a string). If the value is numeric or other non-character data, the string must be
parsed.
The following is a skeleton of CheckerApplet.java
import java.applet.*;
import java.awt.*;

public class CheckerApplet extends Applet {


int squareSize = 50; // initialized to default size
public void init() {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}

Here are CheckerApplet's init() and private parseSquareSize() methods


public void init () {
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);

String colorParam = getParameter ("color");


Color fg = parseColor (colorParam);

setBackground (Color.black);
setForeground (fg);
}

private void parseSquareSize (String param) {


if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}catch (Exception e) {
// Let default value remain
}

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
}

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.

Specifying Applet Parameters


The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML
file specifies both parameters to the applet by means of the <param> tag.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code = "CheckerApplet.class" width = "480" height = "320">
<param name = "color" value = "blue">
<param name = "squaresize" value = "30">
</applet>
<hr>
</html>

Note Parameter names are not case sensitive.

Application Conversion to Applets


It is easy to convert a graphical Java application (that is, an application that uses the AWT and that
you can start with the Java program launcher) into an applet that you can embed in a web page.
Following are the specific steps for converting an application to an applet.
Make an HTML page with the appropriate tag to load the applet code.
Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet cannot
be loaded.
Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object. The browser instantiates it
for you and calls the init method.
Remove the call to setSize; for applets, sizing is done with the width and height parameters
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
in the HTML file.
Remove the call to setDefaultCloseOperation. An applet cannot be closed; it terminates
when the browser exits.
If the application calls setTitle, eliminate the call to the method. Applets cannot have title
bars. (You can, of course, title the web page itself, using the HTML title tag.)
Don't call setVisible(true). The applet is displayed automatically.

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;

public class ExampleEventHandling extends Applet implements MouseListener {


StringBuffer strBuffer;

public void init() {


addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}

public void start() {


addItem("starting the applet ");
}

public void stop() {


addItem("stopping the applet ");
}

public void destroy() {


addItem("unloading the applet");
}

void addItem(String word) {


System.out.println(word);
strBuffer.append(word);
repaint();
}

public void paint(Graphics g) {


// Draw a Rectangle around the applet's display area.
g.drawRect(0, 0,
getWidth() - 1,
getHeight() - 1);
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai

// display the string inside the rectangle.


g.drawString(strBuffer.toString(), 10, 20);
}

public void mouseEntered(MouseEvent event) {


}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}

Now, let us call this applet as follows


<html>
<title>Event Handling</title>
<hr>
<applet code = "ExampleEventHandling.class"
width = "300" height = "300">
</applet>
<hr>
</html>

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.*;

public class ImageDemo extends Applet {


private Image image;
private AppletContext context;

public void init() {


context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null) {
imageURL = "java.jpg";
}
try {
URL url = new URL(this.getDocumentBase(), imageURL);
Sem-III Sub:-OOP with Java Programming
Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
image = context.getImage(url);
}catch(MalformedURLException e) {
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
}
}

public void paint(Graphics g) {


context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
g.drawString("www.javalicense.com", 35, 100);
}
}

Now, let us call this applet as follows


<html>
<title>The ImageDemo applet</title>
<hr>
<applet code = "ImageDemo.class" width = "300" height = "200">
<param name = "image" value = "java.jpg">
</applet>
<hr>
</html>

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.*;

public class AudioDemo extends Applet {


private AudioClip clip;
private AppletContext context;

public void init() {


context = this.getAppletContext();
String audioURL = this.getParameter("audio");
if(audioURL == null) {

Sem-III Sub:-OOP with Java Programming


Department of Electronics and Telecommunication ACPCE,Kharghar Navi Mumbai
audioURL = "default.au";
}
try {
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e) {
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}

public void start() {


if(clip != null) {
clip.loop();
}
}

public void stop() {


if(clip != null) {
clip.stop();
}
}
}

Now, let us call this applet as follows


<html>
<title>The ImageDemo applet</title>
<hr>
<applet code = "ImageDemo.class" width = "0" height = "0">
<param name = "audio" value = "test.wav">
</applet>
<hr>
</html>

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); } };

Sem-III Sub:-OOP with Java Programming

You might also like