0% found this document useful (0 votes)
3 views31 pages

Ajay Computer Project

Uploaded by

sonachavan39
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)
3 views31 pages

Ajay Computer Project

Uploaded by

sonachavan39
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

JAVA PROGRAMS

SPICER HIGHER SECONDARY


SCHOOL

Computer Application
Submitted to:
Submitted by:
Date:

__________ __________
Internal Examiner External Examiner
INDEX
1. If statement
a. if
b. if else
c. if else ladder
2. Loops (using switch statement)
a. for loop - nested loop pattern
b. while loop
c. do while loop
3. Method / Functions
a. Function overloading
4. Constructor
a. parameterized constructor
b. non parameterized constructor
5. Strings
6. Array
a. single dimensional array
b. linear search
c. binary search
d. selection sort
e. double dimensional array
7. Special number
8. Bibliography
1. IF STATEMENT
a. If
DEFINE :

An if statement is a conditional statement in programming that, if true, performs a specified


function or displays information on the screen. Below is a general example of an if statement,
not specific to any particular programming language.

SYNTAX :
if (condition)
{
// block of code to execute if condition is true
}

PROGRAM :

To check if you can Vote or not:


public class AGE
{
public static void main(String[] args)
{
Scanner in=new Scanner([Link]);
[Link]("Enter the Age:.");
int Age=[Link]();
if(Age>=18)
{
[Link]("You are eligible to vote.");
}
else
{
[Link]("You are not eligible to vote.");
}
Sample Input: 21
Sample Output: You are eligible to vote.

[Link] else

DEFINE :
If else statements in Java is also used to control the program flow based on some
condition, only the difference is: it's used to execute some statement code block if the
expression is evaluated to true, otherwise executes else statement code block.

SYNTAX :

if (condition) {
// block of code to execute if condition is true
} else {
// block of code to execute if condition is false
}

PROGRAM:

To check if the Student has Passed or Failed his Exam:

public class Grade


{
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);

[Link]("Enter your Marks: ");

int m = [Link]();

if (m >= 33)
{
[Link]("PASS.");
}
else
{
[Link]("FAIL.");
}
}
}

Sample Input: 17
Sample Output: FAIL
b. If else ladder

DEFINE :
The if-else-if ladder in C programming is used to test a series of conditions sequentially. It
allows for the evaluation of multiple conditions, where each condition is checked in order. If
a condition evaluates to true, the corresponding block of code is executed, and the entire if-
else ladder is terminated.

SYNTAX :
if (condition1) {
// Block of code executed if condition1 is true
} else if (condition2) {
// Block of code executed if condition2 is true
} else if (condition3) {
// Block of code executed if condition3 is true
} else {
// Block of code executed if none of the above conditions are true
}

PROGRAM :
To find largest three number :
public class LargestNumber {
public static void main(String[] args) {
// Create a Scanner object to read user input
Scanner scanner = new Scanner([Link]);

// Ask the user to enter three numbers


[Link]("Enter first number: ");
int num1 = [Link]();

[Link]("Enter second number: ");


int num2 = [Link]();
[Link]("Enter third number: ");
int num3 = [Link]();

// Use if-else ladder to find the largest number


if (num1 >= num2 && num1 >= num3) {
[Link]("The largest number is: " + num1);
} else if (num2 >= num1 && num2 >= num3) {
[Link]("The largest number is: " + num2);
} else {
[Link]("The largest number is: " + num3);
}
}
}

Sample Input: 2,43,12


Sample Output: 43
2. LOOPS

a. for loops

DEFINE :
A for loop is a control flow statement that allows code to be executed repeatedly based on a
given boolean condition.

SYNTAX :
for (initialization; condition; update) {
// block of code to be executed
}

PROGRAM :
To print sum of all Natural Numbers from 0 to n :
public class Natural
{
public static void main(String[] args)
{
Scanner in=new Scanner([Link]);
[Link]("Enter the value of n.");
Int n=[Link]();
// Using a for loop to print sum of all Natural Numbers from 0 to n
For(int a=1;a<=n;a++)
{
int s=s+a;
[Link]("Sum of natural numbers upto”+n+”=”+s.");
}
}
}
Sample Input: 10
Sample Output: 55

[Link] loops

DEFINE :
The while loop in Java is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. It is useful when the number of
iterations is not fixed.

SYNTAX:
while (condition) {
// block of code to be executed as long as condition is true
}

PROGRAM :
To check sum of loop from 1 to 50:
public class SumWhileLoop
{
public static void main(String[] args)
{
int sum = 0; // variable to hold the sum
int i = 1; // initialization
while (i <= 50)
{
sum += i; // add i to sum
i++; // update the loop variable
}
[Link]("The sum of numbers from 1 to 50 is: " + sum);
}
}
Sample Input:
Sample Output:1275

[Link] while loops

DEFINE :

A do-while loop in Java is a control flow statement that executes a block of code at least
once, and then repeatedly executes the block as long as a given condition is true. This is
particularly useful when you need to ensure that the code block runs at least one time
regardless of the condition.

SYNTAX

do {
// block of code to be executed
} while (condition);

PROGRAM:

To print all Even Numbers from 1 to 10:


public class DoWhileExample
{
public static void main(String[] args)
{
int a=0;
[Link]("The Output of Program:.")
do {
a++;
if(a%2!-0){
Continue;
[Link](a);
}
While(a<=10);
}

Sample Input:
Sample Output: The Output of Program:
2
4
6
8
10
3. METHOD / FUNCTION

a. function overloading

DEFINE :
In Java, Method Overloading allows us to define multiple methods with the same
name but different parameters within a class. This difference can be in the number of
parameters, the types of parameters, or the order of those parameters.

SYNTAX :

returnType methodName(parameter1Type parameter1, parameter2Type


parameter2, ...) {
// method body
}

returnType methodName(parameter1Type parameter1, parameter2Type


parameter2, ...) {
// method body
}

PROGRAM :
To check sum of Two Numbers using method:
public class Main {
// create a method
public class add Numbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}
public static void main(String[] args) {
int num1 = 25;
int num2 = 15;
// create an object of Main
Main obj = new Main();
// calling method
int result = [Link](num1, num2);
[Link]("Sum is: " + result);
}
}

Sample Input:
Sample Output: Sum is: 40
[Link]

a. Parameterized constructor

DEFINE :
A constructor is called Parameterized Constructor when it accepts a specific number
of parameters. To initialize data members of a class with distinct values.

SYNTAX :

class ClassName {
// Constructor with parameters
public ClassName(parameterType1 parameter1, parameterType2 parameter2, ...) {
// Initialize instance variables using the parameters
}
}

PROGRAM:

To initialize an object’s attributes with specific values using


parameterized constructor:

// Java Program for Parameterized Constructor


import [Link].*;

class number {

// data members of the class


String name;
int id;

G(String name, int id) {


[Link] = name;
[Link] = id;
}
}

class Num
{
public static void main(String[] args)
{
// This would invoke the parameterized constructor
G1 = new G("Sweta", 68);
[Link]("GName: " + [Link]
+ " and GId: " + [Link]);
}
}

Sample Input:
Sample Output:GName:Sweta
b. Non Parameterized constructor
DEFINE :
The constructors that have an empty parameter are known as non-parameterized
constructors. They are used to initialize the object with default values or certain
specific constants depending upon the user. In case the user does not define
any constructor for the object then Java automatically creates a default constructor to
assign the various members to default values depending upon their type.

SYNTAX :

class ClassName {
// Non-parameterized constructor
public ClassName() {
// Initialize instance variables with default values
}
}

PROGRAM :
To initiate car details using non-parameterized constructor:

class Car
{
String make;
String model;
int year;
public Car()
{// Initializing with default values
make = "Unknown";
model = "Unknown";
year = 0;
}
void display() {
[Link]("Car Details: " + make + " " + model + " " + year);
}
public static void main(String[] args) {
// Creating an object using the non-parameterized constructor
Car myCar = new Car();
[Link](); // Output: Car Details: Unknown Unknown 0
} }
Sample Input:
Sample Output:Unknown Unknown 0

[Link]

DEFINE :

String can also be defined as a sequence of characters, stored in contiguous memory


locations, terminated by a special character called the null character ‘\0’.

SYNTAX :

String myString = "Hello, World!";

PROGRAM :

To Take String Input in Java using Scanner Class:

import [Link];

public class Test {

public static void main(String[] args) {


// create Scanner class object
Scanner scan = new Scanner([Link]);

// read input
[Link]("Enter Name: ");
String name = [Link]();

// display
[Link]("Entered value: " + name);
[Link]();
}
}

Sample Input: Atharv


Sample Output:Atharv

Here is another program, to reversed the string enter by the user:

To Reverse the String ‘Hello World’:

public class Main {


public static void main(String[] args) {
String string = "Hello World";

// create StringBuilder object by using String


StringBuilder sb = new StringBuilder(string);
// find reverse
[Link]();

// convert StringBuilder to String


String reverse = [Link]();

// display both string


[Link]("String: " + string);
[Link]("String after reverse: " + reverse);
}
}

Sample Input : Hello World


Sample Output:dlrow olleh
[Link]

a. Single dimensional array


DEFINE :

A single dimensional array (also known as a one-dimensional array) is a collection of


elements stored at contiguous memory locations. The elements of an array are of the
same data type, and they are indexed with a unique integer. The index, typically
starting from zero, is used to access individual elements.

SYNTAX :

// Declaration and initialization


int[] arr = {10, 20, 30, 40, 50};
// Alternative declaration
int[] arr = new int[5]; // Creates an array of size 5
arr[0] = 10; // Assigning values
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

PROGRAM:

To print the elements of single dimensional Array:


public class singledimensionalStandard
{
public static void main(String args[])
{
int[] a=new int[3];//declaration
a[0]=10;//initialization
a[1]=20;
a[2]=30;
//printing array
[Link]("Single dimensional array elements are");
[Link](a[0]);
[Link](a[1]);
[Link](a[2]);
}
}
Sample Input:
Sample Output:10
20
30

[Link] search

DEFINE :

Linear search, also known as sequential search, is a straightforward


algorithm that sequentially traverses a sorted list until it finds the desired
element. It's commonly employed when dealing with small datasets or
linked lists, offering a simple and intuitive solution for locating the first
element, whether it's a number, string, or any other data type.

SYNTAX :
In java, the syntax for linear search looks like this:
public class LinearSearch {
public static int search(int[] arr, int key) {
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}

public static void main(String[] args) {


int[] numbers = {10, 20, 30, 40, 50};
int key = 30; // Element to search

int index = search(numbers, key);


if (index != -1) {
[Link]("Element found at index: " + index);
} else {
[Link]("Element not found.");
}
}
}
PROGRAM:
write a Java program to perform linear search:
import [Link];

public class linearsearch


{
public static void main(String[] args)
{
int i, num, pos=0;
int[] arr = new int[10];
Scanner s = new Scanner([Link]);

[Link]("Enter 10 Elements: ");


for(i=0; i<10; i++)
arr[i] = [Link]();

[Link]("Enter an Element to Search: ");


num = [Link]();

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


{
if(num==arr[i])
{
pos = i+1;
break;
}
}
if(pos==0)
[Link]("\nThe element not found!");
else
[Link]("\nThe element found at position: " +pos);
}
}

Sample Input: 1,2,3,4,5,6,7,8,9,10 ;4


Sample Output: The element found at position: 5
[Link] search

DEFINE :

Binary search represents a more sophisticated approach, particularly


suitable for large datasets or arrays sorted in ascending or descending
order. By repeatedly dividing the search space in half, binary search
quickly homes in on the target element, making it highly efficient for
locating integers, strings, or any other data types within a sorted list.

SYNTAX :

import [Link];

public class BinarySearchExample {


public static int binarySearch(int[] arr, int key) {
int left = 0, right = [Link] - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if key is present at mid


if (arr[mid] == key) {
return mid;
}

// If key is greater, ignore left half


if (arr[mid] < key) {
left = mid + 1;
} else { // If key is smaller, ignore right half
right = mid - 1;
}
}
return -1; // Return -1 if not found
}

public static void main(String[] args) {


int[] numbers = {10, 20, 30, 40, 50, 60, 70};
int key = 40;

// Binary search requires sorted arrays


[Link](numbers);

int index = binarySearch(numbers, key);


if (index != -1) {
[Link]("Element found at index: " + index);
} else {
[Link]("Element not found.");
}
}
}

PROGRAM:
To perform binary search based on 10 elements:

import [Link];
public class CodesCracker
{
public static void main(String[] args)
{
int size=10, i, search, first, last, middle;
int[] arr = new int[size];
Scanner scan = new Scanner([Link]);
[Link]("Enter 10 Elements (in Ascending): ");
for(i=0; i<size; i++)
{
arr[i] = [Link]();
}
[Link]("Enter an Element to Search: ");
search = [Link]();
first = 0;
last = size-1;
middle = (first+last)/2;
while(first<=last)
{
if(arr[middle]<search)
{
first = middle+1;
}
else if(arr[middle]==search)
{
[Link]("\nThe element is available at Index No." +middle);
break;
}
else
{
last = middle-1;
}
middle = (first+last)/2;
}
if(first>last)
{
[Link]("\nThe element is not available in given array");
}
}
}

Sample Input: 1,2,3,4,5,6,7,8,9,10; 11


Sample Output: The element is not available in given array.
[Link] sort

DEFINE :

Selection Sort is a simple comparison-based sorting algorithm. It works by repeatedly


selecting the smallest (or largest) element from the unsorted portion of the array and
swapping it with the first unsorted element. This process continues until the entire
array is sorted

SYNTAX :

public class SelectionSortExample {


public static void selectionSort(int[] arr) {
int n = [Link];

for (int i = 0; i < n - 1; i++) {


int minIndex = i;

// Find the minimum element in the remaining array


for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}

// Swap the found minimum element with the first element


int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] numbers = {64, 25, 12, 22, 11};

selectionSort(numbers);

// Print sorted array


[Link]("Sorted array:");
for (int num : numbers) {
[Link](num + " ");
}
}
}
PROGRAM:

For selection sort in ascending order:

import [Link];

public class Size


{
public static void main(String[] args)
{
int tot, i, j, count, small, index=0, x;
Scanner scan = new Scanner([Link]);
[Link]("Enter the Size of Array: ");
tot = [Link]();
int[] arr = new int[tot];
[Link]("Enter " +tot+ " Elements for the Array: ");
for(i=0; i<tot; i++)
arr[i] = [Link]();
for(i=0; i<(tot-1); i++)
{
count=0;
small = arr[i];
for(j=(i+1); j<tot; j++)
{
if(small>arr[j])
{
small = arr[j];
count++;
index = j;
}
}
if(count!=0)
{
x = arr[i];
arr[i] = small;
arr[index] = x;
}
}

[Link]("\nThe new sorted array is: ");


for(i=0; i<tot; i++)
[Link](arr[i]+ " ");

}
}
Sample Input:5; 23 5 18 7 1
Sample Output: The new sorted array is: 1 5 7 18 23

[Link] dimensional array

DEFINE :
A two-dimensional array or 2D array is the simplest form of the multidimensional
array. We can visualize a two-dimensional array as one-dimensional arrays stacked
vertically forming a table with ‘m’ rows and ‘n’ columns.

SYNTAX :
// Declaration and initialization
int[][] arr = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Alternative way: Declaring first, then initializing


int[][] arr = new int[3][3]; // Creates a 3x3 array
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
// ... and so on

PROGRAM:
Here is java program for two dimensional program, it will construct a 3*3 matrix :

import [Link];

public class TwoDimensionalArrayExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

// Define array size


int rows = 3, columns = 3;
int[][] matrix = new int[rows][columns];
// User input for filling the array
[Link]("Enter elements for a " + rows + "x" + columns + " matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
[Link]("Element at [" + i + "][" + j + "]: ");
matrix[i][j] = [Link]();
}
}

// Display the matrix


[Link]("\nThe matrix is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
[Link](matrix[i][j] + " ");
}
[Link](); // New line for each row
}

[Link]();
}
}

OUTPUT:

Enter elements for a 3x3 matrix:


Element at [0][0]: 1
Element at [0][1]: 2
Element at [0][2]: 3
Element at [1][0]: 4
Element at [1][1]: 5
Element at [1][2]: 6
Element at [2][0]: 7
Element at [2][1]: 8
Element at [2][2]: 9

The matrix is:


123
456
789

[Link] NUMBERS
DEFINE :
A number is known as Special number when sum of the factorial of digits is equal to
the original number (given number).

SYNTAX :

public class Number {


public static boolean isArmstrong(int num) {
int originalNum = num, sum = 0;
int digits = [Link](num).length();
while (num > 0) {
int digit = num % 10;
sum += [Link](digit, digits); // Raise digit to the power of number of digits
num /= 10;
}
return sum == originalNum;
}

PROGRAM:

A number is said to be Krishnamurthy Number when the sum of factorial of its digits is equal
to the number itself. Example- 145 is a Krishnamurthy Number as 1!+4!+5!=145.

import [Link];

public class SpecialNumber


{
public static void main(String[] args)
{
// TODO code application logic here
int n, num, r,
sumOfFactorial = 0;
Scanner sc = new Scanner([Link]);
[Link]("Enter number=");
n = [Link]();
num = n;
while (num > 0)
{
r = num % 10;
int fact=1;
for(int i=1;i<=r;i++)
{
fact=fact*i;
}
sumOfFactorial = sumOfFactorial+fact;
num = num / 10;
}
if(n==sumOfFactorial)
{
[Link]("Special Number" );
}
else
{
[Link]("Not Special Number" );
}
}
}

OUTPUT:

Enter number=124
Not Special Number.

[Link]
 [Link]
 [Link]
 [Link]
 [Link]
 [Link]

You might also like