JAVA LAB PRACTICALS
1. Write a Program to display Hello world.
// Your First Program
class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
2. Write a Program to implement the different
operators.
class Main {
public static void main(String[] args) {
// declare variables
int a = 12, b = 5;
// addition operator
[Link]("a + b = " + (a + b));
// subtraction operator
[Link]("a - b = " + (a - b));
// multiplication operator
[Link]("a * b = " + (a * b));
// division operator
[Link]("a / b = " + (a / b));
// modulo operator
[Link]("a % b = " + (a % b));
}
}
3. Write a Program to calculate the sum of all
numbers of array.
// Java Program to find sum of elements in a given array
class Test {
static int arr [] = {12, 3, 4, 15};
// method for sum of elements in an array
static int sum ()
{
int sum = 0; // initialize sum
int i;
// Iterate through all elements and add them to sum
for (i = 0; i < [Link]; i++)
sum += arr[i];
return sum;
}
// Driver method
public static void main (String [] args)
{
[Link]("Sum of given array is "
+ sum ());
}
}
[Link] a Program to find weather a no. is prime
or not.
public class Main {
public static void main(String[] args) {
int num = 29;
boolean flag = false;
for (int i = 2; i <= num / 2; ++i) {
// condition for nonprime number
if (num % i == 0) {
flag = true;
break;
}
}
if (!flag)
[Link](num + " is a prime number.");
else
[Link](num + " is not a prime number.");
}
}
[Link] a Program to calculate matrix operations.
(i) Addition (ii) Multiplication
(i) Additon
import [Link].*;
public class Main
{
public static void main(String[] args)
{
int n, m;
Scanner sc = new Scanner([Link]);
[Link](“\nEnter the order of the matrix : “);
m = [Link]();
n = [Link]();
int[][] mat1 = new int[m][n];
int[][] mat2 = new int[m][n];
int[][] mat3 = new int[m][n];
[Link](“\nInput the matrix 1 elements : “);
int i, j;
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
mat1[i][j] = [Link]();
}
[Link](“\nInput the matrix 2 elements : “);
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
mat2[i][j] = [Link]();
}
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
{
mat3[i][j] = mat1[i][j] + mat2[i][j];
}
}
[Link](“Addition of the two matrices :”);
for(i = 0; i < m; i++)
{
for(j = 0; j < n; j++)
[Link](mat3[i][j] + ” “);
[Link]();
}
}
}
6 . Write a Program to demonstrate static variables, methods
and blocks.
public class Demo {
static int x = 10;
static int y;
static void func(int z) {
[Link]("x = " + x);
[Link]("y = " + y);
[Link]("z = " + z);
}
static {
[Link]("Running static initialization
block.");
y = x + 5;
}
public static void main(String args[]) {
func(8);
}
}