[Go to site: main page, start]

0% found this document useful (0 votes)
24 views9 pages

Java Function Programs Overview

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

Java Function Programs Overview

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

//program to print cube of any number by using functions.

class cube

float cube1(float a)

float n=a*a*a;

[Link](“cube of number is “+n);

public static void main(String args[])

float x=3.5;

cube obj=new cube();

obj.cube1(x);

//Write a program to swap numbers by call by value method.

import [Link].*;

class ch6swap

public static void main(String args[])

int n1,n2,temp;

Scanner sc=new Scanner([Link]);

[Link]("Enter two numbers : " );

n1=[Link]();

n2=[Link]();

ch6swap obj=new ch6swap();

[Link](n1,n2);

[Link]("Number n1 is "+n1 + "n2 is "+n2);

void swap(int a,int b)


{

int temp;

temp=a;

a=b;

b=temp;

[Link]("first Number after swapping "+a +"second number"+b);

//Write a program to swap numbers by call by reference method.

import [Link].*;

class ch6swapreference

public static int num1=10,num2=15;

public static void main(String args[])

ch6swapreference obj=new ch6swapreference();

swap(obj);

public static void swap(ch6swapreference obj1)

int temp;

temp=obj1.num1;

obj1.num1=obj1.num2;

obj1.num2=temp;

[Link]("first Number after swapping "+obj1.num1 +"second number"+obj1.num2);

//WAP to apply various operations using nested if.


import [Link].*;

class nestedifeg

public void calculator(int a,int b,char op)

int result=0;

if(op=='+')

result=a+b;

else if(op=='-')

result=a-b;

else if(op=='*')

result=a*b;

else if(op=='/')

result=a/b;

else

[Link]("Wrong Operator");

[Link]("result is : "+result);

public static void main(String args[])

nestedifeg obj=new nestedifeg();

[Link](9,4,'+');

[Link](9,4,'-');

[Link](9,4,'*');

[Link](9,4,'/');

//Write a prog. to find out the number is prime or not by using function call method.

import [Link].*;

public class ch6prime


{

void Prime(int pr)

int i=1,c=0;

while(i<=pr)

if(pr%i==0)

c++;

i++;

if(c==2)

[Link]("It is a Prime Number");

else

[Link]("It is not a prime Number");

public static void main(String args[])

int num;

Scanner in=new Scanner([Link]);

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

num=[Link]();

ch6prime fn=new ch6prime();

[Link](num);
}

//WAP for armstrong & palindrome by function calling method.

import [Link].*;

class ch6arms

public void armstrong(int n)

int c=0,s,r;

s=n;

do

r=n%10;

c=c+r*r*r;

n=n/10;

}while(n!=0);

if(c==s)

[Link]("NUMBER IS ARMSTRONG");

else

[Link]("NUMBER IS NOT AN ARMSTRONG");

void palindrome(int no)

int d,r=0;

int m=no;

while(m>0)

d=m%10;

r=r*10+d;
m=m/10;

if(r==no)

[Link]("It is a Palindrome No.");

else

[Link]("It is not a Palindrome no.");

public static void main(String args[])

int n,ch;

Scanner in=new Scanner([Link]);

[Link]("Enter your choice:- ");

ch=[Link]();

[Link]("ENTER THE VALUE OF N:- ");

n=[Link]();

ch6arms f1=new ch6arms();

switch(ch)

case 1:

[Link](n);

break;

case 2:

[Link](n);

break;

default:

[Link]("Wrong choice");

}
}

//Write a program with the help of function overloading.

import [Link].*;

public class OverloadEg


{
public void compare(int a,int b)
{
if(a>b)
[Link](a);
else
[Link](b);
}
public void compare(char ch1,char ch2)
{
if((int)ch1>(int)ch2)
[Link](ch1);
else
[Link](ch2);
}
public void compare(String s1,String s2)
{
if([Link]()>[Link]())
[Link](s1);
else
[Link](s2);
}
}

//WAP to calculate the area ,perimeter & diagonal of rectangle.

import [Link].*;

class rectangle

public void area(float l,float b)

double area=l*b;

[Link]("Area of rectangle : "+area);

public void perimeter(float l,float b)


{

double perimeter=2*(l+b);

[Link]("Perimeter of rectangle is : "+perimeter);

public void diagonal(float l,float b)

double diag;

diag=[Link]((l*l)+(b*b));

[Link]("Diagonal : "+diag);

public static void main(String args[])

rectangle obj=new rectangle();

Scanner sc=new Scanner([Link]);

[Link]("Enter length & breadth : ");

float l=[Link]();

float b=[Link]();

int ch;

do

[Link]("AREA");

[Link]("PERIMETER");

[Link]("DIAGONAL");

[Link]("Enter ur choice ");

ch=[Link]();

if(ch==1)

[Link](l,b);

else if(ch==2)

[Link](l,b);

else if(ch==3)
[Link](l,b);

else

[Link]("Wring choice");

}while(ch>=1&&ch<=3);

}}

Common questions

Powered by AI

Nested if-else statements can be used to perform arithmetic operations by evaluating conditions and executing corresponding blocks of code. For example, in the 'nestedifeg' class, a method 'calculator' uses nested if-else structures to determine the arithmetic operation based on the character input corresponding to '+', '-', '*', or '/'. It calculates and prints the result for operations on two integer inputs based on the specified operator, handling different scenarios via branching logic . This structuring is helpful for implementing decision-making in programs where user input determines the code execution path.

Recursion could be applied to check for palindrome properties by using a function that calls itself with incrementally reduced parameters. For a string, this approach would involve a recursive method that checks if the first character is equal to the last character and then calls itself with the substring excluding those characters. For numbers, it can convert the number to a string or use modulo operations to isolate and compare digits from the front and back, continuing recursively until the center of the number is reached . This approach highlights the elegance and utility of recursion for problems that naturally fit into a divide-and-conquer strategy, emphasizing problem decomposition.

Function call methods are beneficial for checking if a number is an Armstrong number because they encapsulate processing logic into reusable, isolated units that can be easily tested and applied. For instance, the program uses a 'do-while' loop to iterate over each digit of the number, summing the cubes of its digits, and compares the result to the original number to determine if it is an Armstrong number . By encapsulating this logic in a method, the code is modular and can easily be reused or adapted for different inputs, aiding maintainability and readability. Also, function calls allow parameterization, abstracting repeated logic into single, cohesive components.

The program determines if a number is prime by counting the number of divisors. It initializes a counter 'c', iterating over each number up to 'pr' and incrementing 'c' every time 'pr' is divisible by 'i'. A number is identified as prime if it has exactly two divisors (1 and itself), which is checked at the end of the loop . This method is effective because it employs basic mathematical principles of prime numbers, ensuring accuracy. However, it is not the most efficient for large numbers since its complexity is O(n). Optimizations could include checking divisibility only up to the square root of 'pr' or incorporating the Sieve of Eratosthenes.

User input validation plays a crucial role in ensuring the robustness and reliability of the Java programs provided. For example, in programs like 'ch6prime' and 'ch6arms', users are prompted to enter numbers or choices driving the flow of operations . Effective validation can prevent errors such as invalid format inputs or out-of-bound selections, ensuring the program processes inputs correctly and behaves predictably. Without such checks, the programs are susceptible to runtime errors and logical bugs that could result in improper execution or crashes. Incorporate mechanisms like try-catch blocks and input type verification to manage user interaction reliably.

In Java, call by value means passing a copy of the variable's value to the function, so modifications to the parameter within the function do not affect the original variable. In the 'ch6swap' class program, integer values are swapped inside a method, but the changes do not persist outside the method . On the contrary, call by reference involves passing the reference of the variable, meaning the function can modify the original variable's value. In the 'ch6swapreference' class, a method that swaps values does affect the original values since it's working with their references . This difference impacts how data is manipulated within methods.

Function overloading in Java allows multiple methods to have the same name with different parameters, either by changing the number of parameters or the type of parameters. This enhances code flexibility and readability by enabling the same operation to be performed in different ways depending on input arguments. For instance, the class 'OverloadEg' uses overloading to compare two integers, characters, and strings using a single method name, 'compare,' with appropriate logic based on the parameter types . This abstraction allows developers to define more intuitive and reusable interfaces.

Implementing swap operations using call by reference in Java presents challenges because Java inherently uses pass-by-value for everything, including object references. This means that modifying a reference parameter in a method does not change the original object's reference. To emulate call by reference, one workaround involves encapsulating the variables within objects and passing these objects into methods, as seen in the 'ch6swapreference' class, which utilizes object attributes to swap values . This implies indirect manipulation of data and often involves added complexity in object creation and attribute management. Additionally, it can lead to increased memory usage and processing overhead, complicating straightforward procedural operations.

The use of Math.sqrt in Java enhances the calculation of a rectangle's diagonal by providing a straightforward approach to implement the Pythagorean theorem. In the 'rectangle' class, the method calculates the diagonal by taking the square root of the sum of the squares of the rectangle's length and breadth (l² + b²). Math.sqrt provides a built-in, efficient way to compute square roots, facilitating accurate and concise implementations of functionality that requires this mathematical operation . Using Math.sqrt ensures both precision and adherence to standard mathematical procedures in programming.

Methodical comparisons using overloaded methods in Java present significant advantages such as increased readability, code reuse, and flexibility. The 'OverloadEg' class provides overloaded methods 'compare' for integers, characters, and strings . This abstraction allows different data types to be compared without rewriting the logic for each type, adhering to DRY (Don't Repeat Yourself) principles. Overloading improves code clarity by maintaining a consistent method interface (compare' across different parameter inputs), making the code base easier to understand and maintain. It also enables developers to extend program capabilities with minimal code changes.

You might also like