java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 9

Method Overloading

With method overloading, multiple methods can have the same name
with different parameters:
int myMethod(int x)
float myMethod(float x)
double myMethod(double x, double y)
static int plusMethodInt(int x, int y) {
return x + y;
}

static double plusMethodDouble(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethodInt(8, 5);
double myNum2 = plusMethodDouble(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
static int plusMethod(int x, int y) {
return x + y;
}

static double plusMethod(double x, double y) {


return x + y;
}

public static void main(String[] args) {


int myNum1 = plusMethod(8, 5);
double myNum2 = plusMethod(4.3, 6.26);
System.out.println("int: " + myNum1);
System.out.println("double: " + myNum2);
}
Array
Create an ArrayList object called cars that will store strings:
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList object
import java.util.ArrayList;
import java.util.Collections; // Import the Collections class
public class Main {
public static void main(String[] args) {ArrayList<Integer> myNumbers = new ArrayList<Integer>();
myNumbers.add(33);
myNumbers.add(15);
myNumbers.add(20);
myNumbers.add(34);
myNumbers.add(8);
myNumbers.add(12);
Collections.sort(myNumbers); // Sort myNumbers
for (int i : myNumbers) {
System.out.println(i);
}
}
}
// Java Program to find maximum in arr[]
// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};

// Method to find maximum in arr[]


static int largest()
{
int i;
// Initialize maximum element
int max = arr[0];
// Traverse array elements from second and
// compare every element with current max
for (i = 1; i < arr.length; i++)
if (arr[i] > max)
max = arr[i];
return max;
}
// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is " + largest());
}
}
// Java Program to find the if the arrays are equal
import java.util.Arrays;
public class CheckArraysEqual {
public static void main(String[] args)
{
// Initializing the first array
int a[] = { 30, 25, 40 };

// Initializing the second array


int b[] = { 30, 25, 40 };
// store the result
// Arrays.equals(a, b) function is used to check
// whether two arrays are equal or not
boolean result = Arrays.equals(a, b);

// condition to check whether the


// result is true or false
if (result == true) {
// Print the result
System.out.println("Two arrays are equal");
}
else {
// Print the result
System.out.println("Two arrays are not equal");
}
}
}

You might also like