functions in java example

Ben 66 Published: 07/06/2024

functions in java example

I apologize for the misunderstanding earlier. Here's an example of using Java to create a simple calculator program that can perform addition, subtraction, multiplication, and division operations.

import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

while (true) {

System.out.println("Enter operation (+, -, *, /):");

String operation = scanner.next();

switch (operation) {

case "+":

additionOperation();

break;

case "-":

subtractionOperation();

break;

case "*":

multiplicationOperation();

break;

case "/":

divisionOperation();

break;

default:

System.out.println("Invalid operation. Please try again.");

}

}

}

public static void additionOperation() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter first number:");

double num1 = scanner.nextDouble();

System.out.println("Enter second number:");

double num2 = scanner.nextDouble();

double result = num1 + num2;

System.out.println("The sum is: " + result);

}

public static void subtractionOperation() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter first number:");

double num1 = scanner.nextDouble();

System.out.println("Enter second number:");

double num2 = scanner.nextDouble();

double result = num1 - num2;

System.out.println("The difference is: " + result);

}

public static void multiplicationOperation() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter first number:");

double num1 = scanner.nextDouble();

System.out.println("Enter second number:");

double num2 = scanner.nextDouble();

double result = num1 * num2;

System.out.println("The product is: " + result);

}

public static void divisionOperation() {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter first number:");

double num1 = scanner.nextDouble();

System.out.println("Enter second number:");

double num2 = scanner.nextDouble();

if (num2 != 0) {

double result = num1 / num2;

System.out.println("The quotient is: " + result);

} else {

System.out.println("Error! Division by zero is not allowed.");

}

}

}

In this example, we have a main method that repeatedly prompts the user to enter an operation (+, -, *, /). Based on the entered operation, it calls the corresponding method (additionOperation(), subtractionOperation(), multiplicationOperation(), or divisionOperation()).

Each of these methods prompts the user to enter two numbers and then performs the specified operation using those numbers. The result is displayed to the user.

For the division operation, we also include a check to make sure that the second number is not zero before performing the division. This is because dividing by zero is undefined in mathematics and would cause an error in our program.

Note that this is a simple example and does not include any form of error handling or exception checking. In a real-world application, you might want to add more robust error handling and possibly handle invalid inputs differently.

java functions list

Here are some common Java functions that you can use:

String Functions:

toLowerCase(): converts a string to lowercase. toUpperCase(): converts a string to uppercase. concat(String s): concatenates a string with another string. substring(int beginIndex, int endIndex): returns a subset of characters from the original string. indexOf(String str): finds the index of the first occurrence of a specified value within an array. lastIndexOf(String str): finds the index of the last occurrence of a specified value within an array. split(String regex): splits this string around matches of the given regular expression. trim(): removes whitespace from both ends of a string. replace(String oldPattern, String newPattern): replaces all occurrences of the first argument with the second.

Math Functions:

abs(int a): returns the absolute value of an integer. ceil(double a): returns the smallest integer that is greater than or equal to the input value. floor(double a): returns the largest integer that is less than or equal to the input value. max(double a, double b): returns the maximum value of two numbers. min(double a, double b): returns the minimum value of two numbers. pow(double a, double b): calculates the power of one number raised to another. random(): returns a pseudorandom number in the range 0.0 through 1.0. sqrt(double a): calculates the square root of a number.

Array Functions:

length(): returns the size of an array. get(int index): returns the value at the specified position in an array. set(int index, int value): assigns a new value to the element at the specified position. equals(Object obj): checks whether two arrays are equal.

Date and Time Functions:

format(String format): formats a date according to a given pattern. parse(String text): parses a string into a Date object. getTime(): returns the current system time in milliseconds. sleep(long milliseconds): causes the calling thread to sleep for a specified period of time.

File and Directory Functions:

listFiles(): returns an array of files that can be found within this directory. mkdir(String dir): creates a new directory with the specified name. delete(): deletes the file or directory denoted by this abstract path name. exists(): checks whether a file or directory exists.

Miscellaneous Functions:

className(): returns the name of the class of which an invocation is part. getClass(): returns the runtime class of this Java object. notify(): resets the lock on this object and test whether it should be notified. wait(long timeout): causes the current thread to wait until either another thread invades the Object's critical section or a specified amount of real time has elapsed.

This is not an exhaustive list, but it gives you an idea of the types of functions available in Java.