Commonly Used Java Functions & Real-Life Application Problems
1. Commonly Used Java Functions
toString()
Converts an object to a string representation.
Integer num = 10;
[Link]([Link]()); // Output: "10"
length()
Returns the length of a string or array.
String text = "Hello";
[Link]([Link]()); // Output: 5
charAt(index)
Returns the character at a given index.
String word = "Java";
[Link]([Link](2)); // Output: "v"
substring(start, end)
Extracts part of a string.
String text = "Programming";
[Link]([Link](3, 7)); // Output: "gram"
equals()
Compares two strings for equality.
String str1 = "Hello";
String str2 = "hello";
[Link]([Link](str2)); // Output: false
equalsIgnoreCase()
Compares two strings, ignoring case differences.
[Link]([Link](str2)); // Output: true
toUpperCase() / toLowerCase()
Converts a string to uppercase or lowercase.
[Link]([Link]()); // Output: "HELLO"
replace(oldChar, newChar)
Replaces characters in a string.
String sentence = "I like Java";
[Link]([Link]("Java", "Python")); // Output: "I like Python"
trim()
Removes leading and trailing spaces.
String spacedText = " Hello World ";
[Link]([Link]()); // Output: "Hello World"
split(delimiter)
Splits a string into an array based on a delimiter.
String csv = "apple,banana,grape";
String[] fruits = [Link](",");
[Link](fruits[1]); // Output: "banana"
parseInt() / parseDouble()
Converts a string into an integer or double.
String number = "123";
int num = [Link](number);
[Link](num * 2); // Output: 246
[Link](a, b) / [Link](a, b)
Finds the maximum or minimum of two numbers.
[Link]([Link](10, 20)); // Output: 20
[Link](base, exponent)
Raises a number to a power.
[Link]([Link](2, 3)); // Output: 8.0
[Link]()
Generates a random number between 0.0 and 1.0.
[Link]([Link]());
2. Real-Life Application Problems
Password Strength Checker
A program that checks if a password meets these criteria:
- At least 8 characters long
- Contains an uppercase letter, a lowercase letter, a digit, and a special character (@, #, $,
%, &).
import [Link];
public class PasswordStrengthChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a password: ");
String password = [Link]().trim();
if (isStrongPassword(password)) {
[Link]("Your password is strong.");
} else {
[Link]("Weak password! Follow the rules.");
}
}
public static boolean isStrongPassword(String password) {
if ([Link]() < 8) return false;
boolean hasUpper = false, hasLower = false, hasDigit = false, hasSpecial = false;
String specialCharacters = "@#$%&";
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if ([Link](ch)) hasUpper = true;
if ([Link](ch)) hasLower = true;
if ([Link](ch)) hasDigit = true;
if ([Link]([Link](ch))) hasSpecial = true;
}
return hasUpper && hasLower && hasDigit && hasSpecial;
}
}