Java Programs Complete
Java Programs Complete
1.import java.util.Scanner;
2.public class Add_Matrix
3.{
4. public static void main(String[] args)
5. {
6. int p, q, m, n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter number of rows
in first matrix:");
9. p = s.nextInt();
10. System.out.print("Enter number of
columns in first matrix:");
11. q = s.nextInt();
12. System.out.print("Enter number of
rows in second matrix:");
13. m = s.nextInt();
14. System.out.print("Enter number of
columns in second matrix:");
15. n = s.nextInt();
16. if (p == m && q == n)
17. {
18. int a[][] = new int[p][q];
19. int b[][] = new int[m][n];
20. int c[][] = new int[m][n];
21. System.out.println("Enter all
the elements of first matrix:");
22. for (int i = 0; i < p; i++)
23. {
24. for (int j = 0; j < q; j+
+)
25. {
26. a[i][j] = s.nextInt();
27. }
28. }
29. System.out.println("Enter all
the elements of second matrix:");
30. for (int i = 0; i < m; i++)
31. {
32. for (int j = 0; j < n; j+
+)
33. {
1
34. b[i][j] = s.nextInt();
35. }
36. }
37. System.out.println("First
Matrix:");
38. for (int i = 0; i < p; i++)
39. {
40. for (int j = 0; j < q; j+
+)
41. {
42. System.out.print(a[i]
[j]+" ");
43. }
44. System.out.println("");
45. }
46. System.out.println("Second
Matrix:");
47. for (int i = 0; i < m; i++)
48. {
49. for (int j = 0; j < n; j+
+)
50. {
51. System.out.print(b[i]
[j]+" ");
52. }
53. System.out.println("");
54. }
55. for (int i = 0; i < p; i++)
56. {
57. for (int j = 0; j < n; j+
+)
58. {
59. for (int k = 0; k < q;
k++)
60. {
61. c[i][j] = a[i][j]
+ b[i][j];
62. }
63. }
64. }
65. System.out.println("Matrix
after addition:");
2
66. for (int i = 0; i < p; i++)
67. {
68. for (int j = 0; j < n; j+
+)
69. {
70. System.out.print(c[i]
[j]+" ");
71. }
72. System.out.println("");
73. }
74. }
75. else
76. {
77. System.out.println("Addition
would not be possible");
78. }
79. }
80. }
1.import java.util.Scanner;
2.public class Odd_Even
3.{
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the number you
want to check:");
9. n = s.nextInt();
10. if(n % 2 == 0)
11. {
12. System.out.println("The given
number "+n+" is Even ");
13. }
14. else
15. {
16. System.out.println("The given
number "+n+" is Odd ");
3
17. }
18. }
19. }
//Largest of 3 numbers
1.import java.util.Scanner;
2.public class Biggest_Number
3.{
4. public static void main(String[] args)
5. {
6. int x, y, z;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the first
number:");
9. x = s.nextInt();
10. System.out.print("Enter the second
number:");
11. y = s.nextInt();
12. System.out.print("Enter the third
number:");
13. z = s.nextInt();
14. if(x > y && x > z)
15. {
16. System.out.println("Largest
number is:"+x);
17. }
18. else if(y > z)
19. {
20. System.out.println("Largest
number is:"+y);
21. }
22. else
23. {
24. System.out.println("Largest
number is:"+z);
25. }
26.
27. }
28. }
4
//Equals Program in java
1.import java.util.Scanner;
2.public class Equal_Integer
3.{
4. public static void main(String[] args)
5. {
6. int m, n;
7. Scanner s = new Scanner(System.in);
8. System.out.print("Enter the first
number:");
9. m = s.nextInt();
10. System.out.print("Enter the second
number:");
11. n = s.nextInt();
12. if(m == n)
13. {
14. System.out.println(m+" and
"+n+" are equal ");
15. }
16. else
17. {
18. System.out.println(m+" and
"+n+" are not equal ");
19. }
20. }
21. }
1. import java.util.Scanner;
2.
3. class LinearSearchExample2
4. {
5. public static void main(String args[])
6. {
7. int c, n, search, array[];
8.
9. Scanner in = new Scanner(System.in);
10. System.out.println("Enter number of elements");
11. n = in.nextInt();
12. array = new int[n];
13.
14. System.out.println("Enter those " + n + " elements
");
15.
16. for (c = 0; c < n; c++)
17. array[c] = in.nextInt();
18.
19. System.out.println("Enter value to find");
20. search = in.nextInt();
21.
22. for (c = 0; c < n; c++)
23. {
24. if (array[c] == search) /* Searching element is
present */
25. {
26. System.out.println(search + " is present at loca
tion " + (c + 1) + ".");
27. break;
28. }
7
29. }
30. if (c == n) /* Element to search isn't present */
31. System.out.println(search + " isn't present in arra
y.");
32. }
33. }
1. class BinarySearchExample{
2. public static void binarySearch(int arr[], int first, int las
t, int key){
3. int mid = (first + last)/2;
4. while( first <= last ){
5. if ( arr[mid] < key ){
6. first = mid + 1;
7. }else if ( arr[mid] == key ){
8. System.out.println("Element is found at index: " + mi
d);
9. break;
10. }else{
11. last = mid - 1;
12. }
13. mid = (first + last)/2;
14. }
15. if ( first > last ){
16. System.out.println("Element is not found!");
17. }
18. }
19. public static void main(String args[]){
20. int arr[] = {10,20,30,40,50};
21. int key = 30;
22. int last=arr.length-1;
23. binarySearch(arr,0,last,key);
24. }
25. }
8
//Binary search in java Using recursion
1. class BinarySearchExample1{
2. public static int binarySearch(int arr[], int first, int la
st, int key){
3. if (last>=first){
4. int mid = first + (last - first)/2;
5. if (arr[mid] == key){
6. return mid;
7. }
8. if (arr[mid] > key){
9. return binarySearch(arr, first, mid-1, key);//search
in left subarray
10. }else{
11. return binarySearch(arr, mid+1, last, key);//
search in right subarray
12. }
13. }
14. return -1;
15. }
16. public static void main(String args[]){
17. int arr[] = {10,20,30,40,50};
18. int key = 30;
19. int last=arr.length-1;
20. int result = binarySearch(arr,0,last,key);
21. if (result == -1)
22. System.out.println("Element is not found!");
23. else
24. System.out.println("Element is found at index
: "+result);
25. }
26. }
9
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of n:");
n = s.nextInt();
System.out.print("Fibonacci Series:");
for(int i = 1; i <= n; i++)
{
a = b;
b = c;
c = a + b;
System.out.print(a+" ");
}
}
}
//Illustrate Various Boolean operators
1. public static void main(String args[])
2. {
3. Scanner s = new Scanner(System.in);
4. System.out.print("Enter a:");
5. boolean a = s.nextBoolean();
6. System.out.print("Enter b:");
7. boolean b = s.nextBoolean();
8. boolean c = a | b;
9. boolean d = a & b;
10. boolean e = a ^ b;
11. boolean f = (!a & b) | (a & !b);
12. boolean g = !a;
13. System.out.println("a = " + a);
10
14. System.out.println("b = " + b);
15. System.out.println("a|b = " + c);
16. System.out.println("a&b = " + d);
17. System.out.println("a^b = " + e);
18. System.out.println("!a&b|a&!b = "
+ f);
19. System.out.println("!a = " + g);
20. }
21. }
12
58. System.exit(0);
59. }
60. }
61. }
62. }
import java.util.Scanner;
public class ArmStrong
{
public static void main(String[] args)
{
int n, count = 0, a, b, c, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter a number:");
n = s.nextInt();
a = n;
c = n;
while(a > 0)
{
a = a / 10;
count++;
}
while(n > 0)
{
b = n % 10;
sum = (int) (sum+Math.pow(b, count));
n = n / 10;
}
if(sum == c)
{
System.out.println(c+ " is an Armstrong
number");
}
else
{
System.out.println(c+ " is not an
Armstrong number");
}
13
}
}
if (sum == c)
{
System.out.println(c + " is an Armstrong
number");
}
14
else
{
System.out.println(c + " is not an
Armstrong number");
}
}
}
// Class
class GFG {
// Class
class GFG {
15
// Main driver method
public static void main(String[] args)
{
// Checking if length of args array is
// greater than 0
if (args.length > 0) {
// Print statements
System.out.println("The command line"
+ " arguments are:");
16
Local Variable Type Inference is one of the most evident
change to language available from Java 10 onwards. It allows to
define a variable using var and without specifying the type of it.
The compiler infers the type of the variable using the value
provided. This type inference is restricted to local variables.
Noteworthy points
Example
17
import java.util.List;
Output
Julie
Robert
Chris
Joseph
Julie
Robert
Chris
Joseph
class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5
import java.io.*;
class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 3; i++) {
one : { // label one
two : { // label two
three : { // label three
System.out.println("i=" + i);
if (i == 0)
break one; // break to label one
if (i == 1)
break two; // break to label two
if (i == 2)
break three; // break to label three
}
System.out.println("after label three");
}
System.out.println("after label two");
}
System.out.println("after label one");
}
}
}
Continue Statement
20
The continue statement pushes the next repetition of the
loop to take place, hopping any code between itself and the
conditional expression that controls the loop.
class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6){
System.out.println();
// using continue keyword
// to skip the current iteration
continue;
}
System.out.println(i);
}
}
}
Output
0
1
2
3
4
5
7
8
9
In the program, when the value of i is 6, the compiler
encounters the continue statement, and then 6 is skipped.
21
Return Statement
The “return” keyword can help you transfer control from one
method to the method that called it. Since the control jumps
from one part of the program to another, the return is also a
jump statement.
“return” is a reserved keyword means we can’t use it
as an identifier.
It is used to exit from a method, with or without a
value.
import java.io.*;
class ReturnExample {
// A simple method that takes two integers as input and
// returns their sum
public static int calculateSum(int num1, int num2)
{
// Print a message indicating the method has started
System.out.println("Calculating the sum of " + num1
+ " and " + num2);
int sum = num1 + num2;
System.out.println("The sum is: " + sum);
22
// Print the result
System.out.println("Result: " + result);
}
}
Output
Calculating the sum of 5 and 10
The sum is: 15
Result: 15
Output Explanation:
When we are calling a class calculateSum method that has
return sum which returns the value of sum and that value gets
displayed on the console.
23
Write a program in Java to develop user defined exception for
‘Divide by Zero’ error.
class MyException extends Exception
{
private int ex;
MyException(int b)
{
ex=b;
}
public String toString()
{
return "My Exception : Number is not divided
by "+ex;
}
}
class DivideByZeroException
{
static void divide(int a,int b) throws
MyException
{
if(b<=0)
{
throw new MyException(b);
}
else
{
System.out.println("Division : "+a/b);
}
}
public static void main(String arg[])
{
try
{
divide(10,0);
}
catch(MyException me)
{
System.out.println(me);
}
24
}
}
// Resizable.java
// Interface Resizable
interface Resizable {
Copy
// Rectangle.java
25
private int height;
this.width = width;
this.height = height;
this.width = width;
this.height = height;
}
26
}
Copy
// Main.java
rectangle.printSize();
rectangle.resizeWidth(150);
rectangle.resizeHeight(200);
rectangle.printSize();
27
7. Write a program to illustrate the creation of threads using a
runnable class. (start method starts each of the newly created
thread. Inside the run method, there is sleep() to suspend the
thread for 500 milliseconds).
MyThread.java:
public class MyThread implements Runnable {
public void run() {
//works till i is at most 5
for (int i = 1; i<= 5; i++) {
System.out.println(Thread.currentThread().getName()+" i is " + i);
try {
//sleep current thread for 500 ms
Thread.sleep(500);
} catch (InterruptedException e) {
//print the exception message if occurred
System.out.println(e.getMessage());
}
}
}
}
Main.java:
public class Main {
public static void main(String[] args) {
//Common object
MyThread myThread = new MyThread();
//thread 1
Thread t1 =new Thread(myThread);
//thread2
Thread t2 =new Thread(myThread);
//thread 3
28
Thread t3 =new Thread(myThread);
//starting all 3 threads now
t1.start();
t2.start();
t3.start();
}
}
Explanation:
The Runnable interface comprises one run method which is abstract.
Each class implementing the Runnable interface should override the run
method.
The MyThread class implements the Runnable interface and overrides the
run method.
The run method prints the thread name along with the value of the
variable i, that is, the iteration variable.
In each iteration of the run method, the sleep method is called to suspend
the currently running thread for 500 milliseconds.
Within the Main class, the object of MyThread class is created. This
object is passed as a parameter to each Thread class object created within
the main method.
Further, the start method is called to start the thread, which internally
calls the run method.
Total three threads are created and all three threads are started one by one
by calling the start method.
start();
}
public void run()
{
29
try
{
for ( int i =5; i > 0; i--)
{
System.out.println (“Child thread” + i);
Thread.sleep (500);
}
} catch (InterruptedException e) { }
System.out.println (“exiting child thread …”);
}
}
class TestMyThread
{
public static void main(String args[])
{
new MyThread();
try {
for ( int k = 5; k < 0; k--)
{
System.out.println (“Running main thread :” + k);
Thread.sleep(1000);
}
}catch (InterruptedException e) { }
System.out.println (“Exiting main thread . . .”);
}
}
30