Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

CJP PRACTICALS

Practical 1
1. Write a program to display “Welcome To Java World”.
Code:
public class cjp_practical_1_1
{
Public static void main(Strin[] args) {
System.out.println(“Welcome to java world”);
}
}

Output
2. Write a program to find whether the number is prime or not.
Code:
import java.util.Scanner;
public class cjp_practical_1_2
{
public static void main(String[] args) {
Boolean flag = false;
Scanner sc = new Scanner(System.in);
Int a = sc.nextInt();
For (int I =2; i<= a/2; ++i) {
If(a%i == 0) {
Flag = true;
break;
}
}
If(!flag) {
System.out.println(a+ “ is prime number”);
}
Else {
System.out.println(a+ “ is not a prime number);
}
}
}
Output

3. Write a program to find a greater number among given three


numbers using a) ternary operator b) nested if.
a)
Code:
import java.util.Scanner;
public class cjp_practical_1_3
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the value of a:”);
int a = sc.nextInt();
System.out.print(“Enter the value of b:”);
int b = sc.nextInt();
System.out.print(“Enter the value of c:”);
int c = sc.nextInt();
int max = (a>b) ? (a>c ? a:c) : (b>c ? b:c);
System.out.println(“Maximum number among” +a+ ”,”
+b+ ”and” +c+ ”is” +max);
}
}

Output
b)
code:
import java.util.Scanner;
public class cjp_practical_1_3
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the value of a:”);
int a = sc.nextInt();
System.out.print(“Enter the value of b:”);
int b = sc.nextInt();
System.out.print(“Enter the value of c:”);
int c = sc.nextInt();
if(a>=b) {
if(a>=c)
System.out.println(“Among the three values ”
+a+ “is the largest Number”);
Else
System.out.println(“Among the three values ”
+c+ ”is the largest Number” );
}
else {
if(b>=c)
System.out.println(“Among the three values”
+b ”is the largest Number”);
Else
System.out.println(“Among the three values”
+c ”is the largest Number”);
}
}
Output

4. Write a program to print the Fibonacci series.


Code:
import java.util.Scanner;
public class cjp_practical_1_4
{
Public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the number:”);
int n = sc.nextInt();
int a = 0;
int b = 1;
int c = 0;
int i = 0;
if(n<=1) {
System.out.println(a+ “ ”);
}
else {
System.out.println(a+ “ ”);
System.out.println(b+ “”);
for(i=3; i<=n; i++) {
c=a+b;
a=b;
b=c;
System.out.println(c+ “”);
}
}
}
}
Output
Practical 2
Write a program to find the average of n numbers stored in
an Array.
Code:
import java.util.Scanner;
public class cjp_practical_2
{
Public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print(“Enter size of Array: ”);
Int n = sc.nextInt();
Double sum = 0;
int[] ary = new int[n];
System.out.print(“Enter elements of array : ”);
for(int i=0; i<n; i++)
ary[i] = sc.nextInt();
for (int i=0; i<n; i++)
sum += ary[i];
System.out.println(“Sum is : “ + sum + “\nAverage is “ +
sum/n);
}
}

Output
Practical 3
1. WAP to replace substring with other substring in the given
string.
Code:
public class cjp_practical_3_1
{
public static void main(String[] args) {
String str = “Hello World”;
System.out.println(“\nAfter replacing H with W”);
System.out.println(str.replace(‘H’ , ‘W’));
System.out.println(“\nAfter replacing He with
Wa”);
System.out.println(str.replace(“He” , “Wa”));
}
}
Output
2. WAP that to sort given strings into alphabetical order.
Code:
import java.util.Scanner;
public class cjp_practical_3_2
{
public static void main(String[] args) {
int count;
String temp;
Scanner scan = new Scanner(System.in);
System.out.print(“Enter number of strings you
would like to enter:”);
count = sc.nextInt();
String atr[] = new String[count];
Scanner sc2 = new Scanner(System.in);
System.out.println(“Enter the Strings one by one:”);
for(int i=0; i<count; i++)
{
str[i] = sc2.nextLine();
}
sc.close();
sc.close();
for(int i=0; i<count; i++)
{
for(int j=i+1; j<count; j++) {
if(str[i].compareTo(str[j])>0)
{
Temp = str[i];
Str[i] = str[j];
str[j] = temp;
}
}
}
System.out.print(“Strings in Sorted Order:”);
for(int i=0; i<=count-1; i++)
{
System.out.print(str[i] + “,”);
}
}
}

Output
3. Create a String Buffer with some default string. Append
any string to ith position of original string and display the
modified string. Also display the reverse of modified string.
Code:
import java.lang.*;
public class cjp_practical_3_3
{
public static void main(String[] args) {
StringBuffer s = new StringBuffer(“Indus
University”);
int p = s.length();
int q = s.capacity();
System.out.println(“Length of string Indus
University = ” +p );
Syatem.out.println(“Capacity of string Indus
University = ” +q );
}
}

Output
Practical 4
1. a) WAP that declares a class named Person. It should have
instance variables to record name, age and salary. Use new
operator to create a Person object. Set and display its
instance variables. b) Add a constructor to the Person class
developed above.
a)
Code:
import java.util.Scanner;
public class person
{
Scanner sc = new Scanner(System.in);
String name;
int age, salary;
public void input()
{
System.out.print(“Enter the name: ”);
name = sc.nextLine();
System.out.print(“Enter the age: ”);
age = sc.nextInt();
System.out.print(“Enter the salary: ”);
salary = sc.nextInt();
}
public void display()
{
System.out.println(“The name is ” +name);
System.out.println(“The age is ” +age);
System.out.println(“The salary is ” +salary);
}
public static void main(String[] args) {
person ob = new person();
ob.input();
ob.display();
}
}
Output
b)
Code:
import java.util.Scanner;
public class person_con
{
Scanner sc = new Scanner(System.in);
String name;
int age, salary;
person_con()
{
name = “”;
age = 0;
salary = 0;
}
public void input()
{
System.out.print(“Enter the name: ”);
name = sc.nextLine();
System.out.print(“Enter the age: ”);
age = sc.nextInt();
System.out.print(“Enter the salary: ”);
salary = sc.nextInt();
}
public void display()
{
System.out.println(“The name is ” +name);
System.out.println(“The age is ” +age);
System.out.println(“The salary is ” +salary);
}
public static void main(String[] args) {
person ob = new person();
ob.input();
ob.display();
}
}
Output
2. The employee list for a company contains employee code,
name, designation and basic pay. The employee is given HRA
of 10% of the basic and DA of 45% of the basic pay. The total
pay of the employee is calculated as Basic pay+HRA+ DA.
Write a class to define the details of the employee. Write a
constructor to assign the required initial values. Add a
method to calculate HRA, DA and Total pay and print them
out. Write another class with a main method. Create objects
for three different employees and calculate the HRA, DA and
total pay.
Code:
import java.util.Scanner;
class data
{
Scanner s = new Scanner(System.in);
int ec;
String name;
String d;
double basic;
double HRA;
double DA;
double tp;
data()
{
System.out.println(“Enter your Employee code: ”);
ec = s.nextInt();
System.out.println(“Enter your Name: ”);
name = s.next();
System.out.println(“Enter your Designation: ”);
d = s.next();
System.out.println(“Enter your Basic pay: ”);
basicp = s.nextDouble();
}
Public void calc()
{
HRA = (basic*10)/100;
DA = (basicp*45)/100;
tp = basicp + HRA + DA;
System.out.println(“Your HRA is: ”+HRA);
System.out.println(“Your DA is: ”+DA);
System.out.println(“Your TOATAL SALARY is: ”+tp);
}
}
public class salary
{
public static void main(String args[])
{
for(int i = 0; i<=2; i++).
{
data d = new data();
d.calc();
}
}
}
Output
Practical 5
1. Write a program which defines base class Employee having
three data members, namely name[30], emp_numb and
gender and two methods namely input_data() and
show_data(). Derive a class SalariedEmployee from Employee
and adds a new data member, namely salary. It also adds two
member methods, namely allowance (if gender is female
HRA=0.1 *salary else 0.09* salary. DA= 0.05*salary) and
increment (salary= salary+0.1*salary). Display the gross
salary in main class. (Tip: Use super to call base class’s
constructor0).
Code:
import jav.util.*;
class Employee {
String name;
int emp_num;
char gender;
public Employee() {
input_data();
}
void input_dat() {
Scanner sc = new Scanner(System.in);
System.out.println(“Enter name: ”);
name = sc.nextLine();
System.out.println(“Employee number: ”);
emp_num = sc.nextInt();
System.out.println(“Gender: ”);
gender = sc.next().charAt(0);
}
void show_dta() {
System.out.println(“Employee%15s\nID%16d\nGender
%11c\n”, name, emp_num,gender);
}
}
public class SalaryEmployee extends Employee {
int salary;
double HRA,DA;
double allowance() {
if(gender == ‘F’)
HRA = 0.1*salary;
Else
HRA = 0.09*salary;
DA = 0.05*salary;
return (HRA+DA);
}
double increment () {
return salary*0.1;
}
public SalariedEmployee() {
super();
System.out.println(“Enter Salary for ” +name);
Scanner s = new Scanner(System.in);
salary = s.nextInt();
s.close();
}
public static void main(String[] args) {
SalariedEmployee e1 = new SalariedEmployee();
e1.show_data();
System.out.println(“Gross Salary\t” +
(e1.allowance()+e1.increment() + e1.salary));
}
}
Output
2. WAP that illustrates method overriding. Class A3 is
extended by Class B3. Each of these classes defines a
hello(string s) method that outputs the string “A3: Hello
From” or “B3: Hello From” respectively. Use the concept
Dynamic Method Dispatch and keyword super.
Code:
class A3 {
void hello (String s) {
System.out.println("A3 : Hello from " + s);
}
}
class B3 extends A3{
void hello (String s) {
System.out.println("B3 : Hello from " + s);
System.out.println("Call through super keyword");
super.hello(s);
}
}
public class MethodOverriding {
public static void main(String[] args) {
A3 a1 = new A3();
A3 a2 = new B3();
a1.hello("Rahul");
a2.hello("Abhi");
}
}

Output
Practical 6
1. Write an abstract class shape, which defines abstract
method area. Derive class circle from shape. It has data
member radius and implementation for area function. Derive
class Triangle from shape. It has data members height, base
and implementation for area function. Derive class Square
from shape. It has data member side and implementation for
area function. In main class, use dynamic method dispatch in
order to call correct version of method.
Code:
abstract class Shape {
abstract double area();
}
class circle extends Shape {
double radius;
circle (double radius) {
this.radius = radius;
}
double area() {
System.out.print("Area of circle is : ");
return Math.PI*Math.pow(radius, 2);
}
}
class triangle extends Shape {
double base, height;
triangle (double base, double height) {
this.base = base;
this.height = height;
}
double area() {
System.out.print("Area of triangle is : ");
return (base*height)/2;
}
}
class square extends Shape {
double side;
square (double side) {
this.side = side;
}
double area() {
System.out.print("Area of square is : ");
return Math.pow(side, 2);
}
}
public class shapeMain {
public static void main(String[] args) {
Shape cr = new circle(2.5);
Shape tr = new triangle(5, 7);
Shape sq = new square(5);
System.out.println(cr.area());
System.out.println(tr.area());
System.out.println(sq.area());
}
}
Output

2. Create an interface Shape2D which declares a getArea()


method. Point 3D contains coordinates of a point. The
abstract class Shape declares abstract display() method and is
extended by Circle class. it implements the Shape2D
interface. The Shapes class instantiates this class and
exercises its methods.
Code:
interface Shape2D {
double getArea();
}
abstract class shape {
abstract void display();
}
class Circle extends shape implements Shape2D {
int r;
Circle (int r) {
this.r = r;
}
void display() {
System.out.println("Area of circle is " + getArea());
}
public double getArea() {
return Math.PI*r*r;
}
}
public class interfaceExample {
public static void main(String[] args) {
Circle c = new Circle(5);
c.display();
}
}
Output

Practical 7
Create a package “employee” and define a Class Employee
having three data members, name, emp_num, and gender
and two methods- input_data and show_data. Inherit class
SalariedEmployee from this class and keep it in package
“employee”. Add new variable salary and methods allowance
(if female hra=0.1* salary else 0.09* salary. DA= 0.05*salary)
and increment (salary= salary+0.01 * salary). Calculate gross
salary in main class defined in the same package

Code:
import jav.util.*;
class Employee {
String name;
int emp_num;
char gender;
public Employee() {
input_data();
}
void input_dat() {
Scanner sc = new Scanner(System.in);
System.out.println(“Enter name: ”);
name = sc.nextLine();
System.out.println(“Employee number: ”);
emp_num = sc.nextInt();
System.out.println(“Gender: ”);
gender = sc.next().charAt(0);
}
void show_dta() {
System.out.println(“Employee%15s\nID%16d\nGender
%11c\n”, name, emp_num,gender);
}
}
public class SalaryEmployee extends Employee {
int salary;
double HRA,DA;
double allowance() {
if(gender == ‘F’)
HRA = 0.1*salary;
Else
HRA = 0.09*salary;
DA = 0.05*salary;
return (HRA+DA);
}
double increment () {
return salary*0.1;
}
public SalariedEmployee() {
super();
System.out.println(“Enter Salary for ” +name);
Scanner s = new Scanner(System.in);
salary = s.nextInt();
s.close();
}
public static void main(String[] args) {
SalariedEmployee e1 = new SalariedEmployee();
e1.show_data();
System.out.println(“Gross Salary\t” +
(e1.allowance()+e1.increment() + e1.salary));
}
}

Output
Practical 8
1. WAP using try catch block. User should enter two
command line arguments. If only one argument is entered
then exception should be caught. In case of two command
line arguments, if fist is divided by second and if second
command line argument is 0 then catch the appropriate
exception.
Code:
public static void main(String[] args) {
try {
int x = Integer.parseInt(args[0]), y =
Integer.parseInt(args[1]);
try {
System.out.println(x / y);
}
catch (ArithmeticException e) {
System.out.println("Second argument can't be zero.");
}
}
catch (NullPointerException n) {
System.out.println("Null Pointer Exception created!!!");
}
catch (ArrayIndexOutOfBoundsException n) {
System.out.println("Array Index Out Of Bounds");
}
catch (Exception e) {
System.out.println("Exception Created");
}
}
output

2. Define an exception called “NoMatchException” that is


thrown when a string is not equal to “India”. Write a program
that uses this exception.
Code:
class nomatchexception {
String s;
nomatchexception(String s) {
this.s = s;

if (s.equals("India")) {
System.out.print("Matched!\n");
}
else {
throw new NoMatchException("Not Matched!\n");
}
}
}

class nomatchex {
public static void main(String[] a) {
nomatchexception v = new
nomatchexception("America");
}
}
Output
Practical 9
1. The program to creates and run the following three
threads. The first thread prints the letter ‘a’ 100 times. The
second thread prints the letter ‘b’ 100 times. The third thread
prints the integer 1 to 100.

Code:
class PrintChar implements Runnable {
private char charToPrint;
private int times;
public PrintChar(char c, int t) {
charToPrint = c; times = t;
}
public void run() {
for(int i=0; i<times; i++)
{
System.out.print(charToPrint);
}
}
}
class PrintNum implements Runnable {
private int lastNum;
public PrintNum(int n) {
lastNum = n;
}
public void run() {
for (int i = 1; i <= lastNum; i++)
{
System.out.print(" " + i);
}
}
}
public class TaskThreadDemo {
public static void main(String[] args) {
Runnable printA = new PrintChar('a', 100);
Runnable printB = new PrintChar('b', 100);
Runnable print100 = new PrintNum(100);
Thread thread1 = new Thread(printA);
Thread thread2 = new Thread(printB);
Thread thread3 = new Thread(print100);

thread1.start();
thread2.start();
thread3.start();
}
}
Output

2. Write the thread program -1using Runnable interface.


Code:
public class RunnableDemo {
public static void main(String[] args)
{
System.out.println(“Main thread is -” +
Thread.currentThread().getName());
Thread t1 = new Thread(new
RunnableDemo().new RunnableImpl());
T1.start();
}
private class RunnableImpl implements Runnable {
public void run()
{
System.out.println(Thread.currentThread().getName()
+ “, executing run() method”);
}
}
}

Output
Practical 10

1. Write a program that takes two files names (source and


destination) as command line argument. Copy source file’s
content to destination file. Use character stream class. Also
do same using byte stream and buffer stream.

Character stream:
Code:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class hello
{
public static void main(String[] args)
{
try
{
FileInputStream source = new
FileInputStream("Mitul.txt");
FileOutputStream target = new
FileOutputStream("Patel.java");

int bytev;

while ((bytev = source.read()) != -1)


{
target.write(bytev);
}
source.close();
target.close();

System.out.println("File copied");
}
catch(IOException e)
{
System.out.println("Exception : "
+e.toString());
}
}
}
Output
2.Write a program which generates random integers and
stores them in a file named “rand.dat”. The program then
reads the integers from the file and displays on the screen

Code:
import java.io.*;
import java.util.*;
class S9P2_Random
{
public static void main(String args[])
{
FileWriter FW = null;
BufferedWriter bfwr = null;
File inFile = new File("rand.dat");
try
{
int rand_int;
FW = new FileWriter(inFile);
bfwr = new BufferedWriter(FW);
Random generate_rand = new Random();
System.out.println("\nGenerating & Storing Random
integers from 0 to 99..\n");
for(int i=0; i<10; i++)
{
rand_int = generate_rand.nextInt(100);
System.out.print(rand_int+"\t");
bfwr.write(rand_int+"\r\n");
}
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
bfwr.close();
}
catch(IOException e){ }
}
try
{
System.out.println("\nRetrieving Random integers stored in
file 'rand.dat'..");
Scanner scanner = new Scanner(inFile);
while(scanner.hasNextInt())
{
System.out.println(scanner.nextInt()+"\t");
}
}
catch(NullPointerException e)
{
System.out.println(e.getMessage());
}
catch(FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
}

Output

Practical 11
Write the program that demonstrate the use of Stack, Vector
and ArrayList classes

Stack
Code:
import java.util.*;
public class TestJavaCollection4 {
public static void main(String args[]) {
Stack<String> stack = new Stack<String>();
stack.push("Nihar");
stack.push("Param");
stack.push("Veer");
stack.push("Vedant");
stack.push("Vijay");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output
Vector
Code:
import java.util.*;
public class TestJavaCollection3 {
public static void main(String args[]) {
Vector<String> v=new Vector<String>();
v.add("Garishma");
v.add("Aayush");
v.add("Rahul");
v.add("Abhi");
Iterator<String> itr=v.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output
Arraylist
Code:
import java.util.*;
class TestJavaCollection1 {
public static void main(String args[]) {
ArrayList<String> list=new ArrayList<String>();
list.add("Mitul");
list.add("Vedant");
list.add(“Shaurabh");
list.add("Harsh");
Iterator itr=list.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Output

Practical 12
Write a Network program that client sends the data as redius
of circle to server and server received that data and send the
resultant area of circle to requested client.
Code:
Server:
import java.io.*;
import java.net.*;
class Server
{
Public static void main(String args[])
{
try
{
ServerSocket ss = new ServerSocket(1064);
System.out.println(“Waiting for Client
Request”);
Socket s = ss.accept();
BufferedReader br;
PrintStream ps;
String str;
br = new BufferREader(new
InputStreamReader(s.getInputStream()));
str = br.readLine();
System.out.println(“Received radius”);
Double r = Double.parseDouble(str);
double area = 3.14*r*r;
ps = new PrintStream(s.getOutputStream());
ps.println(String.valueof(area));
br.close();
ps.close();
s.close();
ss.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Client:
import java.io.*;
import java.net.*;
class Client
{
public static void main(String args[]) throws IOException
{
Socket s = new
Socket(InetAddress.getLocalHost(),1064);
BufferedReader br;
PrintStream ps;
String str;
System.out.println(“Enter Radius: ”);
br = new BufferedReader(new
InputStreamReader(System.in));
ps = new PrintStream(s.getOutputStream());
ps.println(br.readLine());
br = new BufferedReader(new
InputStreamReader(s.getInputStream()));
str = br.readLine();
System.out.println(“Area of the circle is:” +str);
br.close();
ps.close();
}
}
Output

Practical 13
Write a program to count occurrence of character in a string
Code:
import java.util.*;
public class countChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter String :");
char[] s = sc.nextLine().toLowerCase().toCharArray();
sc.close();
HashMap<Character, Integer> c = new
HashMap<Character, Integer>();
for (char i: s) {
if (i<123 && i>96)
if(c.containsKey(i)) {
int x = c.get(i);
c.replace(i, ++x);
}
else
c.put(i, 1);
}
System.out.println("Case Ignored");
System.out.println("Alphabet - No of times repeated");
for (char i : c.keySet())
System.out.println(i + " - " + c.get(i));
System.out.println("All other alphabets are not present.");
}
}
Output

You might also like