Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java Programming

The document is a practical record for the Bachelor of Computer Application program at Navajyothi College, detailing various Java programming, shell programming, and Linux administration tasks completed during the 4th semester of the 2022-2023 academic year. It includes a certificate of authenticity, an index of tasks, and sample code for Java programs covering string operations, interfaces, exception handling, file I/O, applet lifecycle, and shell scripting. Each section provides code examples and explanations for the respective programming concepts.

Uploaded by

alexthomasatk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java Programming

The document is a practical record for the Bachelor of Computer Application program at Navajyothi College, detailing various Java programming, shell programming, and Linux administration tasks completed during the 4th semester of the 2022-2023 academic year. It includes a certificate of authenticity, an index of tasks, and sample code for Java programs covering string operations, interfaces, exception handling, file I/O, applet lifecycle, and shell scripting. Each section provides code examples and explanations for the respective programming concepts.

Uploaded by

alexthomasatk
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

BACHELOR OF COMPUTER APPLICATION

PRATICAL RECORD
4th SEMESTER 2022-2023

4B11BCA LAB IV: JAVA PROGRAMMING,

SHELL PROGRAMMING & LINUX ADMINISTRATION

1
NAVAJYOTHI COLLEGE
[AFFILIATED TO KANNUR UNIVERSITY]
Cherupuzha-670511

CERTIFICATE

Certified that it is the bonafide record of work done by


__________________________________________ in the computer
Laboratory NAVAJYOTHI COLLEGE during the academic
year 2022-2023

Place: Cherupuzha
Date:

Head of Department

Lecturer in charge:
External Examiners 1: 2:

2
JAVA PROGRAMMING

3
Index
JAVA
Sl. no Content Page no
Write a java program to perform various string
1 5
operations using java class
2 Write a java program to implement interface 7
Write a java program that handles various
3 8
exception. use try-catch statement
Write java program to implement file I/O operation
4 using java iostreams.
10
Write a java program to implement Applet life
5 12
cycle.
Write java program to implement a calculator
6 14
using suitable AWT controls
Write a java program to implement packages.
7 17
Write a java program with API support write
8 demo programs for menu display import 19

Write a java program to demonstrate threads.


9 21
Demonstration of FileInput Stream and
10 FileOutput Stream Classes. 23

4
1. Write a java program to perform various string operations using java
class.

import java.util.*;
class StringMan
{
public static void main(String args[ ])
{
Scanner sc= new Scanner(System.in);
System.out.print("Enter a string: ");
String str= sc.nextLine(); //reads string

System.out.println("Entered string :"+str);


System.out.println("Length of string: "+str.length());
for (int i=0;i < str.length(); i++)
{
int p = i+1;
System.out.println("Character at position "+ p + " is " +str.charAt(i));

}
System.out.print("Enter a string: ");
String str1= sc.nextLine();
System.out.println("String: "+str1);
System.out.println("*String Concatenation*");

String st=str.concat(str1);
System.out.println("Modifed string: "+st);

System.out.println("*To Lowercase*");

String stlower=st.toLowerCase();
System.out.println("Lower case: "+stlower);

5
System.out.println("To Uppercase");
String stupper=st.toUpperCase();
System.out.println("Upper case: "+stupper);

}
}

Output:

6
2 Write a program to implement interface
interface Area
{
final static float pi=3.14F;
float compute(float x,float y);
}
class Rectangle implements Area
{
public float compute(float x,float y)
{
return(x*y);
}
}
class Circle implements Area
{
public float compute(float x,float y)
{
return(pi*x*x);
}
}

class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect=new Rectangle();
Circle cir=new Circle();
Area area;
area=rect;
System.out.println("Area of Rectangles"+ area.compute(10,20));
area=cir;
System.out.println("Area of circle"+ area.compute(10,0));
}
}

7
3 Write java program that handles various exception . use try – catch
statement
import java.io.*;
import java.util.Scanner;
class ExceptionHandling1
{
public static void main(String args[])
throws IOException
{
int div,a,b;
int arr[]=new int[3];
Scanner ob= new Scanner(System.in);
System.out.println("\nEnter two numbers:");
try
{
a=Integer.valueOf(ob.nextLine());
b=Integer.valueOf(ob.nextLine());
div=a/b;
System.out.println("\n"+a+"/"+b+"="+div);
System.out.println("\nEnter a number: ");
arr[2]=Integer.parseInt(ob.nextLine());

}
catch(ArithmeticException e)
{
System.out.println("\nDivision by zero not possible");
}
catch(NumberFormatException e)
{
System.out.println("\nEnter integers only next time");

8
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("\nArray index out of bound");
}
}

9
4. Write java program to implement file I/O operation using java iostreams.

import java.io.*;

public class FileIO

public static void main(String args[])

File file=new File("file.txt");

int ch;

StringBuffer strContent=new StringBuffer(" ");

FileInputStream fin=null;

try

fin=new FileInputStream(file);

while((ch=fin.read())!=-1)

strContent.append((char)ch);

fin.close();

catch(Exception e)

System.out.println(e);

System.out.println("Output from file.txt is : "+strContent.toString());

10
}

11
5. Write a java program to implement Applet life cycle.
/*<applet code = Appletskeleton.class width=300 Height=200>
</applet>*/
import java.awt.*;
import java.applet.*;

public class Appletskeleton extends Applet


{
String msg;
public void init()
{
setForeground(Color.red);
setBackground(Color.white);
msg="Initialization state.";
}
public
void start()
{
msg+="Running state.";
}
public
void stop()
{
msg+="Idle/Stopped state.";
}
public void destroy()
{
msg="destroying state.";
}

12
public void paint(Graphics g)
{
msg+="display state.";
g.drawString("Applet Life Cycle",90,180);
stop();
destroy();
g.drawString(msg,10,200);
}
}

Output:

13
6. Write java program to implement a calculator using suitable AWT
controls .

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet Code =Calculator.class width=250 Height=350>
</applet>*/
public class Calculator extends Applet implements ActionListener
{
TextField t=new TextField(1000);
float a,b,ans; int i;
char op;
Button sum=new Button("+");
Button sub=new Button("-");
Button mul=new Button("*");
Button div=new Button("/");
Button mod=new Button("%");
Button eq=new Button("=");
Button clear=new Button("CLEAR");
public void init()
{
setBackground(Color.black);
Button b[]=new Button[10];
GridLayout g=new GridLayout(6,3);
setLayout(g);
for(i=0;i<10;i++)
{
b[i]=new Button(""+i);
}

add(t); add(eq); add(clear);


add(sum); add(sub);
add(mul); add(div);
add(mod);
eq.addActionListener(this);
clear.addActionListener(this)
;
sum.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this)
; for(i=0;i<10;i++)
{
add(b[i]);
}
for(i=0;i<10;i++)

14
{
b[i].addActionListener(this);
}
}
public void actionPerformed(ActionEvent e)
{
String str=e.getActionCommand();
char ch=str.charAt(0);
if(Character.isDigit(ch))
{
t.setText(t.getText()+str);
}
else if(str.equals("+"))

{
a=Float.parseFloat(t.getText());
op='+';
t.setText("");
} else
if(str.equals("-"))
{
a=Float.parseFloat(t.getText());
op='-';
t.setText("");
} else
if(str.equals("*"))
{
a=Float.parseFloat(t.getText());
op='*';
t.setText("");
} else
if(str.equals("/"))
{
a=Float.parseFloat(t.getText());
op='/';
t.setText("");
} else
if(str.equals("%"))
{
a=Float.parseFloat(t.getText());
op='%';
t.setText("");
} else
if(str.equals("="))

b=Float.parseFloat(t.getText());
if(op=='+') ans=a+b;
if(op=='-')

15
ans=a-b;
if(op=='*')
ans=a*b;
if(op=='/')
ans=a/b;
if(op=='%')
ans=a%b;
t.setText(""+ans);
}
if(str.equals("CLEAR"))
{
t.setText("");
}
}
}

Output:

16
7)Write a java program to implement packages.

// collegecourse/ College.java.

package collegecourse;
public class College
{
public void displayA()
{
System.out.println("Navajyothi College Cherupuzha ");
System.out.println("BCA, BA.economics,BBA ");
}
}

// collegedept/ Dept.java.

package collegedept;
public class Dept
{

public void displayB()


{
System.out.println("Dept");
System.out.println("BCA Dept,BA Dept,BBA Dept");
}
}

17
// Njccollege.java.

import collegecourse.College;
import collegedept.*;
class Njccollege
{
public static void main(String args[])
{
College objectA=new College();
Dept objectB=new Dept();
objectA.displayA();
objectB.displayB();
}
}

Output:

18
8 Write a java program with API support write demo programs for menu
display import

import java.awt.*;
public class MyMenu extends Frame
{
MenuBar mbar;
Menu menu,submenu;
MenuItem m1,m2,m3,m4,m5;
public MyMenu()
{
//set frarme properties
setTitle(" Menu"); //set the title
setSize(400,400); //set size to the frame
setLayout(new FlowLayout());//set layout
setVisible(true); //make frame visible
setLocationRelativeTo(null); //center the frame
//create menubar
mbar=new MenuBar();
//create the menu
menu=new Menu("Menu");
//create submenu
submenu=new Menu("Zoom");
//create menu items
m1=new MenuItem("New");
m2=new MenuItem("Save ");
m3=new MenuItem("Save as");
m4=new MenuItem("Zoom In");
m5=new MenuItem("Zoom Out");
//attach menu items to menu
menu.add(m1);
2. menu.add(m2);
3. menu.add(m3);

19
4. //attach menu item to submenu
5. submenu.add(m4);
6. submenu.add(m5);
7. //attach submenu to menu
8. menu.add(submenu);
9. //attach menu to menubar
10. mbar.add(menu);
11. //set menubar to the frame
12. setMenuBar(mbar);
13. }
14. public static void main(String args[])
15. { new MyMenu();
16. }
17. }
18. Output:

20
9. Write a java program to demonstrate threads.

class A extends Thread


{
public void run()
{

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

{
if(i == 1) yield( );
System.out.println("\tFrom Thread A : i = " +i);
}
System.out.println("exit from A ");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
System.out.println("\tFrom Thread B : j =" +j);
if(j ==3) stop();
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5; k++)
{
System.out.println("\tfrom Thread C : k = " +k);
if(k==1)
try
{
sleep(1000);
}
catch (Exception e)
{
}
}
System.out.println( "Exit from C ");
}
}
class ThreadMethods
{
public static void main(String args[])

21
{
A threadA = new A( );
B threadB = new B( );
C threadC = new C( );
System.out.println("Start thread A");
threadA.start( );
System.out.println("Start thread B");
threadB.start( );
System.out.println("Start thread C");
threadC.start( );
System.out.println("End of main thread");
}
}

Output:

22
10. Demonstration of FileInputStream and FileOutputStream Classes.
import java.io.*;
class ReadWritePrimitive
{
public static void main(String args[]) throws IOException
{
File primitive = new File ("prim.dat");
FileOutputStream fos = new FileOutputStream (primitive);
DataOutputStream dos = new DataOutputStream (fos);

dos.writeInt (1999);
dos.writeDouble (375.85);
dos.writeBoolean (false);
dos.writeChar ('X');
dos.close();
fos.close();

FileInputStream fis = new FileInputStream (primitive);


DataInputStream dis = new DataInputStream (fis);
System.out.println(dis.readInt());
System.out.println(dis.readDouble());
System.out.println(dis.readBoolean());
System.out.println(dis.readChar());
dis.close();
fis.close();
}
}
Output:

23
24
SHELL PROGRAMMING

25
INDEX
SHELL PROGRAMMING

Sl. No Content Page No


1 Get a name and number from the user, create a file
with that name and number. Also display the 27
contents of the file.
2 Write a program to greet a user by 'Good Morning',
Good Afternoon' or 'Good Evening' based on time. 29
3 Write a shell program to check whether a number is
positive, negative or zero. 30
4 Shell script to print a number in reverse order. 31
5 Write a program to check whether a user has logged
in or not. The username is passed as command line 32
argument.
6 Write a demo program for the number and string
comparison operators 33
7 Write a demo program using basic calculator 34
8 A program to create 10 users 35
9 A demo program to test different file operators 36
10 Write a program with 3 different functions. Use
Menu driven program and invoke the function 37
accordingly

26
1. Get a name and number from the user, create a file with that name and
number. Also display the contents of the file.
a) If the name is XXX and number is 2 the filename must be XXX_2
b) Use cat command to create a file
b) Create the file with 10 different lines, then display the first 5 lines of file using head
command.
echo "Enter a name: "
read name

echo "Enter a number: "


read number

filename="${name}_${number}.txt"

cat << EOF > "$filename"


Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
EOF
cat "$filename"
Output:

27
28
2. Write a program to greet a user by 'Good Morning', Good Afternoon' or
'Good Evening' based on time.
a) Get the system time using 'date' command 47
b) Read the name from the user
c) If the name is 'XXX' then greet with 'Hello XXX, Good Morning! '
current_hour=$(date +%H)
read -p "What is your name? " name
if [ "$name" = "xxx" ]; then
echo "Hello $name. Good morning!"
else
if [ $current_hour -lt 12 ]; then
echo "hello $name Good morning!"
elif [ $current_hour -lt 18 ]; then
echo "hello $name Good afternoon!"
else
echo "hello $name Good evening!"

fi
fi
Output:

29
3. Write a shell program to check whether a number is positive, negative or
zero.
echo "Enter a number:"
read n
if [ $n -gt 0 ]
then
echo "It is a positive number"
elif [ $n -lt 0 ]
then
echo "It is a negative number"
elif [ $n = 0 ]
then
echo "It is zero"
else
echo "Invalid input"
fi
Output:

30
4. Shell script to print a number in reverse order.
echo enter a number
read no
rev=0
while [ $no -gt 0 ]
do
rev=$(expr $rev \* 10)
digit=$(expr $no % 10)
rev=$(expr $rev + $digit)
no=$(expr $no / 10)
done
echo reverse is $rev
Output:

31
5. Write a program to check whether a user has logged in or not. The
username is passed as command line argument.
username=$1
if who | grep -qw $username
then
echo $username logged in
else
echo $username not logged in
fi
Output:

32
6. Write a demo program for the number and string comparison operators
a) Verify whether the entered username and password is of admin user's. If
so display a warning message 'Permission denied'
b) Read a number from the user. Check whether number of files in a
folder is greater than the read number.
echo "Enter the user name:"
read usname
echo "Enter the password:"
read pass
if [ $usname = "admin" ]
then
echo "Permission denied"
else
echo Enter the path to a folder
read path
set 'ls $path'
echo enter a number:
read n
if [ $# -gt $n ]
then
echo total number of files in the specified folder is greater than $n
else
echo total no of files is less than given no
fi
fi
Output:

33
7. Write a demo program using basic calculator
echo enter a
read a
echo enter b
read b
echo choose an operation
echo 1.addition
echo 2.subtraction
echo 3.multiplication
echo 4.division
read choice
case $choice in
1)
sum=`expr $a + $b`
echo result = $sum ;;
2)
diff=`expr $a - $b`
echo result = $diff ;;
3)
mul=`expr $a \* $b`
echo result = $mul ;;
4)
div=`expr $a / $b`
echo result = $div ;;

esac
Output:

34
8. A program to create 10 users
• Use loop structure
• Get the usernames from the user
• Assign same password to all the users
for i in use 1 2
do
echo "Enter username for $1"
read name
sudo useradd -m $name
echo "$1 added successfully"
echo "$name :123" |sudo chpasswd
echo "password created for the user $name"
done
Output:

35
9. A demo program to test different file operators
a) Read filename from the user
b) Check if the file exists, if exists then display the contents, otherwise
create the file
c) Check whether the size of the file is zero
d) Check whether the file is having read, write and execute permission
if [ -f $fname ]
then
echo "file $fname exits and the content of the file:\n"
cat < $fname
else
echo the file does not exist.Create a new file
echo enter the content of the file $fname:and press Ctrl+d
cat >$fname
fi

if [ -s $fname ]
then
echo -e "the size of file is greater than zero\n"
else
echo -e "the size of file is zero\n"
fi

if [ -r $fname -a -w $fname -a -x $fname ]


then
echo read write and execute $fname
else
echo not have read write and execute
fi
Output:

36
10. Write a program with 3 different functions. Use Menu driven program
and invoke the function accordingly
a) Function for listing the contents of a folder ◦ Function for checking
whether a file is available in a folder or not if so display the contents
b) Function to check whether a user is already a member of a group
listing()
{
echo Enter path to a folder
read path
if[-d $path]
then
echo -e "contents of the directory $path:\n \n"
ls $path
else
echo no such directory exist
fi
}
display()
{
echo enter a file name:
read fname
if[-f $fname]
then
echo -e"the file $fname exists.the contents of the file is:\n\n"
cat<$fname
else
echo file $fname does not exist
fi
}
while[true]
do
echo -e"\n\nMenu \n 1.list the contents of a directory \n 2.display the contents of a
file \n 3.check whether user belongs to a group \n 4.Exit
echo enter your choice
read ch
case $ch in
1)listing ;;
2)display ;;
3)groupcheck
;;
4)Exit
;;
*)echo enter a valid choice
;;
esac
done

37
LINUX ADMINISTRATION

38
INDEX
LINUX ADMINISTRATION

SL NO CONTENT PAGE NO
Linux installation, upgradation, Installation and
removal of packages and lnstallation of a
1 peripheral devices (Printer) - lnstallation steps and 40
configuration.

Starting and stopping services in run level. The


2 service command. 40

Managing process- viewing status, killing,


restarting etc using ps.
3 40
Managing process

Adding and deleting user accounts, changing


passwords.
4 41
Add account

5 Changing the environment variables like PATH 41


6 Scheduling jobs using cron 42
Mounting and unmounting extemal file systems.
7 42
Setting the value of umask changing the
8 42
permissions, changing owner and groups
9 Archiving and Backup using tar. Restoring backup. 43
Compressing and uncompressing files using any
10 one tool. 43

39
1. Linux installation, upgradation, Installation and removal of packages
and lnstallation of a peripheral devices (Printer) - lnstallation steps and
configuration.

Installing a package

rpm-i packages_name.rpm

Updating a package

rpm – u package_name.rpm

Removing a package name

rpm – e package_name.rpm

2. Starting and stopping services in run level. The service command.

#telinit 0
#telinit 6

3. Managing process- viewing status, killing, restarting etc using ps.

Managing process

ps - aux

Viewing status

ps

40
Killing process

kill pid

Restarting process

sudo service mysqld restart

4. Adding and deleting user accounts, changing passwords.

Add account

sudo adduser person

Change password

password person

Delete account

sudo userdel person

5. Changing the environment variables like PATH.

To setting a user defined variable(called test_var)

Initializing variable
[root@localhost/]# test_var=’BCA’

Setting variable using export command

[root@localhost/]# export test_var

Printing that variable only

[root@localhost/]# printenv|grep_var
Test_var=BCA

To show all environmental variable

[root@localhost/]# printenv

41
Setting PATH variable

Already defined path


[root@dhcppc2/]# echo $PATH
/sbin:/bin:/usr/sbin:/usr/bin

Setting a new PATH


[root@dhcppc2/]# export PATH=/home/BCA:$PATH

6. Scheduling jobs using cron.

Editing cron file

crontab – e

Listing cron jobs

crontab - l

Removing cron jobs

crontab – r

7. Mounting and unmounting extemal file systems.

Creating directory for mounting.


[root@localhost Desktop]# mkdir /etc/alwin
Displays the filesystems in the system.
[root@localhost Desktop]# df –l
Choose the required file system to be mounted
[root@localhost Desktop]# mount /dev/sdb1 /etc/Alwin
[root@localhost Desktop]# df –l
Choose the required file system to be unmounted
[root@localhost Desktop]# umount /etc/alwin
[root@localhost Desktop]# df –l

8. Setting the value of umask changing the permissions, changing owner


and groups.

Umask 026
Touch qsc
Ls-l qsc

42
9. Archiving and Backup using tar. Restoring backup.

tar -cvf bca.tar bca

10. Compressing and uncompressing files using any one tool.

tar -cvzf bca.tar .gz -cvz bca

43

You might also like