[go: up one dir, main page]

0% found this document useful (0 votes)
53 views50 pages

Java 2 Sycs 13

1. The program demonstrates user defined packages in Java by creating a mypack package with two classes ClassA and ClassB. A third class PackDemo outside the package imports mypack and calls methods from ClassA and ClassB. 2. The program creates an interface Callback with a method callme() and constant MAX. Class InterFaceDemo1 implements the interface and overrides callme() while defining its own method myMethod(). 3. The question asks to write a program to find factorial of a number recursively using interfaces. The program is to create an interface FactDemo with a method Factorial() and a class FactImp that implements the interface overriding Factorial() to calculate factorial recursively.

Uploaded by

Payal Kori
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)
53 views50 pages

Java 2 Sycs 13

1. The program demonstrates user defined packages in Java by creating a mypack package with two classes ClassA and ClassB. A third class PackDemo outside the package imports mypack and calls methods from ClassA and ClassB. 2. The program creates an interface Callback with a method callme() and constant MAX. Class InterFaceDemo1 implements the interface and overrides callme() while defining its own method myMethod(). 3. The question asks to write a program to find factorial of a number recursively using interfaces. The program is to create an interface FactDemo with a method Factorial() and a class FactImp that implements the interface overriding Factorial() to calculate factorial recursively.

Uploaded by

Payal Kori
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/ 50

BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST

PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-06 Date:30/06/2023

Practical -6
Demonstrate the use this keyword, static keyword and abstract classes
1)Write a java program to demonstrate the working of this keyword.
CODE:
class Emp{
String name,eid;
Emp(String name,String eid){
this.name=name;
this.eid=eid;
}
String retName(){
return name;
}
String retEid(){
return eid;
}
}
class EmpData{
public static void main(String arr[]){
Emp e1=new Emp("Anu","SYCS23");
System.out.println("Employee Details \nName: "+e1.retName());
System.out.println("ID: "+e1.retEid());
}
}
OUTPUT:
C:\Users\LAB01-PC22\Documents\Java>javac EmpData.java
C:\Users\LAB01-PC22\Documents\Java>java EmpData
Employee Details
Name: Anu
ID: SYCS23

2)Write a java program that demonstrate the working of static keyword.


CODE:
class TestStatic{
static{
System.out.println("I am the static block...called/executed before main()" );
}
static int num1=100;
static int num2=200;

static int add(){


return num1+num2;
}
void disp(){
System.out.println("num1="+num1+"num2= "+num2);
}
}
class StaticDemo{
public static void main(String arg[]){
Page 1 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-06 Date:30/06/2023

TestStatic t1=new TestStatic();


System.out.println("Called via obj name "+t1.add());
t1.disp();
TestStatic.num1=900;
TestStatic.num2=100;
System.out.println("Called via class name num1="+TestStatic.num1);
System.out.println("Called via class name num2="+TestStatic.num2);
System.out.println("Called via class name result addtion="+TestStatic.add());
}
}
OUTPUT:
C:\Users\LAB01-PC22\Documents\Java>javac StaticDemo.java

C:\Users\LAB01-PC22\Documents\Java>java StaticDemo
I am the static block...called/executed before main()
Called via obj name 300
num1=100num2= 200
Called via class name num1=900
Called via class name num2=100
Called via class name result addtion=1000

3)Write a java program that illustrate the usage of abstract classes.


CODE:
abstract class Demo{
//Method defined inside Abstract class
void disp(){
System.out.println("Regular Defined method inside abstract class...");
}
abstract void ab_method();
}
class Calling extends Demo{
//Method of abstract class defined in child class
void ab_method(){
System.out.println("Abstract method ab_method() defined in child class...");
}
}
class AbstractDemo{
public static void main (String arr[]){
Calling c=new Calling();
c.disp();
c.ab_method();
}
}
OUTPUT:
C:\Users\LAB01-PC22\Documents\Java>javac AbstractDemo.java

C:\Users\LAB01-PC22\Documents\Java>java AbstractDemo
Regular Defined method inside abstract class...
Abstract method ab_method() defined in child clas
Page 2 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-07 Date:01/07/2023

PRACTICAL-07
Packages and Interfaces
• Package
• Interface
• Package and Interfaces

Q1. Write a Java program to demonstrate the concept of user defined packages.

Create mypack folder inside java folder


Inside it create package class A and B on same or different files
Now go outside mypack folder and create a 3rd .java file with main function to import the
mypack folder packages.
Make both class and methods inside package classes public

Inside Mypack folder:


ClassA.java CODE:
package mypack;
public class ClassA{
public void dispA(){
System.out.println("Package class A is imported");
}
}
ClassB.java CODE:
package mypack;
public class ClassB{
public void dispB(){
System.out.println("Package class B is imported");
}
}
Outside mypack folder:
PackDemo.java
import mypack.*; //IMPORTING ALL PACKAGES FROM mypack folder
class PackDemo{
public static void main(String arr[]){
ClassA a=new ClassA();
a.dispA();
ClassB b=new ClassB();
b.dispB();
}
}
OUTPUT:

// Go inside java folder


C:\Users\LAB1\Desktop\java\mypack>cd C:\Users\LAB1\Desktop\java

Page 3 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-07 Date:01/07/2023

// Go inside mypack folder


C:\Users\LAB1\Desktop\java>cd mypack

C:\Users\LAB1\Desktop\java\mypack>set path="C:\Program Files\Java\jdk1.8.0_151\bin"


//All packages(i.e.all .java files) are compiled
C:\Users\LAB1\Desktop\java\mypack>javac *.java
//packages , interfaces are only compiled not interpreted
C:\Users\LAB1\Desktop\java\mypack>cd..
//cd .. to go back to the previous location i.e outside package mypack
//Compiling
C:\Users\LAB1\Desktop\java>javac PackDemo.java

C:\Users\LAB1\Desktop\java>java PackDemo
Package class A is imported
Package class B is imported

Q.2 Write a Java program to create and implement interfaces


CODE:
interface Callback.java
interface Callback{
// interfaces are incomplete by itself
public void callme(int param);
final int MAX=100; //constant is written in Capital

}
CLASS InterFaceDemo1.java
class InterFaceDemo1 implements Callback{
public void callme(int p){
if(p>MAX)
System.out.println("p value is more than MAX "+MAX);
}
void myMethod(){
System.out.println("The classes can have their own methods other than
implemented methods");
}
public static void main(String arg[]){
InterFaceDemo1 d1=new InterFaceDemo1();
d1.callme(108);
d1.myMethod();
}
}
OUTPUT:
//Compiling the interface
C:\Users\LAB1\Desktop\java>javac Callback.java

Page 4 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-07 Date:01/07/2023

C:\Users\LAB1\Desktop\java>javac InterFaceDemo1.java

C:\Users\LAB1\Desktop\java>java InterFaceDemo1
p value is more than MAX 100
The classes can have their own methods other than implemented methods

Q.3 Write a java program to find out the factorial of given number by using concept of
recursive function
package sycspack;
public class FactImp implements FactDemo{

public int Factorial(int x){


int fact=1;
if(x>0){
fact=Factorial(x-1);
}
else if(x==0){
return 1;
}
else
return 0;
}

Code:
Inside java//sycspack folder
a) Package sycspack with interface FactDemo

package sycspack;

public interface FactDemo{

public int factorial(int x);

}
b)Package sycspack with class implementing the above interface

package sycspack;

public class FactImp implements FactDemo{


public int factorial(int x){
if(x==0){
return 1;
}

Page 5 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-07 Date:01/07/2023

else if(x<0){
return -1;
}
else{
return x*factorial(x-1);
}
}
}
//OUTSIDE sycspack folder package
c)class using the class and interface of package
import sycspack.*;
class CallFact{
public static void main(String arg[]){
int x=Integer.parseInt(arg[0]);
FactImp f=new FactImp();
int result=f.factorial(x);
if(result!=-1){
System.out.println("Factorial of "+ x +" is "+result);
}
else
System.out.println("Factorial of negative number is not possible");
}
}
OUTPUT:
C:\Users\Rag\Desktop\java\New folder\p6>set path="C:\Users\Rag\Downloads\jdk-
20_windows-x64_bin\jdk-20.0.1\bin"

C:\Users\Rag\Desktop\java\New folder\p6>cd C:\Users\Rag\Desktop\java\New folder\p6

C:\Users\Rag\Desktop\java\New folder\p6>cd sycspack

C:\Users\Rag\Desktop\java\New folder\p6\sycspack>javac *.java

C:\Users\Rag\Desktop\java\New folder\p6\sycspack>cd..

C:\Users\Rag\Desktop\java\New folder\p6>javac CallFact.java

C:\Users\Rag\Desktop\java\New folder\p6>java CallFact -2


Factorial of negative number is not possible

C:\Users\Rag\Desktop\java\New folder\p6>java CallFact 5


Factorial of 5 is 12

Page 6 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-08 Date:04/07/2023

Practical-08
Strings

• String class -has immutable methods


• StringBuffer class -has mutable methods
• StringTokenizer class - to split the string into small tokens(parts) from a delimiter

Q1. Write a java program to get data from user using BufferedReader class
(4th method to get input data from user)
CODE:
import java.io.*; // io means inputoutput package
class ConsoleInput{
public static void main(String args[]) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str[]=new String[100];
System.out.println("Enter the lines of code....");
System.out.println("Enter 'stop' to quit...");

for(int i=0;i<100;++i){
str[i]=br.readLine();
if(str[i].equals("stop"))
break;
}
System.out.println("\n\n Here is your Content .....\n\n");

for(int i=0;i<100;++i){
if(str[i].equals("stop"))
break;
System.out.println(str[i]);
}
}
}
OUTPUT:
C:\Users\LAB1\Desktop\java2>javac ConsoleInput.java
C:\Users\LAB1\Desktop\java2>java ConsoleInput
Enter the lines of code....
Enter 'stop' to quit...
hi
hello
good
morning
stop

Here is your Content .....

hi

Page 7 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-08 Date:04/07/2023

hello
good
morning

Q.2 Write a java program to demonstrate the working of String and StringBuffer class
methods .
CODE:
class StringDemo{
public static void main(String args[]){
String s1 = "Bhavans college";
String s2 = " RJ ";
String s3 ="Bhavans college";
System.out.println("\nStrings before using methods of String Class" );
System.out.println("s1="+s1+" s2="+s2+" s3="+s3);
System.out.println("\n..........Using Methods of String Class..........");
System.out.println("1 .Char at 4 index is :"+s1.charAt(4));
System.out.println("2 .Length of string is:"+s1.length());
System.out.println("3 .Comparing string s1 and s3 : "+s1.compareTo(s3));
System.out.println("4 .Lower Case :"+s1.toLowerCase());
System.out.println("5 .Upper Case :"+s1.toUpperCase());
System.out.println("6 .Value of string is :"+s1.toString());
System.out.println("8 .Index at char 'B' :"+s1.indexOf("Bha"));
System.out.println("9 .Concatenating s1 to s2 :"+s1.concat(s2));
System.out.println("10 .Using trim :"+s2.trim());
System.out.println("11.After Replace:"+s1.replace("Bhavans",s2));
System.out.println("12.Substring from index 0 to 7 :"+s1.substring(1,8));
System.out.println("13.Is string s1 empty?:"+s1.isEmpty());
System.out.println("14.Is string s1 and s2 equal?:"+s1.equals(s2));
System.out.println("15.Ignoring case, comparing :"+s1.equalsIgnoreCase(s2));
System.out.println("16.String joined :"+String.join("@",s1,s2));
System.out.println("\nStrings after using methods of String Class : no change in
strings" );
System.out.println("s1="+s1+" s2="+s2+" s3="+s3);

StringBuffer sb=new StringBuffer("Object Language");


System.out.println("\n.........StringBuffer CLASS Methods....");
System.out.println("\nOriginal String is.."+sb);
//1.length()
System.out.println("\nLength of String is .."+sb.length());
//2.indexOf()
int pos=sb.indexOf(" Language");
//3.insert() method
sb.insert (pos,"Oriented");
System.out.println("\nAfter insertion.."+sb);
//4.setCharAt() method
sb.setCharAt(6,'-');

Page 8 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-08 Date:04/07/2023

System.out.println("\nsetting char at 6th position.."+sb);


//5.append() method
sb.append(" follow bottom up approach");
System.out.println("\n Appending string ....New String is \n"+sb);
//6.setLength() method
sb.setLength(100);
System.out.println("\nNew Length of string is.... "+sb.length());
System.out.println(sb);
//7.delete() method
sb.delete(3,6);
System.out.println("\nAfter Deleting : "+ sb);
//8.capacity()
System.out.println("Capacity of sb : "+sb.capacity());
//9.ensureCapacity()
sb.ensureCapacity(131);
System.out.println("Capacity of sb after using ensureCapacity : "+sb.capacity());
//10.charAt()
System.out.println("CharAt index 6: "+sb.charAt(6) );
//11.deleteCharAt()
System.out.println("Deleting CharAt index 6: "+sb.deleteCharAt(6) );
//12.replace()
System.out.println("After Replacing :"+ sb.replace(3,10," OOP"));
//13.trimToSize()
sb.trimToSize();
System.out.println("Trimming : "+sb);
//14.substring()
System.out.println("Substring : "+sb.substring(0,7));
//15.reverse()
sb.reverse();
System.out.println("After using reverse : " +sb);
//15.toString()
System.out.println("Final String:"+sb.toString());
}
}
OUTPUT:
C:\Users\Rag\Desktop\java\p11>javac StringDemo.java

C:\Users\Rag\Desktop\java\p11>java StringDemo

Strings before using methods of String Class


s1=Bhavans college s2= RJ s3=Bhavans college

..........Using Methods of String Class..........


1 .Char at 4 index is :a
2 .Length of string is:15
3 .Comparing string s1 and s3 : 0

Page 9 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-08 Date:04/07/2023

4 .Lower Case :bhavans college


5 .Upper Case :BHAVANS COLLEGE
6 .Value of string is :Bhavans college
8 .Index at char 'B' :0
9 .Concatenating s1 to s2 :Bhavans college RJ
10 .Using trim :RJ
11.After Replace: RJ college
12.Substring from index 0 to 7 :havans
13.Is string s1 empty?:false
14.Is string s1 and s2 equal?:false
15.Ignoring case, comparing :false
16.String joined :Bhavans college@ RJ

Strings after using methods of String Class : no change in strings


s1=Bhavans college s2= RJ s3=Bhavans college

.........StringBuffer CLASS Methods....

Original String is..Object Language

Length of String is ..15

After insertion..ObjectOriented Language

setting char at 6th position..Object-riented Language

Appending string ....New String is


Object-riented Language follow bottom up approach

New Length of string is.... 100


Object-riented Language follow bottom up approach

After Deleting : Obj-riented Language follow bottom up approach


Capacity of sb : 130
Capacity of sb after using ensureCapacity : 262
CharAt index 6: e
Deleting CharAt index 6: Obj-rinted Language follow bottom up approach
After Replacing :Obj OOP Language follow bottom up approach
Trimming : Obj OOP Language follow bottom up approach
Substring : Obj OOP
After using reverse : hcaorppa pu mottob wollof egaugnaL POO jbO
Final String:hcaorppa pu mottob wollof egaugnaL POO jbO

Page 10 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-08 Date:04/07/2023

Q3) Write a java program to demonstrate the working of string tokenizer class methods

CODE 1:
import java.util.StringTokenizer;
public class StringToken{
public static void main(String arg[]){
StringTokenizer st=new StringTokenizer("i am bhavanite");
System.out.println("Total Token are ..."+st.countTokens());
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
OUTPUT: By default, delimiter is space.

C:\Users\LAB01PC16\Desktop\SYCS36>javac StringToken.java

C:\Users\LAB01PC16\Desktop\SYCS36>java StringToken
Total Token are ...3
i
am
bhavanite

CODE 2:
import java.util.StringTokenizer;
public class StringToken{
public static void main(String arg[]){
StringTokenizer st=new StringTokenizer("i am + bhavanite" , "+");
System.out.println("Total Token are ..."+st.countTokens());
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}

OUTPUT: Here the delimiter is “+” sign in given string.

C:\Users\LAB01PC16\Desktop\SYCS36>javac StringToken.java

C:\Users\LAB01PC16\Desktop\SYCS36>java StringToken
Total Token are ...2
i am
bhavanite

Page 11 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-09 Date:06/07/2023

Practical-09
Exceptional Handling
Q.1 Write a java program to demonstrate the basics of exception handling.
CODE:
class ExceptionDemo{
public static void main(String arg[]){
int d,a;
try{
d=0;
a=42/d;
System.out.println("This will not be printed.");
}
catch(ArithmeticException e){
System.out.println("Division by zero");
}
System.out.println("After catch statement");
}
}
OUTPUT:
C:\Users\LAB01PC16\Desktop\SYCS36>javac ExceptionDemo.java

C:\Users\LAB01PC16\Desktop\SYCS36>java ExceptionDemo
Division by zero
After catch statement
Q2. Write a Java program to demonstrate multi-catch block .
CODE:
class MultiCatch{
public static void main(String args[]){
try{
int a=args.length;
System.out.println("a = "+a);
int b=42/a;
int c[]={1};
c[42]=99; //Exception thrown
}
catch(ArithmeticException e){
System.out.println("Divide by 0: "+e);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Array index object: "+e.toString());
}
catch(Exception e){
System.out.println("Caught Exception: "+e);
}
System.out.println("After try/catch blocks.");

Page 12 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-09 Date:06/07/2023

}
}
OUTPUT 1:
C:\Users\LAB01-PC19\Desktop\java excep>javac MultiCatch.java

C:\Users\LAB01-PC19\Desktop\java excep>java MultiCatch


a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
OUTPUT 2:
C:\Users\LAB01-PC19\Desktop\java excep>java MultiCatch hello
a=1
Array index object: java.lang.ArrayIndexOutOfBoundsException: 42
After try/catch blocks.

Q3. Write a java program using Random class to handle exceptions.


CODE:
import java.util.Random;
class HandleError{
public static void main(String args[]){
int a=0,b=0,c=0;
Random r=new Random();
for(int i=0;i<5;++i){ //while(hasmore
try{
b=r.nextInt();
c=r.nextInt();
a=12345/(b/c);
}
catch(ArithmeticException e){
System.out.println("Division by zero.");
System.out.println("You have Exception"+e);
a=0;
}
System.out.println("a ="+a);
}
}
}
OUTPUT:
C:\Users\LAB01-PC19\Desktop\java excep>javac HandleError.java
C:\Users\LAB01-PC19\Desktop\java excep>java HandleError
a =12345
a =-2469
a =12345

Page 13 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-09 Date:06/07/2023

Division by zero.
You have Exceptionjava.lang.ArithmeticException: / by zero
a =0
Division by zero.
You have Exceptionjava.lang.ArithmeticException: / by zero
a =0

Q4. Write a java program to demonstrate the use of throw keyword


CODE:
class ThrowDemo{
static void proc(){
try{
//NullPointerException e=new NullPointerException("demo");
//throw e;
throw new NullPointerException("demo");
}
catch(NullPointerException e){
System.out.println("Caught inside proc");
throw e; //Rethrow the exception
}
}
public static void main(String args[]){
try{
proc();
}
catch(NullPointerException e){
System.out.println("Recaught: "+e);
}
}
}
OUTPUT:
C:\Users\LAB01-PC19\Desktop\java excep>javac ThrowDemo.java

C:\Users\LAB01-PC19\Desktop\java excep>java ThrowDemo


Caught inside proc
Recaught: java.lang.NullPointerException: demo

//throw keyword: Used to raise an built-in or user defined exception manually and also to
rethrow an exception
//throws keyword: Gives list of Exceptions that can be raised by the program
//caller of the method should safeguard the code using try block which is prone to exceptions
mentioned in throws list

Page 14 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-09 Date:06/07/2023

Q5. Write a java program to demonstrate the use of throws keyword


CODE:
class ThrowsDemo{
static void throwOne() throws IllegalAccessException{
System.out.println("Inside throwOne");
throw new IllegalAccessException("demo");
}
public static void main(String args[]){
try{
throwOne();
}
catch(IllegalAccessException e){
System.out.println("Caught "+e);
}
}
}
OUTPUT:
C:\Users\LAB01-PC19\Desktop\java excep>javac ThrowsDemo.java
C:\Users\LAB01-PC19\Desktop\java excep>java ThrowsDemo
Inside throwOne
Caught java.lang.IllegalAccessException: demo

Q5. Write a java program to demonstrate user defined exception.


Write a java program to demonstrate the use of Throwable class, by illustrating that the
object of class that extends Throwable can be thrown and caught.
Hint:(Note that Exception is a subclass of The Throwable and thus create a user defined
class MyException that will extend Throwable class)
CODE:
import java.lang.Exception;
class MyException extends Exception{
MyException(String msg){
super(msg); //calling constructor of Parent class Exception
}
}
class TestException{
public static void main(String args[]){
int x=5,y=1000;
try{
float z=(float)x/(float)y;
if(z<0.01){
throw new MyException("Number is too small ....");
}
}

Page 15 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-09 Date:06/07/2023

catch(MyException e){
System.out.println("Caught My Exception"+e);
System.out.println(e.getMessage());
}
finally{
System.out.println("....I am always here....");
}
}
}
OUTPUT:
C:\Users\LAB01-PC19\Desktop\java excep>javac TestException.java
C:\Users\LAB01-PC19\Desktop\java excep>java TestException
Caught My ExceptionMyException: Number is too small ....
Number is too small ....
....I am always here....

Page 16 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-10 Date:07/07/2023

PRACTICAL-10
Java programming on FILE HANDLING

Q.1 Write a java program for reading data from one file and copy it to another file by using
FileReader and FileWriter class.

Create a input.txt file for reading the data:

CODE:
import java.io.*;
class CopyFile{
public static void main(String args[]){
File FI=new File("input.txt");
File FO=new File("output.txt");
FileReader fr=null;
FileWriter fw=null;

try{
fr=new FileReader(FI);
fw=new FileWriter(FO);
int ch;
while((ch=fr.read())!=-1){
fw.write(ch);
System.out.print(""+ch);
}
}
catch(IOException e){
System.out.println(e);
System.exit(-1);
}
finally{
try{
fr.close();
fw.close();
System.out.println("\n\n.........Its Done ..........\n");
System.out.println("...See input.txt and output.txt file...\n\n");
}
catch(IOException e) { }
}
}
}

Page 17 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-10 Date:07/07/2023

OUTPUT in Console:
C:\Users\LAB01-PC19\Desktop\java file>javac CopyFile.java

C:\Users\LAB01-PC19\Desktop\java file>java CopyFile


10410532104101108108111

.........Its Done ..........

...See input.txt and output.txt file...


OUTPUT in output.txt file: This file in which writing is done will be created automatically

Page 18 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-11 Date:11/07/2023

Practical-11
Java Programming on threads and multithreading
Q1. Write a java program to create and execute a thread.
CODE:
//Creating only one thread

class CurrentThreadDemo{
public static void main(String args[]){ //Main is always the first thread to be formed

Thread t=Thread.currentThread();
System.out.println("Current thread:"+t);
//change the name of the thread
t.setName("My SYCS Thread");

System.out.println("After name change:"+t);


try{
for(int n=5;n>0;n--){
System.out.println(n);
//Thread.sleep(1000);
Thread.sleep(5000);
}
}
catch( InterruptedException e){
System.out.println("Main thread is interrupted");
}
}
}
OUTPUT:
C:\Users\LAB01-PC18\Desktop\java>javac CurrentThreadDemo.java

C:\Users\LAB01-PC18\Desktop\java>java CurrentThreadDemo
Current thread:Thread[main,5,main]
After name change:Thread[My SYCS Thread,5,main]
5
4
3
2
1
Java threads can be created in two ways:
• By Extending Thread Class
• Implementing a Runnable interface

Q.2 Write a java program to demonstrate multi-threading by extending thread class


//Multi - threading : Creating two or more threads at a time
//Creating a second thread by extending parent class thread

Page 19 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-11 Date:11/07/2023

CODE:
class MyThread extends Thread{
MyThread(){
//Create a new, second thread
super("Demo Thread");
System.out.println("Child Thread:"+this);
start(); //Start the threads
//start() method calls the run() method
}
//This is the entry point for the second thread i.e. run() method

public void run(){ //Overriding run() method of thread class


try{
for(int n=5;n>0;n--){
System.out.println("Child Thread: "+n);
Thread.sleep(500);
}
}
catch( InterruptedException e){
System.out.println("Child thread is interrupted");
}
System.out.println("Exiting child thread");
}
}
class ExtendThread{
public static void main(String args[]){ //Main is the parent thread (first thread)

new MyThread(); //creating obj and calling constructor of class MyThread


try{
for(int n=5;n>0;n--){
System.out.println("Main Thread: "+n);
Thread.sleep(1000);
}
}
catch( InterruptedException e){
System.out.println("Main thread is interrupted");
}
System.out.println("Main thread exiting");
}
}
OUTPUT:
C:\Users\LAB01-PC18\Desktop\java>javac ExtendThread.java

C:\Users\LAB01-PC18\Desktop\java>java ExtendThread
Child Thread:Thread[Demo Thread,5,main]

Page 20 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-11 Date:11/07/2023

Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread
Main Thread: 2
Main Thread: 1
Main thread exiting

Q.3 Write a java program to demonstrate multi-threading by implementing Runnable


interface.
CODE:
class MyNewThread implements Runnable{
Thread t;
MyNewThread(){
t=new Thread(this,"Demo Thread");
System.out.println("Child Thread:"+t);
t.start(); //start() method calls the run() method
}
public void run(){ // defining the run() method of Runnable interface
try{
for(int i=5;i>0;i--){
System.out.println("Child Thread:"+i);
Thread.sleep(500);
}
}
catch(InterruptedException e){
System.out.println("Child Interrupted...");
}
System.out.println("Exiting child thread");
}
}
class ThreadDemo{
public static void main(String args[]){
new MyNewThread();
try{
for(int i=5;i>0;i--){
System.out.println("Main Thread :"+i);
Thread.sleep(1000);
}
}

Page 21 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-11 Date:11/07/2023

catch(InterruptedException e){
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting");
}
}
OUTPUT:
C:\Users\Rag\Desktop\java\p11>javac ThreadDemo.java

C:\Users\Rag\Desktop\java\p11>java ThreadDemo
Child Thread:Thread[#20,Demo Thread,5,main]
Main Thread :5
Child Thread:5
Child Thread:4
Main Thread :4
Child Thread:3
Child Thread:2
Child Thread:1
Main Thread :3
Exiting child thread
Main Thread :2
Main Thread :1
Main thread exiting

Q4.Write a java thread program to demonstrate the use of synchronised keyword.


CODE:
class Callme {
synchronized void call(String msg) {
System.out.print("[" + msg);
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println("Interrupted");
}
System.out.println("]");
}
}
class Caller implements Runnable {
String msg;
Callme target;
Thread t;
public Caller(Callme targ, String s) {
target = targ;
msg = s;
t = new Thread(this);

Page 22 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-11 Date:11/07/2023

t.start();
}
public void run() {
target.call(msg);
}
}
class Synch {
public static void main(String args[]) {
Callme target = new Callme();
Caller ob1 = new Caller(target, "Hello");
Caller ob2 = new Caller(target, "Synchronized");
Caller ob3 = new Caller(target, "World");
// wait for threads to end
try {
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch(InterruptedException e) {
System.out.println("Interrupted");
}
}
}
OUTPUT1 : Without Using synchronised keyword
C:\Users\Rag\Desktop\java\p11>javac Synch.java
C:\Users\Rag\Desktop\java\p11>java Synch
[Hello[World[Synchronized]
]
]
OUTPUT 2: Using synchronised keyword
C:\Users\Rag\Desktop\java\p11>javac Synch.java

C:\Users\Rag\Desktop\java\p11>java Synch
[Hello]
[Synchronized]
[World]

Page 23 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-12 Date:17/07/2023

Practical-12
Java socket programming

Q. Write a Java program to demonstrate socket programming.


Server CODE:
import java.net.*;
import java.io.*;
class MyServer {
public static void main(String args[]) throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("Client says:"+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}
}
Client CODE:
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[]) throws Exception {
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says:"+str2);

Page 24 of 25
BHAVANS COLLEGE AUTONOMOUS, ANDHERI WEST
PRACTICAL JOURNAL
SYCS
Class: _____________ 3
Sem: _____ Date of Performance: ___________
Introduction to Java Programming
Course Name:_________________________ BH.USCSP302
Course Number: __________
Practical Number: _______ Page Number: _______

Aim:

Teacher’s Signature : ____________________________


SYCS13 Practical-12 Date:17/07/2023

}
dout.close();
s.close();
}
}
Note:
➢ Open two Command Prompt – one for server and another for client program execution.
➢ Run the server code first. Send a first message from client to server and then message
from server to client. Continue messaging.
➢ When messaging is done then Type ‘stop’ from client side first then type stop from
server side.
Server OUTPUT:
C:\Users\Rag\Desktop\java\p11>cd C:\Users\Rag\Desktop\java\p11
C:\Users\Rag\Desktop\java\p11>set path="C:\Users\Rag\Downloads\jdk-20_windows-
x64_bin\jdk-20.0.1\bin"
C:\Users\Rag\Desktop\java\p11>javac MyServer.java

C:\Users\Rag\Desktop\java\p11>java MyServer
Client says:Client speaking
Server here, hi hello client
Client says:i being client request for the data access
ok Request processing
Client says:Waiting ..... for server reply
Access permitted to client
Client says:stop
stop
Client OUTPUT:
C:\Users\sycs13\Desktop\java\p11>cd C:\Users\sycs13\Desktop\java\p11
C:\Users\sycs13\Desktop\java\p11>set path="C:\Users\sycs13\Downloads\jdk-20_windows-
x64_bin\jdk-20.0.1\bin"

C:\Users\sycs13\Desktop\java\p11>javac MyClient.java

C:\Users\sycs13\Desktop\java\p11>java MyClient
Client speaking
Server says:Server here, hi hello client
i being client request for the data access
Server says:ok Request processing
Waiting ..... for server reply
Server says:Access permitted to client
stop
Server says:stop

Page 25 of 25

You might also like