Java Programming
Java Programming
PRATICAL RECORD
4th SEMESTER 2022-2023
1
NAVAJYOTHI COLLEGE
[AFFILIATED TO KANNUR UNIVERSITY]
Cherupuzha-670511
CERTIFICATE
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
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.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.*;
int ch;
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);
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.*;
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);
}
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
{
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.
{
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();
23
24
SHELL PROGRAMMING
25
INDEX
SHELL PROGRAMMING
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
filename="${name}_${number}.txt"
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
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.
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
rpm – e package_name.rpm
#telinit 0
#telinit 6
Managing process
ps - aux
Viewing status
ps
40
Killing process
kill pid
Restarting process
Add account
Change password
password person
Delete account
Initializing variable
[root@localhost/]# test_var=’BCA’
[root@localhost/]# printenv|grep_var
Test_var=BCA
[root@localhost/]# printenv
41
Setting PATH variable
crontab – e
crontab - l
crontab – r
Umask 026
Touch qsc
Ls-l qsc
42
9. Archiving and Backup using tar. Restoring backup.
43