0% found this document useful (0 votes)
15 views12 pages

Java Programs for B.Sc Cyber Security

The Java Lab Manual for III B.Sc (Cyber Security) includes various programming exercises such as calculating factorials, displaying prime numbers, sorting names, matrix addition, and character counting. It also covers advanced topics like method overloading, constructor overloading, interface implementation, package creation, multithreading, and exception handling. Each section provides sample code and expected output for practical understanding.

Uploaded by

rabhisikta92
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)
15 views12 pages

Java Programs for B.Sc Cyber Security

The Java Lab Manual for III B.Sc (Cyber Security) includes various programming exercises such as calculating factorials, displaying prime numbers, sorting names, matrix addition, and character counting. It also covers advanced topics like method overloading, constructor overloading, interface implementation, package creation, multithreading, and exception handling. Each section provides sample code and expected output for practical understanding.

Uploaded by

rabhisikta92
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

Java Lab Manual – III B.

Sc(Cyber Security)

1. Write a program to find factorial of list of number reading input as command


line argument.

public class FactorialCalculator {


public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a number as a command line argument.");
return;
}
int number = [Link](args[0]);
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
[Link]("Factorial of " + number + " is: " + factorial);
}
}
Output:

The Factorial of 4 is 24

[Link] D, Assistant Professor, School of CSA Page 1


Java Lab Manual – III [Link](Cyber Security)

2. Write a program to display all prime numbers between two limits.


import [Link];
import [Link].*;
public class Prime{
public static void main(String[] args){
// Scanner class for taking input
Scanner scn = new Scanner([Link]);
[Link]("Enter the first number: ");
// input for first number
int num1 = [Link]();
[Link]("Enter the second number: ");
// imput for second number
int num2 = [Link]();
[Link]("Prime numbers between " + num1 + " and " + num2 + " are: ");
// loop for printing the Numbers between a given range
for (int i = num1; i <= num2; i++) {
boolean isPrime = true;
if (i <= 1) {
isPrime = false;
} else {
// loop to check whether a number is prime or not
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
[Link](i + " ");
}
}
[Link]();
}
}

Output:
Enter the first number: 20
Enter the second number: 45
Prime numbers between 20 and 45 are: 23 29 31 37 41 43

3. Write a Java program for sorting a given list of names in ascending order.
import [Link].*;

[Link] D, Assistant Professor, School of CSA Page 2


Java Lab Manual – III [Link](Cyber Security)

class Sorting
{
void sortStrings()
{
Scanner s = new Scanner([Link]);
[Link]("Enter the value of n: ");
int n = [Link]();
String[] str = new String[n];
[Link]("Enter strings: ");
for(int i = 0; i < n; i++)
{
str[i] = new String([Link]());
}
for(int i = 0; i < n; i++)
{
for(int j = i+1; j < n; j++)
{
if(str[i].compareTo(str[j])>0)
{
String temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
[Link]("Sorted list of strings is:");
for(int i = 0; i < n ; i++)
{
[Link](str[i]);
}
}
}
class Sort
{
public static void main(String[] args)
{
Sorting obj = new Sorting();
[Link]();
}
}

[Link] D, Assistant Professor, School of CSA Page 3


Java Lab Manual – III [Link](Cyber Security)

4. Write a java program to add two Matrices.

public class MatrixAddition{


public static void main(String args[])
{
//creating two matrices
int a[][]={{10,13,4},{2,4,3},{3,4,5}};
int b[][]={{5,8,7},{-5,2,9},{1,2,4}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//adding and printing addition of 2 matrices


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
[Link](c[i][j]+" ");
}
[Link](); //new line
}
}
}

5. Write a java program to accept a string from user and display number of vowels,
consonants, digits and special characters present in each of the words of the given text.

import [Link].*;
public class strings {

// Function to count number of vowels, consonant,


// digitsand special character in a string.
static void countCharacterType(String str)
{
// Declare the variable vowels, consonant, digit
// and special characters
int vowels = 0, consonant = 0, specialChar = 0,
digit = 0;

// [Link]() function to count number of


// character in given string.
for (int i = 0; i < [Link](); i++) {

char ch = [Link](i);

[Link] D, Assistant Professor, School of CSA Page 4


Java Lab Manual – III [Link](Cyber Security)

if ( (ch >= 'a' && ch <= 'z') ||


(ch >= 'A' && ch <= 'Z') ) {

// To handle upper case letters


ch = [Link](ch);

if (ch == 'a' || ch == 'e' || ch == 'i' ||


ch == 'o' || ch == 'u')
vowels++;
else
consonant++;
}
else if (ch >= '0' && ch <= '9')
digit++;
else
specialChar++;
}

[Link]("Vowels: " + vowels);


[Link]("Consonant: " + consonant);
[Link]("Digit: " + digit);
[Link]("Special Character: " + specialChar);
}

// Driver function.
static public void main (String[] args)
{
String str = "hello java_welcome";

countCharacterType(str);
}
}

6. Write a program to find area of geometrical figures using method overloading.

public class GeometricMethodOverloading


{
void calcArea(float a)
{
float area = a * a;
[Link]("The Area of a Square = " + area + " Sq Units");
}
void calcArea(float a, float b)
{
float area = a * b;

[Link] D, Assistant Professor, School of CSA Page 5


Java Lab Manual – III [Link](Cyber Security)

[Link]("The Area of a Rectangle = " + area + " Sq Units");


}
void calcArea(double r)
{
double area = 3.14 * r * r;
[Link]("The Area of a Circle = " + area + " Sq Units");
}
void calcArea(double a, double b)
{
double area = (a * b) / 2;
[Link]("The Area of a Triangle = " + area);
}
public static void main(String[] args)
{
GeometricMethodOverloading obj = new GeometricMethodOverloading();

[Link](10.6f);

[Link](14.3f, 22.5f);

[Link](11.67);

[Link](18.0, 25.4);
}
}

7. Write a program to implement constructor overloading by passing different number


of parameter of different types.

public class Student {


//instance variables of the class
int id;
String name;
Student(){
[Link]("This a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
//object creation
Student s = new Student();
[Link]("\nDefault Constructor values: \n");
[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);
[Link]("\nParameterized Constructor values: \n");
Student student = new Student(10, "Arun");

[Link] D, Assistant Professor, School of CSA Page 6


Java Lab Manual – III [Link](Cyber Security)

[Link]("Student Id : "+[Link] + "\nStudent Name : "+[Link]);


}
}

8. Write a program to calculate bonus for different departments using method


overriding.

abstract class Department


{
double salary,bonus,totalsalary;
public abstract void calBonus(double salary);
public void displayTotalSalary(String dept)
{
[Link](dept+"\t"+salary+"\t\t"+bonus+"\t"+totalsalary);
}
}
class Accounts extends Department
{
public void calBonus(double sal)
{
salary = sal;
bonus = sal * 0.2;
totalsalary=salary+bonus;
}
}
class Sales extends Department
{
public void calBonus(double sal)
{
salary = sal; bonus = sal * 0.3;
totalsalary=salary+bonus;
}
}
public class BonusCalculate
{
public static void main(String args[])
{
Department acc = new Accounts();
Department sales = new Sales();
[Link](10000);
[Link](20000);

[Link]("Department \t Basic Salary \t Bonus \t Total Salary");


[Link](" ");
[Link]("Accounts");
[Link]("Sales");
[Link](" ");
}
}

[Link] D, Assistant Professor, School of CSA Page 7


Java Lab Manual – III [Link](Cyber Security)

Part B

1. Write a java program to demonstrate Interface concept in java.

Interface Polygon {
void getArea();
default void getSides() {
[Link]("I can get sides of polygon.");
}
}
class Rectangle implements Polygon
{
public void getArea()
{
int length = 6;
int breadth = 5;
int area = length * breadth;
[Link]("The area of the rectangle is "+area);
}
public void getSides() {
[Link]("I have 4 sides.");
}
class Square implements Polygon {
public void getArea() {
int length = 5;
int area = length * length;
[Link]("The area of the square is "+area);
}
}
class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle();
[Link]();
[Link]();
Square s1 = new Square();
[Link]();
}
}

2. Write a java program to demonstrate creation and importing packages.

[Link]

package p1;
import [Link].*;
public class Add
{
int s;
public void sum()

[Link] D, Assistant Professor, School of CSA Page 8


Java Lab Manual – III [Link](Cyber Security)

{
[Link]("Enter the first number: ");
Scanner scan=new Scanner([Link]);
int x=[Link]();
[Link]("Enter the second number: ");
Scanner scan1=new Scanner([Link]);
int y=[Link]();
s=x+y;
[Link]("sum="+s);
}
}

[Link]
package p2;
import [Link].*;
public class Sub
{
int d;
public void diff()
{
[Link]("Enter the first number: ");
Scanner scan=new Scanner([Link]);
int x=[Link]();
[Link]("Enter the second number: ");
Scanner scan1=new Scanner([Link]);
int y=[Link]();
d=x-y;
[Link]("Difference="+d);
}
}

[Link]

//importing pre-defined package


import [Link].*;
//importing user-defined package
import [Link];
import [Link];
public class Calculator
{
public static void main(String args[])
{
[Link]("Enter your choice: ");
Scanner scan=new Scanner([Link]);
int t=[Link]();
switch(t)
{
case 1:
Add a=new Add();
[Link]();

[Link] D, Assistant Professor, School of CSA Page 9


Java Lab Manual – III [Link](Cyber Security)

break;
case 2:
Sub s=new Sub();
[Link]();
break;
}
}
}

3. Write a java program to demonstrate of creating new thread and starts running.

import [Link].*;
import [Link].*;
class Multi3 implements Runnable{
public void run()
{
[Link]("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
[Link]();
}
}

4. Demonstrate multiple thread concepts in java with help of program.


import [Link].*;
import [Link].*;
class TestMethod1 extends Thread{
public void run(){
for(int i=1;i<5;i++){
try{[Link](500);}
catch(InterruptedException e){
[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
TestMethod1 t1=new TestMethod1();
TestMethod1 t2=new TestMethod1();
[Link]();
[Link]();
}
}

[Link] D, Assistant Professor, School of CSA Page 10


Java Lab Manual – III [Link](Cyber Security)

5. Write a java program to implement thread priorities.


import [Link].*;
import [Link].*;
public class Threadpriority extends Thread
{
// the main method
public static void main(String argvs[])
{
// Now, priority of the main thread is set to 10
[Link]().setPriority(10);
// The current thread is retrieved
// using the currentThread() method
// displaying the main thread priority
// using the getPriority() method of the Thread class
[Link]("Priority of the main thread is : " + [Link]().getPriority());
}
}

6. Implement program to handle Exceptions in java programming.


import [Link].*;
import [Link].*;
class Exception{
public static void main(String args[]){
try{
int data=25/0;
[Link](data);
}
catch(ArithmeticException e1)
{
[Link](e1);
}
finally
{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}

[Link] D, Assistant Professor, School of CSA Page 11


Java Lab Manual – III [Link](Cyber Security)

[Link] D, Assistant Professor, School of CSA Page 12

Common questions

Powered by AI

Method overloading can be employed to calculate the area of different geometric figures by defining multiple methods with the same name but different parameters to handle various cases. For example, a method `calcArea(float a)` can be used to compute the area of a square, another method `calcArea(float a, float b)` for a rectangle, and another one `calcArea(double r)` for a circle. This way, each method calculates the area based on the number and type of arguments provided .

Constructor overloading provides flexibility by allowing object instantiation through different parameter combinations. It enables initialization variance in properties at the object creation phase. For example, the `Student` class can have both default and parameterized constructors, permitting object creation with initial values for properties or with default values, thereby supporting diverse construction scenarios .

Polymorphism through method overriding allows different departments to have distinct implementations for calculating bonuses while using a common interface. For example, the `Department` class can define an abstract method `calBonus(double salary)`, which is overridden in subclasses like `Accounts` and `Sales`. Each subclass implements the bonus calculation differently, e.g., `Accounts` with a 20% bonus rate and `Sales` with a 30% rate, thus facilitating customizable behavior for diverse department requirements .

Constructor overloading in Java involves defining multiple constructors within a class with different parameter lists, allowing for multiple ways to instantiate objects. For instance, a `Student` class might have a default constructor `Student()` and another parameterized constructor `Student(int i, String n)`. This enables the creation of student objects with or without initial values for properties like `id` and `name`, providing flexibility in object creation .

Exception handling enhances robustness by managing runtime errors gracefully, preventing program crashes and offering opportunities for problem resolution. For example, using a `try-catch-finally` block, divide-by-zero can be caught and handled through the `ArithmeticException`, avoiding abrupt termination. This block ensures that specific recovery code executes after exceptions are caught, and the `finally` block executes regardless, thus maintaining consistent program flow .

Threads in Java allow concurrent execution by separating processes into smaller units. A thread can be created by extending the `Thread` class or implementing the `Runnable` interface. The thread lifecycle includes creating a `Thread` instance, calling `start()` to invoke the `run()` method, enabling simultaneous task execution. This supports program efficiency by utilizing CPU time better and managing multiple tasks concurrently .

The Java threading model leverages principles like thread synchronization, priority settings, and daemon threads to effectively manage multiple threads. Synchronization prevents race conditions by controlling access to shared resources. Thread priorities influence thread scheduling, and daemon threads run as service providers in the background, enabling a responsive and efficient application environment .

Interfaces in Java define methods that a class must implement, establishing a contract that promotes code abstraction and multiple inheritance. For instance, the `Polygon` interface might contain a method `getArea()`, implemented differently by classes like `Rectangle` and `Square` to compute their respective areas. This way, interfaces enable diverse implementations while maintaining a consistent interface method signature across different classes .

Command line argument processing allows users to input parameters at program launch, facilitating dynamic input acquisition. For instance, a program can compute the factorial of a number provided as a command line argument by converting the input string to an integer using `Integer.parseInt()`. It significantly enhances flexibility by enabling user-driven configurations for program execution at runtime .

Packages in Java organize classes and interfaces into bundles, improving structure and avoiding name conflicts. They allow functionality grouping, making classes more manageable and reusable. An example is the creation of `package p1` and `package p2`, containing classes `Add` and `Sub`. Importing these packages into a `Calculator` class illustrates modular design, facilitating easy maintenance and code organization .

You might also like