0% found this document useful (0 votes)
6 views87 pages

Dharmsinh Desai University, Nadiad Department of Information Technology Core Java Technology, IT510 B.Tech. IT, Sem: V

Uploaded by

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

Dharmsinh Desai University, Nadiad Department of Information Technology Core Java Technology, IT510 B.Tech. IT, Sem: V

Uploaded by

20ecuos009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 01 (Problem-1)

Submitted By
Roll No.: IT124
Name: Yasvi Patel

Aim: Write the programs using the concept of nested for loops and recursion.

Note: Write source code, input and output for below programs.

1.1 Generate following pattern:

Code: class Pattern1


{
public static void main(String[] s)
{
for(int i=0;i<4;i++)
{
//print blank spaces
for(int j=0;j<i;j++)
{
System.out.print(" ");
}
//print stars("*")
for(int k=4;k>i;k--)
{
System.out.print("* ");
}
System.out.println();
}
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

1.2 Generate following pattern:

Code: class Pattern2


{
public static void main(String[] s)
{
//upper half
for(int i=0;i<3;i++)
{
//print blank spaces
for(int j=2;j>i;j--)
{
System.out.print(" ");
}
//print stars
for(int k=0;k<=i;k++)
{
System.out.print("* ");
}
System.out.println();
}

//lower half
for(int i=0;i<2;i++)
{
//print blank spaces
for(int j=0;j<i;j++)
{
System.out.print(" ");
}
//print stars
for(int k=2;k>i;k--)
{
System.out.print(" *");
}
System.out.println();
}
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

1.3 Generate following pattern:

Code: class Pattern3


{
public static void main(String[] s)
{
int i,j,k;
for (i= 4; i>= 1; i--)
{
//print blank spaces
for (j=4; j>i;j--)
{
System.out.print(" ");
}
//print stars
for (k=1;k<=i;k++)
{
System.out.print("*");
}
System.out.println("");
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

1.4 Generate following pattern:

Code: public class Pattern4


{
public static void main(String[] args)
{
for (int i= 1; i<=3 ; i++)
{
//print blank spaces
for (int j=i; j<3 ;j++)
{
System.out.print(" ");
}
//print stars
for (int k=1; k<=i;k++)
{
System.out.print("*");
}
System.out.println("");
}

for (int i=3; i>=1; i--)


{
//print blank spaces
for(int j=i; j<=3;j++)
{
System.out.print(" ");
}
//print stars
for(int k=1; k<i ;k++)
{
System.out.print("*");
}
System.out.println("");
}
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 01 (Problem-2 and 3)

Submitted By
Roll No.: IT124
Name: Yasvi Patel

Aim: Write the programs using the concept of nested for loops and recursion.

Note: Write source code, input and output for below programs.

1.2 Write a program that prints Fibonacci series.

Note: Write recursive solution

Code: import java.util.*;

class Fibonacci
{
static int n1=1,n2=2,n3=0;
public static void main(String[] s)
{
//Taking input
System.out.print("Enter Number of terms in Fibonacci Series : ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
//First 2 elements
System.out.println("1");
System.out.println("1");
//Calling Method fib()
fib(num-1);
}

//Recursive method
public static void fib(int n)
{
if(n>1) //To terminate loop
{
n3 = n1+n2;
n1 = n2;
n2 = n3;
System.out.println(n3);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

//Recursion starts here


fib(n-1);
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

1.3 Write a program that finds out sum of digits of a number.

Note: Write recursive solution

Code: import java.util.*;

class SumOfDigit
{
static int sum=0;
public static void main(String[] s)
{
System.out.print("Enter the Number : ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
int sum_of_digit = 0;
//calling method
sum_of_digit = sod(num);
System.out.print("Sum of Digits : "+sum_of_digit);
}

//Recursive method which returns sum of digit


public static int sod(int n)
{
int m=n/10;
sum = sum + n%10;
if(m < 10)
sum = sum+m;
else
sod(m);
return sum;
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 02

Submitted By:
Roll No.: IT124
Name: Yasvi Patel

Aim: Write the programs using the concept of command line argument.

Note: Write source code, input and output for below programs.

2.1 Write a program that implements a command line calculator.

Code:
// Java source code
class argclc {
public static void main(String[] args){
if(args.length == 3){
int x = Integer.parseInt(args[0]); //Converting 1nd arg to Integer
String op = args[1]; //take operator
int y = Integer.parseInt(args[2]); //Converting 2nd arg to Integer
int r=0;
if (op.equals("+")) {
r = x+y;
}
else if (op.equals("-")){
r = x-y;
}
else if (op.equals("x")){
r = x*y;
}
else if (op.equals("/")){
r = x/y;
}
else{
System.out.println("Operator Invalid");
}
System.out.println("result is: "+r); //Result as output
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

}
}

Input/Output:

Input:
6+2
6–2
6x2
6/2
6$2

Output:

2.2 Write a program to implement user interactive calculator.

Code:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

// Java source code


import java.util.*;

class iacalc {
public static void main(String[] args) {
int num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter 1st number:");
num1 = scanner.nextInt();
System.out.print("Enter 2nd number:");
num2 = scanner.nextInt();

System.out.print("Enter an operator : ");


char operator = scanner.next().charAt(0);
int result=0;

switch(operator)
{
case '+':
result = num1 + num2;
break;

case '-':
result = num1 - num2;
break;

case '*':
result = num1 * num2;
break;

case '/':
result = num1 / num2;
break;

default:
System.out.printf("Invalid Operator");
return;
}

System.out.println("result is: "+result);


}
}

Input/Output:

Input:
1st time input
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

6
2
*
2nd time input
6
2
$
Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

2.3 Write a program to print all combinations of four digit number. A four digit number is
generated using only four digits {1, 2, 3, 4} and the number has second digit greater
than first digit and fourth digit is less than third digit.
Case 1: Duplication of digit is allowed.
Case 2: Duplication of digit is not allowed.

Code:
// Java source code
import java.util.*;

class Combination
{
public static void main(String[] s)
{
System.out.print("Enter 1 for Printing with Duplication and 2 for without Duplication : ");
Scanner input = new Scanner(System.in);
int num = input.nextInt();
System.out.println();
System.out.println();
int i,j,k,l;
switch(num){
case 1: //For printing with Duplication
for(i=1;i<5;i++){
for(j=1;j<5;j++){
for(k=1;k<5;k++){
for(l=1;l<5;l++){
if(i<j && k>l){
System.out.print(i);
System.out.print(j);
System.out.print(k);
System.out.print(l);
System.out.print(" ");
}
}
}
}
}
System.out.println();
System.out.println();
break;
case 2: //For printing without Duplication
for(i=1;i<5;i++){
for(j=1;j<5;j++){
for(k=1;k<5;k++){
for(l=1;l<5;l++){
if(i<j && k>l){
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

if(i!=j && i!=k && i!=l && j!=k && j!=l && k!=l){
System.out.print(i);
System.out.print(j);
System.out.print(k);
System.out.print(l);
System.out.print(" ");
}
}
}
}
}
}
System.out.println();
System.out.println();
break;
}
}
}

Input/Output:

Input:
Enter 1 for Printing with Duplication and 2 for without Duplication : 1
Enter 1 for Printing with Duplication and 2 for without Duplication : 2

Output:

2.4 Write a program that prints multiplication table in a matrix format from the number 1
to 10.

Code:
// Java source code
class Multiplication {
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

public static void main(String[] args) {


System.out.print("\t"+"|"+"\t");
for(int k=1;k<=10;k++){
System.out.print(k+"\t");
}
System.out.println();
for(int k=1;k<=10;k++){
System.out.print("--------");
}
System.out.println();
for(int j=1;j<=10;j++){
System.out.print(j+"\t"+"|"+"\t");
for (int i=1;i<=10;i++){
System.out.print(i*j+"\t");
}
System.out.println();
}
}
}
Input/Output:
Input:
Output
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

2.5 Write a program that finds out factorial of a number.

Code:
// Java source code
import java.util.*;
class Factorial {
public static void main(String[] args) {
long num;
Scanner input = new Scanner(System.in);
System.out.print("Enter the number : ");
num = input.nextLong(); //Taking input
int facto = 1;
for(long i = num;i > 0;i--) {
facto *= i;
}
System.out.println("factorial of "+num+" is: "+facto); //output
}
}

Input/Output:

Input:
10

Output:

2.6 Write a program that finds out nth Fibonacci number.

Code:
// Java source code
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

import java.util.*;

class fibonacci1 {
//main Function
public static void main(String args[]) {
int m; //m is maximum number
System.out.print("enter max no: ");
Scanner s=new Scanner(System.in);
m=s.nextInt(); //take input from user

System.out.print("fibonacci series of "+m+" numbers: "); //output

for(int i=1;i<=m;i++)
System.out.print(fibonaccirecursion(i) +" "); //Calling Recursive Function
}

//Recursive Function
public static int fibonaccirecursion(int n) {
if(n==1 || n==2)
return 1;
return fibonaccirecursion(n-2)+fibonaccirecursion(n-1);
}
}

Input/Output:

Input:
10

Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 03

Submitted By:
Roll No.: IT124
Name: Yasvi Patel

Aim: Write the programs using the concept of arrays and StringBuffer class.

Note: Write source code, input and output for below programs.

3.1 Write a program to merge two arrays in third array. Also sort the third array in
ascending order.

Code:
// Java source code
import java.util.*;

public class Merge


{
public static void main(String args[])
{
int n1, n2, n3, i, j, k;
int arr1[] = new int[100];
int arr2[] = new int[100];
int final_array[] = new int[200];
//Defining Scanner for input
Scanner scan = new Scanner(System.in);

//Taking the size of 1nd array


System.out.print("Enter Size of 1st array : ");
n1 = scan.nextInt();
//Taking elements of 1st array
System.out.println("Enter Elements of 1st array : ");
for(i=0; i<n1; i++)
{
arr1[i] = scan.nextInt();
}

//Taking the size of 2nd array


BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

System.out.print("Enter Size of 2nd array: ");


n2 = scan.nextInt();
//Taking elements of 2nd array
System.out.println("Enter Elements of 2nd array: ");
for(i=0; i<n2; i++)
{
arr2[i] = scan.nextInt();
}

//Merging both arrays


System.out.print("After Merge two Arrays \n");
for(i=0; i<n1; i++)
{
final_array[i] = arr1[i];
}
n3 = n1 + n2;
for(i=0, k=n1; k<n3 && i<n2; i++, k++)
{
final_array[k] = arr2[i];
}

//Printing Merged array


System.out.print("Array after Merging :\n");
for(i=0; i<n3; i++)
{
System.out.print(final_array[i] + " ");
}
System.out.println();

//Sorting the final array


for(i=0;i<n3;i++)
{
for(j=i+1;j<n3;j++)
{
if(final_array[i]>final_array[j])
{
int temp=final_array[i];
final_array[i]=final_array[j];
final_array[j]=temp;
}
}
}

//Printing Sorted array


System.out.print("After Sorting Array is :\n");
for(i=0; i<n3; i++)
{
System.out.print(final_array[i] + " ");
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

3.2 Write a program to add and to multiply two int matrices.

Code:
// Java source code
import java.util.*;

public class Add_Mul


{
public static void main(String args[])
{
int a,b,c,d,i,j,k,sum=0;
//Defining the scanner for input
Scanner in=new Scanner(System.in);
//Taking number of rows and columns
System.out.println("Enter the number of rows and column of 1st Matrix");
a=in.nextInt();
b=in.nextInt();
//Declaring the matrix of taken rows and columns
int matrix1[][]=new int [a][b];
//Taking input in matrix
System.out.println("enter the element of 1st Matrix");
for(i=0;i<a;i++)
for(j=0;j<b;j++)
matrix1[i][j]=in.nextInt();

//Taking number of rows and columns


System.out.println("enter the number of rows and column of 2nd matrix");
c=in.nextInt();
d=in.nextInt();
//Declaring the matrix of taken rows and columns
int matrix2[][]=new int [c][d];
//Taking input in matrix
System.out.println("enter the element of 2nd matrix");
for(i=0;i<c;i++)
for(j=0;j<d;j++)
matrix2[i][j]=in.nextInt();

//Addition of both matrix


if(a==c && b==d)
{
int add[][]=new int[a][b];
for(i=0;i<a;i++)
for(j=0;j<b;j++)
add[i][j]=matrix1[i][j]+matrix2[i][j];
//Printing matrix after addition
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

System.out.println("addition is: ");


for(i=0;i<a;i++){
for(j=0;j<b;j++)
System.out.print(add[i][j]+"\t");
System.out.println();
}
}
else
System.out.println("addition is not possible");

//multiplication of both matrix


if(b!=c)
System.out.println("multiplication is not possible");
else
{
int mul[][]=new int[a][d];
for(i=0;i<a;i++){
for(j=0;j<d;j++){
for(k=0;k<c;k++)
sum+=matrix1[i][k]*matrix2[k][j];
mul[i][j]=sum;
sum=0;
}
}
//Printing matrix after multiplication
System.out.println("multiplication is ");
for(i=0;i<a;i++){
for(j=0;j<d;j++)
System.out.print(mul[i][j]+"\t");
System.out.println();
}
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

3.3 Write a program that reads email address from user and check whether email address
is valid or not and separate out email id from email server name.

If input is [email protected]
Output: It is valid address
Email id: abc
Email server address: xyz.com

Code:
// Java source code
import java.util.*;

class Email {
public static void main(String[] s) {
//Define variable input for scanning input
Scanner input = new Scanner(System.in);
System.out.print("Enter the Email : ");
//Take input
String email = input.next();
//Using Regression Expression
if(email.matches("(.*)@(.*)\\.(.*)") == true) {
//If the email obey [email protected] format
//then print valid message
System.out.println("It is valid address");
//Using split function to split string before and after "@"
String[] parts = email.split("[@]");
//First part is Email
System.out.println("Email id : "+parts[0]);
//Second part is email server address
System.out.println("Email server address : "+parts[1]);
}
else {
//If the email does not obey [email protected] format
//then print invalid message
System.out.println("Invalid Address");
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

3.4 Write a program that converts all characters of a string in capital letters. (Use

StringBuffer to store a string). Don’t use any inbuilt function.

Code:
// Java source code
import java.util.*;

class CapitalLetters {
public static void main(String[] s) {
//Define variable input for scanning input
Scanner input = new Scanner(System.in);
System.out.print("Enter the string : ");

//Take input
String str = input.next();

//Store Input string in StringBuffer


StringBuffer buffer = new StringBuffer();
buffer.append(str);

//Defining new StringBuffer to store output value


StringBuffer buff = new StringBuffer();

//Itteration over StringBuffer


for(int i=0;i<buffer.length();i++) {
//Convert Char to it's ASCII value
int c = buffer.charAt(i);
//If there is small letter in string then sub 32 to its ASCII value
//to convert into Capital Letters
if(c >= 97 && c <= 122) {
c = c - 32;
}

//Again convert ASCII to Char datatype


char m = (char)c;
//Store into buff
buff.append(m);
}
//print output of buff
System.out.println(buff);
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 04

Submitted By:
Roll No.:IT124
Name: Yasvi Patel

Aim: Write the programs using the concept of Generic class, Inheritance, Interface and

Package.

Note: Write source code, input and output for below programs.

4.1 Write a program to add and to multiply two matrices using Generic class concept.

Code:
// Java source code
abstract class GenericMatrix{
Object[][] matrix;
GenericMatrix(Object[][] matrix){
this.matrix=matrix;
}
public Object[][] addMatrix(Object[][] matrix){
Object[][] result=new
Object[matrix.length][matrix[0].length];
//check size
if((this.matrix.length!=matrix.length) || (this.matrix[0].length!=matrix[0].length)){
System.out.println("Error: matrices do not have the same size");
System.exit(0);
}
//perform addition
for(int i=0;i<result.length;i++)
for(int j=0;j<result[i].length;j++)
result[i][j]=add(this.matrix[i][j], matrix[i][j]);
return result;
}
public Object[][] multiplyMatrix(Object[][] matrix){
Object[][] result=new
Object[this.matrix.length][matrix[0].length];
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

//check sizes
if(this.matrix[0].length!=matrix.length){
System.out.println("Error: matrices do not have valid size");
System.exit(0);
}
//perform multiplication
for(int i=0;i<result.length;i++)
for(int j=0;j<result[i].length;j++){
result[i][j]=zero();
for(int k=0;k<this.matrix[0].length;k++){
result[i][j]=add(result[i][j],multiply(this.matrix[i][k], matrix[k][j]));
}
}
return result;
}

abstract public Object add(Object o1, Object o2);


abstract public Object multiply(Object o1, Object o2);
abstract public Object zero();

public static void displayMatrix(Object[][] m){


for(int i=0;i<m.length;i++){
for(int j=0;j<m[0].length;j++)
System.out.print(m[i][j].toString()+" ");
System.out.println();
}
}
}

class IntegerMatrix extends GenericMatrix{


IntegerMatrix(Integer[][] matrix){
super(matrix);
}
public Object add(Object o1,Object o2){
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return new Integer(i1.intValue()+i2.intValue());
}
public Object multiply(Object o1,Object o2){
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return new Integer(i1.intValue()*i2.intValue());
}
public Object zero(){
return new Integer(0);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

}
}

class TestIntegerMatrix{
public static void main(String[] args){
Integer[][] m1=new Integer[3][3];
Integer[][] m2=new Integer[3][3];
//initialize two matrices
for(int i=0;i<m1.length;i++)
for(int j=0;j<m1[0].length;j++){
m1[i][j]=new Integer(i);
m2[i][j]=new Integer(i+j);
}
//create an instance of IntegerMatrix
IntegerMatrix im=new IntegerMatrix(m1);
//perform integer matrix addition and multiplication
Object[][] addResult=im.addMatrix(m2);
Object[][] mulResult=im.multiplyMatrix(m2);
//display m1, m2, addResult, and mulResult
System.out.println("m1=");
IntegerMatrix.displayMatrix(m1);
System.out.println("m2=");
IntegerMatrix.displayMatrix(m2);
System.out.println("addResult=");
IntegerMatrix.displayMatrix(addResult);
System.out.println("mulResult=");
IntegerMatrix.displayMatrix(mulResult);
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

4.2 Create an abstract class Shape and derived classes Rectangle and Circle from Shape
class. Implement abstract method of shape class in Rectangle and Circle class. Shape class
contains:
origin (x,y) as data member.
display() and area() as abstract methods.
Circle class contains: radius as data member.
Rectangle class contains: length and width
(Use Inheritance, overloading, and overriding concept)

Code:
// Java source code
import java.lang.Math;

//Abstract class so it's Object cannot be created


abstract class Shape
{
abstract void area(); //abstract method area()
abstract void display(); //abstract method area()
double area; //area variable of double datatype
}

//Derived class of abstract shape class


class Rectangle extends Shape
{
double w=70,h=20;
//Overriding the abstract method area()
void area()
{
//Calculating the Area
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

area = w*h;
}
//Overriding the abstract method display()
void display()
{
//Display Output
System.out.println("area of Rectangle -->"+area);
}
}

class Circle extends Shape


{
double r=5;
//Overriding the abstract method area()
void area()
{
//Calculating the Area
area = Math.PI * r * r;
}
//Overriding the abstract method display()
void display()
{
//Display Output
System.out.println("area of Circle -->"+area);
}
}

class AbstractShape
{
public static void main(String [] args)
{
//Creating object of Rectangle
Rectangle r =new Rectangle();
//Creating object of Circle
Circle c =new Circle();

r.area(); //Calling the area method area() of Rectangle


c.area(); //Calling the area method of area() Circle
r.display(); //Calling the area method display() of Rectangle
c.display(); //Calling the area method display() of Circle
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

4.3 Write a program to show an implementation of Package.

Code:
// Java source code

//Creating 2 folder :

//1st folder contains Display method and its .class file.

//In 1st Folder named b

package b; //To create the importable file

public class Display {


public void display()
{
//Print Output
System.out.println("Accessing from Disp");
}
}

//2nd folder contains Main function for java program

//In 2nd Folder named com

import java.lang.*; //It is necessary as we will change classpath variable


import b.Display; //To import the .class file of Display named package b

public class a {
public static void main(String[] s)
{
//To Display it is in same file
System.out.println("Accessing Default print");
//Creating the object from imported pacakage
Display dobj = new Display();
//Calling Display Method
dobj.display();
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:

4.4 Write a program to show an implementation of Interface.

Code:
// Java source code
class InterfaceImply
{
{
//1st interface
System.out.println("This is Interface Number 1");
}
{
//2st interface
System.out.println("This is Interface Number 2");
}
public static void main(String[] args)
{
//Creating Object to call the Interfaces
InterfaceImply in = new InterfaceImply();
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 05

Submitted By:
Roll No.: IT124
Name: Yasvi Patel

Aim: Write the program which creates the Frame and implements MouseListener.

Note: Write source code, input and output for below programs.

5.1 Write a program to display mouse position when the mouse is pressed.
Code:
// Java source code

import java.awt.*;
import java.awt.event.*;
class MousePressedPosition_ex5 extends Frame implements MouseListener
{
int cx = 0, cy = 0;
public MousePressedPosition_ex5(String title)
{
super(title);
addMouseListener(this);
setVisible(true);
setSize(300,400);
}
public void mousePressed(MouseEvent e)
{
cx = e.getX();
cy = e.getY();
repaint();
}
public void paint(Graphics g)
{
g.drawString("Mouse at X = " + cx,20,100);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

g.drawString("Mouse at Y = " + cy,20,120);


}
public void mouseClicked(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}

public static void main(String[] s)


{
new MousePressedPosition_ex5("Mouse Pressed");
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

5.2 Write a program to display multiplication table in a Frame.

Code:
// Java source code

import java.awt.*;
import java.awt.event.*;
public class MatrixMulFrame extends Frame{
public static void main(String[] args){
MatrixMulFrame f = new MatrixMulFrame();
f.setSize(600,400);
f.setVisible(true);
f.repaint();
}
MatrixMulFrame(){}
public void paint(Graphics g){
for(int i=1;i<=10;i++){
for(int j=1;j<=10;j++){
String str = Integer.toString(i*j);
g.drawString(str,(i*30),30+(j*30));
}
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 06

Submitted By:
Roll No.:IT124
Name:Yasvi Patel

Implementing a GUI based calculator application and drawing different figures on a

Canvas.

Note: Write source code, input and output for below programs.

6.1 Implement a GUI based calculator application. It has two TextFields for two
input numbers, one TextField for result and four Buttons named Add, Sub, Mul and Div
for addition, subtraction, multiplication and division respectively.

Code:
// Java source code

import java.awt.*;
import
java.awt.event.*;

class MyFrame2 extends Frame


{
Label l1,l2;
TextField
t1,t2,t3;
Button add,sub,mul,div;

MyFrame2(String title)
{
super(title);
setVisible(true);
setSize(300,30
0);
setLayout(new FlowLayout());

l1 = new Label("First");
l2 = new
Label("second"); t1 =
new TextField();
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

t2 = new
TextField(); t3 =
new TextField();
add = new
Button("Add"); sub =
new Button("Sub"); mul
= new Button("Mul"); div
= new Button("Div");

add(l1);
add(t1);
add(l2);
add(t2);
add(t3);
add(add);
add(sub);
add(mul);
add(div);
//here no adapter because ActionListener has only one method to
override add.addActionListener(new Addition());
sub.addActionListener(new
Subtraction());
mul.addActionListener(new
Multiplication());
div.addActionListener(new Division());
//Adapter is used if you want to not override all listeners
Interfaces addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent
we){ System.exit(0);
}
});
}

class Addition implements ActionListener


{
public void actionPerformed(ActionEvent
ae){ int n1,n2,n3;
String text;
n1 =
Integer.parseInt(t1.getText());
n2 =
Integer.parseInt(t2.getText());
n3 = n1+n2;
text =
Integer.toString(n3);
t3.setText(text);
}
}
class Subtraction implements ActionListener
{
public void actionPerformed(ActionEvent
ae){ int n1,n2,n3;
String text;
n1 = Integer.parseInt(t1.getText());
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

n2 =
Integer.parseInt(t2.getText());
n3 = n1-n2;
text =
Integer.toString(n3);
t3.setText(text);
}
}
class Multiplication implements ActionListener
{
public void actionPerformed(ActionEvent
ae){ int n1,n2,n3;
String text;
n1 =
Integer.parseInt(t1.getText());
n2 =
Integer.parseInt(t2.getText());
n3 = n1*n2;
text =
Integer.toString(n3);
t3.setText(text);
}
}
class Division implements ActionListener
{
public void actionPerformed(ActionEvent
ae){ int n1,n2,n3;
String text;
n1 =
Integer.parseInt(t1.getText());
n2 =
Integer.parseInt(t2.getText());
n3 = n1/n2;
text =
Integer.toString(n3);
t3.setText(text);
}
}
}

public class Calc


{
public static void main(String[] args)
{
new MyFrame2("Calculator");
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

6.2 Write a program to draw various figures on a Canvas. The user selects figure
from a CheckboxGroup, the selected figure is then displayed in the Canvas.

Code:
// Java source code
import java.awt.*;
import
java.awt.event.*;

class Mycan extends Canvas


{
private int
i=0; Mycan()
{

public void paint(Graphics g)


{
if(i==1
)
{ g.drawRect(50,50,75,75);

else if(i==2)
{
g.drawRect(50,50,100,150);
}
else if(i==3)
{
g.drawOval(70,70,75,75);
}
}
public void square()
{
i=1;
repaint();
}
public void rect()
{
i=2;
repaint();
}
public void circle()
{
i=3;
repaint();
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

public class Shape extends Frame implements ItemListener


{
Mycan mc=new Mycan();
public static void main(String args[])
{
Shape f=new Shape();
f.setSize(500,500);
f.setVisible(true);
f.setTitle("Canvas
} Program");
Shape
()
{
mc.setBackground(Color.gr
ay);
mc.setForeground(Color.red
); mc.setSize(500,300);
add(mc);

Panel p1=new Panel();


CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new
Checkbox("Square",cbg,false); Checkbox
cb2=new Checkbox("Rectangle",cbg,false);
Checkbox cb3=new
Checkbox("Circle",cbg,false);

p1.add(cb1);
p1.add(cb2);
p1.add(cb3);
add(p1);
cb1.addItemListener(thi
s);
cb2.addItemListener(thi
s);
cb3.addItemListener(thi
s);
addWindowListener(new WindowAdapter(){public void
windowClosing(WindowEvent e){System.exit(0);}});
}
public void itemStateChanged(ItemEvent e)
{
if(e.getItem().equals("Square"))
{
mc.square();
}
else if(e.getItem().equals("Rectangle"))
{
mc.rect();
}
els
e
{ mc.circle();
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 07

Submitted By:
Roll No.:IT124
Name:Yasvi Patel

Write applications to simulate traffic lights and calculator using GridbagLayout.

Note: Write source code, input and output for below programs.

7.1 Write an application to simulate traffic lights. The program lets the user select one of
the three lights red, yellow and green. Upon selecting a menu item, the light is turned on
and there is only one light on at a time.

Code:
// Java source code
import java.awt.*;
import java.awt.event.*;

class Mycan extends Canvas


{
private int i=0;
public void paint(Graphics g)
{
g.drawRect(70,70,250,100);
g.drawOval(80,85,75,75);
g.drawOval(160,85,75,75);
g.drawOval(240,85,75,75);

if(i==1)
{
g.setColor(Color.red);
g.fillOval(80,85,75,75);
}
else if(i==2)
{
g.setColor(Color.yellow);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

g.fillOval(160,85,75,75);
}
else if(i==3)
{
g.setColor(Color.green);
g.fillOval(240,85,75,75);
}
}
public void re()
{
i=1;
repaint();
}
public void ye()
{
i=2;
repaint();
}
public void gr()
{
i=3;
repaint();
}
}

public class Signal extends Frame implements ItemListener


{
Mycan dk=new Mycan();
public static void main(String args[])
{
Frame f=new Signal();
f.setSize(400,300);
f.setVisible(true);
f.setTitle("Traffic Signal Program");
}
Signal()
{
dk.setSize(400,300);
add(dk);

Panel p1=new Panel();


CheckboxGroup cbg=new CheckboxGroup();
Checkbox cb1=new Checkbox("Stop",cbg,false);
Checkbox cb2=new Checkbox("Wait",cbg,false);
Checkbox cb3=new Checkbox("Go",cbg,false);

p1.add(cb1);
p1.add(cb2);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

p1.add(cb3);
add(p1, BorderLayout.SOUTH);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){System.exit(0);}});
}
public void itemStateChanged(ItemEvent e)
{
if(e.getItem().equals("Stop"))
{
dk.re();
}
else if(e.getItem().equals("Wait"))
{
dk.ye();
}
else
{
dk.gr();
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

7.2 Using GridBagLayout to lay out, implement Windows’ 98 calculator like


application. Implement four basic arithmetic operations.

Code:
// Java source code
import java.awt.*;
import java.awt.event.*;

public class Cal extends Frame implements ActionListener


{
private TextField tf;
private Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16;
private GridBagLayout gbl;
private GridBagConstraints gbcn;

private int a;
private Double n;
private String s1,s2,s3,s4,s5;

public static void main(String args[])


{
Frame f=new Cal();
f.setSize(500,500);
f.setVisible(true);
f.setTitle("Calculator");
}
public void addComp(Component c, GridBagLayout gbl, GridBagConstraints gbcn, int ro,int co,int
nr,int nc,int wx,int wy)
{
gbcn.gridx=co;
gbcn.gridy=ro;
gbcn.gridwidth=nc;
gbcn.gridheight=nr;
gbcn.weightx=wx;
gbcn.weighty=wy;

gbl.setConstraints(c,gbcn);

add(c);
}
public Cal()
{
addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent
e){System.exit(0);}});
tf=new TextField("",15);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

b0=new Button("0");
b1=new Button("1");
b2=new Button("2");
b3=new Button("3");
b4=new Button("4");
b5=new Button("5");
b6=new Button("6");
b7=new Button("7");
b8=new Button("8");
b9=new Button("9");
b10=new Button("+");
b11=new Button("-");
b12=new Button("*");
b13=new Button("/");
b14=new Button(".");
b15=new Button("=");
b16=new Button("C");

gbl=new GridBagLayout();
gbcn=new GridBagConstraints();
setLayout(gbl);

gbcn.fill=GridBagConstraints.BOTH;
gbcn.anchor=GridBagConstraints.WEST;
addComp(tf,gbl,gbcn,0,0,1,5,0,0);

addComp(b16,gbl,gbcn,1,4,4,1,0,0);

addComp(b7,gbl,gbcn,1,0,1,1,0,0);
addComp(b8,gbl,gbcn,1,1,1,1,0,0);
addComp(b9,gbl,gbcn,1,2,1,1,0,0);
addComp(b10,gbl,gbcn,1,3,1,1,0,0);

addComp(b4,gbl,gbcn,2,0,1,1,0,0);
addComp(b5,gbl,gbcn,2,1,1,1,0,0);
addComp(b6,gbl,gbcn,2,2,1,1,0,0);
addComp(b11,gbl,gbcn,2,3,1,1,0,0);

addComp(b1,gbl,gbcn,3,0,1,1,0,0);
addComp(b2,gbl,gbcn,3,1,1,1,0,0);
addComp(b3,gbl,gbcn,3,2,1,1,0,0);
addComp(b12,gbl,gbcn,3,3,1,1,0,0);

addComp(b0,gbl,gbcn,4,0,1,1,0,0);
addComp(b14,gbl,gbcn,4,1,1,1,0,0);
addComp(b15,gbl,gbcn,4,2,1,1,0,0);
addComp(b13,gbl,gbcn,4,3,1,1,0,0);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b10.addActionListener(this);
b11.addActionListener(this);
b12.addActionListener(this);
b13.addActionListener(this);
b14.addActionListener(this);
b15.addActionListener(this);
b16.addActionListener(this);

}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b0)
{
s1=tf.getText();
s2="0";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b1)
{
s1=tf.getText();
s2="1";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b2)
{
s1=tf.getText();
s2="2";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b3)
{
s1=tf.getText();
s2="3";
s3=s1+s2;
tf.setText(s3);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

}
if(e.getSource()==b4)
{
s1=tf.getText();
s2="4";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b5)
{
s1=tf.getText();
s2="5";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b6)
{
s1=tf.getText();
s2="6";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b7)
{
s1=tf.getText();
s2="7";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b8)
{
s1=tf.getText();
s2="8";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b9)
{
s1=tf.getText();
s2="9";
s3=s1+s2;
tf.setText(s3);
}
if(e.getSource()==b14)
{
s1=tf.getText();
s2=".";
s3=s1+s2;
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

tf.setText(s3);
}
if(e.getSource()==b10)
{
s4=tf.getText();
tf.setText("");
a=1;
}
if(e.getSource()==b11)
{
s4=tf.getText();
tf.setText("");
a=2;
}
if(e.getSource()==b12)
{
s4=tf.getText();
tf.setText("");
a=3;
}
if(e.getSource()==b13)
{
s4=tf.getText();
tf.setText("");
a=4;
}

if(e.getSource()==b15)
{
s5=tf.getText();
if(a==1)
{
n=Double.parseDouble(s4)+Double.parseDouble(s5);
tf.setText(String.valueOf(n));
}
if(a==2)
{
n=Double.parseDouble(s4)-Double.parseDouble(s5);
tf.setText(String.valueOf(n));
}
if(a==3)
{
n=Double.parseDouble(s4)*Double.parseDouble(s5);
tf.setText(String.valueOf(n));
}
if(a==4)
{
if((Double.parseDouble(s5))==0)
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

{
tf.setText("Cannot Divide By Zero");
}
else
{
n=Double.parseDouble(s4)/Double.parseDouble(s5);
tf.setText(String.valueOf(n));
}
}
}
if(e.getSource()==b16)
{
tf.setText("");
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 08

Submitted By:
Roll No.:IT124
Name:Yasvi Patel

Write applications that use the concept of Applet and Exception Handling.

Note: Write source code, input and output for below programs.

8.1 Write an Applet that allows free hand drawing. (Pencil tool of Paint Brush
Application).

Code:
// Java source code
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="FreeHand" width="400" height="400">
</applet>
*/
public class FreeHand extends Applet
{
public static void main(String[] s)
{
FreeHand f=new FreeHand();
FreeHand fhd=new FreeHand();
fhd.init();
f.add("center",fhd);
f.setSize(400,400);
f.setVisible(true);
}
public void init()
{
Canvas c=new Paintc();
setLayout(new BorderLayout());
add("Center",c);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

}
}

class Paintc extends Canvas implements MouseListener,MouseMotionListener


{
final int csize=20;
private Point linestart=new Point(0,0);
private Graphics g;

public Paintc()
{
g=getGraphics();
addMouseListener(this);
addMouseMotionListener(this);
}
public void mousePressed(MouseEvent e)
{
if(e.isMetaDown())
{
setForeground(getBackground());
}
linestart.move(e.getX(),e.getY());
}
public void mouseClicked(MouseEvent e)
{

}
public void mouseEntered(MouseEvent e)
{

}
public void mouseExited(MouseEvent e)
{

}
public void mouseReleased(MouseEvent e)
{

}
public void mouseDragged(MouseEvent e)
{
g=getGraphics();
if(e.isMetaDown())
{
g.fillOval(e.getX()-(csize/2),e.getY()-(csize/2),csize,csize);
}
else
{
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

g.drawLine(linestart.x,linestart.y,e.getX(),e.getY());
}
linestart.move(e.getX(),e.getY());
}
public void mouseMoved(MouseEvent e)
{

}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

8.2 Write a program to meet following requirements:


• Create an array with 100 elements that are randomly chosen.
• Create a TextField to enter an array index and another TextField to display the
array element at the specified index.
• Create a show Button to cause the array element to be displayed. If the specified
index is out bound, display message “Out of Bound”.

Code:
// Java source code
import java.awt.*;
import java.awt.event.*;
import java.util.*;

class ArrayIndex extends Frame implements ActionListener {


int[] list = new int[100];
TextField tf1 = new TextField(20);
TextField tf2 = new TextField(20);
Button b = new Button("OK");

public ArrayIndex(String title) {


super(title);
Random rand = new Random();
for(int i=0;i<100;i++){
list[i] = rand.nextInt(1000);
}
Panel p1 = new Panel();
p1.add(new Label("Index"));
p1.add(tf1);
p1.add(new Label("Value"));
p1.add(tf2);
add("North",p1);
Panel p2 = new Panel();
p2.add(b);
add("South",p2);
b.addActionListener(this);
setSize(600,100);
setVisible(true);
}

public static void main(String[] args) {


new ArrayIndex("Array Index test");
}

public void actionPerformed(ActionEvent ae) {


int index = Integer.parseInt(tf1.getText().trim());
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

try {
int value = list[index];
String txt = Integer.toString(value);
tf2.setText(txt);
}
catch(ArrayIndexOutOfBoundsException aie) {
tf2.setText("Out of Bound");
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 09

Submitted By:
Roll No.:IT124
Name:Yasvi Patel

Write the programs that uses the concept of Threads.

Note: Write source code, input and output for below programs.

9.1 Write an application to display moving banner. Enter message to be moved, color and
size through three different TextFields. Select direction (left or right) using Choice. On
pressing start Button message should start moving.

Code:
// Java source code
import java.awt.*;
import java.awt.event.*;
import java.util.*;

class MovingBanner extends Frame implements Runnable,ActionListener


{
//defining components
Button b;
TextField tf1;
TextField tf2;
TextField tf3;
Label l1;
Label l2;
Label l3;
Choice c;
Thread t;
String msg="";
String col="";
int x=200;
int y=200;
int z=0;
public static void main(String[] args)
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

{
MovingBanner f=new MovingBanner("MOVING BANNER");
}
MovingBanner(String title)
{
super(title);
t=new Thread(this,title);
//container containing components
Panel p=new Panel();
tf1=new TextField(20);
tf2=new TextField(10);
tf3=new TextField(3);
l1=new Label("Enter the String");
l2=new Label("Color");
l3=new Label("Size");
Panel p2=new Panel();
b=new Button("Start");
c=new Choice();
c.add("Right");
c.add("Left");
setLayout(new BorderLayout());
p.add(l1);
p.add(tf1);
p.add(l2);
p.add(tf2);
p.add(l3);
p.add(tf3);
add("North",p);
p2.add(b);
p2.add(c);
add("South",p2);
setSize(800,400);
setVisible(true);
//setBackground(Color.white);
b.setBackground(Color.gray);
b.setForeground(Color.white);
b.addActionListener(this);
//closing the window
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
public void run()
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

{
//Proper formatting of the movement of the banner.Handling exception
try
{
while(true)
{
Thread.sleep(200);
msg=tf1.getText();
z=Integer.parseInt(tf3.getText());
col=tf2.getText();
if(c.getSelectedItem().equals("Left"))
{
x=x-20;
if(x<(-100))
x=800;
repaint();
}
else
{
x=x+20;
if(x>(800))
x=0;
repaint();
}
}
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
public void paint(Graphics g)
{
//Changing the colour of the text as per user requirement
Font f=new Font("Serif",Font.BOLD,z);
g.setFont(f);
if(col.equals("red"))
setForeground(Color.red);
else if(col.equalsIgnoreCase("blue"))
setForeground(Color.blue);
else if(col.equalsIgnoreCase("orange"))
setForeground(Color.orange);
else if(col.equalsIgnoreCase("cyan"))
setForeground(Color.cyan);
else if(col.equalsIgnoreCase("magenta"))
setForeground(Color.magenta);
else if(col.equalsIgnoreCase("yellow"))
setForeground(Color.yellow);
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

else
setForeground(Color.black);
g.drawString(msg,x,y);
}
public void actionPerformed(ActionEvent ae)
{
//Start button is pressed - start moving the banner
String s=ae.getActionCommand();
if(ae.getSource() instanceof Button) //if source of event is button the do the following
{
if(s.equals("Start"))
t.start();
}
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

9.2 Write an applet that shows four moving objects (balls) as shown below:

Four directions are used. On touching boundary, the object (ball) changes its direction
and start moving in that changed direction.

Code:
// Java source code
import java.awt.*;
import java.applet.*;
import java.awt.*;
/*
<applet code="screen.class" width="300" height="200">
</applet>
*/
class circle extends Thread
{
public int x,y,r;
public int inc;
public int dir;
public screen s1;
public void draw(Graphics g)
{
g.fillOval(x,y,r,r);
}
public circle(int xx,int yy,int rr,int d,int l,screen s)
{
x=xx;y=yy;r=rr;
dir=d;
s1=s;
inc=l;
start();
}
public void run()
{
for(;;)
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

{
if(y>=300)
{
if(dir==1)
{
dir=2;
}
if(dir==-2)
{
dir=-1;
}
}
if(y<=0)
{
if(dir==-1)
{
dir=-2;
}
if(dir==2)
{
dir=1;
}
}
if(x>=600)
{
if(dir==1)
{
dir=2;
}
if(dir==2)
{
dir=-1;
}
}
if(x<0)
{
if(dir==-1)
{
dir=2;
}
if(dir==-2)
{
dir=1;
}
}
if(dir==1)
{
x=x+inc;
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

y=y+inc;
}
else if(dir==2)
{
y=y-inc;
x=x+inc;
}
else if(dir==-1)
{
x=x-inc;
y=y-inc;
}
else if(dir==-2)
{
y=y+inc;
x=x-inc;
}
s1.repaint();
try
{
sleep(50);
}
catch(Exception e){
}
}
}
}
public class screen extends Applet
{
public circle c1,c2,c3,c4;
public screen(){}
public void init()
{
c1=new circle(0,300,20,1,10,this);
c2=new circle(400,300,20,2,5,this);
c3=new circle(400,0,20,-1,10,this);
c4=new circle(400,300,20,-2,5,this);
}
public void start(){}
public void stop(){}
public void paint(Graphics g)
{
setBackground(Color.white);
c2.draw(g);
c1.draw(g);
c3.draw(g);
c4.draw(g);
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 10

Submitted By:
Roll No.:IT124
Name:Yasvi Patel

Aim: Write a program that uses the concept of File I/O.

Note: Write source code, input and output for below programs.

10.1 Write a program to implement Notepad like application.

Code:
// Java source code

import java.io.*;
import java.awt.*;
import java.awt.event.*;

class Notepad extends Frame implements ActionListener


{
MenuBar mb;
TextArea ta;

public Notepad(String title)


{
super(title);
setVisible(true);
setSize(500,500);
ta=new TextArea();
mb=new MenuBar();
setMenuBar(mb);

Menu m=new Menu("File");


MenuItem n=new MenuItem("New");
MenuItem o=new MenuItem("Open");
MenuItem s=new MenuItem("Save");
MenuItem e=new MenuItem("Exit");
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

m.add(n);
m.add(o);
m.add(s);
m.add(e);
mb.add(m);
add(ta);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
}
public void windowClosed(WindowEvent e){
System.exit(0);
}
});
n.addActionListener(this);
o.addActionListener(this);
s.addActionListener(this);
e.addActionListener(this);
}

public static void main(String args[])


{ new Notepad("My Notepad");
}

public void actionPerformed(ActionEvent ae)


{
String str=ae.getActionCommand();
if(str.equals("New"))
{
ta.setText("");
}

else if(str.equals("Open"))
{
FileDialog fd=new FileDialog(this,"Open",FileDialog.LOAD);
fd.setVisible(true);
String fn=fd.getFile();

BufferedReader br=null;
try
{
br=new BufferedReader(new FileReader(fn));
String path=br.readLine();
boolean firstLine=true;

while(br!=null)
{
if(firstLine)
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

{
firstLine=false;
ta.append(path);
}
else
{
ta.append("\n"+path);
}
path=br.readLine();
if(path==null)
break;
}
}
catch(FileNotFoundException fnf)
{
System.out.println("File Not Found.");
}
catch(IOException fnf)
{
System.out.println("IO Exception!");
}
}

else if(str.equals("Save"))
{
try
{
FileDialog fd=new FileDialog(this,"Save",FileDialog.SAVE);
fd.setVisible(true);
String txt=ta.getText();
String dir=fd.getDirectory();
String fname=fd.getFile();
FileOutputStream fos=new FileOutputStream(dir+fname);
DataOutputStream dos=new DataOutputStream(fos);
dos.writeBytes(txt);
dos.close();
}
catch(Exception e){}
}
else if(str.equals("Exit"))
System.exit(0);
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

10.2 Write a program that will count number of characters, words and lines in a file. The
name should be passes as command line argument.

Code:
// Java source code
import java.io.*;

public class CountCMD


{
public static void main(String[] args) throws IOException
{

if(args.length!=1)
{
System.out.println("Enter Filename as one argument");
System.exit(0);
}
File file = new File(args[0]);
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);

String line;

// Initializing counters
int characterCount = 0;
int countWord = 0;
int lineCount = 0;
int whitespaceCount = 0;

// Reading line by line from the


// file until a null is returned
while((line = reader.readLine()) != null)
{
if(!line.equals(""))
{
characterCount += line.length();
// \\s+ is the space delimiter in java
String[] wordList = line.split("\\s+");

countWord += wordList.length;
whitespaceCount += countWord -1;

// [!?.:]+ is the sentence delimiter in java


String[] sentenceList = line.split("[!?.:]+");
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

lineCount += sentenceList.length;

}
}
System.out.println("Total number of characters = " + characterCount);
System.out.println("Total word count = " + countWord);
System.out.println("Total number of lines = " + lineCount);
}
}

Input/Output:
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Dharmsinh Desai University, Nadiad


Department of Information Technology
Core Java Technology, IT510
B.Tech. IT, Sem: V

Experiment – 11

Submitted By:
Roll No.:IT124
Name:Yasvi Patel

Aim: Write a program that uses the concept of socket programming.

Note: Write source code, input and output for below program.

11.1 Implement multiple client chat application using socket programming.

Code:
// Java source code

ServerDemo.java

import java.net.*;
import java.io.*;

public class ServerDemo extends Thread


{
private ServerSocket ServerSocket;

public ServerDemo(int port) throws IOException


{
ServerSocket = new ServerSocket(port);
ServerSocket.setSoTimeout(100000);
}

public void run()


{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
ServerSocket.getLocalPort() + "...");
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Socket ServerDemo = ServerSocket.accept();


System.out.println("Just connected to "
+ ServerDemo.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(ServerDemo.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(ServerDemo.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ ServerDemo.getLocalSocketAddress() + "\nGoodbye!");
ServerDemo.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
System.out.println("Press ctrl+c to terminate");
int port = Integer.parseInt(args[0]);
try
{
Thread t = new ServerDemo(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

ClientDemo.java

import java.net.*;
import java.io.*;

public class ClientDemo


{
public static void main(String [] args)
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName +
" on port " + port);
Socket ClientDemo = new Socket(serverName, port);
System.out.println("Just connected to "
+ ClientDemo.getRemoteSocketAddress());
OutputStream outToServer = ClientDemo.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ ClientDemo.getLocalSocketAddress());
InputStream inFromServer = ClientDemo.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
ClientDemo.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
BTech-IT, Sem-5, Term Work, Core Java Technology, IT510

Input/Output:

You might also like