You are on page 1of 71

PROGRAMMING WITH JAVA LAB

Subject Code: LPCIT-109

PRACTICAL FILE

SUBMITTED BY: SUBMITTED TO:


Vivek Dhiman Prof. Rupinder kaur
1921116/1905415
D3IT-B2

Information Technology Department


GURU NANAK DEV ENGINEERING COLLEGE
LUDHIANA, INDIA
INDEX
S7No. Name of the Experinent Page Date of Daie of Remarl
No. Experiment Submission

02 s/9/21
Hand Ling dada yf 2 Is//1
19/4/21
ID/LD Avvay 31 22/7/21
Varjou dslov G/lol
Kecusio -9 14 1|21
Method ovtr loding 7-8 1 |1M
Construcor overloncing 9 lo
Vurio o AL Condrell
A-vSay
hd 4n ie a 1 2
Date. /5/2/2 L

Expt. 1 Page No.

Pim Han dlin VUu0u2 dta yhna

Pumitive data tps J Jova

CHarat Integu Floating Poirt Bookann

byte Shart tht toN n t do bases


Chor

Pho gran
CHAR

ChaDataTste
ps Stli vold main ( Sting ar L1)

Chor mayks gYAd4


maYks = "8
greck B'
Sysa m o bintln C Mav lo tnmayks);
em brintkn C"aad 1 ynde )j

Toacher's Sign.
ProblemsJavadoc Declaration Console Git Staging
<terminated> DataTypes [Java Application] D:teclipse-jee-2021-06-R-win32-x86_64\e
123322
-42937.9
19.98
false
vivek
Date.

Page No. 2
Expt.

ALL DtaTyha In Ons froqysm


cls Deda Tyhs
pubtiz Sttic a i d m a i n CSiing av ) 2
long num 1 23322L
Sytdmot.prinln (hom)

doulle numl-42137,1d
System.od.pintln num)

Mot num2 19218


Syslum o pintln (hum

boadean b =-
Syslarm ost pintln CA2;

Char ch Vivek *_
Sysam opiniln(Ch)j

Teacher's Sign.
ProblemsJavadoc Declaration Console 2 Git Staging

terminated» Test (Java Application) D:\eclipse-jee-2021-06-R-win32-xe6 64\eclipse pi

Int Value 100


long Value 100
float Value 100.0
Double Value 100.04
Long Value 100
Int Value 100
Date 19/3121
Page No.
Expt. 2

Aim teCastng

Cla Test
public S t i vehd main Sting arj L )

automaic tyte Comyeion


Long = L

Iautomal he_Lonyeuion
Syatim out pinl 2n Trd Vlut. " iD
Syaim o nnto " Leng Va e);
Systany ok þnnta ( pat ek t)
d loo oY

piatut tya Casli ng


lon m Lkong)d

itn int ) ,
Siyslin ou_pit. C DoA Mahs+d);
I_rtiond povt s
Teacher's Sign.
ProblemsJavadocDeclaration Console Git Staging

D:\eclipse-jee-2021-06-R-win32-x86_64\eclipse
terminated> Test1 [Java Application]
Conversion of int to byte
i-257b=1

Conversion of double to byte


d 323.142b=67
Date

Expt. Page No.

Syst maul pn n Cong valu. "tm)

IL uonal parf lost


Syatim ou p n " Zt Malue +h)

Split ghConveion
mLAnd domui n isdd th pyoqYimmu
Imilicit1 Conveysiym
miams Jhat as donu b th Compi

Java rogya m u sus trai_Conyusion t


and doulo A byt
ClaTet S
puHshD id main(Stri_arol)
byi bj
nt 252
dousle d 3 , 112
Syo pintln C Conysio n int & b y ) ;

Sysüm. o pinte ("i: " + "b- "+ b );

dos to by )

bbyad " "


dyjum. out. pri nt n "d : "u+ b: +5);
Te acher's Sig1.
ProblemsJavadocDeclarationConsole Git Staging
cterminated Example lava Application) DNeclipse-jee-2021-06-R-win32-x86 64\eclipse
11
22
33

ProblemsJavadoc Declaration Console Git Staging

terminateds TwoDimensional [lava Application) D'leclipse-jee-2021-06-R-win32-x86.6

MrKumar
MrsKumar
Date. 2z//
Expt. 2 Page No.

Aim ray D 4 2p

On dimunsionsN

public clas Exambl


plie stslit vsid main CShi axg C1)
nt C num
numbu n t Clol
numur C]
num1-22,
a mbu [2]: 33
J r lint i=o numbeu Rongf tt2
Syslimed Bintln numku Ci1 D
3

Tn dim r
Clas Iubdimmaions
public Shut vaid mdin ( Shinyarg C3)
SSthng ) IM Sluton
Mrs Ms

lo) [»1 salutio L17 [:J


ysum.oud pi ntn Saldat
Sysum od pnnt (Su ti[o}[i) Slub4iow Til
Teacher's Sign.
ProblemsJavadoc t Declaration Console 2 Git Staging

terminated> do_while [Java Application] D\eclipse-jee-2021-06-R-win32 86 54\ecipse


Enter Your Marks:

Great You Are Pass


Date.
Expt. 5 Page No.

Aim Vanous Dedsisn Strutor


robln
pblitclas de.wh
puslir SBilic votd main Shhnj oC)1
Scann Scan new SCanT CSysimin)
Syatem u t pvi dlh Ehtiy ouy Mavka "),

Lat mar ks Scan. nMtInd


do
(mads
>:6o)
Sysin o. pintln 7eslYou Ae Pas*)
elac elsc
Syam_o infkn ( Sor You a r t feat)
ma leg <60)

Toacher's Sign.
Console DRecursionjava
<terminated> Recursion [Java Application) C:\Program Files Javajdk-16

hello 1
hello 2
hello 3
hello 4
hello 5
Date 3ot 9
Expt. Page No

Reaniipn
bublir as Rtclem
Stu Unt Counl
3tute weidp
Qnt

CCaunt<: s )
Sysem o p n t en
oll +COnt)
3
3
ult Sti vid main (Ating L ang )
poj
3

achor's Sign
Console Recursionjava

cterminated> Recursion [Java Application]

22
33
Date.

Expt. Page No.

Aim Mthod Ove lodiny o

Addu
Aat ist dd int a,int b ) on_at
ShticLnt add Cint a
ini b, iade)
AAuzn atbtc

las TtOnalsacurg
DublicSttir_vid man 31 nmg wug L)
pnt nCAAdee, add l ll, 1D)
Syalimout println Addu add [/1, 1/, 1))

Teacher's Sign.
OConsole Studentjava
terminated> Student [lava Application) C\Program Files Javaljdk-16.0.21binljavav
this a default constructor

Default Constructor values:

Student Id : 0
Student Name null
Parameterized Constructor values:

Student Id 10
Student Name David
Date.

Expt. Page No. 1

Aim Const uctor Ovenlonding paasin


LANU menls

i clas Stclent

Stnng name

Studert C)
Syam pant e the dault congirucho)
Stucdent(mt i Stin )
Nam

publu Sttd void maim (Stmy ay CJ) 1


Studenk S= nus Student ) ,
Ssystim out pnntRn C\n Depdt Const rutar
SyatbnGAt pnatin Studat 1d: "+S.id+"hStu def
eme
SystomdArst (A In Parane lied Cangrvutrr Vilu
Studant Stoden nlu Stdert Clo, David')
Salin out prin1in SHudentIA"tshuont. idt n Sd
Nom Sfudant na m 2
3

Teacher's Sign.
Console 3Studentjava
terminated» Student [Java Application] CAProgram Files Javaljdk-16.0.2
111 VIVEK Gne College
222 GOOGLE Gne College
Date.
Expt Page No.

An aions acc enioal _and Adag


Adagc
Atalu ihal and fins Cit )
Stalit
In uva ca Llass mumb
Muet
inat CYtal n
LnLanLe Lh class
CLasd
B Lhauwill u Attvaluond whetutLoal L
a LumClan. wlhDulCxLalung vauah,

Clas 9tudent

String nem
Stalpo S1ing Colisgt bne Catiey
Stuknt int h
Stiy h )1
n

td
dshle ) Sgaltm ou pitlu ellone "
Celigcoltcyc)j
pubicSthluc vod main tede
S1nng )
ary)
Shudtnt S1 n ew Stedent "Viek ),_
Shdent S
S dis pla,
S play

Teachor iqn
clejava
Java Application] C\Program FilesJava
jdk-16.0.2\binijavaw.exe (16-Nov-2021, 3:59:27 pm -3:59:32 pm
thread "main" java.lang.Error: Unresolved
compilation
final field Vehicle. speedlimit cannot be assigned

ecursion.vivek. Vehicle. controlSpeed (Vehicle. java:8)


ecursion.vivek.Vehicle.main (Vehicle.java:12)

OConsole demojava
<terminated» demo Java Application] C\Program
Files\Javaljdk-16.0.2\bin\javaw.exe (16-Nov-2021, 4
inside demo's finalize ())
Calling finalize method of the Object class
Date.
Expt. Page No.

inal sdk_dnst C2ta- Lacdwrlb


vauahles mihdb

publue a s hicu
hina imt ptzd nut KO
Veid LonthadSpuul) 1
Lptud aiii 1So

1tmahn Sting o )
VehrrleO
_cb Cont rd Spd C)

inaliz (

Jnpart
pabirClas dne
peli
palkclicld nali zu ) hias Thenble
t S Cam cui pirtinInde dimes nalizu")

cikh CThrowrbis e) fhro


in L Syslim cut bnile Cally kinal mehod

DuhlrStie main (ing av )thoew Threwrsu


neu dime)
c
Teacher's Sign.
31
Console 3demojava
<terminated> demo [lava Application]
C:\Program Files\Java
Argument One=apple jdk-16.0.2binjavaw.exe (16-Nov-2021, 4
Argument Two orange
Date.

Expt.0 Page No. / L

ommsnd lise gsumisf

Th Comman as a7gumat
Jhi bragremmA the rgu mn
eXculuon proqysm T
COn t h Orauminlu dusing
mmird d lis
ei by pa
Argums

Command
1, 4
bulie
Ora
Suan d pd O Argamint_Dra + b L:] )
Sttm.ot prialln Aryume tuo t bl/)

Teacher's Sign.
PROGRAMMING WITH JAVA LAB
Subject Code: LPCIT-109

PRACTICAL FILE

SUBMITTED BY: SUBMITTED TO:


Vivek Dhiman Prof. Rupinder kaur
1921116/1905415
D3IT-B2

Information Technology Department


GURU NANAK DEV ENGINEERING COLLEGE
LUDHIANA, INDIA
PRACTICAL 11
Various types of inheritance by applying various access controls to its data
members and methods

SINGLE INHERITANCE

package programs;
class Animal{
void eat(){
System.out.println("eating...\n");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking....\n");
}
}
public class SingleInheritance {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.eat();
d1.bark();

}
}

OUTPUT:
MULTILEVEL INHERITANCE
package programs;

package programs;

class Student {
final String clg = "GNDEC";
int year;

void setYear(int yr) {


year = yr;
}

class ItStudent extends Student {


long rollNo;

void setRollNO(long rollNo) {


this.rollNo = rollNo;
}

void showDetail() {
System.out.println("clg: " + clg + " year: " + year);
}

class SmaElectiveStudent extends ItStudent {


void showElective() {
System.out.println("Elective: SMA");
}

void showDetail() {
System.out.println("clg: " + clg + " year: " + year +" RollNO. : "+rollNo);
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
// Student s0 = new Student();
// s0.setYear(3);
ItStudent s1 = new ItStudent();
SmaElectiveStudent s2 = new SmaElectiveStudent();
s2.setYear(3);
s1.setRollNO(12345);
s2.setRollNO(56789);
s2.showDetail();

s2.showElective();

s1.showDetail();

}
}

OUTPUT:
HIERARCHICAL INHERITANCE
package programs;
class Cycle{
protected String companyName = "Hero";
void NoOfWheels(){
System.out.println("Bicycle have 2 wheels\n");
}
}
class CycleWithGear extends Cycle{
void NoOfGears(){
System.out.println("This Bicycle have 3 gears\nCompanyName: "+ companyName);
}
}
class CycleWithoutGear extends Cycle{
void typeOfBrake(){
System.out.println("This Bicycle is fitted with Disk brake\n");
}
}

public class HierarchicalInheritance {


public static void main(String[] args) {
CycleWithGear c1 = new CycleWithGear();
c1.NoOfWheels();
c1.NoOfGears();
}
}
OUTPUT:
PRACTICAL 12
Method overriding

package programs;
class CollegeStudent{
void degreeCourse(){
System.out.println("\n\nEnrolled in a degree course");
}
}
class BtechStudent extends CollegeStudent{
@Override
void degreeCourse(){
System.out.println("\n\nEnrolled in B.tech degree course");
}
}

class BcaStudent extends CollegeStudent{


@Override
void degreeCourse(){
System.out.println("\n\nEnrolled in BCA degree course");
}
}

class Itstudents extends BtechStudent{


@Override
void degreeCourse(){
System.out.println("\n\nEnrolled in IT branch Btech degree course");
}
}
public class MethodOverriding {
public static void main(String[] args) {
BtechStudent s1 = new BtechStudent();
s1.degreeCourse();

Itstudents s2 = new Itstudents();


s2.degreeCourse();

}
}

OUTPUT:
PRACTICAL 13
Abstract class
package programs;
abstract class TwoWheelerVehicle{
TwoWheelerVehicle(){
System.out.println("It is a Two Wheeler vehicle (Parent Constructor Called)");
}

abstract void type();

void haveGear(){
System.out.println("It has gears");
}
}

class Bike extends TwoWheelerVehicle{

void type(){
System.out.println("This is a sports Bike");
}
}

class Scooter extends TwoWheelerVehicle{


void type(){
System.out.println("This is a Scooter");
}
}

public class AbstractClass {


public static void main(String[] args) {
TwoWheelerVehicle v1;
v1 = new Scooter();
v1.haveGear();
v1.type();

v1 = new Bike();
v1.haveGear();
v1.type();

}
}
OUTPUT:
PRACTICAL 14
Nested class

package programs;
class OuterClass {
private static int p = 10;
static int s = 12;

int x = 11;

void fun() {
System.out.println("This is method inside outer class");
}

static class StaticNestedClass {


void display() {
System.out.println("private static member of OuterClass: " + p);
System.out.println("static member of OuterClass: " + s);

}
}

class InnerClass {
void display() {
System.out.println("private static member of OuterClass: " + p);
System.out.println("static member of OuterClass: " + s);
System.out.println("non-static member of OuterClass: " + x);
}
}
void getValue() {
int sum = 10;
// Local Inner class
class LocalInnerClass {
int divisor;
int remainder;

LocalInnerClass(int divisor) {
this.divisor = divisor;
}

int division() {
remainder = sum % divisor;
return remainder;
}
}
LocalInnerClass localInnerClass = new LocalInnerClass(4);
System.out.println("Division Remainder: " + localInnerClass.division());
}

public class NestedClasses {


public static void main(String[] args) {
OuterClass.StaticNestedClass innerStatic = new OuterClass.StaticNestedClass();
// innerStatic.fun(); // can't access
innerStatic.display();

// Anonymous Class
OuterClass outerClass = new OuterClass(){
@Override
void fun(){
System.out.println("This is fun method overridden in anonymous class");
}

};
OuterClass.InnerClass innerClass = outerClass.new InnerClass();
// innerClass.fun(); // can't access
innerClass.display();

outerClass.getValue();
System.out.println("___________________");

outerClass.fun();
}
}

OUTPUT:
PRACTICAL 15

Constructor chaining

package programs;
class Shape{
String shapeName;
int sides;
Shape(){
System.out.println("This is a Shape class");
}

Shape(String shapeName){
this();
this.shapeName = shapeName;
System.out.println("Shape: "+shapeName);
}

Shape(int sides){
this("rectangle");
this.sides = sides;
System.out.println("sides: "+sides);
}

class Rectangle extends Shape{


int length;
int breadth;
int area;

Rectangle(){
super(4);
System.out.println("This is Rectangle Class");
}

Rectangle(int x, int y){


this();
length = x;
breadth = y;
}

void area(){
System.out.println("Area: "+ length*breadth);
}
}

public class ConstructorChainingParvesh {


public static void main(String[] args) {
Rectangle r1 = new Rectangle(4, 5);

r1.area();
}
}

OUTPUT:
PRACTICAL 16
Importing classes from user defined package and creating packages using
access protection

//Saved as UserDefinedPackage.java
package com.mypack;
public class UserDefinedPackage{
private int x = 78;
protected String name = "Parvesh";
public int y = 19;

protected UserDefinedPackage(){
System.out.println("This is A class in com.mypack");
}

protected void show(){


System.out.println("This is show method of A class in com.mypack");
System.out.println("Name: "+ name);
System.out.println("x: "+x);
System.out.println("y: "+y);
}
}
// This file saved as ImportClass.java in protectedacces package
package protectedaccess;
import com.mypack.*;
public class ImportClass extends UserDefinedPackage {
void showDetails(){
y = 2;
name = "Ram";
System.out.println("y in ImportClass: "+ y);
System.out.println("Name in ImportClass: "+name);
}
public static void main(String[] args) {
ImportClass impc1 = new ImportClass();
impc1.show();
impc1.showDetails();

}
}

OUTPUT:
PRACTICAL 17
Interfaces, nested interfaces and use of extending interfaces

INTERFACE
package programs;
interface Book{
void showTitle();
void showPrice();
}

class JavaBook implements Book{


int price;
String name;

JavaBook(String name, int price){


this.name = name;
this.price = price;
}

@Override
public void showTitle(){
System.out.println("Book Name: "+name);
}

@Override
public void showPrice(){
System.out.println("Price: "+price);
}
}
public class InterfacesInJava {
public static void main(String[] args) {
JavaBook jb1 = new JavaBook("JavaProgramming", 300);
jb1.showTitle();
jb1.showPrice();
}
}
OUTPUT:

NESTED INTERFACES AND USE OF EXTENDING INTERFACES


package programs;
//Interface inside a class
class Car{
protected interface ShowModel{
void show();
}
}
// Nested interface inside a interface
interface Vehicles{
interface FourWheelers{
void showEngine();
void showFuelType();
}
}

interface TwoWheelers extends Vehicles.FourWheelers{


void showModel();
}
class Ferrari implements Car.ShowModel, Vehicles.FourWheelers{
@Override
public void show(){
System.out.println("\nCar Model: Ferrari 812");
}

public void showEngine(){


System.out.println("Engine: 6496cc");
}

public void showFuelType(){


System.out.println("Fuel Type: Petrol\n");
}
}

class KTM implements TwoWheelers{


public void showModel(){
System.out.println("Model: KTM RC 200");
}

public void showEngine(){


System.out.println("Engine: 199cc");
}

public void showFuelType(){


System.out.println("Fuel type: Petrol\n");
}
}
public class NestedInterfaces {
public static void main(String[] args) {
Car.ShowModel sm1 = new Ferrari(); //upcasting here
sm1.show();
Vehicles.FourWheelers tw1 = new Ferrari(); //upcasting here
tw1.showEngine();
tw1.showFuelType();

TwoWheelers tw2 = new KTM();


tw2.showModel();
tw2.showEngine();
tw2.showFuelType();
}
}

OUTPUT:
PRACTICAL 18
To Demonstrate Exception Handling - using predefined exception

package com.mypack;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

class Division{
int a, b;
Division(int a, int b){
this.a = a;
this.b = b;
if(b==0){
throw new ArithmeticException("Can not divide by zero!!");
}
}

void showQuotient(){
System.out.println("Quotient: "+a/b);
}
}

class CheckedException{
void readFile() throws FileNotFoundException{
File f1 = new File("D:\\FileOne.txt");

Scanner sc = new Scanner(f1);


while(sc.hasNextLine()){
String s1 = sc.nextLine();
System.out.println(s1);
}
sc.close();
}
}
public class PredefinedException {
public static void main(String[] args) {
try{
try{
Division d1 = new Division(12, 0);
d1.showQuotient();
}catch(ArithmeticException e){
System.out.println("Can not divide by zero");
e.printStackTrace();
}

CheckedException che1 = new CheckedException();


che1.readFile();
}
catch(FileNotFoundException fe1){
System.out.println("unexpected error occur, can't read from file!!");
fe1.printStackTrace();
}
System.out.println("Rest of code after exception ....");
}
}

OUTPUT:
PRACTICAL 19
To Demonstrate Exception Handling - creating user defined exceptions
package com.mypack;

class NotFitForVote extends Exception{


NotFitForVote(){
System.out.println("Age is less than 18, You can't vote :(");
}
NotFitForVote(String s){
System.out.println(s);
}
}

class Vote{
int age;
Vote(){

}
void checkAgeForVoting(int age) throws NotFitForVote{
if(age<18){
throw new NotFitForVote("You can not vote now, but after "+(18-age)+" year/years
you can vote");
}else{
System.out.println("You can Vote :)");
}
}
}
public class UserDefinedException {
public static void main(String[] args) {
try {
Vote v1 = new Vote();
v1.checkAgeForVoting(17);
} catch (Exception e) {
e.printStackTrace();
}

System.out.println("Rest of the code after exception....");


}
}

OUTPUT:
PRACTICAL 20
TO DEMONSTRATE MULTITHREADING BY EXTENDING THREAD
CLASS

package com.mypack;

class DemoThread extends Thread{


@Override
public void run() {
try {
System.out.println("Thread "+Thread.currentThread().getId()+" is running");
} catch (Exception e) {
e.printStackTrace();
}

for(int i=0; i<5; i++){


System.out.println("DemoThread loop is running: "+i);
}
}
}

public class MultithreadingByExtendingThreadClass {


public static void main(String[] args) {
DemoThread dmt = new DemoThread();
dmt.start();
for(int i=0; i<5; i++){
System.out.println("MainThread loop is running: "+i);
}
}
}
OUTPUT:
PRACTICAL 21
TO DEMONSTRATE MULTITHREADING BY IMPLEMENTING
RUNNABLE INTERFACE

package com.mypack;

class DemoClass implements Runnable {

public void run(){

for(int i=0; i<=5; i++)

System.out.println("DemoClass thread: "+i);

public class ThreadByImplementRunnable {

public static void main(String[] args) {

DemoClass dm1 = new DemoClass();

Thread th = new Thread(dm1);

th.start();

for(int i=0; i<=5; i++)

System.out.println("Main thread: "+i);

OUTPUT:
PRACTICAL 22
To demonstrate Thread life cycle

package com.mypack;

class MyThread implements Runnable

public void run()

// moving thread2 to timed waiting state

try

Thread.sleep(1500);

catch (InterruptedException e)

e.printStackTrace();

System.out.println("State of thread1 while it called join() method on thread2 -"+

ThreadLifeCycle.thread1.getState());

try

Thread.sleep(200);

catch (InterruptedException e)

e.printStackTrace();
}

public class ThreadLifeCycle implements Runnable

public static Thread thread1;

public static ThreadLifeCycle tlc;

public static void main(String[] args)

tlc = new ThreadLifeCycle();

thread1 = new Thread(tlc);

// thread1 created and is currently in the NEW state.

System.out.println("State of thread1 after creating it - " + thread1.getState());

thread1.start();

// thread1 moved to Runnable state

System.out.println("State of thread1 after calling .start() method on it - " +

thread1.getState());

public void run()

MyThread myThread = new MyThread();

Thread thread2 = new Thread(myThread);

// thread2 created and is currently in the NEW state.

System.out.println("State of thread2 after creating it - "+ thread2.getState());

thread2.start();
// thread2 moved to Runnable state

System.out.println("State of thread2 after calling .start() method on it - " +

thread2.getState());

// moving thread1 to timed waiting state

try

//moving thread1 to timed waiting state

Thread.sleep(200);

catch (InterruptedException e)

e.printStackTrace();

System.out.println("State of thread2 after calling .sleep() method on it - "+

thread2.getState() );

try

// waiting for thread2 to die

thread2.join();

catch (InterruptedException e)

e.printStackTrace();

System.out.println("State of thread2 when it has finished it's execution - " +

thread2.getState());

}
}

OUTPUT:
PRACTICAL 23
To demonstrate Applet life cycle
package com.mypack;

import java.applet.*;

import java.awt.*;

@SuppressWarnings("serial")

/*

<applet code="Hello World" width=200 height=60>

</applet>

*/

public class AppletLifeCycle extends Applet

public void init()

System.out.println("1.I am init()");

public void start()

System.out.println("2.I am start()");

public void paint(Graphics g){

System.out.println("3.I am paint()");

public void stop()

{
System.out.println("4.I am stop()");

public void destroy()

System.out.println("5.I am destroy()");

OUTPUT:
PRACTICAL 24
To demonstrate Applet for configuring Applets by passing parameters

package com.mypack;

import java.awt.*;

import java.applet.*;

/*

<applet code="Applet8" width="400" height="200">

<param name="Name" value="Roger">

<param name="Age" value="26">

<param name="Sport" value="Tennis">

<param name="Food" value="Pasta">

<param name="Fruit" value="Apple">

<param name="Destination" value="California">

</applet>

*/

public class AppletParam extends Applet{

String name;

String age;

String sport;

String food;

String fruit;

String destination;
public void init(){

name = getParameter("Name");

age = getParameter("Age");

food = getParameter("Food");

fruit = getParameter("Fruit");

destination = getParameter("Destination");

sport = getParameter("Sport");

public void paint(Graphics g) {

g.drawString("Reading parameters passed to this applet -", 20, 20);

g.drawString("Name -" + name, 20, 40);

g.drawString("Age -" + age, 20, 60);

g.drawString("Favorite fruit -" + fruit, 20, 80);

g.drawString("Favorite food -" + food, 20, 100);

g.drawString("Favorite destination -" + name, 20, 120);

g.drawString("Favorite sport -" + sport, 20, 140);

OUTPUT:
PRACTICAL 25
To demonstrate Event Handling

package com.mypack;

import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class EventHandling implements ActionListener{

JButton b;

TextField textField;

EventHandling(){

JFrame f = new JFrame("EventHandling");

textField = new TextField();

textField.setBounds(100, 50 , 200 , 40);

b = new JButton("Click Me");

b.setBounds(150, 150, 100, 30);

f.add(b);

f.add(textField);

f.setSize(400, 400);

f.setLayout(null);
f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

b.addActionListener(this);

public void actionPerformed(ActionEvent e){

b.setText("Hi! clicked..");

textField.setText("Welcome to EventHandling");

public static void main(String[] args){

new EventHandling();

OUTPUT:
PRACTICAL 26
To demonstrate Reading and writing from a particular file

Reading from File

package com.mypack;
import java.io.*;
public class ReadingAFile {
public static void main(String[] args) {
File file = new File("D:\\5th
Semester\\ProgrammingWithJava\\ParveshBhatt_1905375\\readFile.txt");
try{
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null){
System.out.println(str);
}
br.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
OUTPUT:

Writing to file
package com.mypack;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class WritingToFile {

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

Scanner sc = new Scanner(System.in);

System.out.println("Enter the text to be enetered in writeFile.txt file: ");

String text = sc.nextLine();

File file = new File("D:\\5th


Semester\\ProgrammingWithJava\\ParveshBhatt_1905375\\writeFile.txt");

BufferedWriter bfr = new BufferedWriter(new FileWriter(file));

bfr.write(text);

System.out.println("File is created successfully with the contents");

bfr.close();

sc.close();
}

OUTPUT:

PRACTICAL 27
To demonstrate Database connectivity for various DDL and DML
operations
package com.mypack;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

public class DatabaseConnectivity {

Connection connection;

Statement statement;

DatabaseConnectivity(){

try {

Class.forName("com.mysql.cj.jdbc.Driver");

System.out.println("1. Driver Loaded");

} catch (Exception e) {

System.out.println("Something went wrong: "+e);


}

public void createConnection(){

try {

String user = "Parvesh";

String password = "1234";

String url = "jdbc:mysql://localhost/parveshjavadb";

connection = DriverManager.getConnection(url, user, password);

System.out.println("2. connection created");

} catch (Exception e) {

System.out.println("Something went wrong: "+e);

public void createAndExecuteSQL(){

try {

statement = connection.createStatement();

System.out.println("4.1 Statement Created ");

String sql = "insert into Customer values(null, 'John', '9877665544', 'john@example.com');";

statement.executeUpdate(sql);

System.out.println("customer inserted successfully!!");

} catch (Exception e) {

}
}

public void closeConnection(){

try {

connection.close();

System.out.println("4. connection closed");

} catch (Exception e) {

System.out.println("something went wrong: "+e);

public static void main(String[] args) {

DatabaseConnectivity dbc = new DatabaseConnectivity();

dbc.createConnection();

dbc.createAndExecuteSQL();

dbc.closeConnection();

OUTPUT:
PRACTICAL 28
To demonstrate String class and its methods
package com.mypack;

import java.lang.String;

public class StringClass {

public static void main(String[] args) {

String str1="This is JAVA practical file";

String str2="Parvesh 1921078";

//methods in string class

String s1= str1.toLowerCase();

System.out.println(s1);

String s2=str2.toUpperCase();

System.out.println(s2);

if(s1.equals(s2)){

System.out.println("s1 and s2 are same");

} else{

System.out.println("s1 and s2 are not same");


}

String str3="CompuTEr";

String str4="COMputer";

if(str3.equalsIgnoreCase(str4)){

System.out.println("Str3 and str4 are same ");

} else{

System.out.println("Both are not same");

String str5="A boy";

String str6="A BoY";

System.out.println("Is it true"+str5==str6);

int a=str5.indexOf('b') ;

System.out.println("The index of b in str5 is: "+a);

int b=str6.indexOf('b', 2);

System.out.println(b);

int c=str6.indexOf("oY");

System.out.println(c);

int d=str6.lastIndexOf("oY", 5);

System.out.println(d);

String sc=str6.substring(2, 5);

System.out.println(sc);

OUTPUT:
PRACTICAL 29
To demonstrate StringBuffer class and its methods

package com.mypack;
import java.lang.StringBuffer;
public class StringBufferClass {
public static void main(String[] args) {
StringBuffer str=new StringBuffer("This is JAVA practical 29 ");
str.append("to demonstrate StringBuffer class and its method");
System.out.println(str);
StringBuffer str1= new StringBuffer("This is laptop");
str1.insert(8, "gaming ");
System.out.println(str1);
StringBuffer str2=new StringBuffer("code in Python");
str2.replace(8, 14, "Java");
System.out.println(str2);
str2.delete(5, 7);
System.out.println(str2);
StringBuffer str3=new StringBuffer("Java programming");
str3.reverse();
System.out.println(str3);
System.out.println(str2.capacity());
str2.ensureCapacity(45);
System.out.println(str2.capacity());
}
}
OUTPUT:

You might also like