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

java program

The document provides a collection of Java programs that cover various programming concepts such as printing messages, calculating sums, handling user input, using conditional statements, and working with arrays. It includes examples for printing numbers, calculating factorials, generating Fibonacci sequences, checking for prime numbers, and manipulating arrays. Additionally, it explains multidimensional arrays and provides syntax for their declaration and initialization.

Uploaded by

rajsaini088
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

java program

The document provides a collection of Java programs that cover various programming concepts such as printing messages, calculating sums, handling user input, using conditional statements, and working with arrays. It includes examples for printing numbers, calculating factorials, generating Fibonacci sequences, checking for prime numbers, and manipulating arrays. Additionally, it explains multidimensional arrays and provides syntax for their declaration and initialization.

Uploaded by

rajsaini088
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Java program

1. Print hello

public class hellows


{
public static void main(String []args)
{
System.out.println("hello");
}
}
Output is :hello

2.sum of two number

public class sumof2


{
public static void main (String [] args)
{
int a=4,b=6;

int c=a+b;
System.out.println("sum of a + b is " +c);

}
Output is : sum of a + b is 10

3.sum of two number using user input

import java.util.Scanner;

public class sumof2


{
public static void main (String [] args)
{

Scanner sc=new Scanner(System.in);


System.out.println("enter first number");
int a=sc.nextInt();
System.out.println("enter second number");
int b=sc.nextInt();
int c=a+b;
System.out.println("sum of a + b is " +c);

}
4.Three digit sum & reverse

import java.util.Scanner;

public class dsumreverse


{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the 3 digit number");
int n=sc.nextInt();
int a=n%10;
n=n/10;
int b=n%10;
n=n/10;
int sum=a+b+n;
int rev=a*100+b*10+n;
System.out.println(" 3 digit number is ");
System.out.println(sum);

System.out.println(" 3 digit number reverse is ");


System.out.println(rev);
}
}

5.if else program

import java.util.*;

class IfElse
{
public static void main(String[] args)
{

Scanner input = new Scanner(System.in);

System.out.println("Input marks scored by you");

int marksObtained = input.nextInt();

if (marksObtained >= 40)


{
System.out.println("You passed the exam.");
}
else {
System.out.println("you failed to pass the exam.");
}
}
}
6.leap year or not

import java.util.Scanner;
public class leapyear
{
public static void main (String []args)
{
Scanner sc = new Scanner(System.in);
System.out.println("enter the year");
int input=sc.nextInt();
if (input%4==0){
System.out.println("this is leap year");
}
else{
System.out.println("this is not leap year");
}

7. print 1-7 number and print Sunday to Saturday by switch case

import java.util.Scanner;
public class printday
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter the number");
int day=sc.nextInt();
switch(day)
{
case 1:
System.out.println("monday");
break;
case 2:
System.out.println("tuesday");
break;
case 3:
System.out.println("wednesday");
break;
case 4:
System.out.println("thrusday");
break;
case 5:
System.out.println("friday");
break;
case 6:
System.out.println("saturday");
break;
case 7:
System.out.println("saturday");
break;
default:
System.out.println("invalid day");
break;
}
}
}

8. This program will print 1 to 1 by for loop

class GFG
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
System.out.println(i);
}
}

Output
1
2
3
4
5
6
7
8
9
10

9. program will try to print “Hello World” 5 times.

class forLoopDemo
{
public static void main(String args[])
{

for (int i = 1; i <= 5; i++)


System.out.println("Hello World");
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World
10 factorial program
import java.util.Scanner;
class FactorialExample
{
public static void main(String args[])
{
int i,fact=1;
System.out.println("enter the number ");
Scanner s = new Scanner(System.in);
int number = s.nextInt();

for(i=1;i<=number;i++)
{
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}
10 fibonacci program
import java.util.Scanner;
class FibonacciExample1
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i;
Scanner s = new Scanner(System.in);
System.out.print("Enter a number : ");
int count = s.nextInt();
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}

10. prime no or not


import java.util.Scanner;
class PrimeNo
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter The number");


int num=sc.nextInt();
int count=0;
for(int i=1; i<=num;i++)
{
if (num%i==0)
{
count++;
}
}
if(count==2)
System.out.println("This is a prime number");
else
System.out.println("This is not a prime number");
}
}

10.2 Prime number with given range

import java.util.Scanner;
public class Prime
{
public static void main(String args[])
{
int min, max, flag = 0, i, j;
Scanner s = new Scanner(System.in);
System.out.println ("Enter the lower limit :");
min= s.nextInt();
System.out.println ("Enter the upper limit :");
max = s.nextInt();
System.out.println ("The prime numbers in between the entered limits are :");
for(i = min; i <=max; i++)
{
for( j = 2; j < i; j++)
{
if(i % j == 0)
{
flag = 1;
break;
}
else
{
flag = 0;
}
}
if(flag == 0)
{
System.out.println(i);
}
flag = 0;
}
}
}

10 program prints the sum of x ranging from 1 to 20.


class forLoopDemo {
public static void main(String args[])
{
int sum = 0;

for (int x = 1; x <= 20; x++)


{
sum = sum + x;
}
System.out.println("Sum: " + sum);
}
}
Out put is : 210

12.array program –simple


public class array
{
public static void main(String args[])
{
int a[]={11,12,13,14,15};
/*
int a[] =new int[5];
a[0]=11;
a[1]=12;
a[2]=13;
a[3]=14;
a[4]=15;
*/
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}

}
}

Ouput is

11

12

13

14

15

13. Access Array Elements


class Main {
public static void main(String[] args) {

// create an array
int[] age = {12, 4, 5, 2, 5};

// access each array elements


System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
Run Code

Output

Accessing Elements of Array:


First Element: 12
Second Element: 4
Third Element: 5
Fourth Element: 2
Fifth Element: 5

14 Print array element with user input

import java.util.Scanner;
public class arraywithui
{
public static void main(String args[])
{
System.out.println("enter the size of array");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("enter the element of array");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();

}
System.out.println("array elements are -- ");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}

15.sum of array element

import java.util.Scanner;
public class ararysumofel
{
public static void main(String args[])
{
System.out.println("enter the size of array");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
int sum=0;
System.out.println("enter the element of array");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();

}
System.out.println("array elements are -- ");
for(int i=0;i<n;i++)
{
System.out.println(a[i]);
sum=sum+a[i];
}

System.out.println("Sum of the elements ::" +sum);

}
}
16.largest element in array among three number

import java.util.Scanner;
public class arraylargestel
{
public static void main(String[] args)
{

Scanner sc=new Scanner(System.in);


System.out.println("enter the first number");
int a=sc.nextInt();
System.out.println("enter the second number");
int b=sc.nextInt();
System.out.println("enter the third number");
int c=sc.nextInt();

if(a>=b && a>=c)


System.out.println(a+" is the largest Number");

else if (b>=a && b>=c)


System.out.println(b+" is the largest Number");
else

System.out.println(c+" is the largest number");


}
}

17.array print even number

import java.io.*;
import java.util.Scanner;

public class arrayeven


{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);

System.out.println("Enter the size of the array: ");


int n=sc.nextInt(); //Intialize the array size

int arr[]=new int[n]; //Declare an array


System.out.println("Enter the array elements: ");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt(); //Initialize the array elements
}
//Print the even elements
System.out.println("The Even Elements are...");
for(int i=0;i<n;i++)
{
if(arr[i]%2==0) //Check whether even or not
{
System.out.print(arr[i]+" ");
}
}
System.out.println(" ");
}
}

17.array print odd number

import java.io.*;
import java.util.Scanner;

public class arrayeven


{
public static void main(String[] args)
{
//Take input from the user
Scanner sc=new Scanner(System.in);

System.out.println("Enter the size of the array: ");


int n=sc.nextInt(); //Intialize the array size

int arr[]=new int[n]; //Declare an array


System.out.println("Enter the array elements: ");
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt(); //Initialize the array elements
}

// Print the odd elements


System.out.println("The Odd Elements are...");
for(int i=0;i<n;i++)
{
if(arr[i]%2!=0) //check whether odd or not
{
System.out.print(arr[i]+" ");
}
}

}
}

18.array even number sum

import java.util.Scanner;

public class arrayevensum


{

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
int Size, i, EvenSum = 0;
sc = new Scanner(System.in);

System.out.print(" Please Enter Number of elements in an array : ");


Size = sc.nextInt();

int [] a = new int[Size];

System.out.print(" Please Enter " + Size + " elements of an Array : ");


for (i = 0; i < Size; i++)
{
a[i] = sc.nextInt();
}

for(i = 0; i < Size; i++)


{
if(a[i] % 2 == 0)
{
EvenSum = EvenSum + a[i];
}
}
System.out.println("\n The Sum of Even Numbers in this Array = " + EvenSum);
}
}

Multidimensional Arrays in Java


Array-Basics in Java Multidimensional Arrays can be defined in simple words as array of arrays.
Data in multidimensional arrays are stored in tabular form (in row major order).
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new data_type[size1]
[size2]….[sizeN];
where:
 data_type: Type of data to be stored in the array. For example: int, char, etc.
 dimension: The dimension of the array created. For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, …, sizeN: Sizes of the dimensions respectively.
Examples:
Two dimensional array:
int[][] twoD_arr = new int[10][20];

Three dimensional array:


int[][][] threeD_arr = new int[10][20][30];
Size of multidimensional arrays: The total number of elements that can be stored in a
multidimensional array can be calculated by multiplying the size of all the dimensions.
For example: The array int[][] x = new int[10][20] can store a total of (10*20) = 200 elements.
Similarly, array int[][][] x = new int[5][10][20] can store a total of (5*10*20) = 1000 elements.
Two – dimensional Array (2D-Array)
Two – dimensional array is the simplest form of a multidimensional array. A two – dimensional array
can be seen as an array of one – dimensional array for easier understanding.
Indirect Method of Declaration:
 Declaration – Syntax:
data_type[][] array_name = new data_type[x][y];
For example: int[][] arr = new int[10][20];
 Initialization – Syntax:
array_name[row_index][column_index] = value;
For example: arr[0][0] = 1;
Example:
 Java

class GFG {

public static void main(String[] args)

int[][] arr = new int[10][20];

arr[0][0] = 1;

System.out.println("arr[0][0] = " + arr[0][0]);

Output

arr[0][0] = 1

Direct Method of Declaration: Syntax:


data_type[][] array_name = {
{valueR1C1, valueR1C2, ....},
{valueR2C1, valueR2C2, ....}
};

For example: int[][] arr = {{1, 2}, {3, 4}};


Example:
 Java

class GFG {

public static void main(String[] args)

{
int[][] arr = { { 1, 2 }, { 3, 4 } };

for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

System.out.println("arr[" + i + "][" + j + "] = "

+ arr[i][j]);

Output

arr[0][0] = 1
arr[0][1] = 2
arr[1][0] = 3
arr[1][1] = 4

Accessing Elements of Two-Dimensional Arrays

Elements in two-dimensional arrays are commonly referred by x[i][j] where ‘i’ is the row number and
‘j’ is the column number.
Syntax:
x[row_index][column_index]
For example:
int[][] arr = new int[10][20];
arr[0][0] = 1;
The above example represents the element present in first row and first column. Note: In arrays if size
of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual row number is 2+1 =
3. Example:
 Java

class GFG {

public static void main(String[] args)

{
int[][] arr = { { 1, 2 }, { 3, 4 } };

System.out.println("arr[0][0] = " + arr[0][0]);

Output

arr[0][0] = 1
Representation of 2D array in Tabular Format:
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the row number
ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3
rows and 3 columns is shown below:

Print 2D array in tabular format:


To output all the elements of a Two-Dimensional array, use nested for loops. For this two for loops are
required, One to traverse the rows and another to traverse columns.
Example:
 Java

class GFG {

public static void main(String[] args)

int[][] arr = { { 1, 2 }, { 3, 4 } };
for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

System.out.print(arr[i][j] + " ");

System.out.println();

Output

1 2
3 4
Three – dimensional Array (3D-Array)
Three – dimensional array is a complex form of a multidimensional array. A three – dimensional array
can be seen as an array of two – dimensional array for easier understanding.
Indirect Method of Declaration:
 Declaration – Syntax:
data_type[][][] array_name = new data_type[x][y][z];
For example: int[][][] arr = new int[10][20][30];
 Initialization – Syntax:
array_name[array_index][row_index][column_index] = value;
For example: arr[0][0][0] = 1;
Example:
 Java

class GFG {

public static void main(String[] args)

{
int[][][] arr = new int[10][20][30];

arr[0][0][0] = 1;

System.out.println("arr[0][0][0] = " + arr[0][0][0]);

Output

arr[0][0][0] = 1
Direct Method of Declaration: Syntax:
data_type[][][] array_name = {
{
{valueA1R1C1, valueA1R1C2, ....},
{valueA1R2C1, valueA1R2C2, ....}
},
{
{valueA2R1C1, valueA2R1C2, ....},
{valueA2R2C1, valueA2R2C2, ....}
}
};

For example: int[][][] arr = { {{1, 2}, {3, 4}}, {{5, 6}, {7,
8}} };
Example:
 Java

class GFG {

public static void main(String[] args)

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };
for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

for (int z = 0; z < 2; z++)

System.out.println("arr[" + i

+ "]["

+ j + "]["

+ z + "] = "

+ arr[i][j][z]);

Output

arr[0][0][0] = 1
arr[0][0][1] = 2
arr[0][1][0] = 3
arr[0][1][1] = 4
arr[1][0][0] = 5
arr[1][0][1] = 6
arr[1][1][0] = 7
arr[1][1][1] = 8

Accessing Elements of Three-Dimensional Arrays

Elements in three-dimensional arrays are commonly referred by x[i][j][k] where ‘i’ is the array
number, ‘j’ is the row number and ‘k’ is the column number.
Syntax:
x[array_index][row_index][column_index]
For example:
int[][][] arr = new int[10][20][30];
arr[0][0][0] = 1;
The above example represents the element present in the first row and first column of the first array in
the declared 3D array.
Note: In arrays if size of array is N. Its index will be from 0 to N-1. Therefore, for row_index 2, actual
row number is 2+1 = 3.
Example:
 Java

class GFG {

public static void main(String[] args)

int[][][] arr = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } };

System.out.println("arr[0][0][0] = " + arr[0][0][0]);

Output

arr[0][0][0] = 1
Representation of 3D array in Tabular Format:
A three – dimensional array can be seen as a tables of arrays with ‘x’ rows and ‘y’ columns where the
row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A three – dimensional
array with 3 array containing 3 rows and 3 columns is shown below:

Print 3D array in tabular format:


To output all the elements of a Three-Dimensional array, use nested for loops. For this three for loops
are required, One to traverse the arrays, second to traverse the rows and another to traverse
columns.
Example:
 Java

class GFG {

public static void main(String[] args)

int[][][] arr = { { { 1, 2 }, { 3, 4 } },

{ { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++) {

for (int j = 0; j < 2; j++) {

for (int k = 0; k < 2; k++) {

System.out.print(arr[i][j][k] + " ");

System.out.println();

System.out.println();
}

Output

1 2
3 4

5 6
7 8
Inserting a Multi-dimensional Array during Runtime:
This topic is forced n taking user-defined input into a multidimensional array during runtime. It is
focused on the user first giving all the input to the program during runtime and after all entered input,
the program will give output with respect to each input accordingly. It is useful when the user wishes
to make input for multiple Test-Cases with multiple different values first and after all those things
done, program will start providing output. As an example, let’s find the total number of even and odd
numbers in an input array. Here, we will use the concept of a 2-dimensional array.
Here are a few points that explain the use of the various elements in the upcoming code:
 Row integer number is considered as the number of Test-Cases and Column values are considered
as values in each Test-Case.
 One for() loop is used for updating Test-Case number and another for() loop is used for taking
respective array values.
 As all input entry is done, again two for() loops are used in the same manner to execute the
program according to the condition specified.
 The first line of input is the total number of TestCases.
 The second line shows the total number of first array values.
 The third line gives array values and so on.
Implementation:
 Java

import java.util.Scanner;

class GFGTestCase {

public static void main(String[] args)

// Scanner class to take


// values from console

Scanner scanner = new Scanner(System.in);

// totalTestCases = total

// number of TestCases

// eachTestCaseValues =

// values in each TestCase as

// an Array values

int totalTestCases, eachTestCaseValues;

// takes total number of

// TestCases as integer number

totalTestCases = scanner.nextInt();

// An array is formed as row

// values for total testCases

int[][] arrayMain = new int[totalTestCases][];

// for loop to take input of

// values in each TestCase

for (int i = 0; i < arrayMain.length; i++) {

eachTestCaseValues = scanner.nextInt();
arrayMain[i] = new int[eachTestCaseValues];

for (int j = 0; j < arrayMain[i].length; j++) {

arrayMain[i][j] = scanner.nextInt();

} // All input entry is done.

// Start executing output

// according to condition provided

for (int i = 0; i < arrayMain.length; i++) {

// Initialize total number of

// even & odd numbers to zero

int nEvenNumbers = 0, nOddNumbers = 0;

// prints TestCase number with

// total number of its arguments

System.out.println("TestCase " + i + " with "

+ arrayMain[i].length

+ " values:");

for (int j = 0; j < arrayMain[i].length; j++) {

System.out.print(arrayMain[i][j] + " ");


// even & odd counter updated as

// eligible number is found

if (arrayMain[i][j] % 2 == 0) {

nEvenNumbers++;

else {

nOddNumbers++;

System.out.println();

// Prints total numbers of

// even & odd

System.out.println(

"Total Even numbers: " + nEvenNumbers

+ ", Total Odd numbers: " + nOddNumbers);

// This code is contributed by Udayan Kamble.

Output:
Input:
2
2
1 2
3
1 2 3

Output:
TestCase 0 with 2 values:
1 2
Total Even numbers: 1, Total Odd numbers: 1
TestCase 1 with 3 values:
1 2 3
Total Even numbers: 1, Total Odd numbers: 2

Input:
3
8
1 2 3 4 5 11 55 66
5
100 101 55 35 108
6
3 80 11 2 1 5

Output:
TestCase 0 with 8 values:
1 2 3 4 5 11 55 66
Total Even numbers: 3, Total Odd numbers: 5
TestCase 1 with 5 values:
100 101 55 35 108
Total Even numbers: 2, Total Odd numbers: 3
TestCase 2 with 6 values:
3 80 11 2 1 5
Total Even numbers: 2, Total Odd numbers: 4

You might also like