0% found this document useful (0 votes)
3 views

Java Manual

The document contains multiple Java programming exercises covering various topics such as prime numbers, sorting matrices, method overloading, registration number generation, and inheritance. Each exercise includes sample outputs, code implementations, and explanations of the functionality. The programs demonstrate practical applications of Java concepts like input handling, data structures, and object-oriented programming.

Uploaded by

krandomaccess123
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 Manual

The document contains multiple Java programming exercises covering various topics such as prime numbers, sorting matrices, method overloading, registration number generation, and inheritance. Each exercise includes sample outputs, code implementations, and explanations of the functionality. The programs demonstrate practical applications of Java concepts like input handling, data structures, and object-oriented programming.

Uploaded by

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

JAVA MANUAL

PART- A
1. Write a Java program to display only those multi-digit prime numbers between a given range whose
digit sum is prime. Display the prime number and its digit sum side by side. Read the value for the range
using readLine() method of BufferedReader class.
Sample output:
If range is; m = 20, n=50
Prime number Sum of digits
23 - 5
29 - 11
41 - 5
43 - 7
47 – 11

import java.io.*;

public class PrimeNumber {

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

int m, n, val = 0;

while(true)

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter value for m and n");

m = Integer.parseInt(reader.readLine());

n = Integer.parseInt(reader.readLine());

if(m>9 && n>9)

System.out.println("Prime Number\tSum of Digits");

for (int i = m; i<= n; i++)

if (isPrime(i))

BCA, SRNMNC, SHIMOGA Page 1


JAVA MANUAL

int x= digitSum(i);

if(isPrime(x))

System.out.print(i);

System.out.println("\t\t"+x);

System.exit(0);

else

System.out.println("enter multiple digit number");

public static int digitSum(int x)

int sum = 0;

while (x != 0)

sum = sum + x % 10;

x = x/10;

return sum;

public static boolean isPrime(int y)

for (int i = 2; i<= y/2; i++)

if (y % i == 0)
BCA, SRNMNC, SHIMOGA Page 2
JAVA MANUAL

return false;

return true;

2. Write a Java program to sort the elements of a square matrix. Read the order and elements of the
matrix during execution. Before sorting the elements of the matrix, display the source matrix.
Sample output:
Input Matrix is:
20 2 35
4 17 7
41 3 2
Matrix elements after sorting:

2 2 3

4 7 17

20 35 41

import java.io.*;

import java.util.*;

class SquareMatrixSum {

static void sortMat(int mat[][],int m, int n)

int temp[] = new int[m * n];

int k = 0;

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

for (int j = 0; j < n; j++)

temp[k++] = mat[i][j];

Arrays.sort(temp);

BCA, SRNMNC, SHIMOGA Page 3


JAVA MANUAL

k = 0;

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

for (int j = 0; j < n; j++)

mat[i][j] = temp[k++];

static void printMat(int mat[][],int m, int n)

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

for (int j = 0; j < n; j++)

System.out.print( mat[i][j] + " ");

System.out.println();

public static void main(String args[])

while(true)

int m,n,i,j;

Scanner input = new Scanner(System.in);

System.out.println("Enter the number of rows of the matrix");

m = input.nextInt();

System.out.println("Enter the number of columns of the matrix");

n = input.nextInt();

if(m==n)

{
BCA, SRNMNC, SHIMOGA Page 4
JAVA MANUAL

int mat[][] = new int[m][n];

System.out.println("Enter the elements of the matrix");

for (i = 0; i< m; i++)

for (j = 0; j < n; j++)

mat[i][j] = input.nextInt();

System.out.println("Original Matrix:");

printMat(mat, m, n);

sortMat(mat, m, n);

System.out.println("Matrix After Sorting:");

printMat(mat, m, n);

System.exit(0);

else

System.out.println("enter row and coloumn values equal");

4.Write java program to demonstrate method overloading to generate random numbers, random
alphabet sequence and random strings.

import java.io.*;

import java.lang.Math;

BCA, SRNMNC, SHIMOGA Page 5


JAVA MANUAL

import java.util.Random;

import java.util.*;

public class RandomProg

static int SIZE = 26;

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter upper range and count for random numbers ");

int max = Integer.parseInt(br.readLine());

int count = Integer.parseInt(br.readLine());

System.out.println("Random Numbers are: ");

printRandom(count,max);

System.out.print("Enter the size for the string to generate: ");

int n = Integer.parseInt(br.readLine());

System.out.println("Random String: "+printRandom(n));

System.out.println("Random alphabet: "+printRandom());

static char printRandom()

Random rnd = new Random();

char c = (char) ('a' + rnd.nextInt(26));

return c;

static int printRandom(int count, int max)

{
BCA, SRNMNC, SHIMOGA Page 6
JAVA MANUAL

Random rnd = new Random();

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

int r=rnd.nextInt(max);

System.out.println(r);

return 0;

static String printRandom(int n)

char []alphabet = { 'a', 'b', 'c', 'd', 'e', 'f', 'g',

'h', 'i', 'j', 'k', 'l', 'm', 'n',

'o', 'p', 'q', 'r', 's', 't', 'u',

'v', 'w', 'x', 'y', 'z' };

String res = "";

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

res = res + alphabet[(int) (Math.random() * 10 % SIZE)];

return res;

5. Assume that an examination authority conducts qualifying examination for candidates twice
eachyear. First, in the month of June, second, in the month of December. Before the exam, it
opens a registration process so that candidates register themselves. After the end of the
registration dates, the authority consolidates the list of candidates and generates the unique
register numbers. These numbers are assigned to each candidate. The format of the register
numbers is as below. Each register number should contain exactly 10 characters.

For example, if year of registration 2018, cycle 2 and there are five candidates registered then,
registration numbers are: QE20182001, QE20182002, QE20182003, QE20182004, QE20182005.
The serial numbers should contain exactly 3 digits. To maintain it, prefix zeros as needed. (up to
9 serial number should be prefixed with two zeros, after 9, upto 99 it should be prefixed with
single zero and after 99, no zeros). Write a Java program to generate the registration numbers
as per the above requirement.

import java.io.*;

BCA, SRNMNC, SHIMOGA Page 7


JAVA MANUAL

import java.lang.*;

import java.util.Formatter;

public class RegNumGenerator

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

String comb="QE",year,cycle,srNo;

int num=0;

String[] regArray;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter number of students registered");

int n = Integer.parseInt(br.readLine());

//srNo=String.format("%03d",n);

regArray=new String[n];

System.out.println("Enter details of Student");

String reg="";

System.out.print("Enter year: ");

year = br.readLine();

while(true)

System.out.println("Enter cycle: ");

cycle = br.readLine();

int c = Integer.parseInt(cycle);

if(c<3)

break;

else

BCA, SRNMNC, SHIMOGA Page 8


JAVA MANUAL

System.out.print("cycle should be 1 or 2");

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

num++;

if(num<=9)

srNo=String.format("%03d",num);

else if(num>9 &&num<99)

srNo=String.format("%03d",num);

else

srNo=String.valueOf(num);

reg=comb+year+cycle+srNo;

regArray[i]=reg;

for(String val:regArray){

System.out.println("Generated Register Numbers:");

System.out.println(val);

6. Write a Java program to read name, register number, date of birth, address, phone number a student.
Concatenate these to frame a single content by delimiting each detail with a special symbol, pass it to
a method which should separate and display the details of the student. Declare a class containing the
following methods:
void getInformation() – to read student information. It should call concatenate(,,,,) by passing relevant
information.
void concatenate(String name, string regNo, String dob, String address, String phoneNo) to join the
information to frame a single content. It should call extractInformation(…) by passing the concatenated
information.
void extractInformation(String joinedInfo) to extracted concatenated contents and to display the

BCA, SRNMNC, SHIMOGA Page 9


JAVA MANUAL

information.
Declare another class to contain main () method which calls void getInformation().
Sample output:
Student Name: Venkata Krishna
Register Number: BC171128
Date of Birth: 10/05/1996
Address: No. 5, First Cross, Nehru Nagar, Sagar.
Phone Number: 9900990099
Concatenated content:
Venkata Krishna%BC171128%10/05/1996%No. 5, First Cross, Nehru Nagar, Sagar.%9900990099
(Application: This is the way using which collection of information is communicated between client
and server in networked environment)

import java.util.*;

import java.io.*;

class ConcatDemo

void getInformation() throws IOException

String name;

String regNo;

String dob;

String address;

String phoneNo;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter the name,regnum,dob, address,phoneNo");

name=br.readLine();

regNo=br.readLine();

dob=br.readLine();

address=br.readLine();

phoneNo=br.readLine();

System.out.println("===================");

System.out.println("Student Name:"+name);

System.out.println("Register Number"+regNo);

System.out.println("Date of Birth::"+dob);

BCA, SRNMNC, SHIMOGA Page 10


JAVA MANUAL

System.out.println("Address:"+address);

System.out.println("Phone Number:"+phoneNo);

System.out.println("===================");

concatenate(name, regNo,dob,address,phoneNo);

void concatenate(String name, String regNo, String dob, String address, String phoneNo)

String joinedInfo = name+"%"+regNo+"%"+dob+"%"+address+"%"+phoneNo;

System.out.println("concatenated info="+joinedInfo);

extractInformation(joinedInfo);

void extractInformation(String joinedInfo)

String s1 = new String(joinedInfo);

String[] words=s1.split("\\%");

System.out.println("===================");

System.out.println("extracted information");

for(String w:words){

System.out.println(w);

public class SplitDemo

public static void main(String []a) throws IOException

ConcatDemo c=new ConcatDemo();

c.getInformation();

}
BCA, SRNMNC, SHIMOGA Page 11
JAVA MANUAL

7. Consider class person with fields name, address and date of birth and methods read_data() and show()
and another class employee inherited form person class with fields emp_id, date of join and salary and
methods read() and show(). Write java program to implement the concept of single inheritance
with method overriding concepts for the above classes.

import java.util.*;

class Person

String name;

String address;

String dob;

Scanner sc= new Scanner(System.in);

void read_data()

System.out.println("enter the name");

name=sc.next();

System.out.println("enter the address");

address=sc.next();

System.out.println("enter the dob");

dob=sc.next();

void show()

System.out.println("name="+name);

System.out.println("address="+address);

System.out.println("dob="+dob);

BCA, SRNMNC, SHIMOGA Page 12


JAVA MANUAL

class Employee extends Person

int emp_id;

String date_of_joining;

int salary;

Scanner sc= new Scanner(System.in);

void read()

read_data();

System.out.println("enter the empid");

emp_id=sc.nextInt();

System.out.println("enter the dateofjoining");

date_of_joining=sc.next();

System.out.println("enter the salary");

salary=sc.nextInt();

void show()

System.out.println("emp_id="+emp_id);

System.out.println("address="+date_of_joining);

System.out.println("dob="+salary);

public class SingleDemo

public static void main( String [] a)

Person p=new Person();

Employee e= new Employee();


BCA, SRNMNC, SHIMOGA Page 13
JAVA MANUAL

e.read();

p.show();

e.show();

Part B

1. Write a Java program to create a vector, add elements at the end, at specified location onto the
vectorand display the elements. Write an option driven program using switch…case and also insertion
ofany type of objects must be possible. Read input as strings and find the type of data and convert them
into appropriate objects of appropriate classes. ( Ex: 10 must be converted to object of Integer class, 2.5
into object of Float class etc.). Handle exception while converting the inputs.

import java.io.*;

import java.util.*;

public class VectorDemo

public static void main(String [] args)

Vector v=new Vector();

int ch,pos;

String c;

Scanner sc=new Scanner(System.in);

while(true)

System.out.println(" Enter your choice");

System.out.println(" 1 to add Element at end");

System.out.println(" 2 to add at specified positon ");

System.out.println(" 3 to diplay");

System.out.println(" 4 to exit");

ch=sc.nextInt();
BCA, SRNMNC, SHIMOGA Page 14
JAVA MANUAL

switch(ch)

case 4: System.exit(0); break;

case 1: System.out.println(" Enter the value");

c=sc.next();

try

Double ele=Double.valueOf(c);

v.addElement(ele);

catch (Exception e)

break;

case 3: System.out.println("elements of Vector are"+v);

break;

case 2: System.out.println(" Enter the value");

c=sc.next();

try

Integer el=Integer.valueOf(c);

System.out.println("enter the position");

pos=sc.nextInt();

v.insertElementAt(el,pos);

catch (Exception e)

break;

BCA, SRNMNC, SHIMOGA Page 15


JAVA MANUAL

3. Write java program to demonstrate multi level inheritance using appropriate real life example.

class Car

public Car()

System.out.println("Class Car");

public void vehicleType()

System.out.println("Vehicle Type: Car");

class Maruti extends Car

public Maruti()

System.out.println("Class Maruti");

public void brand()

System.out.println("Brand: Maruti");

public void speed()

BCA, SRNMNC, SHIMOGA Page 16


JAVA MANUAL

System.out.println("Max: 90Kmph");

class Maruti800 extends Maruti

public Maruti800()

System.out.println("Maruti Model: 800");

public void speed()

System.out.println("Max: 80Kmph");

public class MultiLevelDemo

public static void main(String args[])

Maruti800 obj=new Maruti800();

obj.vehicleType();

obj.brand();

obj.speed();

BCA, SRNMNC, SHIMOGA Page 17


JAVA MANUAL

4. Write a java program to create a package Number which contains a class with three static methods
prime, fibanocii and Armstrong that checks whether the passed value is belongs to the corresponding
types.

package number;
import java.util.Scanner;

public class NumDemo


{

public static void fibo(int n){


int firstTerm = 0;

int secondTerm = 1;

int thirdTerm = 0;

while (thirdTerm < n)


{
thirdTerm = firstTerm + secondTerm;

firstTerm = secondTerm;

secondTerm = thirdTerm;
}

if(thirdTerm == n)

System.out.println(n+" is fib");

else

System.out.println(n+"is not fib");

public static void armst(int n)


{

int num = n, num1, remainder, result = 0;

num1 = num;

while (num1 != 0)
{
remainder = num1 % 10;
result += Math.pow(remainder, 3);
num1 /= 10;
}

BCA, SRNMNC, SHIMOGA Page 18


JAVA MANUAL

if(result == num)
System.out.println(num + " is an Armstrong number.");
else

System.out.println(num + " is not Armstrong number.");

public static void isPrime(int n)


{
int num = n;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i)
{

// condition for nonprime number


if (num % i == 0) {
flag = true;
break;

}
}

if (!flag)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}

import number.NumDemo;
import java.util.*;

class Packnum

{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter positive number :");

int num = sc.nextInt();


NumDemo.fibo(num);
NumDemo.armst(num);
NumDemo.isPrime(num);

BCA, SRNMNC, SHIMOGA Page 19


JAVA MANUAL

}
}

5. Write a java program to demonstrate multithreading using runnable interface.

import java.util.*;
class ThreadDemo

{
public static void main (String [] args)
{
GenOdd g=new GenOdd();
GenEven e=new GenEven();
GenFib f=new GenFib();
Thread t1=new Thread(g);
Thread t2=new Thread(e);
Thread t3=new Thread(f);
t2.start();
t1.start();
t3.start();
}
}

class GenEven implements Runnable


{
public void run()
{
for(int j=1;j<20;j++)
{
if(j%2==0) System.out.println(" even is"+j);
}
}
}

class GenOdd implements Runnable


{
public void run()
{
for(int i=1;i<20;i++)
{
if(i%2!=0)
System.out.println("odd no is "+i);
}
}
}

BCA, SRNMNC, SHIMOGA Page 20


JAVA MANUAL

class GenFib implements Runnable


{
public void run()
{
int fib1=0, fib2=1, fib3;
System.out.println ("Fibonacci series is");
System.out.println (fib1);
System.out.println (fib2);
for(int i=2;i<20;i++)
{
fib3=fib1+fib2;
System.out.println (fib3);
fib1=fib2;
fib2=fib3;
}
}
}

6. Write an applet to display the address of a person (atleast 4 lines) using parameter passing concept.
Appropriate message should be displayed for wrong input.

import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet
{
public void paint(Graphics g)
{

String str1=getParameter("name");

g.drawString("Ram",50,50);

g.drawString(str1,50, 50);

String str2=getParameter("home");
g.drawString(str2,50, 70);

String str3=getParameter("road");
g.drawString(str3,50, 90);

String str4=getParameter("name");
g.drawString(str4,50, 110);

}
}

BCA, SRNMNC, SHIMOGA Page 21


JAVA MANUAL

<html >

<body>
<applet code="UseParam.class" width="300" height="300">
<param name="name" value="SRNM">
<param name="home" value="#111,marvel ">
<param name="road" value="old post office road">
<param name="city" value="shivamoga,577201">

</applet>
</body>
</html>

8. Write an applet to draw n squares, rectangle and circles.

import java.awt.*;
import java.applet.*;
import java.util.*;
public class Polly extends Applet
{
TextField t1;
int n;
public void init()
{
t1=new TextField(3);
add(t1);
t1.setText("0");
}
public boolean action(Event e,Object o)
{
repaint();
return true;
}
public void paint(Graphics g)
{
g.drawString(" enter a no. ", 60,50);
try
{
n=Integer.parseInt(t1.getText());
}
catch(Exception e)
{
}
for(int i=0;i<n;i++)
{
g.drawOval(100+i*5,100+i*5,100-i*10,100-i*10);

BCA, SRNMNC, SHIMOGA Page 22


JAVA MANUAL

g.drawRect(100+i*5,250+i*5,100-i*10,100-i*10);
g.drawRect(100+i*5,400+i*5,250-i*10,100-i*10);

<html>
<body>
<applet code="Polly" height=500 width=500>
</applet>
</body>
</html>

BCA, SRNMNC, SHIMOGA Page 23

You might also like