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

Java Programmes

Uploaded by

Pallavi Soni
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)
22 views

Java Programmes

Uploaded by

Pallavi Soni
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
You are on page 1/ 16

JAVA PROGRAMMING

(LAB MANUAL)

MR. NAVDEEP CHARAN | LECTURER | ABHINAV COLLEGE


2

Q.1 WRITE A JAVA PROGRAM AND COMPUTE THE SUM OF THE DIGITS OF AN
INTEGER.
import java.util.Scanner;
public class Exercise {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer: ");
long n = input.nextLong();
System.out.println("The sum of the digits is: " +
sumDigits(n));

public static int sumDigits(long n) {


int sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
return sum;
}
}

OUTPUT:
Input an integer: 25
The sum of the digits is: 7
3

Q.2 WRITE A JAVA PROGRAM TO FIND THE K ’TH SMALLEST AND LARGEST ELEMENT
IN A GIVEN ARRAY. ELEMENTS IN THE ARRAY CAN BE IN ANY ORDER.
import java.util.*;
public class Exercise {
public static void main(String[] args)
{
Integer arr[] = new Integer[]{1, 4, 17, 7, 25, 3, 100};
int k = 2;
System.out.println("Original Array: ");
System.out.println(Arrays.toString(arr));
System.out.println("K'th smallest element of the said
array: ");
Arrays.sort(arr);
System.out.print(arr[k-1] + " ");
System.out.println("\nK'th largest element of the said
array:");
Arrays.sort(arr, Collections.reverseOrder());
System.out.print(arr[k-1] + " ");
}
}

OUTPUT:
Original Array:
[1, 4, 17, 7, 25, 3, 100]
K'th smallest element of the said array:
3
K'th largest element of the said array:
25
4

Q.3 WRITE A JAVA PROGRAM TO CONVERT TEMPERATURE FROM FAHRENHEIT TO


CELSIUS DEGREE.
import java.util.Scanner;
public class Exercise {

public static void main(String[] Strings) {

Scanner input = new Scanner(System.in);

System.out.print("Input a degree in Fahrenheit: ");


double fahrenheit = input.nextDouble();

double celsius =(( 5 *(fahrenheit - 32.0)) / 9.0);


System.out.println(fahrenheit + " degree Fahrenheit is equal
to " + celsius + " in Celsius");
}
}

OUTPUT:
Input a degree in Fahrenheit: 212
212.0 degree Fahrenheit is equal to 100.0 in Celsius
5

Q.4 WRITE A JAVA PROGRAM TO DISPLAY PASCAL'S TRIANGLE.


import java.util.Scanner;
public class Exercise {

public static void main(String[] args)


{
int no_row,c=1,blk,i,j;
System.out.print("Input number of rows: ");
Scanner in = new Scanner(System.in);
no_row = in.nextInt();
for(i=0;i<no_row;i++)
{
for(blk=1;blk<=no_row-i;blk++)
System.out.print(" ");
for(j=0;j<=i;j++)
{
if (j==0||i==0)
c=1;
else
c=c*(i-j+1)/j;
System.out.print(" "+c);
}
System.out.print("\n");
}
}
}

OUTPUT:
Input number of rows: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
6

Q.5 WRITE A JAVA PROGRAM TO INSERT AN ELEMENT ( AT SPECIFIC POSITION)


INTO AN ARRAY.
import java.util.Arrays;
public class Exercise {

public static void main(String[] args) {

int[] my_array = {25, 14, 56, 15, 36, 56, 77, 18, 29, 49};

// Insert an element in 3rd position of the array (index->2,


value->5)

int Index_position = 2;
int newValue = 5;

System.out.println("Original Array: "+Arrays.toString(my_array));

for(int i=my_array.length-1; i > Index_position; i--){


my_array[i] = my_array[i-1];
}
my_array[Index_position] = newValue;
System.out.println("New Array: "+Arrays.toString(my_array));
}
}

OUTPUT:
Original Array: [25, 14, 56, 15, 36, 56, 77, 18, 29, 49]
New Array: [25, 14, 5, 56, 15, 36, 56, 77, 18, 29]
7

Q.6 WRITE A JAVA PROGRAM TO COMPARE TWO STRINGS LEXICOGRAPHICALLY.


TWO STRINGS ARE LEXICOGRAPHICALLY EQUAL IF THEY ARE THE SAME LENGTH
AND CONTAIN THE SAME CHARACTERS IN THE SAME POSITIONS.
public class Exercise {
public static void main(String[] args)
{
String str1 = "This is Exercise 1";
String str2 = "This is Exercise 2";

System.out.println("String 1: " + str1);


System.out.println("String 2: " + str2);

// Compare the two strings.


int result = str1.compareTo(str2);

// Display the results of the comparison.


if (result < 0)
{
System.out.println("\"" + str1 + "\"" +
" is less than " +
"\"" + str2 + "\"");
}
else if (result == 0)
{
System.out.println("\"" + str1 + "\"" +
" is equal to " +
"\"" + str2 + "\"");
}
else // if (result > 0)
{
System.out.println("\"" + str1 + "\"" +
" is greater than " +
"\"" + str2 + "\"");
}
}
}

OUTPUT:
String 1: This is Exercise 1
String 2: This is Exercise 2
"This is Exercise 1" is less than "This is Exercise 2"
8

Q.7 WRITE A JAVA PROGRAM TO GET CURRENT FULL DATE AND TIME.
import java.util.*;
public class Exercise {
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
System.out.println();
System.out.println("Current full date and time is : " +
(now.get(Calendar.MONTH) + 1) + "-"
+ now.get(Calendar.DATE) + "-" + now.get(Calendar.YEAR) + "
"
+ now.get(Calendar.HOUR_OF_DAY) + ":" +
now.get(Calendar.MINUTE) + ":"
+ now.get(Calendar.SECOND) + "." +
now.get(Calendar.MILLISECOND));
System.out.println();
}
}

OUTPUT:
Current full date and time is : 6-20-2017 14:51:24.303
9

Q.8 WRITE A JAVA METHOD TO COUNT ALL VOWELS IN A STRING.


import java.util.Scanner;
public class Exercise {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();

System.out.print("Number of Vowels in the string: " +


count_Vowels(str)+"\n");
}
public static int count_Vowels(String str)
{
int count = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' ||
str.charAt(i) == 'i'
|| str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
count++;
}
}
return count;
}
}

OUTPUT:
Input the string: w3resource
Number of Vowels in the string: 4
10

Q.9 WRITE A JAVA PROGRAM TO WRITE AND READ A PLAIN TEXT FILE.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;

public class Eexercise {


public static void main(String a[]){
StringBuilder sb = new StringBuilder();
String strLine = "";
try
{
String filename= "/home/students/myfile.txt";
FileWriter fw = new FileWriter(filename,false);
//appends the string to the file
fw.write("Abhinav College\n");
fw.close();
BufferedReader br = new BufferedReader(new
FileReader("/home/students/myfile.txt"));
//read the file content
while (strLine != null)
{
sb.append(strLine);
sb.append(System.lineSeparator());
strLine = br.readLine();
System.out.println(strLine);
}
br.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
}

OUTPUT:
Abhinav College
Abhinav College
11

Q.10 WRITE A JAVA PROGRAM TO COMPARE TWO TREE SETS.


import java.util.TreeSet;
import java.util.Iterator;

public class Exercise {


public static void main(String[] args) {
// Create a empty tree set
TreeSet<String> t_set1 = new TreeSet<String>();
// use add() method to add values in the tree set
t_set1.add("Red");
t_set1.add("Green");
t_set1.add("Black");
t_set1.add("White");
System.out.println("Free Tree set: "+t_set1);

TreeSet<String> t_set2 = new TreeSet<String>();


t_set2.add("Red");
t_set2.add("Pink");
t_set2.add("Black");
t_set2.add("Orange");
System.out.println("Second Tree set: "+t_set2);
//comparison output in tree set
TreeSet<String> result_set = new TreeSet<String>();
for (String element : t_set1){
System.out.println(t_set2.contains(element) ? "Yes" :
"No");
}
}
}

OUTPUT:
Free Tree set: [Black, Green, Red, White]
Second Tree set: [Black, Orange, Pink, Red]
Yes
No
Yes
No
12

Q.11 WRITE A JAVA PROGRAM TO REVERSE AN INTEGER NUMBER.


public class Exercise {
public static void main(String[] args) {
int num =1287;
int is_positive = 1;
if (num < 0) {
is_positive = -1;
num = -1 * num;
}
int sum = 0;
while (num > 0) {
int r = num % 10;

int maxDiff = Integer.MAX_VALUE - sum * 10;


if (sum > Integer.MAX_VALUE / 10 || r > maxDiff)
System.out.println("Wrong number");;

sum = sum * 10 + r;
num /= 10;
}
System.out.println(is_positive * sum);
}
}

OUTPUT:
7821
13

Q.12 WRITE A JAVA PROGRAM TO SORT AN ARRAY OF GIVEN INTEGERS USING


QUICK SORT ALGORITHM.
import java.util.Arrays;
public class QuickSort {

private int temp_array[];


private int len;

public void sort(int[] nums) {

if (nums == null || nums.length == 0) {


return;
}
this.temp_array = nums;
len = nums.length;
quickSort(0, len - 1);
}
private void quickSort(int low_index, int high_index) {

int i = low_index;
int j = high_index;
// calculate pivot number
int pivot = temp_array[low_index+(high_index-low_index)/2];
// Divide into two arrays
while (i <= j) {
while (temp_array[i] < pivot) {
i++;
}
while (temp_array[j] > pivot) {
j--;
}
if (i <= j) {
exchangeNumbers(i, j);
//move index to next position on both sides
i++;
j--;
}
}
// call quickSort() method recursively
if (low_index < j)
quickSort(low_index, j);
if (i < high_index)
quickSort(i, high_index);
}

private void exchangeNumbers(int i, int j) {


int temp = temp_array[i];
temp_array[i] = temp_array[j];
temp_array[j] = temp;
14

// Method to test above


public static void main(String args[])
{
QuickSort ob = new QuickSort();
int nums[] = {7, -5, 3, 2, 1, 0, 45};
System.out.println("Original Array:");
System.out.println(Arrays.toString(nums));
ob.sort(nums);
System.out.println("Sorted Array");
System.out.println(Arrays.toString(nums));
}
}

OUTPUT:
Original Array:
[7, -5, 3, 2, 1, 0, 45]
Sorted Array
[-5, 0, 1, 2, 3, 7, 45]
15

Q.13 WRITE A JAVA PROGRAM TO FIND A SPECIFIED ELEMENT IN A GIVEN ARRAY


OF ELEMENTS USING BINARY SEARCH.
public class Main {
public static int binarySearch(int[] nums, int flag) {
int hi_num = nums.length - 1;
int lo_num = 0;
while (hi_num >= lo_num) {
int guess = (lo_num + hi_num) >>> 1;
if (nums[guess] > flag) {
hi_num = guess - 1;
} else if (nums[guess] < flag) {
lo_num = guess + 1;
} else {
return guess;
}
}
return -1;
}

public static void main(String[] args) {


int[] nums = {1, 5, 6, 7, 8, 11};
int search_num = 7;
int index = binarySearch(nums, search_num);
if (index == -1) {
System.out.println(search_num + " is not in the array");
} else {
System.out.println(search_num + " is at index " +
index);
}
}
}

OUTPUT:
7 is at index 3
16

You might also like