Day 4 Programming (JAVA) (Methods) (Random class) (Math class ) (Wrappers ) (Arrays List )
Skilled in managing carrier-grade ISP infrastructure, enterprise environments, and server operations. Enthusiastic about optimizing high-performance networks and exploring emerging technologies. Committed to continuous learning and driven to leverage cloud solutions and automation tools to enhance innovation and efficiency.
Methods.
In Java, methods are blocks of code that perform specific operations, such as printing a name or performing calculations e.t.c. Methods can have a return type (e.g., int, String, float, etc.) that specifies the type of value the method will return. Additionally, methods can accept inputs in the form of parameters, allowing you to pass values into the method for processing.
returnType methodName(dataType parameterName) {
// method body
}
What are parameters?
Imagine you have a vending machine. To get a snack, you must input a code for the item you want. That code is like a parameter for the machine—it tells it which snack to give you
Key Points about Parameters
Definition:
- Parameters are variables listed in the method declaration, inside the parentheses
().
- Parameters are variables listed in the method declaration, inside the parentheses
Purpose:
- They allow a method to accept specific data or arguments when it is called.
Syntax:
Parameters are defined in the method signature (declaration).
Each parameter has a data type and a name.
Arguments:
- When you call a method, the actual values you pass to the parameters are called arguments.
di
class Main {
public static void main(String[] args) {
System.out.println("This is a main class");
Example ex = new Example();
ex.greet("Shanon", 25);
}
}
class Example {
// Method that accepts two parameters
public void greet(String name, int age) {
System.out.println("Hello, " + name + "! You are " + age + " years old.");
}
}
In the above code, we have created a separate class called Example. Inside the Example class, we defined a method named greet, which has two parameters: a String (name) and an int (age).
In the main method of the Main class, we created an object of the Example class (ex) and used it to call the greet method. We passed "Shanon" as the name and 25 as the age.
The greet method has a void return type, meaning it does not return any value. Instead, it simply prints a message to the console.
It is important to note that the return type of a method does not depend on the types of its parameters. Methods can accept parameters of different types (as in this example, String and int) and still have any return type, including void. For example, a method could return a value of type int, String, or any other type, regardless of the parameter types.
The return type in a method is the type of value that the method gives back to the caller when it finishes execution. It specifies what kind of data the method will return, such as:
Primitive types like
int,double, orbooleanReference types like
String,Array, or custom objectsOr, if no value is returned, the return type is
void.
class Main {
public static void main(String[] args) {
Example ex = new Example();
System.out.println(ex.add(30, 25));
}
}
class Example {
// Method that accepts two parameters
public int add(int a, int b) {
return a + b; // Returns an integer
}
}
In the above code, we created a method named add in the Example class. This method performs a simple calculation of adding two integers (a and b) and returns the result on the same line using the return keyword. The method has a return type of int, which ensures that the result of the addition is returned as an integer
class Main {
public static void main(String[] args) {
Example ex = new Example();
System.out.println(ex.printingage("Sumeet", 25));
}
}
class Example {
// Method that accepts two parameters
public String printingage(String name, int age) {
return name + " you are " + age + " Years " + " old";
}
}
Random class.
Random class is used to generate random numbers and values. It is part of the java.util package and provides methods to generate random integers, floating-point numbers, boolean values, and more.
Key Points
Purpose: The Random class helps you create random values, such as numbers for a game, simulations, or testing.
How to Use:
First, create a
Randomobject.Then, use its methods to generate random values.
import java.util.Random;
class Main {
public static void main(String[] args) {
Random random = new Random(); // Create a Random object
System.out.println(random.nextInt(100)); // Random integer between 0 and 99
System.out.println(random.nextDouble()); // Random double between 0.0 and 1.0
System.out.println(random.nextBoolean()); // Random true or false
}
}
Common Methods:
nextInt(): Generates a random integer.nextInt(n): Generates a random integer between0(inclusive) andn(exclusive).nextDouble(): Generates a random double between0.0and1.0.nextBoolean(): Generates a random boolean (trueorfalse).
Math class.
Math class is a utility class that provides methods for performing basic mathematical operations, such as trigonometric functions, exponentiation, and rounding. It is part of the java.lang package and is static, meaning you don't need to create an object to use its methods.
Key Points
Purpose: The Math class helps you perform mathematical operations easily without needing to write complex formulas or algorithms.
How to Use:
- You can directly call the methods from the
Mathclass using the class name (no object needed).
- You can directly call the methods from the
class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-5)); // Absolute value: 5
System.out.println(Math.pow(2, 3)); // 2 raised to the power of 3: 8.0
System.out.println(Math.sqrt(16)); // Square root: 4.0
System.out.println(Math.random()); // Random value between 0.0 and 1.0
}
}
Common Methods:
Math.abs(x): Returns the absolute value ofx.Math.pow(x, y): Returnsxraised to the power ofy.Math.sqrt(x): Returns the square root ofx.Math.random(): Returns a randomdoublevalue between0.0and1.0.Math.round(x): Roundsxto the nearest integer.
Wrappers.
Wrapper classes allow primitive data types (like int, char, etc.) to be used as reference data types (objects). This means primitives can be treated like objects, which is useful in scenarios where only objects are allowed, such as in collections (e.g., ArrayList) or for utility methods provided by the wrapper classes. Reference types are objects or classes, which have additional capabilities (e.g., methods or storing in data structures).
Each primitive type has a corresponding wrapper class.
- For example:
int→Integer,char→Character,double→Double.
- For example:
class Main {
public static void main(String[] args) {
int num = 5; // Primitive type
Integer wrappedNum = num; // Wrapped into an Integer object (Auto-boxing)
System.out.println(wrappedNum); // Use as an object
int unboxed = wrappedNum; // Convert back to primitive (Unboxing)
System.out.println(unboxed);
}
}
Common Wrapper Classes:
| Primitive Type | Wrapper Class |
int | Integer |
double | Double |
char | Character |
boolean | Boolean |
float | Float |
long | Long |
byte | Byte |
short | Short |
Why Use Wrappers?
Work with Collections: Collections in Java (like
ArrayList) can only store objects, not primitives.Utility Methods: Wrapper classes provide useful methods for conversion, parsing, and operations (e.g.,
Integer.parseInt()to convert a string to an integer).Autoboxing & Unboxing: Java automatically converts between primitives and wrapper classes, making them easy to use.
ArrayList.
An ArrayList is a resizable array that is part of the java.util package. Unlike a regular array, an ArrayList can grow or shrink dynamically as elements are added or removed. It allows you to store a collection of objects and provides methods to access, modify, and manipulate that collection.
Key Points
Dynamic Size: Unlike arrays, which have a fixed size, an ArrayList can automatically resize as needed when elements are added or removed.
Stores Objects:
ArrayListcan store only objects, not primitive types. However, with autoboxing, you can store wrapper objects likeInteger,Double, etc.Provides Useful Methods:
ArrayListhas many methods likeadd(),get(),remove(), andsize()to manage elements.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> fruits = new ArrayList<>();
// Add elements to the ArrayList
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
// Access elements
System.out.println(fruits.get(0)); // Output: Apple
// Get the size of the ArrayList
System.out.println(fruits.size()); // Output: 3
// Remove an element
fruits.remove("Banana");
// Print updated list
System.out.println(fruits); // Output: [Apple, Mango]
}
}
Common Methods:
add(E e): Adds an element to the end of the list.get(int index): Retrieves an element at the specified index.remove(Object o): Removes the specified element.size(): Returns the number of elements in the list.
Why Use ArrayList?
Dynamic Size: It grows automatically when elements are added.
Convenient Methods: Provides easy-to-use methods for adding, removing, and accessing elements.
Flexibility: You don't need to define the size of the list when creating it, unlike regular arrays.



