0% found this document useful (0 votes)
10 views28 pages

Java Matrix Addition Program

Uploaded by

moh24amme
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views28 pages

Java Matrix Addition Program

Uploaded by

moh24amme
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

//Matrix Addition

[Link] [Link];
[Link] class Add_Matrix
3.{
4. public static void main(String[] args)
5. {
6. int p, q, m, n;
7. Scanner s = new Scanner([Link]);
8. [Link]("Enter number of rows
in first matrix:");
9. p = [Link]();
10. [Link]("Enter number of
columns in first matrix:");
11. q = [Link]();
12. [Link]("Enter number of
rows in second matrix:");
13. m = [Link]();
14. [Link]("Enter number of
columns in second matrix:");
15. n = [Link]();
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. [Link]("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] = [Link]();
27. }
28. }
29. [Link]("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] = [Link]();
35. }
36. }
37. [Link]("First
Matrix:");
38. for (int i = 0; i < p; i++)
39. {
40. for (int j = 0; j < q; j+
+)
41. {
42. [Link](a[i]
[j]+" ");
43. }
44. [Link]("");
45. }
46. [Link]("Second
Matrix:");
47. for (int i = 0; i < m; i++)
48. {
49. for (int j = 0; j < n; j+
+)
50. {
51. [Link](b[i]
[j]+" ");
52. }
53. [Link]("");
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. [Link]("Matrix
after addition:");

2
66. for (int i = 0; i < p; i++)
67. {
68. for (int j = 0; j < n; j+
+)
69. {
70. [Link](c[i]
[j]+" ");
71. }
72. [Link]("");
73. }
74. }
75. else
76. {
77. [Link]("Addition
would not be possible");
78. }
79. }
80. }

[Link] [Link];
[Link] class Odd_Even
3.{
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner s = new Scanner([Link]);
8. [Link]("Enter the number you
want to check:");
9. n = [Link]();
10. if(n % 2 == 0)
11. {
12. [Link]("The given
number "+n+" is Even ");
13. }
14. else
15. {
16. [Link]("The given
number "+n+" is Odd ");

3
17. }
18. }
19. }

//Largest of 3 numbers
[Link] [Link];
[Link] class Biggest_Number
3.{
4. public static void main(String[] args)
5. {
6. int x, y, z;
7. Scanner s = new Scanner([Link]);
8. [Link]("Enter the first
number:");
9. x = [Link]();
10. [Link]("Enter the second
number:");
11. y = [Link]();
12. [Link]("Enter the third
number:");
13. z = [Link]();
14. if(x > y && x > z)
15. {
16. [Link]("Largest
number is:"+x);
17. }
18. else if(y > z)
19. {
20. [Link]("Largest
number is:"+y);
21. }
22. else
23. {
24. [Link]("Largest
number is:"+z);
25. }
26.
27. }
28. }

4
//Equals Program in java
[Link] [Link];
[Link] class Equal_Integer
3.{
4. public static void main(String[] args)
5. {
6. int m, n;
7. Scanner s = new Scanner([Link]);
8. [Link]("Enter the first
number:");
9. m = [Link]();
10. [Link]("Enter the second
number:");
11. n = [Link]();
12. if(m == n)
13. {
14. [Link](m+" and
"+n+" are equal ");
15. }
16. else
17. {
18. [Link](m+" and
"+n+" are not equal ");
19. }
20. }
21. }

//Digits extraction in java


[Link] [Link];
[Link] class Extract_Digits
3.{
4. public static void main(String args[])
5. {
6. int n, m, a, i = 1, counter = 0;
7. Scanner s=new Scanner([Link]);
8. [Link]("Enter any number:");
9. n = [Link]();
10. m = n;
11. while(n > 0)
5
12. {
13. n = n / 10;
14. counter++;
15. }
16. while(m > 0)
17. {
18. a = m % 10;
19. [Link]("Digits at
position "+counter+":"+a);
20. m = m / 10;
21. counter--;
22. }
23. }
24. }

//Integer Palindrome in java


import [Link];
public class Palindrome
{
public static void main(String args[])
{
int n, m, rev = 0, x;
Scanner s = new Scanner([Link]);
[Link]("Enter the number:");
n = [Link]();
m = n;
while(n > 0)
{
x = n % 10;
rev = rev * 10 + x;
n = n / 10;
}
if(rev == m)
{
[Link](" "+m+" is a
palindrome number");
}
else
{
[Link](" "+m+" is not a
palindrome number");
6
}
}
}

//Linear Search in java

1. import [Link];
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([Link]);
10. [Link]("Enter number of elements");
11. n = [Link]();
12. array = new int[n];
13.
14. [Link]("Enter those " + n + " elements
");
15.
16. for (c = 0; c < n; c++)
17. array[c] = [Link]();
18.
19. [Link]("Enter value to find");
20. search = [Link]();
21.
22. for (c = 0; c < n; c++)
23. {
24. if (array[c] == search) /* Searching element is
present */
25. {
26. [Link](search + " is present at loca
tion " + (c + 1) + ".");
27. break;
28. }

7
29. }
30. if (c == n) /* Element to search isn't present */
31. [Link](search + " isn't present in arra
y.");
32. }
33. }

//Binary Search in java

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. [Link]("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. [Link]("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=[Link]-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=[Link]-1;
20. int result = binarySearch(arr,0,last,key);
21. if (result == -1)
22. [Link]("Element is not found!");
23. else
24. [Link]("Element is found at index
: "+result);
25. }
26. }

//Print Fibonacci numbers


import [Link];
public class Main

9
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner([Link]);
[Link]("Enter value of n:");
n = [Link]();
[Link]("Fibonacci Series:");
for(int i = 1; i <= n; i++)
{
a = b;
b = c;
c = a + b;
[Link](a+" ");
}
}
}
//Illustrate Various Boolean operators
1. public static void main(String args[])
2. {
3. Scanner s = new Scanner([Link]);
4. [Link]("Enter a:");
5. boolean a = [Link]();
6. [Link]("Enter b:");
7. boolean b = [Link]();
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. [Link]("a = " + a);
10
14. [Link]("b = " + b);
15. [Link]("a|b = " + c);
16. [Link]("a&b = " + d);
17. [Link]("a^b = " + e);
18. [Link]("!a&b|a&!b = "
+ f);
19. [Link]("!a = " + g);
20. }
21. }

//Illustrate Various Boolean operators


[Link] [Link];
[Link] class Bitwise_Operation
3.{
4. public static void main(String[] args)
5. {
6. int m, n, x, a;
7. Scanner s = new Scanner([Link]);
8. [Link]("Enter First
number:");
9. m = [Link]();
10. [Link]("Enter Second
number:");
11. n = [Link]();
12. while(true)
13. {
14. [Link]("");
15. [Link]("Press 1
for Right Shift by 2:");
16. [Link]("Press 2
for Left Shift by 2:");
17. [Link]("Press 3
for Bitwise AND:");
18. [Link]("Press 4
for Bitwise OR by 2:");
19. [Link]("Press 5
for Bitwise Exclusive OR:");
20. [Link]("Press 6
for Bitwise NOT:");
21. [Link]("Press 7 to
Exit:");
11
22. [Link]("");
23. [Link]("Option:");
24. x = [Link]();
25. switch(x)
26. {
27. case 1:
28. a = m << 2;
29. [Link]("Result
after left shift by 2:"+a);
30. break;
31.
32. case 2:
33. a = n >> 2;
34. [Link]("Result
after right shift by 2:"+a);
35. break;
36.
37. case 3:
38. a = m & n;
39. [Link]("Result
after bitwise AND:"+a);
40. break;
41.
42. case 4:
43. a = m | n;
44. [Link]("Result
after bitwise OR:"+a);
45. break;
46.
47. case 5:
48. a = m ^ n;
49. [Link]("Result
after bitwise Exclusive OR:"+a);
50. break;
51.
52. case 6:
53. a = ~ m;
54. [Link]("Result
after bitwise NOT:"+a);
55. break;
56.
57. case 7:

12
58. [Link](0);
59. }
60. }
61. }
62. }

//Armstrong number using While loop in java

import [Link];
public class ArmStrong
{
public static void main(String[] args)
{
int n, count = 0, a, b, c, sum = 0;
Scanner s = new Scanner([Link]);
[Link]("Enter a number:");
n = [Link]();
a = n;
c = n;
while(a > 0)
{
a = a / 10;
count++;
}
while(n > 0)
{
b = n % 10;
sum = (int) (sum+[Link](b, count));
n = n / 10;
}
if(sum == c)
{
[Link](c+ " is an Armstrong
number");
}
else
{
[Link](c+ " is not an
Armstrong number");
}

13
}
}

//Armstrong number using for loop in java


import [Link];

public class ArmStrong


{
public static void main(String[] args)
{
int n, count = 0, a, b, c, sum = 0;
Scanner s = new Scanner([Link]);
[Link]("Enter a number:");
n = [Link]();
a = n;
c = n;

// Calculate the number of digits in 'n'


using a for loop
for (; a > 0; a /= 10)
{
count++;
}

// Reset 'a' and 'sum' for the following loop


a = n;
sum = 0;

// Calculate the sum of cubes of digits using


a for loop
for (; n > 0; n /= 10)
{
b = n % 10;
sum += [Link](b, count);
}

if (sum == c)
{
[Link](c + " is an Armstrong
number");
}
14
else
{
[Link](c + " is not an
Armstrong number");
}
}
}

Examples of command-line argument


Example 1:
 Java

// Java Program to Illustrate First Argument

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Printing the first argument
[Link](args[0]);
}
}

Java Program to Check for Command Line Arguments

// Class
class GFG {
15
// Main driver method
public static void main(String[] args)
{
// Checking if length of args array is
// greater than 0
if ([Link] > 0) {

// Print statements
[Link]("The command line"
+ " arguments are:");

// Iterating the args array


// using for each loop

for (String val : args)


// Printing command line arguments
[Link](val);
}
else
// Print statements
[Link]("No command line "
+ "arguments
found.");
}
}

Local Variable Type Inference

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.

Old way of declaring local variable.

String name = "Welcome to [Link]";

New Way of declaring local variable.

var name = "Welcome to [Link]";

Now compiler infers the type of name variable as String by


inspecting the value provided.

Noteworthy points

 No type inference in case of member variable, method


parameters, return values.
 Local variable should be initialized at time of declaration
otherwise compiler will not be infer and will throw error.
 Local variable inference is available inside initialization
block of loop statements.
 No runtime overhead. As compiler infers the type based
on value provided, there is no performance loss.
 No dynamic type change. Once type of local variable is
inferred it cannot be changed.
 Complex boilerplate code can be reduced using local
variable type inference.
Map<Integer, String> mapNames = new HashMap<>();

var mapNames1 = new HashMap<Integer, String>();

Example

Following Program shows the use of Local Variable Type


Inference in JAVA 10.

17
import [Link];

public class Tester {


public static void main(String[] args) {
var names = [Link]("Julie", "Robert", "Chris",
"Joseph");
for (var name : names) {
[Link](name);
}
[Link]("");
for (var i = 0; i < [Link](); i++) {
[Link]([Link](i));
}
}
}

Output

Julie
Robert
Chris
Joseph

Julie
Robert
Chris
Joseph

Jump Statements in Java

Jumping statements are control statements that transfer


execution control from one point to another point in the
program. There are three Jump statements that are provided
in the Java programming language:
1. Break statement.
2. Continue statement.
3. Return Statement
18
Break statement

1. Using Break Statement to exit a loop:


In java, the break statement is used to terminate the
execution of the nearest looping statement or switch
statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.
Syntax:
break;

// Java program to illustrate the


// break keyword in Java
import [Link].*;

class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
[Link](i);
}
}
}
Output
0
1
2
3
4
5

Note :In a switch statement, if the break statement is


missing, every case label is executed till the end of the
switch.

2. Use Break as a form of goto


19
Java does not have a goto statement because it produces an
unstructured way to alter the flow of program execution. Java
illustrates an extended form of the break statement. This form
of break works with the label. The label is the name of a
label that identifies a statement or a block of code.
Syntax:
break label;
When this form of break executes, control jumps out of the
labeled statement or block.

import [Link].*;

class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 3; i++) {
one : { // label one
two : { // label two
three : { // label three
[Link]("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
}
[Link]("after label three");
}
[Link]("after label two");
}
[Link]("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.

Java program to illustrate the


// continue keyword in Java
import [Link].*;

class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6){
[Link]();
// using continue keyword
// to skip the current iteration
continue;
}
[Link](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 [Link].*;

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
[Link]("Calculating the sum of " + num1
+ " and " + num2);
int sum = num1 + num2;
[Link]("The sum is: " + sum);

// Return the calculated sum


return sum;

// Note: Any code after the 'return' statement will


// not be executed. But "Final" is an exception in
// the case of try-catch-final block.
// [Link]("end"); // error : unreachable
// statement
}
public static void main(String[] args)
{
// Call the calculateSum method
int result = calculateSum(5, 10);

22
// Print the result
[Link]("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
{
[Link]("Division : "+a/b);
}
}
public static void main(String arg[])
{
try
{
divide(10,0);
}
catch(MyException me)
{
[Link](me);
}

24
}
}

// [Link]

// Interface Resizable

// Declare the Resizable interface

interface Resizable {

// Declare the abstract method "resizeWidth" to


resize the width

void resizeWidth(int width);

// Declare the abstract method "resizeHeight" to


resize the height

void resizeHeight(int height);

Copy
// [Link]

// Declare the Rectangle class, which implements the


Resizable interface

class Rectangle implements Resizable {

// Declare private instance variables to store


width and height

private int width;

25
private int height;

// Constructor for initializing the width and


height

public Rectangle(int width, int height) {

[Link] = width;

[Link] = height;

// Implement the "resizeWidth" method to resize


the width

public void resizeWidth(int width) {

[Link] = width;

// Implement the "resizeHeight" method to resize


the height

public void resizeHeight(int height) {

[Link] = height;

// Method to print the current width and height


of the rectangle

public void printSize() {

[Link]("Width: " + width + ",


Height: " + height);

}
26
}

Copy
// [Link]

// Declare the Main class

public class Main {

public static void main(String[] args) {

// Create an instance of the Rectangle class


with an initial size

Rectangle rectangle = new Rectangle(100,


150);

// Print the initial size of the rectangle

[Link]();

// Resize the rectangle by changing its width


and height

[Link](150);

[Link](200);

// Print the updated size of the rectangle

[Link]();

27
28

Common questions

Powered by AI

The Rectangle class's implementation of the Resizable interface demonstrates several object-oriented programming principles: abstraction, by providing a clear interface without revealing the implementation details; encapsulation, by handling changes to the class's internal state through defined methods without external interference; and polymorphism, allowing different classes to interact with and adapt their behavior when using the same operations defined by the interface. This design promotes modularity and code flexibility, making it easier to manage and scale applications .

Implementing interfaces in Java allows classes to provide specific functionality while adhering to a contract defined by the interface. The Resizable interface defines the methods `resizeWidth` and `resizeHeight`, which any implementing class must provide, as demonstrated in the Rectangle class. This signifies modular design as different classes can implement the same interface but offer specific behaviors tailored to their role. This pattern enhances code reusability and flexibility, allowing easy alternation and extension of functionality without causing disruption to existing code structures .

A linear search involves iterating through each element of the array sequentially and comparing it with the target value. If the element matches the target value, the position of the element is returned or printed; if no match is found by the end of the array, the search concludes with confirmation of absence. This search technique is straightforward and does not require the array to be sorted, but has a time complexity of O(n) due to its sequential nature .

An Armstrong number is determined by summing the power of its digits raised to the number of digits. In the provided Java code, first, the count of digits is calculated by dividing the number repeatedly by 10. Then, in a separate loop, each digit of the number is raised to this power (calculated using Math.pow) and the subsequent values are summed up. If this sum matches the original number, it is classified as an Armstrong number. This logic is implemented both using a while loop and a for loop in the examples provided .

For two matrices to be added in Java, they must have the same dimensions, i.e., the number of rows and columns in the first matrix must be equal to the number of rows and columns in the second matrix. This condition is checked with the condition "if (p == m && q == n)" in the provided code snippet, where 'p' and 'q' are the dimensions of the first matrix and 'm' and 'n' are the dimensions of the second matrix .

Jump statements in Java are control statements that transfer the execution control from one part of the program to another. The primary jump statements are break, continue, and return. The break statement is used to exit a loop or switch statement, the continue statement skips the remaining code inside a loop for the current iteration and proceeds to the next iteration, and the return statement exits from the current method and optionally returns a value. These statements are used to alter the control flow of loops and switch statements efficiently .

The break statement immediately terminates the nearest enclosing loop or switch statement, transferring control to the statement immediately following the terminated statement. For example, in a for loop, the break can be used to exit the loop prematurely if a certain condition is met . The continue statement, on the other hand, skips the current iteration of the loop and proceeds to the next iteration, jumping to the evaluation of the loop's conditional expression. This is useful for skipping certain elements or conditions within loops without exiting the loop entirely .

The 'divide' method checks if the divisor 'b' is less than or equal to zero. If this condition is met, it throws a user-defined exception `MyException`, which indicates an invalid operation. Otherwise, the method performs the division and prints the result. The method is encapsulated in a try-catch block which catches the `MyException` when attempting division by zero and prints a relevant message, thus handling the exception gracefully without terminating the program unexpectedly .

To check if an integer is a palindrome, the algorithm reverses the digits of the number and compares it with the original number. In Java, this involves using a loop to extract each digit (using modulus operation), build the reversed number (by multiplying the current reversed number by 10 and adding the extracted digit), and finally, compare it to the original number. If they match, the integer is a palindrome. This method ensures that the number reads the same backward as forward .

The bitwise NOT operator (~) inverts the bits of its operand; it flips each '0' to '1' and each '1' to '0'. This operation is distinctly different from other bitwise operators like AND (&), OR (|), and XOR (^), which require two operands and perform typical logical operations across corresponding bits. The NOT operation is unary and is generally used for toggling bits or creating one's complement of binary data .

You might also like