SlideShare ist ein Scribd-Unternehmen logo
1 von 50
Downloaden Sie, um offline zu lesen
PROGRAM 51
Write a program in Java to display the pattern like right angle triangle
with a number.
SOLUTION:
importjava.util.Scanner;
public class Pattern3{
public static void main(String[] args)
{
inti,j,n;
System.out.print("Input number of rows : ");
Scanner in = new Scanner(System.in);
n =in.nextInt();
for(i=1;i<=n;i++)
{
for(j=1;j<=i;j++)
System.out.print(j);
System.out.println("");
}}}
OUTPUT:
Input number of rows : 10
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
PROGRAM 52
Write a program in Java to make such a pattern like a pyramid with a
number which will repeat the number in the same row.
SOLUTION:
importjava.util.Scanner;
public class Pattern4{
public static void main(String[] args)
{
inti,j,n,s,x;
System.out.print ("Input number of rows : ");
Scanner in = new Scanner(System.in);
n =in.nextInt();
s=n+4-1;
for(i=1;i<=n;i++)
{
for(x=s;x!=0;x--)
{
System.out.print(" ");
}
for(j=1;j<=i;j++){
System.out.print(i+" ");
}
System.out.println();
s--;
}}}
OUTPUT:
Input Number of Rows : 4
1
2 2
3 3 3
4 4 4 4
PROGRAM 53
Write a Java program to display Pascal's triangle.
SOLUTION:
importjava.util.Scanner;
public class Pattern5 {
public static void main(String[] args)
{
intno_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
PROGRAM 54
Write a Java program that reads an integer and check whether it is
negative, zero, or positive.
SOLUTION:
importjava.util.Scanner;
public class POSITIVE{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input a number: ");
int n =in.nextInt();
if (n > 0)
{
System.out.println("Number is positive");
}
else if (n < 0)
{
System.out.println("Number is negative");
}
else
{
System.out.println("Number is zero");
}
}
}
OUTPUT:
Input a number: 7
Number is positive
PROGRAM 55
Write a program that accepts three numbers from the user and prints
"increasing" if the numbers are in increasing order, "decreasing" if the
numbers are in decreasing order, and "Neither increasing or decreasing
order" otherwise.
SOLUTION:
importjava.util.Scanner;
public class Number {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input first number: ");
double x =in.nextDouble();
System.out.print("Input second number: ");
double y =in.nextDouble();
System.out.print("Input third number: ");
double z =in.nextDouble();
if (x < y && y < z){
System.out.println("Increasing order");
}
else if (x > y && y > z)
{
System.out.println("Decreasing order");
}
else{
System.out.println("Neither increasing or decreasing order");
}}}
OUTPUT:
Input first number: 1524
Input second number: 2345
Input third number: 3321
Increasing order
PROGRAM 56
Write a Java program to sort a numeric array and a string array.
SOLUTION:
importjava.util.Arrays;
public class Array1 {
public static void main(String[] args){
int[] my_array1 = {1789, 2035, 1899, 1456, 2013,1458, 2458,1254,1472,
2365,1456, 2165, 1457, 2456};
String[]my_array2={"Java","Python","PHP","C#","CProgramming",
"C++"}
System.out.println("Original numeric array
:"+Arrays.toString(my_array1));
Arrays.sort(my_array1);
System.out.println("Sorted numeric array :
"+Arrays.toString(my_array1));
System.out.println("Original string array :
"+Arrays.toString(my_array2));
Arrays.sort(my_array2);
System.out.println("Sorted string array : "+Arrays.toString(my_array2));
}
}
OUTPUT:
Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458,
1254, 1472, 2365, 1456, 2165, 1457, 2456]
Sorted numeric array : [1254, 1456, 1456, 1457, 1458, 1472, 1789,
1899, 2013, 2035, 2165, 2365, 2456, 2458]
Original string array : [Java, Python, PHP, C#, C Programming, C++]
Sorted string array :[C Programming, C#, C++, Java, PHP, Python]
PROGRAM 57
Write a Java program to calculate the average value of array
elements.
SOLUTION:
publicclassArray2
{
publicstaticvoidmain(String[]args)
{
int[] numbers =newint[]{20,30,25,35,-16,60,-100};
//calculate sum of all array elements
int sum =0;
for(inti=0;i<numbers.length;i++)
{
sum= sum + numbers[i];
//calculate average value
double average = sum /numbers.length;
System.out.println("Average value of the array elements is : "+
average);
}
}
}
OUTPUT:
Average value of the array elements is : 7.0
PROGRAM 58
Write a Java program to insert an element (specific position) into an
array.
SOLUTION:
importjava.util.Arrays;
public class Array3 {
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)
intIndex_position= 2;
intnewValue= 5;
System.out.println("Original Array :
"+Arrays.toString(my_array));
for(inti=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]
PROGRAM 59
Write a Java program to replace every element with the next
greatest element (from right side) in an given array of integers.
Solution:
import java.io.*;
importjava.util.Arrays;
classArray4 {
public static void main (String[] args)
{
intnums[] = {45, 20, 100, 23, -5, 2, -6};
int result[];
System.out.println("Original Array ");
System.out.println(Arrays.toString(nums));
result = next_greatest_num(nums);
System.out.println("The modified array:");
System.out.println(Arrays.toString(result));
}
staticint [] next_greatest_num(intarr_nums[]) {
int size = arr_nums.length;
intmax_from_right_num = arr_nums[size-1];
arr_nums[size-1] = -1;
for (inti = size-2; i>= 0; i--) {
int temp = arr_nums[i];
arr_nums[i] = max_from_right_num;
if(max_from_right_num< temp)
max_from_right_num = temp;
}
returnarr_nums;
} }
OUTPUT:
Original Array [45, 20, 100, 23, -5, 2, -6]
The modified array:[100, 100, 23, 2, 2, -6, -1]
PROGRAM 60
Write a Java program to separate even and odd numbers of an given
array of integers. Put all even numbers first, and then odd numbers.
Solution:
importjava.util.Arrays;
class Array5{
public static void main (String[] args){
intnums[] = {20, 12, 23, 17, 7, 8, 10, 2, 1, 0};
int result[];
System.out.println("Original Array ");
System.out.println(Arrays.toString(nums));
result=separate_odd_even(nums);
System.out.print("Array after separation ");
System.out.println(Arrays.toString(result));}
staticint [] separate_odd_even(intarr[]){
intleft_side= 0, right_side=arr.length- 1;
while (left_side<right_side){
while (arr[left_side]%2 == 0 &&left_side<right_side)
left_side++;
while (arr[right_side]%2 == 1 &&left_side<right_side)
right_side--;
if (left_side<right_side){
int temp =arr[left_side];
arr[left_side] =arr[right_side];
arr[right_side] = temp;
left_side++;
right_side--;}}
returnarr;}}
OUTPUT:
Original Array [45, 20, 100, 23, -5, 2, -6]
The modified array:[100, 100, 23, 2, 2, -6, -1]
PROGRAM 61
Write a Java program to separate 0s on left side and 1s on right side of
an array of 0s and 1s in random order.
Solution:
importjava.util.Arrays;
classArray6 {
public static void main(String[] args) {
intarr[] = new int[]={ 0, 0, 1, 1, 0, 1, 1, 1,0 };
int result[];
System.out.println("Original Array ");
System.out.println(Arrays.toString(arr));
int n = arr.length;
result = separate_0_1(arr, n);
System.out.println("New Array ");
System.out.println(Arrays.toString(result));
}
staticint [] separate_0_1(intarr[], int n) {
int count = 0;
for (inti = 0; i< n; i++)
if (arr[i] == 0)
count++;}
for (inti = 0; i< count; i++)
arr[i] = 0;
for (inti = count; i< n; i++)
arr[i] = 1;
returnarr;
}}
OUTPUT:
Original Array [0, 0, 1, 1, 0, 1, 1, 1, 0]
New Array [0, 0, 0, 0, 1, 1, 1, 1, 1]
PROGRAM 62
Write a Java program to find the rotation count in a given rotated
sorted array of integers.
Solution:
importjava.util.*;
importjava.lang.*;
import java.io.*;
public class Array7
{
staticintcount_rotations(intarr_int[], int n)
{
intmin_val=arr_int[0], min_index=-1;
for (inti= 0; i< n; i++)
{
if (min_val>arr_int[i])
{
min_val=arr_int[i];
min_index=i;
}
}
returnmin_index;
}
public static void main (String[] args)
{
intarr_int[] = {35, 32, 30, 14, 18, 21, 27};
// intarr_int[] = {35, 32, 14, 18, 21, 27};
// intarr_int[] = {35, 14, 18, 21, 27};
int n =arr_int.length;
System.out.println(count_rotations(arr_int, n));
}}
OUTPUT:
Number of Rotations = 3
PROGRAM 63
Write a Java program to find all pairs of elements in an array whose
sum is equal to a specified number
Solution:
public class Array8 {
static void pairs_value(intinputArray[], intinputNumber)
{
System.out.println("Pairs of elements and their sum : ");
for (inti= 0; i<inputArray.length; i++)
{
for (int j = i+1; j <inputArray.length; j++)
{
if(inputArray[i]+inputArray[j] ==inputNumber)
{
System.out.println(inputArray[i]+" + "+inputArray[j]+" =
"+inputNumber);
}
}}}
public static void main(String[] args)
{
pairs_value(new int[] {2, 7, 4, -5, 11, 5, 20}, 15);
pairs_value(new int[] {14, -15, 9, 16, 25, 45, 12, 8}, 30);
}
}
OUTPUT:
Enter the Number = 15
Pairs of elements and their sum :4 + 11 = 15
-5 + 20 = 15
PROGRAM 64
Write a Java program to add two matrices of the same size
Solution:
importjava.util.Scanner;
public class Array9
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Input number of rows of matrix");
m =in.nextInt();
System.out.println("Input number of columns of matrix");
n =in.nextInt();
int array1[][] = new int[m][n];
int array2[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Input elements of first matrix");
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
{
array1[c][d] =in.nextInt();
System.out.println("Input the elements of second matrix");
}}
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
array2[c][d] =in.nextInt();
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = array1[c][d] + array2[c][d];
System.out.println("Sum of the matrices:-");
for ( c = 0 ; c < m ; c++ ){
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"t");
System.out.println();
}
}}
OUTPUT:
Input number of rows of matrix
2
Input number of columns of matrix
2
Input elements of first matrix
1 2
34
Input the elements of second matrix
5 6
7 8
Sum of the matrices:-
6 8
10 12
PROGRAM 65
Write a Java program to check if an array of integers without 0 and -1.
Solution:
importjava.util.*;
import java.io.*;
public class Array10
{
public static void main(String[] args)
{
int[] array_nums= {50, 77, 12, 54, -11};
System.out.println("Original Array: "+Arrays.toString(array_nums));
System.out.println("Result: "+test(array_nums));
}
public static boolean test(int[] numbers)
{
for (int number : numbers)
{
if (number == 0 || number ==-1)
{
return false;
}
}
return true;
}
}
OUTPUT:
Original Array: [50, 77, 12, 54, -11]
Result: true
PROGRAM 66
Write a Java program to check if the sum of all the 10's in the array is
exactly 30. Return false if the condition does not satisfy, otherwise true.
Solution:
importjava.util.*;
import java.io.*;
public class Array11 {
public static void main(String[] args)
{
int[] array_nums= {10, 77, 10, 54, -11, 10};
System.out.println("Original Array: "+Arrays.toString(array_nums));
intsearch_num= 10;
intfixed_sum= 30;
System.out.println("Result: "+result(array_nums, search_num,
fixed_sum));
}
public static boolean result(int[] numbers, intsearch_num,
intfixed_sum) {
inttemp_sum= 0;
for (int number : numbers) {
if (number ==search_num) {
temp_sum+=search_num;
}
if (temp_sum>fixed_sum) {
break;
}
}
returntemp_sum==fixed_sum;
}}
OUTPUT:
Original Array: [10, 77, 10, 54, -11, 10]
Result: true
PROGRAM 67
Write a Java program to check if an array of integers contains two
specified elements 65 and 77.
Solution:
importjava.util.*;
import java.io.*;
public class Array12 {
public static void main(String[] args)
{
int[] array_nums= {77, 77, 65, 65, 65, 77};
System.out.println("Original Array: "+Arrays.toString(array_nums));
int num1 = 77;
int num2 = 65;
System.out.println("Result: "+result(array_nums, num1, num2));
}
public static boolean result(int[] array_nums, int num1, int num2) {
for (int number :array_nums) {
boolean r = number != num1 && number != num2;
if (r) {
return false;
}
}
return true;
}
}
OUTPUT:
Original Array: [77, 77, 65, 65, 65, 77]
Result: true
PROGRAM 68
Write a Java program to get the character at the given index within the
String.
SOLUTION:
public class String1
{
public static void main(String[] args)
{
String str= "Java Exercises!";
System.out.println("Original String = " +str);
// Get the character at positions 0 and 10.
int index1 =str.charAt(0);
int index2 =str.charAt(10);
// Print out the results.
System.out.println("The character at position 0 is " +
(char)index1);
System.out.println("The character at position 10 is " +
(char)index2);
}
}
OUTPUT:
Original String = Java Exercises!
The character at position 0 is J
The character at position 10 is i
PROGRAM 69
Write a Java program to trim any leading or trailing
whitespace from a given
string.
Solution:
publicclassString2{
publicstaticvoidmain(String[]args)
{
String str=" Java Exercises ";
// Trim the whitespace from the front and back of the
// String.
String new_str=str.trim();
// Display the strings for comparison.
System.out.println("Original String: "+str);
System.out.println("New String: "+new_str);
}
}
OUTPUT:
Original String: Java Exercises
New String: Java Exercises
PROGRAM 70
Write a program in java To find minimum value using overloading.
Solution:
public class ExampleOverloading{
public static void main(String[] args){
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);}
public static intminFunction(int n1, int n2)
{
intmin;if (n1 > n2)min = n2;
elsem in = n1;
return min;
}
public static double minFunction(double n1, double n2)
{
double min;
if (n1 > n2)
min = n2;
elsemin = n1;
return min;
}
}
OUTPUT:
Minimum Value = 6
Minimum Value = 7.3
PROGRAM 71
Write a program in Java to show the use of this keyword.
Solution:
public class This_Example
{
intnum = 10;
This_Example() {
System.out.println("This is an example program on keyword this");
}
This_Example(intnum) {
this();
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Tutorialspoint");
}
public void print() {
intnum = 20;
System.out.println("value of local variable num is : "+num);
System.out.println("value of instance variable num is : "+this.num);
this.greet();
}
public static void main(String[] args)
{
This_Example obj1 = new This_Example(); obj1.print();
This_Exampleobj2 = new This_Example(30); obj2.print();
}}
OUTPUT:
This is an example program on keyword this value of local variable
numis : 20
value of instance variable num is : 10
PROGRAM 72
Write a program in java to demonstrate InputStream and
OutputStream.
SOLUTION:
import java.io.*;
public class fileStreamTest {
public static void main(String args[]) {
try {
bytebWrite [] = {11,21,3,40,5};
OutputStreamos = new FileOutputStream("test.txt"); for(int x = 0; x
<bWrite.length ; x++)
{
os.write(bWrite[x] );
}
os.close();
InputStream is = new FileInputStream("test.txt");
int size = is.available();
for(inti = 0; i< size; i++) {
System.out.print((char)is.read() + " ");
}
is.close();
}
catch (IOException e) {
System.out.print("Exception");
}}}
OUTPUT:
The above code would create file test.txt and would write given
numbers in binary format. Same would be the output on the
stdout screen.
PROGRAM 73
Write a program in java to create
"/tmp/user/java/bin" directory.
SOLUTION:
importjava.io.File;
public class CreateDir
{
public static void main(String args[])
{
String dirname ="/tmp/user/java/bin";
File d = new File(dirname); // Create directory
now. d.mkdirs();
}
}
OUTPUT:
Compile and execute the above code to create
"/tmp/user/java/bin".
PROGRAM 74
Write a program in java to list down all the files and directories
available in a directory.
SOLUTION:
importjava.io.File;
public class ReadDir
{
public static void main(String[] args)
{
File file = null;
String[] paths;
try
{
// create new file object
file = new File("/tmp");
// array of files and directory
paths = file.list();
// for each name in the path array
for(String path:paths)
{
// prints filename and directory name
System.out.println(path);
}}
catch (Exception e) {
// if any error occurs
e.printStackTrace();
} }}
OUTPUT:
test1.txt
test2.txt
ReadDir.java
ReadDir.class
PROGRAM 75
Write a program in java to throw Exceptions occurred by Index
of an array
public class ExcepTest
{
public static void main(String args[])
{
int a[] = new int[2];
try
{
System.out.println("Access element three :" + a[3]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e); }
finally
{
a[0] = 6;
System.out.println("First element value: " + a[0]);
System.out.println("The finally statement is executed");
}
}
}
OUTPUT:
Exception
thrown:java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
PROGRAM 76
Write a program in Java to print the multiplication of two matrices.
public class MatrixMultiplicationExample
{
public static void main(String args[])
{
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
//creating another matrix to store the multiplication of two matrices
int c[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}}}
OUTPUT:
First matrix: Second matrix:
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
Multiplied Matrix:
6 6 6
12 12 12
18 18 18
PROGRAM 77
Write a Java program to find the longest word in a text file
SOLUTION:
importjava.util.Scanner;
import java.io.*;
public class Exercise18 {
public static void main(String [ ] args) throws FileNotFoundException {
new Exercise18().findLongestWords();
}
public String findLongestWords() throws FileNotFoundException {
String longest_word= "";
String current;
Scanner sc= new Scanner(new File("/home/students/test.txt"));
while (sc.hasNext()) {
current=sc.next();
if (current.length() >longest_word.length()) {
longest_word= current;
}
}
System.out.println("n"+longest_word+"n");
returnlongest_word;
}
}
OUTPUT:
general-purpose,
PROGRAM 78
Write a Java program to write and read a plain text file.
SOLUTION:
import java.io.*;
public class Eexercise15 {
public static void main(String a[]){
StringBuildersb= new StringBuilder();
String strLine= "";
try
{
String filename= "/home/students/myfile.txt";
FileWriterfw= new FileWriter(filename,false);
fw.write("Python Exercisesn");
fw.close();
BufferedReaderbr= new BufferedReader(new
FileReader("/home/students/myfile.txt"));
while (strLine!= null)
{
sb.append(strLine);
sb.append(System.lineSeparator());
strLine=br.readLine();
System.out.println(strLine);
}
br.close();
}
catch(IOExceptionioe)
{
System.err.println("IOException: " +ioe.getMessage());
}}}
OUTPUT:
Python Exercises
Null
PROGRAM 79
Write a Java program to append text to an existing file.
SOLUTION:
importjava.io.FileWriter;
public class Exercise16 {
public static void main(String a[]){
StringBuildersb= new StringBuilder();
String strLine= "";
try{
String filename= "/home/students/myfile.txt";
FileWriterfw= new FileWriter(filename,true);
fw.write("Java Exercisesn");
fw.close();
BufferedReaderbr= 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(IOExceptionioe){
System.err.println("IOException: " +ioe.getMessage());
}}}
OUTPUT:
Python Exercises
Java Exercises
null
PROGRAM 80
Write a Java program to read first 3 lines from a file.
SOLUTION:
importjava.io.FileInputStream;
public class Exercise17 {
public static void main(String a[]){
BufferedReaderbr= null;
String strLine= "";
try {
LineNumberReader reader = new LineNumberReader(new
InputStreamReader(new FileInputStream("/home/students/test.txt"),
"UTF-8"));
while (((strLine=reader.readLine()) != null) &&reader.getLineNumber()
<= 3){
System.out.println(strLine);
}
reader.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}}
OUTPUT:
Welcome to w3resource.com.
Append this text.Append this text.Append this text.
Append this text.
PROGRAM 81
Write a program to show the Dynamic Method Dispatch using
inheritance.
SOLUTION:
class parent1{
void sum(inti, int j){
System.out.println(“Parent class” + (i+j));
}}
class child1 extends parent1{
void sum(inti, int j){
System.out.println(“Child class” + (i+j));}}
classdynamic_test{
public static void main(String args[]){
parent1 p1=new parent1();
child1 c1=new child1();
parent1Refi;
Refi=p1;
Refi.sum(10,20);
Refi=c1;
Refi.sum(20,30);
}}
Output:
Parent class 30 Child class 50
PROGRAM: 82
Write a program to accept 10 different word in array and pass the array
to function. Search the word enter by the user is present or not.
SOLUTION:
import java.io.*;
class Searching{
int search(String name[],String ns){
inti,p=0;
for(j=0;j<10;j++){
if(name[j].equals(ns))
p=1;}
return p;}
public static void main()throws IOException{
inti,k=0;
String name[]=new String[10];String ns;
BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in));
Searching ob=new Searching();
System.out.println(“Enter 10 names”);
for(i=0;i<10;i++){
name[i]=br.readLine();}
System.out.println(“Enter the name to be searched:”);
ns=in.readLine();
k=ob.search(name,ns);
if(k==1)
System.out.println(“Search successful”);
else
System.out.println(“NO such name is present”);
}}
OUTPUT:
Enters 10 names
aman, jyoti, deepa, pawan, mayank, arif, abhishek, vishal, lavi, ravi
Enter the name to be searched: arjun
No such name is present
PROGRAM: 83
Write a program in java to accept two numbers and find their sum
using function by creating the object of class.
SOLUTION:
import java.io.*;
public class Addition{
int sum(inta,int b){
int c;
c=a+b;
return c;
}
public static void main()throws IOException{
intm,n,k;
BufferedReaderbr=new BufferedReader(new
InputStreamReader(System.in));
Addition ob=new Addition();
System.out.println(“Enter two numbers”);
m=Integer.parseInt(br.readLine());
n=Integer.parseInt(br.readLine());
k=ob.sum(m,n);
System.out.println(“The sum of two numbers:” + k);
}
}
OUTPUT:
Enter two numbers
3
4
The sum of two numbers: 7
PROGRAM: 84
Write a program to find all combination of four elements of an given
array whose sum is equal to a given value.
SOLUTION:
importjava.util.*;
importjava.lang.*;
class Main
{
public static void main(String args[])
{
intnum[]={10, 20, 30, 40, 1, 2};
int n=num.length;
int s=53;
System.out.println(“The given:” + s);
System.out.println(“The combination of four elements:”);
for(inti=0;i<n-3;i++){
for(int j=i+1;j<n-2;j++){
for(int k=j+1;k<n-1;k++){
for(int l=k+1;l<n;l++)
{
if(num[i]+num[j]+num[k]+num[l]==s)
System.out.print(num[i]+ “ “ + num[j]+ “ “ + num[k]+ “ “+ num[l]);
}}}}
}}
OUTPUT:
Given value: 53
Combination of four elements:
10 40 1 2
20 30 1 2
PROGRAM 85
Write a Java program to store text file content line by line into an
array.
SOLUTION:
importjava.util.Arrays;
public class Exercise14 {
public static void main(String a[]){
StringBuildersb= new StringBuilder();
String strLine= "";
List<String> list = new ArrayList<String>();
try {
BufferedReaderbr= new BufferedReader(new
FileReader("/home/students/test.txt"));
while (strLine!= null)
{
strLine=br.readLine();
sb.append(strLine);
sb.append(System.lineSeparator());
strLine=br.readLine();
if (strLine==null)
break;
list.add(strLine);}
System.out.println(Arrays.toString(list.toArray()));
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}}}
OUTPUT:
[Append this text.Append this text.Append this text., Append this text.,
Append this text.]
PROGRAM 86
Write a java program to read a file line by line and store it into a
variable.
SOLUTION:
importjava.io.FileReader;
public class exercise13 {
public static void main(String a[]){
StringBuildersb= new StringBuilder();
String strLine= "";
String str_data= "";
try {
BufferedReaderbr= new BufferedReader(new
FileReader("/home/students/test.txt"));
while (strLine!= null)
{
if (strLine== null)
break;
str_data+=strLine;
strLine=br.readLine();
}
System.out.println(str_data);
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}}}
OUTPUT:
Welcome to w3resource.com.Append this text.Appendthistext.Append
this text.Append this text.Append this text.Append this text.Append
this text.
PROGRAM 87
Write a Java program to print all the LEADERS in the array.
Note: An element is leader if it is greater than all the elements to
its right side.
SOLUTION:
importjava.util.Arrays;
class Main
{
public static void main(String[] args)
{
intarr[] = {10, 9, 14, 23, 15, 0, 9}; int size = arr.length;
for (inti = 0; i< size; i++)
{
int j;
for (j = i + 1; j < size; j++)
{
if (arr[i] <= arr[j])
break;
}
if (j == size)
System.out.print(arr[i] + " ");
}
}
}
OUTPUT:
23 15 9
PROGRAM 88
Write a Java program to find the sum of the two elements of a given
array which is equal to a given integer.
SOLUTION:
importjava.util.*;
public class Exercise35{
public static ArrayList<Integer>two_sum_array_target(final List<Integer> a,
int b) {
HashMap<Integer, Integer>my_map= new HashMap<Integer, Integer>();
ArrayList<Integer> result = new ArrayList<Integer>();
result.add(0);
result.add(0);
for(inti= 0; i<a.size(); i++){
if(my_map.containsKey(a.get(i))){
int index =my_map.get(a.get(i));
result.set(0, index + 1);
result.set(1, i+ 1);
break;}
else{
my_map.put(b -a.get(i), i);
}}
return result;
}
public static void main(String[] args){
ArrayList<Integer>my_array= new ArrayList<Integer>();
my_array.add(1);
my_array.add(2);my_array.add(4);my_array.add(5);my_array.add(6);
int target = 6;
ArrayList<Integer> result =two_sum_array_target(my_array, target);
for(inti: result)
System.out.print("Index: "+i+ " ");}}
OUTPUT:
Index 1 Index ⁴
PROGRAM 90
Write a Java program to join two linked lists.
Solution:
importjava.util.*;
public class Exercise17 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> c1 = new LinkedList<String> ();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");
System.out.println("List of first linked list: " + c1);
LinkedList<String> c2 = new LinkedList<String> ();
c2.add("Red");
c2.add("Green");
c2.add("Black");
c2.add("Pink");
System.out.println("List of second linked list: " + c2);
LinkedList<String> a = new LinkedList<String> ();
a.addAll(c1);
a.addAll(c2);
System.out.println("New linked list: " + a);
}}
OUTPUT:
List of first linked list: [Red, Green, Black, White, Pink]
List of second linked list: [Red, Green, Black, Pink]
New linked list: [Red, Green, Black, White,Pink,Red,Green,Black, Pink]
PROGRAM 91
Write a Java program to shuffle the elements in a linked list.
SOLUTION:
importjava.util.*;
public class Exercise16 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String>l_list= new LinkedList<String> ();
// use add() method to add values in the linked list
l_list.add("Red");
l_list.add("Green");
l_list.add("Black");
l_list.add("Pink");
l_list.add("orange");
// print the list
System.out.println("Linked list before shuffling:n" +l_list);
Collections.shuffle(l_list);
System.out.println("Linked list after shuffling:n" +l_list);
}
}
OUTPUT:
Linked list before shuffling:[Red, Green, Black, Pink, orange]
Linked list after shuffling: [orange, Pink, Red, Black, Green]
PROGRAM 92
Write a Java program to remove and return the first element of
a linked list.
SOLUTION:
importjava.util.*;
public class Exercise19
{
public static void main(String[] args)
{
// create an empty linked list
LinkedList<String> c1 = new LinkedList<String> ();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");
System.out.println("Original linked list: " + c1);
System.out.println("Removed element: "+c1.pop());
System.out.println("Linked list after pop operation: "+c1);
}
}
OUTPUT:
Original linked list: [Red, Green, Black, White, Pink]
Removed element: Red Linked list after pop operation: [Green,
Black, White, Pink]
PROGRAM 93
Write a Java program to retrieve but does not remove, the first element
of a linked list.
SOLUTION:
importjava.util.*;
publicclassExercise20{
publicstaticvoidmain(String[]args){
// create an empty linked list
LinkedList<String> c1 =newLinkedList<String>();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");
System.out.println("Original linked list: "+ c1);
// Retrieve but does not remove, the first element of a linked list
String x =c1.peekFirst();
System.out.println("First element in the list: "+ x);
System.out.println("Original linked list: "+ c1);
}
}
OUTPUT:
Original linked list: [Red, Green, Black, White, Pink]
First element in the list: Red
Original linked list: [Red, Green, Black, White, Pink]
PROGRAM 94
Write a Java program to retrieve but does not remove, the last element
of a linked list.
SOLUTION:
importjava.util.*;
public class Exercise21 {
public static void main(String[] args) {
// create an empty linked list
LinkedList<String> c1 = new LinkedList<String> ();
c1.add("Red");
c1.add("Green");
c1.add("Black");
c1.add("White");
c1.add("Pink");
System.out.println("Original linked list: " + c1);
// Retrieve but does not remove, the last element of a linked list
String x =c1.peekLast();
System.out.println("Last element in the list: " + x);
System.out.println("Original linked list: " + c1);
}
}
OUTPUT:
Original linked list: [Red, Green, Black, White, Pink]
Last element in the list: Pink
Original linked list: [Red, Green, Black, White, Pink]
PROGRAM 95
Write a Java program to retrieve and remove the first element of a tree
set.
SOLUTION:
importjava.util.TreeSet;
importjava.util.Iterator;
public class Exercise14 {
public static void main(String[] args) {
// creating TreeSet
TreeSet<Integer>tree_num= new TreeSet<Integer>();
TreeSet<Integer>treeheadset= new TreeSet<Integer>();
// Add numbers in the tree
tree_num.add(10);
tree_num.add(22);
tree_num.add(36);
tree_num.add(25);
tree_num.add(16);
tree_num.add(70);
tree_num.add(82);
tree_num.add(89);
tree_num.add(14);
System.out.println("Original tree set: "+tree_num);
System.out.println("Removes the first(lowest) element:
"+tree_num.pollFirst());
System.out.println("Tree set after removing first element: "+tree_num);
}
}
OUTPUT:
Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89]
Removes the first(lowest) element: 10
Tree set after removing first element: [14, 16, 22, 25, 36, 70, 82, 89]
PROGRAM 96
Write a Java program to retrieve and remove the last element of a tree
set.
SOLUTION:
importjava.util.TreeSet;
importjava.util.Iterator;
public class Exercise15 {
public static void main(String[] args) {
// creating TreeSet
TreeSet<Integer>tree_num= new TreeSet<Integer>();
TreeSet<Integer>treeheadset= new TreeSet<Integer>();
// Add numbers in the tree
tree_num.add(10);
tree_num.add(22);
tree_num.add(36);
tree_num.add(25);
tree_num.add(16);
tree_num.add(70);
tree_num.add(82);
tree_num.add(89);
tree_num.add(14);
System.out.println("Original tree set: "+tree_num);
System.out.println("Removes the last element: "+tree_num.pollLast());
System.out.println("Tree set after removing last element: "+tree_num);
}
}
OUTPUT:
Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89]
Removes the last element: 89
Tree set after removing last element: [10, 14, 16, 22, 25, 36, 70, 82]
PROGRAM 97
Write a Java program to remove a given element from a tree set.
SOLUTION:
importjava.util.TreeSet;
importjava.util.Iterator;
public class Exercise16 {
public static void main(String[] args) {
// creating TreeSet
TreeSet<Integer>tree_num= new TreeSet<Integer>();
TreeSet<Integer>treeheadset= new TreeSet<Integer>();
// Add numbers in the tree
tree_num.add(10);
tree_num.add(22);
tree_num.add(36);
tree_num.add(25);
tree_num.add(16);
tree_num.add(70);
tree_num.add(82);
tree_num.add(89);
tree_num.add(14);
System.out.println("Original tree set: "+tree_num);
System.out.println("Removes 70 from the list:
"+tree_num.remove(70));
System.out.println("Tree set after removing last
element: "+tree_num);
}
}
OUTPUT:
Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89]
Removes 70 from the list: true
Tree set after removing last element: [10, 14, 16, 22, 25, 36,82, 89]
PROGRAM 98
Write a Java program to change priorityQueue to maximum
priorityqueue.
SOLUTION:
importjava.util.*;
public class Example12 {
public static void main(String[] args) {
PriorityQueue<Integer> pq1 = new PriorityQueue<>(10,
Collections.reverseOrder());
// Add numbers in the Queue
pq1.add(10);
pq1.add(22);
pq1.add(36);
pq1.add(25);
pq1.add(16);
pq1.add(70);
pq1.add(82);
pq1.add(89);
pq1.add(14);
System.out.println("nOriginal Priority Queue: "+pq1);
System.out.print("nMaximum Priority Queue: ");
Integer val= null;
while( (val= pq1.poll()) != null) {
System.out.print(val+" ");
}
System.out.print("n");
}
}
OUTPUT:
Original Priority Queue: [89, 82, 70, 25, 16, 22, 36, 10, 14]
Maximum Priority Queue: 89 82 70 36 25 22 16 14 10
PROGRAM 99
Write a Java program to convert a Priority Queue elements to a string
representation.
SOLUTION:
importjava.util.*;
public class Example11 {
public static void main(String[] args) {
// Create Priority Queue
PriorityQueue<String> pq1 = new PriorityQueue<String>();
// use add() method to add values in the Priority Queue
pq1.add("Red");
pq1.add("Green");
pq1.add("Black");
pq1.add("White");
System.out.println("Original Priority Queue: "+pq1);
//Convert Priority Queue to a string representation
String str1;
str1 =pq1.toString();
System.out.println("String representation of the Priority Queue:
"+str1);
}
}
OUTPUT:
Original Priority Queue: [Black, Red, Green, White]
String representation of the Priority Queue: [Black, Red,
Green, White]
PROGRAM 100
Write a Java program to convert a priority queue to an array containing
all of the elements of the queue.
SOLUTION:
importjava.util.*;
public class Example10 {
public static void main(String[] args) {
// Create Priority Queue
PriorityQueue<String> pq1 = new PriorityQueue<String>();
// use add() method to add values in the Priority Queue
pq1.add("Red");
pq1.add("Green");
pq1.add("Black");
pq1.add("White");
System.out.println("Original Priority Queue: "+pq1);
//Convert a linked list to array list
List<String>array_list= new ArrayList<String>(pq1);
System.out.println("Array containing all of the elements in the
queue: "+array_list);
}
}
OUTPUT:
Original Priority Queue: [Black, Red, Green, White]
Array containing all of the elements in the queue: [Black, Red,
Green, White]

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Method overloading
Method overloadingMethod overloading
Method overloading
 
2- Dimensional Arrays
2- Dimensional Arrays2- Dimensional Arrays
2- Dimensional Arrays
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Polymorphism in Java
Polymorphism in JavaPolymorphism in Java
Polymorphism in Java
 
Basic Java Programming
Basic Java ProgrammingBasic Java Programming
Basic Java Programming
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 
Applet and graphics programming
Applet and graphics programmingApplet and graphics programming
Applet and graphics programming
 
Array in Java
Array in JavaArray in Java
Array in Java
 
HTML5 - Insert images and Apply page backgrounds
HTML5 - Insert images and Apply page backgroundsHTML5 - Insert images and Apply page backgrounds
HTML5 - Insert images and Apply page backgrounds
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Java arrays
Java arraysJava arrays
Java arrays
 
Strings IN C
Strings IN CStrings IN C
Strings IN C
 
C notes for exam preparation
C notes for exam preparationC notes for exam preparation
C notes for exam preparation
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
C vs c++
C vs c++C vs c++
C vs c++
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
C program to check leap year
C program to check leap year C program to check leap year
C program to check leap year
 
Java practical
Java practicalJava practical
Java practical
 

Ähnlich wie Computer java programs

Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
eyewatchsystems
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
MaruMengesha
 
Write the program in MIPS that declares an array of positive integer.pdf
Write the program in MIPS that declares an array of positive integer.pdfWrite the program in MIPS that declares an array of positive integer.pdf
Write the program in MIPS that declares an array of positive integer.pdf
arihanthtoysandgifts
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
anupamfootwear
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdf
optokunal1
 

Ähnlich wie Computer java programs (20)

Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdfJava AssignmentWrite a program using sortingsorting bubble,sele.pdf
Java AssignmentWrite a program using sortingsorting bubble,sele.pdf
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_15-Feb-2021_L6-...
 
Oot practical
Oot practicalOot practical
Oot practical
 
Presentation1 computer shaan
Presentation1 computer shaanPresentation1 computer shaan
Presentation1 computer shaan
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
Write the program in MIPS that declares an array of positive integer.pdf
Write the program in MIPS that declares an array of positive integer.pdfWrite the program in MIPS that declares an array of positive integer.pdf
Write the program in MIPS that declares an array of positive integer.pdf
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Anjalisoorej imca133 assignment
Anjalisoorej imca133 assignmentAnjalisoorej imca133 assignment
Anjalisoorej imca133 assignment
 
Code javascript
Code javascriptCode javascript
Code javascript
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
6_Array.pptx
6_Array.pptx6_Array.pptx
6_Array.pptx
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 
Java -lec-5
Java -lec-5Java -lec-5
Java -lec-5
 
import java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdfimport java.util.;public class Program{public static void.pdf
import java.util.;public class Program{public static void.pdf
 
Java arrays
Java    arraysJava    arrays
Java arrays
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Array,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN CArray,MULTI ARRAY, IN C
Array,MULTI ARRAY, IN C
 
Programming in Java: Arrays
Programming in Java: ArraysProgramming in Java: Arrays
Programming in Java: Arrays
 

Kürzlich hochgeladen

obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...
obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...
obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...
yulianti213969
 
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai KuwaitThe Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
daisycvs
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
allensay1
 

Kürzlich hochgeladen (20)

PHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation FinalPHX May 2024 Corporate Presentation Final
PHX May 2024 Corporate Presentation Final
 
PARK STREET 💋 Call Girl 9827461493 Call Girls in Escort service book now
PARK STREET 💋 Call Girl 9827461493 Call Girls in  Escort service book nowPARK STREET 💋 Call Girl 9827461493 Call Girls in  Escort service book now
PARK STREET 💋 Call Girl 9827461493 Call Girls in Escort service book now
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAIGetting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
Getting Real with AI - Columbus DAW - May 2024 - Nick Woo from AlignAI
 
obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...
obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...
obat aborsi bandung wa 081336238223 jual obat aborsi cytotec asli di bandung9...
 
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai KuwaitThe Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
The Abortion pills for sale in Qatar@Doha [+27737758557] []Deira Dubai Kuwait
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165Lucknow Housewife Escorts  by Sexy Bhabhi Service 8250092165
Lucknow Housewife Escorts by Sexy Bhabhi Service 8250092165
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
Pre Engineered Building Manufacturers Hyderabad.pptx
Pre Engineered  Building Manufacturers Hyderabad.pptxPre Engineered  Building Manufacturers Hyderabad.pptx
Pre Engineered Building Manufacturers Hyderabad.pptx
 
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGBerhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Berhampur 70918*19311 CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTSJAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR  ESCORTS
JAJPUR CALL GIRL ❤ 82729*64427❤ CALL GIRLS IN JAJPUR ESCORTS
 
Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...
Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...
Ooty Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Avail...
 
Nanded Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Nanded Call Girl Just Call 8084732287 Top Class Call Girl Service AvailableNanded Call Girl Just Call 8084732287 Top Class Call Girl Service Available
Nanded Call Girl Just Call 8084732287 Top Class Call Girl Service Available
 
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
Chennai Call Gril 80022//12248 Only For Sex And High Profile Best Gril Sex Av...
 
Puri CALL GIRL ❤️8084732287❤️ CALL GIRLS IN ESCORT SERVICE WE ARW PROVIDING
Puri CALL GIRL ❤️8084732287❤️ CALL GIRLS IN ESCORT SERVICE WE ARW PROVIDINGPuri CALL GIRL ❤️8084732287❤️ CALL GIRLS IN ESCORT SERVICE WE ARW PROVIDING
Puri CALL GIRL ❤️8084732287❤️ CALL GIRLS IN ESCORT SERVICE WE ARW PROVIDING
 
Falcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business Potential
 
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDINGParadip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
Paradip CALL GIRL❤7091819311❤CALL GIRLS IN ESCORT SERVICE WE ARE PROVIDING
 
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
 
KALYANI 💋 Call Girl 9827461493 Call Girls in Escort service book now
KALYANI 💋 Call Girl 9827461493 Call Girls in  Escort service book nowKALYANI 💋 Call Girl 9827461493 Call Girls in  Escort service book now
KALYANI 💋 Call Girl 9827461493 Call Girls in Escort service book now
 

Computer java programs

  • 1. PROGRAM 51 Write a program in Java to display the pattern like right angle triangle with a number. SOLUTION: importjava.util.Scanner; public class Pattern3{ public static void main(String[] args) { inti,j,n; System.out.print("Input number of rows : "); Scanner in = new Scanner(System.in); n =in.nextInt(); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) System.out.print(j); System.out.println(""); }}} OUTPUT: Input number of rows : 10 1 12 123 1234 12345 123456 1234567 12345678 123456789 12345678910
  • 2. PROGRAM 52 Write a program in Java to make such a pattern like a pyramid with a number which will repeat the number in the same row. SOLUTION: importjava.util.Scanner; public class Pattern4{ public static void main(String[] args) { inti,j,n,s,x; System.out.print ("Input number of rows : "); Scanner in = new Scanner(System.in); n =in.nextInt(); s=n+4-1; for(i=1;i<=n;i++) { for(x=s;x!=0;x--) { System.out.print(" "); } for(j=1;j<=i;j++){ System.out.print(i+" "); } System.out.println(); s--; }}} OUTPUT: Input Number of Rows : 4 1 2 2 3 3 3 4 4 4 4
  • 3. PROGRAM 53 Write a Java program to display Pascal's triangle. SOLUTION: importjava.util.Scanner; public class Pattern5 { public static void main(String[] args) { intno_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
  • 4. PROGRAM 54 Write a Java program that reads an integer and check whether it is negative, zero, or positive. SOLUTION: importjava.util.Scanner; public class POSITIVE{ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input a number: "); int n =in.nextInt(); if (n > 0) { System.out.println("Number is positive"); } else if (n < 0) { System.out.println("Number is negative"); } else { System.out.println("Number is zero"); } } } OUTPUT: Input a number: 7 Number is positive
  • 5. PROGRAM 55 Write a program that accepts three numbers from the user and prints "increasing" if the numbers are in increasing order, "decreasing" if the numbers are in decreasing order, and "Neither increasing or decreasing order" otherwise. SOLUTION: importjava.util.Scanner; public class Number { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Input first number: "); double x =in.nextDouble(); System.out.print("Input second number: "); double y =in.nextDouble(); System.out.print("Input third number: "); double z =in.nextDouble(); if (x < y && y < z){ System.out.println("Increasing order"); } else if (x > y && y > z) { System.out.println("Decreasing order"); } else{ System.out.println("Neither increasing or decreasing order"); }}} OUTPUT: Input first number: 1524 Input second number: 2345 Input third number: 3321 Increasing order
  • 6. PROGRAM 56 Write a Java program to sort a numeric array and a string array. SOLUTION: importjava.util.Arrays; public class Array1 { public static void main(String[] args){ int[] my_array1 = {1789, 2035, 1899, 1456, 2013,1458, 2458,1254,1472, 2365,1456, 2165, 1457, 2456}; String[]my_array2={"Java","Python","PHP","C#","CProgramming", "C++"} System.out.println("Original numeric array :"+Arrays.toString(my_array1)); Arrays.sort(my_array1); System.out.println("Sorted numeric array : "+Arrays.toString(my_array1)); System.out.println("Original string array : "+Arrays.toString(my_array2)); Arrays.sort(my_array2); System.out.println("Sorted string array : "+Arrays.toString(my_array2)); } } OUTPUT: Original numeric array : [1789, 2035, 1899, 1456, 2013, 1458, 2458, 1254, 1472, 2365, 1456, 2165, 1457, 2456] Sorted numeric array : [1254, 1456, 1456, 1457, 1458, 1472, 1789, 1899, 2013, 2035, 2165, 2365, 2456, 2458] Original string array : [Java, Python, PHP, C#, C Programming, C++] Sorted string array :[C Programming, C#, C++, Java, PHP, Python]
  • 7. PROGRAM 57 Write a Java program to calculate the average value of array elements. SOLUTION: publicclassArray2 { publicstaticvoidmain(String[]args) { int[] numbers =newint[]{20,30,25,35,-16,60,-100}; //calculate sum of all array elements int sum =0; for(inti=0;i<numbers.length;i++) { sum= sum + numbers[i]; //calculate average value double average = sum /numbers.length; System.out.println("Average value of the array elements is : "+ average); } } } OUTPUT: Average value of the array elements is : 7.0
  • 8. PROGRAM 58 Write a Java program to insert an element (specific position) into an array. SOLUTION: importjava.util.Arrays; public class Array3 { 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) intIndex_position= 2; intnewValue= 5; System.out.println("Original Array : "+Arrays.toString(my_array)); for(inti=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]
  • 9. PROGRAM 59 Write a Java program to replace every element with the next greatest element (from right side) in an given array of integers. Solution: import java.io.*; importjava.util.Arrays; classArray4 { public static void main (String[] args) { intnums[] = {45, 20, 100, 23, -5, 2, -6}; int result[]; System.out.println("Original Array "); System.out.println(Arrays.toString(nums)); result = next_greatest_num(nums); System.out.println("The modified array:"); System.out.println(Arrays.toString(result)); } staticint [] next_greatest_num(intarr_nums[]) { int size = arr_nums.length; intmax_from_right_num = arr_nums[size-1]; arr_nums[size-1] = -1; for (inti = size-2; i>= 0; i--) { int temp = arr_nums[i]; arr_nums[i] = max_from_right_num; if(max_from_right_num< temp) max_from_right_num = temp; } returnarr_nums; } } OUTPUT: Original Array [45, 20, 100, 23, -5, 2, -6] The modified array:[100, 100, 23, 2, 2, -6, -1]
  • 10. PROGRAM 60 Write a Java program to separate even and odd numbers of an given array of integers. Put all even numbers first, and then odd numbers. Solution: importjava.util.Arrays; class Array5{ public static void main (String[] args){ intnums[] = {20, 12, 23, 17, 7, 8, 10, 2, 1, 0}; int result[]; System.out.println("Original Array "); System.out.println(Arrays.toString(nums)); result=separate_odd_even(nums); System.out.print("Array after separation "); System.out.println(Arrays.toString(result));} staticint [] separate_odd_even(intarr[]){ intleft_side= 0, right_side=arr.length- 1; while (left_side<right_side){ while (arr[left_side]%2 == 0 &&left_side<right_side) left_side++; while (arr[right_side]%2 == 1 &&left_side<right_side) right_side--; if (left_side<right_side){ int temp =arr[left_side]; arr[left_side] =arr[right_side]; arr[right_side] = temp; left_side++; right_side--;}} returnarr;}} OUTPUT: Original Array [45, 20, 100, 23, -5, 2, -6] The modified array:[100, 100, 23, 2, 2, -6, -1]
  • 11. PROGRAM 61 Write a Java program to separate 0s on left side and 1s on right side of an array of 0s and 1s in random order. Solution: importjava.util.Arrays; classArray6 { public static void main(String[] args) { intarr[] = new int[]={ 0, 0, 1, 1, 0, 1, 1, 1,0 }; int result[]; System.out.println("Original Array "); System.out.println(Arrays.toString(arr)); int n = arr.length; result = separate_0_1(arr, n); System.out.println("New Array "); System.out.println(Arrays.toString(result)); } staticint [] separate_0_1(intarr[], int n) { int count = 0; for (inti = 0; i< n; i++) if (arr[i] == 0) count++;} for (inti = 0; i< count; i++) arr[i] = 0; for (inti = count; i< n; i++) arr[i] = 1; returnarr; }} OUTPUT: Original Array [0, 0, 1, 1, 0, 1, 1, 1, 0] New Array [0, 0, 0, 0, 1, 1, 1, 1, 1]
  • 12. PROGRAM 62 Write a Java program to find the rotation count in a given rotated sorted array of integers. Solution: importjava.util.*; importjava.lang.*; import java.io.*; public class Array7 { staticintcount_rotations(intarr_int[], int n) { intmin_val=arr_int[0], min_index=-1; for (inti= 0; i< n; i++) { if (min_val>arr_int[i]) { min_val=arr_int[i]; min_index=i; } } returnmin_index; } public static void main (String[] args) { intarr_int[] = {35, 32, 30, 14, 18, 21, 27}; // intarr_int[] = {35, 32, 14, 18, 21, 27}; // intarr_int[] = {35, 14, 18, 21, 27}; int n =arr_int.length; System.out.println(count_rotations(arr_int, n)); }} OUTPUT: Number of Rotations = 3
  • 13. PROGRAM 63 Write a Java program to find all pairs of elements in an array whose sum is equal to a specified number Solution: public class Array8 { static void pairs_value(intinputArray[], intinputNumber) { System.out.println("Pairs of elements and their sum : "); for (inti= 0; i<inputArray.length; i++) { for (int j = i+1; j <inputArray.length; j++) { if(inputArray[i]+inputArray[j] ==inputNumber) { System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber); } }}} public static void main(String[] args) { pairs_value(new int[] {2, 7, 4, -5, 11, 5, 20}, 15); pairs_value(new int[] {14, -15, 9, 16, 25, 45, 12, 8}, 30); } } OUTPUT: Enter the Number = 15 Pairs of elements and their sum :4 + 11 = 15 -5 + 20 = 15
  • 14. PROGRAM 64 Write a Java program to add two matrices of the same size Solution: importjava.util.Scanner; public class Array9 { public static void main(String args[]) { int m, n, c, d; Scanner in = new Scanner(System.in); System.out.println("Input number of rows of matrix"); m =in.nextInt(); System.out.println("Input number of columns of matrix"); n =in.nextInt(); int array1[][] = new int[m][n]; int array2[][] = new int[m][n]; int sum[][] = new int[m][n]; System.out.println("Input elements of first matrix"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { array1[c][d] =in.nextInt(); System.out.println("Input the elements of second matrix"); }} for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) array2[c][d] =in.nextInt(); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) sum[c][d] = array1[c][d] + array2[c][d]; System.out.println("Sum of the matrices:-");
  • 15. for ( c = 0 ; c < m ; c++ ){ for ( d = 0 ; d < n ; d++ ) System.out.print(sum[c][d]+"t"); System.out.println(); } }} OUTPUT: Input number of rows of matrix 2 Input number of columns of matrix 2 Input elements of first matrix 1 2 34 Input the elements of second matrix 5 6 7 8 Sum of the matrices:- 6 8 10 12
  • 16. PROGRAM 65 Write a Java program to check if an array of integers without 0 and -1. Solution: importjava.util.*; import java.io.*; public class Array10 { public static void main(String[] args) { int[] array_nums= {50, 77, 12, 54, -11}; System.out.println("Original Array: "+Arrays.toString(array_nums)); System.out.println("Result: "+test(array_nums)); } public static boolean test(int[] numbers) { for (int number : numbers) { if (number == 0 || number ==-1) { return false; } } return true; } } OUTPUT: Original Array: [50, 77, 12, 54, -11] Result: true
  • 17. PROGRAM 66 Write a Java program to check if the sum of all the 10's in the array is exactly 30. Return false if the condition does not satisfy, otherwise true. Solution: importjava.util.*; import java.io.*; public class Array11 { public static void main(String[] args) { int[] array_nums= {10, 77, 10, 54, -11, 10}; System.out.println("Original Array: "+Arrays.toString(array_nums)); intsearch_num= 10; intfixed_sum= 30; System.out.println("Result: "+result(array_nums, search_num, fixed_sum)); } public static boolean result(int[] numbers, intsearch_num, intfixed_sum) { inttemp_sum= 0; for (int number : numbers) { if (number ==search_num) { temp_sum+=search_num; } if (temp_sum>fixed_sum) { break; } } returntemp_sum==fixed_sum; }} OUTPUT: Original Array: [10, 77, 10, 54, -11, 10] Result: true
  • 18. PROGRAM 67 Write a Java program to check if an array of integers contains two specified elements 65 and 77. Solution: importjava.util.*; import java.io.*; public class Array12 { public static void main(String[] args) { int[] array_nums= {77, 77, 65, 65, 65, 77}; System.out.println("Original Array: "+Arrays.toString(array_nums)); int num1 = 77; int num2 = 65; System.out.println("Result: "+result(array_nums, num1, num2)); } public static boolean result(int[] array_nums, int num1, int num2) { for (int number :array_nums) { boolean r = number != num1 && number != num2; if (r) { return false; } } return true; } } OUTPUT: Original Array: [77, 77, 65, 65, 65, 77] Result: true
  • 19. PROGRAM 68 Write a Java program to get the character at the given index within the String. SOLUTION: public class String1 { public static void main(String[] args) { String str= "Java Exercises!"; System.out.println("Original String = " +str); // Get the character at positions 0 and 10. int index1 =str.charAt(0); int index2 =str.charAt(10); // Print out the results. System.out.println("The character at position 0 is " + (char)index1); System.out.println("The character at position 10 is " + (char)index2); } } OUTPUT: Original String = Java Exercises! The character at position 0 is J The character at position 10 is i
  • 20. PROGRAM 69 Write a Java program to trim any leading or trailing whitespace from a given string. Solution: publicclassString2{ publicstaticvoidmain(String[]args) { String str=" Java Exercises "; // Trim the whitespace from the front and back of the // String. String new_str=str.trim(); // Display the strings for comparison. System.out.println("Original String: "+str); System.out.println("New String: "+new_str); } } OUTPUT: Original String: Java Exercises New String: Java Exercises
  • 21. PROGRAM 70 Write a program in java To find minimum value using overloading. Solution: public class ExampleOverloading{ public static void main(String[] args){ int a = 11; int b = 6; double c = 7.3; double d = 9.4; int result1 = minFunction(a, b); double result2 = minFunction(c, d); System.out.println("Minimum Value = " + result1); System.out.println("Minimum Value = " + result2);} public static intminFunction(int n1, int n2) { intmin;if (n1 > n2)min = n2; elsem in = n1; return min; } public static double minFunction(double n1, double n2) { double min; if (n1 > n2) min = n2; elsemin = n1; return min; } } OUTPUT: Minimum Value = 6 Minimum Value = 7.3
  • 22. PROGRAM 71 Write a program in Java to show the use of this keyword. Solution: public class This_Example { intnum = 10; This_Example() { System.out.println("This is an example program on keyword this"); } This_Example(intnum) { this(); this.num = num; } public void greet() { System.out.println("Hi Welcome to Tutorialspoint"); } public void print() { intnum = 20; System.out.println("value of local variable num is : "+num); System.out.println("value of instance variable num is : "+this.num); this.greet(); } public static void main(String[] args) { This_Example obj1 = new This_Example(); obj1.print(); This_Exampleobj2 = new This_Example(30); obj2.print(); }} OUTPUT: This is an example program on keyword this value of local variable numis : 20 value of instance variable num is : 10
  • 23. PROGRAM 72 Write a program in java to demonstrate InputStream and OutputStream. SOLUTION: import java.io.*; public class fileStreamTest { public static void main(String args[]) { try { bytebWrite [] = {11,21,3,40,5}; OutputStreamos = new FileOutputStream("test.txt"); for(int x = 0; x <bWrite.length ; x++) { os.write(bWrite[x] ); } os.close(); InputStream is = new FileInputStream("test.txt"); int size = is.available(); for(inti = 0; i< size; i++) { System.out.print((char)is.read() + " "); } is.close(); } catch (IOException e) { System.out.print("Exception"); }}} OUTPUT: The above code would create file test.txt and would write given numbers in binary format. Same would be the output on the stdout screen.
  • 24. PROGRAM 73 Write a program in java to create "/tmp/user/java/bin" directory. SOLUTION: importjava.io.File; public class CreateDir { public static void main(String args[]) { String dirname ="/tmp/user/java/bin"; File d = new File(dirname); // Create directory now. d.mkdirs(); } } OUTPUT: Compile and execute the above code to create "/tmp/user/java/bin".
  • 25. PROGRAM 74 Write a program in java to list down all the files and directories available in a directory. SOLUTION: importjava.io.File; public class ReadDir { public static void main(String[] args) { File file = null; String[] paths; try { // create new file object file = new File("/tmp"); // array of files and directory paths = file.list(); // for each name in the path array for(String path:paths) { // prints filename and directory name System.out.println(path); }} catch (Exception e) { // if any error occurs e.printStackTrace(); } }} OUTPUT: test1.txt test2.txt ReadDir.java ReadDir.class
  • 26. PROGRAM 75 Write a program in java to throw Exceptions occurred by Index of an array public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " + a[0]); System.out.println("The finally statement is executed"); } } } OUTPUT: Exception thrown:java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
  • 27. PROGRAM 76 Write a program in Java to print the multiplication of two matrices. public class MatrixMultiplicationExample { public static void main(String args[]) { int a[][]={{1,1,1},{2,2,2},{3,3,3}}; int b[][]={{1,1,1},{2,2,2},{3,3,3}}; //creating another matrix to store the multiplication of two matrices int c[][]=new int[3][3]; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { c[i][j]=0; for(int k=0;k<3;k++) { c[i][j]+=a[i][k]*b[k][j]; } System.out.print(c[i][j]+" "); } System.out.println();//new line }}} OUTPUT: First matrix: Second matrix: 1 1 1 1 1 1 2 2 2 2 2 2 3 3 3 3 3 3 Multiplied Matrix: 6 6 6 12 12 12 18 18 18
  • 28. PROGRAM 77 Write a Java program to find the longest word in a text file SOLUTION: importjava.util.Scanner; import java.io.*; public class Exercise18 { public static void main(String [ ] args) throws FileNotFoundException { new Exercise18().findLongestWords(); } public String findLongestWords() throws FileNotFoundException { String longest_word= ""; String current; Scanner sc= new Scanner(new File("/home/students/test.txt")); while (sc.hasNext()) { current=sc.next(); if (current.length() >longest_word.length()) { longest_word= current; } } System.out.println("n"+longest_word+"n"); returnlongest_word; } } OUTPUT: general-purpose,
  • 29. PROGRAM 78 Write a Java program to write and read a plain text file. SOLUTION: import java.io.*; public class Eexercise15 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; try { String filename= "/home/students/myfile.txt"; FileWriterfw= new FileWriter(filename,false); fw.write("Python Exercisesn"); fw.close(); BufferedReaderbr= new BufferedReader(new FileReader("/home/students/myfile.txt")); while (strLine!= null) { sb.append(strLine); sb.append(System.lineSeparator()); strLine=br.readLine(); System.out.println(strLine); } br.close(); } catch(IOExceptionioe) { System.err.println("IOException: " +ioe.getMessage()); }}} OUTPUT: Python Exercises Null
  • 30. PROGRAM 79 Write a Java program to append text to an existing file. SOLUTION: importjava.io.FileWriter; public class Exercise16 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; try{ String filename= "/home/students/myfile.txt"; FileWriterfw= new FileWriter(filename,true); fw.write("Java Exercisesn"); fw.close(); BufferedReaderbr= 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(IOExceptionioe){ System.err.println("IOException: " +ioe.getMessage()); }}} OUTPUT: Python Exercises Java Exercises null
  • 31. PROGRAM 80 Write a Java program to read first 3 lines from a file. SOLUTION: importjava.io.FileInputStream; public class Exercise17 { public static void main(String a[]){ BufferedReaderbr= null; String strLine= ""; try { LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream("/home/students/test.txt"), "UTF-8")); while (((strLine=reader.readLine()) != null) &&reader.getLineNumber() <= 3){ System.out.println(strLine); } reader.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Unable to read the file."); } }} OUTPUT: Welcome to w3resource.com. Append this text.Append this text.Append this text. Append this text.
  • 32. PROGRAM 81 Write a program to show the Dynamic Method Dispatch using inheritance. SOLUTION: class parent1{ void sum(inti, int j){ System.out.println(“Parent class” + (i+j)); }} class child1 extends parent1{ void sum(inti, int j){ System.out.println(“Child class” + (i+j));}} classdynamic_test{ public static void main(String args[]){ parent1 p1=new parent1(); child1 c1=new child1(); parent1Refi; Refi=p1; Refi.sum(10,20); Refi=c1; Refi.sum(20,30); }} Output: Parent class 30 Child class 50
  • 33. PROGRAM: 82 Write a program to accept 10 different word in array and pass the array to function. Search the word enter by the user is present or not. SOLUTION: import java.io.*; class Searching{ int search(String name[],String ns){ inti,p=0; for(j=0;j<10;j++){ if(name[j].equals(ns)) p=1;} return p;} public static void main()throws IOException{ inti,k=0; String name[]=new String[10];String ns; BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); Searching ob=new Searching(); System.out.println(“Enter 10 names”); for(i=0;i<10;i++){ name[i]=br.readLine();} System.out.println(“Enter the name to be searched:”); ns=in.readLine(); k=ob.search(name,ns); if(k==1) System.out.println(“Search successful”); else System.out.println(“NO such name is present”); }} OUTPUT: Enters 10 names aman, jyoti, deepa, pawan, mayank, arif, abhishek, vishal, lavi, ravi Enter the name to be searched: arjun No such name is present
  • 34. PROGRAM: 83 Write a program in java to accept two numbers and find their sum using function by creating the object of class. SOLUTION: import java.io.*; public class Addition{ int sum(inta,int b){ int c; c=a+b; return c; } public static void main()throws IOException{ intm,n,k; BufferedReaderbr=new BufferedReader(new InputStreamReader(System.in)); Addition ob=new Addition(); System.out.println(“Enter two numbers”); m=Integer.parseInt(br.readLine()); n=Integer.parseInt(br.readLine()); k=ob.sum(m,n); System.out.println(“The sum of two numbers:” + k); } } OUTPUT: Enter two numbers 3 4 The sum of two numbers: 7
  • 35. PROGRAM: 84 Write a program to find all combination of four elements of an given array whose sum is equal to a given value. SOLUTION: importjava.util.*; importjava.lang.*; class Main { public static void main(String args[]) { intnum[]={10, 20, 30, 40, 1, 2}; int n=num.length; int s=53; System.out.println(“The given:” + s); System.out.println(“The combination of four elements:”); for(inti=0;i<n-3;i++){ for(int j=i+1;j<n-2;j++){ for(int k=j+1;k<n-1;k++){ for(int l=k+1;l<n;l++) { if(num[i]+num[j]+num[k]+num[l]==s) System.out.print(num[i]+ “ “ + num[j]+ “ “ + num[k]+ “ “+ num[l]); }}}} }} OUTPUT: Given value: 53 Combination of four elements: 10 40 1 2 20 30 1 2
  • 36. PROGRAM 85 Write a Java program to store text file content line by line into an array. SOLUTION: importjava.util.Arrays; public class Exercise14 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; List<String> list = new ArrayList<String>(); try { BufferedReaderbr= new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine!= null) { strLine=br.readLine(); sb.append(strLine); sb.append(System.lineSeparator()); strLine=br.readLine(); if (strLine==null) break; list.add(strLine);} System.out.println(Arrays.toString(list.toArray())); br.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Unable to read the file."); }}} OUTPUT: [Append this text.Append this text.Append this text., Append this text., Append this text.]
  • 37. PROGRAM 86 Write a java program to read a file line by line and store it into a variable. SOLUTION: importjava.io.FileReader; public class exercise13 { public static void main(String a[]){ StringBuildersb= new StringBuilder(); String strLine= ""; String str_data= ""; try { BufferedReaderbr= new BufferedReader(new FileReader("/home/students/test.txt")); while (strLine!= null) { if (strLine== null) break; str_data+=strLine; strLine=br.readLine(); } System.out.println(str_data); br.close(); } catch (FileNotFoundException e) { System.err.println("File not found"); } catch (IOException e) { System.err.println("Unable to read the file."); }}} OUTPUT: Welcome to w3resource.com.Append this text.Appendthistext.Append this text.Append this text.Append this text.Append this text.Append this text.
  • 38. PROGRAM 87 Write a Java program to print all the LEADERS in the array. Note: An element is leader if it is greater than all the elements to its right side. SOLUTION: importjava.util.Arrays; class Main { public static void main(String[] args) { intarr[] = {10, 9, 14, 23, 15, 0, 9}; int size = arr.length; for (inti = 0; i< size; i++) { int j; for (j = i + 1; j < size; j++) { if (arr[i] <= arr[j]) break; } if (j == size) System.out.print(arr[i] + " "); } } } OUTPUT: 23 15 9
  • 39. PROGRAM 88 Write a Java program to find the sum of the two elements of a given array which is equal to a given integer. SOLUTION: importjava.util.*; public class Exercise35{ public static ArrayList<Integer>two_sum_array_target(final List<Integer> a, int b) { HashMap<Integer, Integer>my_map= new HashMap<Integer, Integer>(); ArrayList<Integer> result = new ArrayList<Integer>(); result.add(0); result.add(0); for(inti= 0; i<a.size(); i++){ if(my_map.containsKey(a.get(i))){ int index =my_map.get(a.get(i)); result.set(0, index + 1); result.set(1, i+ 1); break;} else{ my_map.put(b -a.get(i), i); }} return result; } public static void main(String[] args){ ArrayList<Integer>my_array= new ArrayList<Integer>(); my_array.add(1); my_array.add(2);my_array.add(4);my_array.add(5);my_array.add(6); int target = 6; ArrayList<Integer> result =two_sum_array_target(my_array, target); for(inti: result) System.out.print("Index: "+i+ " ");}} OUTPUT: Index 1 Index ⁴
  • 40. PROGRAM 90 Write a Java program to join two linked lists. Solution: importjava.util.*; public class Exercise17 { public static void main(String[] args) { // create an empty linked list LinkedList<String> c1 = new LinkedList<String> (); c1.add("Red"); c1.add("Green"); c1.add("Black"); c1.add("White"); c1.add("Pink"); System.out.println("List of first linked list: " + c1); LinkedList<String> c2 = new LinkedList<String> (); c2.add("Red"); c2.add("Green"); c2.add("Black"); c2.add("Pink"); System.out.println("List of second linked list: " + c2); LinkedList<String> a = new LinkedList<String> (); a.addAll(c1); a.addAll(c2); System.out.println("New linked list: " + a); }} OUTPUT: List of first linked list: [Red, Green, Black, White, Pink] List of second linked list: [Red, Green, Black, Pink] New linked list: [Red, Green, Black, White,Pink,Red,Green,Black, Pink]
  • 41. PROGRAM 91 Write a Java program to shuffle the elements in a linked list. SOLUTION: importjava.util.*; public class Exercise16 { public static void main(String[] args) { // create an empty linked list LinkedList<String>l_list= new LinkedList<String> (); // use add() method to add values in the linked list l_list.add("Red"); l_list.add("Green"); l_list.add("Black"); l_list.add("Pink"); l_list.add("orange"); // print the list System.out.println("Linked list before shuffling:n" +l_list); Collections.shuffle(l_list); System.out.println("Linked list after shuffling:n" +l_list); } } OUTPUT: Linked list before shuffling:[Red, Green, Black, Pink, orange] Linked list after shuffling: [orange, Pink, Red, Black, Green]
  • 42. PROGRAM 92 Write a Java program to remove and return the first element of a linked list. SOLUTION: importjava.util.*; public class Exercise19 { public static void main(String[] args) { // create an empty linked list LinkedList<String> c1 = new LinkedList<String> (); c1.add("Red"); c1.add("Green"); c1.add("Black"); c1.add("White"); c1.add("Pink"); System.out.println("Original linked list: " + c1); System.out.println("Removed element: "+c1.pop()); System.out.println("Linked list after pop operation: "+c1); } } OUTPUT: Original linked list: [Red, Green, Black, White, Pink] Removed element: Red Linked list after pop operation: [Green, Black, White, Pink]
  • 43. PROGRAM 93 Write a Java program to retrieve but does not remove, the first element of a linked list. SOLUTION: importjava.util.*; publicclassExercise20{ publicstaticvoidmain(String[]args){ // create an empty linked list LinkedList<String> c1 =newLinkedList<String>(); c1.add("Red"); c1.add("Green"); c1.add("Black"); c1.add("White"); c1.add("Pink"); System.out.println("Original linked list: "+ c1); // Retrieve but does not remove, the first element of a linked list String x =c1.peekFirst(); System.out.println("First element in the list: "+ x); System.out.println("Original linked list: "+ c1); } } OUTPUT: Original linked list: [Red, Green, Black, White, Pink] First element in the list: Red Original linked list: [Red, Green, Black, White, Pink]
  • 44. PROGRAM 94 Write a Java program to retrieve but does not remove, the last element of a linked list. SOLUTION: importjava.util.*; public class Exercise21 { public static void main(String[] args) { // create an empty linked list LinkedList<String> c1 = new LinkedList<String> (); c1.add("Red"); c1.add("Green"); c1.add("Black"); c1.add("White"); c1.add("Pink"); System.out.println("Original linked list: " + c1); // Retrieve but does not remove, the last element of a linked list String x =c1.peekLast(); System.out.println("Last element in the list: " + x); System.out.println("Original linked list: " + c1); } } OUTPUT: Original linked list: [Red, Green, Black, White, Pink] Last element in the list: Pink Original linked list: [Red, Green, Black, White, Pink]
  • 45. PROGRAM 95 Write a Java program to retrieve and remove the first element of a tree set. SOLUTION: importjava.util.TreeSet; importjava.util.Iterator; public class Exercise14 { public static void main(String[] args) { // creating TreeSet TreeSet<Integer>tree_num= new TreeSet<Integer>(); TreeSet<Integer>treeheadset= new TreeSet<Integer>(); // Add numbers in the tree tree_num.add(10); tree_num.add(22); tree_num.add(36); tree_num.add(25); tree_num.add(16); tree_num.add(70); tree_num.add(82); tree_num.add(89); tree_num.add(14); System.out.println("Original tree set: "+tree_num); System.out.println("Removes the first(lowest) element: "+tree_num.pollFirst()); System.out.println("Tree set after removing first element: "+tree_num); } } OUTPUT: Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89] Removes the first(lowest) element: 10 Tree set after removing first element: [14, 16, 22, 25, 36, 70, 82, 89]
  • 46. PROGRAM 96 Write a Java program to retrieve and remove the last element of a tree set. SOLUTION: importjava.util.TreeSet; importjava.util.Iterator; public class Exercise15 { public static void main(String[] args) { // creating TreeSet TreeSet<Integer>tree_num= new TreeSet<Integer>(); TreeSet<Integer>treeheadset= new TreeSet<Integer>(); // Add numbers in the tree tree_num.add(10); tree_num.add(22); tree_num.add(36); tree_num.add(25); tree_num.add(16); tree_num.add(70); tree_num.add(82); tree_num.add(89); tree_num.add(14); System.out.println("Original tree set: "+tree_num); System.out.println("Removes the last element: "+tree_num.pollLast()); System.out.println("Tree set after removing last element: "+tree_num); } } OUTPUT: Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89] Removes the last element: 89 Tree set after removing last element: [10, 14, 16, 22, 25, 36, 70, 82]
  • 47. PROGRAM 97 Write a Java program to remove a given element from a tree set. SOLUTION: importjava.util.TreeSet; importjava.util.Iterator; public class Exercise16 { public static void main(String[] args) { // creating TreeSet TreeSet<Integer>tree_num= new TreeSet<Integer>(); TreeSet<Integer>treeheadset= new TreeSet<Integer>(); // Add numbers in the tree tree_num.add(10); tree_num.add(22); tree_num.add(36); tree_num.add(25); tree_num.add(16); tree_num.add(70); tree_num.add(82); tree_num.add(89); tree_num.add(14); System.out.println("Original tree set: "+tree_num); System.out.println("Removes 70 from the list: "+tree_num.remove(70)); System.out.println("Tree set after removing last element: "+tree_num); } } OUTPUT: Original tree set: [10, 14, 16, 22, 25, 36, 70, 82, 89] Removes 70 from the list: true Tree set after removing last element: [10, 14, 16, 22, 25, 36,82, 89]
  • 48. PROGRAM 98 Write a Java program to change priorityQueue to maximum priorityqueue. SOLUTION: importjava.util.*; public class Example12 { public static void main(String[] args) { PriorityQueue<Integer> pq1 = new PriorityQueue<>(10, Collections.reverseOrder()); // Add numbers in the Queue pq1.add(10); pq1.add(22); pq1.add(36); pq1.add(25); pq1.add(16); pq1.add(70); pq1.add(82); pq1.add(89); pq1.add(14); System.out.println("nOriginal Priority Queue: "+pq1); System.out.print("nMaximum Priority Queue: "); Integer val= null; while( (val= pq1.poll()) != null) { System.out.print(val+" "); } System.out.print("n"); } } OUTPUT: Original Priority Queue: [89, 82, 70, 25, 16, 22, 36, 10, 14] Maximum Priority Queue: 89 82 70 36 25 22 16 14 10
  • 49. PROGRAM 99 Write a Java program to convert a Priority Queue elements to a string representation. SOLUTION: importjava.util.*; public class Example11 { public static void main(String[] args) { // Create Priority Queue PriorityQueue<String> pq1 = new PriorityQueue<String>(); // use add() method to add values in the Priority Queue pq1.add("Red"); pq1.add("Green"); pq1.add("Black"); pq1.add("White"); System.out.println("Original Priority Queue: "+pq1); //Convert Priority Queue to a string representation String str1; str1 =pq1.toString(); System.out.println("String representation of the Priority Queue: "+str1); } } OUTPUT: Original Priority Queue: [Black, Red, Green, White] String representation of the Priority Queue: [Black, Red, Green, White]
  • 50. PROGRAM 100 Write a Java program to convert a priority queue to an array containing all of the elements of the queue. SOLUTION: importjava.util.*; public class Example10 { public static void main(String[] args) { // Create Priority Queue PriorityQueue<String> pq1 = new PriorityQueue<String>(); // use add() method to add values in the Priority Queue pq1.add("Red"); pq1.add("Green"); pq1.add("Black"); pq1.add("White"); System.out.println("Original Priority Queue: "+pq1); //Convert a linked list to array list List<String>array_list= new ArrayList<String>(pq1); System.out.println("Array containing all of the elements in the queue: "+array_list); } } OUTPUT: Original Priority Queue: [Black, Red, Green, White] Array containing all of the elements in the queue: [Black, Red, Green, White]