Welcome To StudyDoc Ltd.
StudyDoc

Java Program's

1
Hello World
class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
2
User Input
import java.util.Scanner; class Main { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); String userName; System.out.println("Enter username"); userName = myObj.nextLine(); System.out.println("Username is: " + userName); } }
3
Add Two Integers
class Main { public static void main(String[] args) { int first = 10; int second = 20; // add two numbers int sum = first + second; System.out.println(first + " + " + second + " = " + sum); } }
4
Multiply Two Floating-Point Number
public class MultiplyTwoNumbers { public static void main(String[] args) { float first = 1.5f; float second = 2.0f; float product = first * second; System.out.println("The product is: " + product); } }
5
ASCII value of a character
public class AsciiValue { public static void main(String[] args) { char ch = 'a'; int ascii = ch; // You can also cast char to int int castAscii = (int) ch; System.out.println("The ASCII value of " + ch + " is: " + ascii); System.out.println("The ASCII value of " + ch + " is: " + castAscii); } }
6
Compute Quotient and Remainder
public class QuotientRemainder { public static void main(String[] args) { int dividend = 25, divisor = 4; int quotient = dividend / divisor; int remainder = dividend % divisor; System.out.println("Quotient = " + quotient); System.out.println("Remainder = " + remainder); } }
7
Swap two numbers
Swap two numbers using temporary variable public class SwapNumbers { public static void main(String[] args) { float first = 1.20f, second = 2.45f; System.out.println("--Before swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); // Value of first is assigned to temporary float temporary = first; // Value of second is assigned to first first = second; // Value of temporary (which contains the initial value of first) is assigned to second second = temporary; System.out.println("--After swap--"); System.out.println("First number = " + first); System.out.println("Second number = " + second); } }
8
even or odd
Check whether a number is even or odd using if...else statement import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { Scanner reader = new Scanner(System.in); System.out.print("Enter a number: "); int num = reader.nextInt(); if(num % 2 == 0) System.out.println(num + " is even"); else System.out.println(num + " is odd"); } }
9
alphabet is vowel or consonant
Check whether an alphabet is vowel or consonant using if..else statement public class VowelConsonant { public static void main(String[] args) { char ch = 'i'; if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ) System.out.println(ch + " is vowel"); else System.out.println(ch + " is consonant"); } }
10
Largest Among three numbers
Find Largest Among three numbers using if..else statement public class Largest { public static void main(String[] args) { double n1 = -4.5, n2 = 3.9, n3 = 2.5; if( n1 >= n2 && n1 >= n3) System.out.println(n1 + " is the largest number."); else if (n2 >= n1 && n2 >= n3) System.out.println(n2 + " is the largest number."); else System.out.println(n3 + " is the largest number."); } }
11
Roots of a Quadratic Equation
public class Main { public static void main(String[] args) { // value a, b, and c double a = 2.3, b = 4, c = 5.6; double root1, root2; // calculate the determinant (b2 - 4ac) double determinant = b * b - 4 * a * c; // check if determinant is greater than 0 if (determinant > 0) { // two real and distinct roots root1 = (-b + Math.sqrt(determinant)) / (2 * a); root2 = (-b - Math.sqrt(determinant)) / (2 * a); System.out.format("root1 = %.2f and root2 = %.2f", root1, root2); } // check if determinant is equal to 0 else if (determinant == 0) { // two real and equal roots // determinant is equal to 0 // so -b + 0 == -b root1 = root2 = -b / (2 * a); System.out.format("root1 = root2 = %.2f;", root1); } // if determinant is less than zero else { // roots are complex number and distinct double real = -b / (2 * a); double imaginary = Math.sqrt(-determinant) / (2 * a); System.out.format("root1 = %.2f+%.2fi", real, imaginary); System.out.format("\nroot2 = %.2f-%.2fi", real, imaginary); } } }
12
Check a Leap Year
public class Main { public static void main(String[] args) { // year to be checked int year = 1900; boolean leap = false; // if the year is divided by 4 if (year % 4 == 0) { // if the year is century if (year % 100 == 0) { // if year is divided by 400 // then it is a leap year if (year % 400 == 0) leap = true; else leap = false; } // if the year is not century else leap = true; } else leap = false; if (leap) System.out.println(year + " is a leap year."); else System.out.println(year + " is not a leap year."); } }
13
Positive or Negative
Check if a Number is Positive or Negative using if else public class PositiveNegative { public static void main(String[] args) { double number = 12.3; // true if number is less than 0 if (number < 0.0) System.out.println(number + " is a negative number."); // true if number is greater than 0 else if ( number > 0.0) System.out.println(number + " is a positive number."); // if both test expression is evaluated to false else System.out.println(number + " is 0."); } }
14
Check Alphabet
Java Program to Check Alphabet using if else public class Alphabet { public static void main(String[] args) { char c = '*'; if( (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) System.out.println(c + " is an alphabet."); else System.out.println(c + " is not an alphabet."); } }
15
Sum of Natural Numbers
Sum of Natural Numbers using for loop public class SumNatural { public static void main(String[] args) { int num = 100, sum = 0; for(int i = 1; i <= num; ++i) { // sum = sum + i; sum += i; } System.out.println("Sum = " + sum); } }
16
Factorial of a number
Find Factorial of a number using for loop public class Factorial { public static void main(String[] args) { int num = 10; long factorial = 1; for(int i = 1; i <= num; ++i) { // factorial = factorial * i; factorial *= i; } System.out.printf("Factorial of %d = %d", num, factorial); } }
17
Multiplication Table
Generate Multiplication Table using for loop public class MultiplicationTable { public static void main(String[] args) { int num = 5; for(int i = 1; i <= 10; ++i) { System.out.printf("%d * %d = %d \n", num, i, num * i); } } }
18
Fibonacci Series
class Main { public static void main(String[] args) { int n = 10, firstTerm = 0, secondTerm = 1; System.out.println("Fibonacci Series till " + n + " terms:"); for (int i = 1; i <= n; ++i) { System.out.print(firstTerm + ", "); // compute the next term int nextTerm = firstTerm + secondTerm; firstTerm = secondTerm; secondTerm = nextTerm; } } }
19
Find GCD of two numbers
Find GCD of two numbers using for loop and if statement class Main { public static void main(String[] args) { // find GCD between n1 and n2 int n1 = 81, n2 = 153; // initially set to gcd int gcd = 1; for (int i = 1; i <= n1 && i <= n2; ++i) { // check if i perfectly divides both n1 and n2 if (n1 % i == 0 && n2 % i == 0) gcd = i; } System.out.println("GCD of " + n1 +" and " + n2 + " is " + gcd); } }
20
LCM
LCM using while Loop and if Statement public class Main { public static void main(String[] args) { int n1 = 72, n2 = 120, lcm; // maximum number between n1 and n2 is stored in lcm lcm = (n1 > n2) ? n1 : n2; // Always true while(true) { if( lcm % n1 == 0 && lcm % n2 == 0 ) { System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm); break; } ++lcm; } } }
21
Display uppercased alphabet
Display uppercased alphabet using for loop class Main { public static void main(String[] args) { char c; for(c = 'A'; c <= 'Z'; ++c) System.out.print(c + " "); } }
22
Count Number of Digits
Count Number of Digits in an Integer using while loop public class Main { public static void main(String[] args) { int count = 0, num = 0003452; while (num != 0) { // num = num/10 num /= 10; ++count; } System.out.println("Number of digits: " + count); }
23
Reverse a Number
Reverse a Number using a while loop in Java class Main { public static void main(String[] args) { int num = 1234, reversed = 0; System.out.println("Original Number: " + num); // run loop until num becomes 0 while(num != 0) { // get last digit from num int digit = num % 10; reversed = reversed * 10 + digit; // remove the last digit from num num /= 10; } System.out.println("Reversed Number: " + reversed); } }
24
Calculate power of a number
class Main { public static void main(String[] args) { int base = 3, exponent = 4; long result = 1; while (exponent != 0) { result *= base; --exponent; } System.out.println("Answer = " + result); } }
25
Palindrome String
class Main { public static void main(String[] args) { String str = "Radar", reverseStr = ""; int strLength = str.length(); for (int i = (strLength - 1); i >=0; --i) { reverseStr = reverseStr + str.charAt(i); } if (str.toLowerCase().equals(reverseStr.toLowerCase())) { System.out.println(str + " is a Palindrome String."); } else { System.out.println(str + " is not a Palindrome String."); } } }
26
prime number
public class Main { public static void main(String[] args) { int num = 29; boolean flag = false; for (int i = 2; i <= num / 2; ++i) { // condition for nonprime number if (num % i == 0) { flag = true; break; } } if (!flag) System.out.println(num + " is a prime number."); else System.out.println(num + " is not a prime number."); } }
27
Prime Numbers Between two Intervals
Display Prime Numbers Between two Intervals public class Prime { public static void main(String[] args) { int low = 20, high = 50; while (low < high) { boolean flag = false; for(int i = 2; i <= low/2; ++i) { // condition for nonprime number if(low % i == 0) { flag = true; break; } } if (!flag && low != 0 && low != 1) System.out.print(low + " "); ++low; } } }
28
Armstrong Number for 3 digit number
Check Armstrong Number for 3 digit number public class Armstrong { public static void main(String[] args) { int number = 371, originalNumber, remainder, result = 0; originalNumber = number; while (originalNumber != 0) { remainder = originalNumber % 10; result += Math.pow(remainder, 3); originalNumber /= 10; } if(result == number) System.out.println(number + " is an Armstrong number."); else System.out.println(number + " is not an Armstrong number."); } }
29
Armstrong Numbers Between Two Integers
class Main { public static void main(String[] args) { int low = 999, high = 99999; for(int number = low + 1; number < high; ++number) { int digits = 0; int result = 0; int originalNumber = number; // number of digits calculation while (originalNumber != 0) { originalNumber /= 10; ++digits; } originalNumber = number; // result contains sum of nth power of its digits while (originalNumber != 0) { int remainder = originalNumber % 10; result += Math.pow(remainder, digits); originalNumber /= 10; } if (result == number) { System.out.print(number + " "); } }
30
Prime Numbers Between Two Integers
public class Prime { public static void main(String[] args) { int low = 20, high = 50; while (low < high) { if(checkPrimeNumber(low)) System.out.print(low + " "); ++low; } } public static boolean checkPrimeNumber(int num) { boolean flag = true; for(int i = 2; i <= num/2; ++i) { if(num % i == 0) { flag = false; break; } } return flag; } }
31
Armstrong Numbers Between Two Integers
public class Armstrong { public static void main(String[] args) { int low = 999, high = 99999; for(int number = low + 1; number < high; ++number) { if (checkArmstrong(number)) System.out.print(number + " "); } } public static boolean checkArmstrong(int num) { int digits = 0; int result = 0; int originalNumber = num; // number of digits calculation while (originalNumber != 0) { originalNumber /= 10; ++digits; } originalNumber = num; // result contains sum of nth power of its digits while (originalNumber != 0) { int remainder = originalNumber % 10; result += Math.pow(remainder, digits); originalNumber /= 10; } if (result == num) return true; return false; } }
32
number as Sum of Two Prime Numbers
public class Main { public static void main(String[] args) { int number = 34; boolean flag = false; for (int i = 2; i <= number / 2; ++i) { // condition for i to be a prime number if (checkPrime(i)) { // condition for n-i to be a prime number if (checkPrime(number - i)) { // n = primeNumber1 + primeNumber2 System.out.printf("%d = %d + %d\n", number, i, number - i); flag = true; } } } if (!flag) System.out.println(number + " cannot be expressed as the sum of two prime numbers."); } // Function to check prime number static boolean checkPrime(int num) { boolean isPrime = true; for (int i = 2; i <= num / 2; ++i) { if (num % i == 0) { isPrime = false; break; } } return isPrime; } }
33
Sum of Natural Numbers
Sum of Natural Numbers Using Recursion public class AddNumbers { public static void main(String[] args) { int number = 20; int sum = addNumbers(number); System.out.println("Sum = " + sum); } public static int addNumbers(int num) { if (num != 0) return num + addNumbers(num - 1); else return num; } }
34
Factorial of a Number Using Recursion
Factorial of a Number Using Recursion public class Factorial { public static void main(String[] args) { int num = 6; long factorial = multiplyNumbers(num); System.out.println("Factorial of " + num + " = " + factorial); } public static long multiplyNumbers(int num) { if (num >= 1) return num * multiplyNumbers(num - 1); else return 1; } }
35
GCD of Two Numbers
GCD of Two Numbers using Recursion public class GCD { public static void main(String[] args) { int n1 = 366, n2 = 60; int hcf = hcf(n1, n2); System.out.printf("G.C.D of %d and %d is %d.", n1, n2, hcf); } public static int hcf(int n1, int n2) { if (n2 != 0) return hcf(n2, n1 % n2); else return n1; } }
36
Binary to Decimal
class Main { public static void main(String[] args) { // binary number long num = 110110111; // call method by passing the binary number int decimal = convertBinaryToDecimal(num); System.out.println("Binary to Decimal"); System.out.println(num + " = " + decimal); } public static int convertBinaryToDecimal(long num) { int decimalNumber = 0, i = 0; long remainder; while (num != 0) { remainder = num % 10; num /= 10; decimalNumber += remainder * Math.pow(2, i); ++i; } return decimalNumber; } }
37
Convert Decimal to Octal
Program to Convert Decimal to Octal public class DecimalOctal { public static void main(String[] args) { int decimal = 78; int octal = convertDecimalToOctal(decimal); System.out.printf("%d in decimal = %d in octal", decimal, octal); } public static int convertDecimalToOctal(int decimal) { int octalNumber = 0, i = 1; while (decimal != 0) { octalNumber += (decimal % 8) * i; decimal /= 8; i *= 10; } return octalNumber; } }
38
reversed sentence
public class Reverse { public static void main(String[] args) { String sentence = "Go work"; String reversed = reverse(sentence); System.out.println("The reversed sentence is: " + reversed); } public static String reverse(String sentence) { if (sentence.isEmpty()) return sentence; return reverse(sentence.substring(1)) + sentence.charAt(0); } }
39
calculate power using recursion
Program to calculate power using recursion class Power { public static void main(String[] args) { int base = 3, powerRaised = 4; int result = power(base, powerRaised); System.out.println(base + "^" + powerRaised + "=" + result); } public static int power(int base, int powerRaised) { if (powerRaised != 0) { // recursive call to power() return (base * power(base, powerRaised - 1)); } else { return 1; } } }
40
Calculate Average
Program to Calculate Average Using Arrays public class Average { public static void main(String[] args) { double[] numArray = { 45.3, 67.5, -45.6, 20.34, 33.0, 45.6 }; double sum = 0.0; for (double num: numArray) { sum += num; } double average = sum / numArray.length; System.out.format("The average is: %.2f", average); } }
41
largest element in an array
Find the largest element in an array public class Largest { public static void main(String[] args) { double[] numArray = { 23.4, -34.5, 50.0, 33.5, 55.5, 43.7, 5.7, -66.5 }; double largest = numArray[0]; for (double num: numArray) { if(largest < num) largest = num; } System.out.format("Largest element = %.2f", largest); } }
42
Calculate Standard Deviation
Program to Calculate Standard Deviation public class StandardDeviation { public static void main(String[] args) { double[] numArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; double SD = calculateSD(numArray); System.out.format("Standard Deviation = %.6f", SD); } public static double calculateSD(double numArray[]) { double sum = 0.0, standardDeviation = 0.0; int length = numArray.length; for(double num : numArray) { sum += num; } double mean = sum/length; for(double num: numArray) { standardDeviation += Math.pow(num - mean, 2); } return Math.sqrt(standardDeviation/length); } }
43
Add Two Matrices
Program to Add Two Matrices public class AddMatrices { public static void main(String[] args) { int rows = 2, columns = 3; int[][] firstMatrix = { {2, 3, 4}, {5, 2, 3} }; int[][] secondMatrix = { {-4, 5, 3}, {5, 6, 3} }; // Adding Two matrices int[][] sum = new int[rows][columns]; for(int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j]; } } // Displaying the result System.out.println("Sum of two matrices is: "); for(int[] row : sum) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
44
Multiply Two Matrices
Program to Multiply Two Matrices public class MultiplyMatrices { public static void main(String[] args) { int r1 = 2, c1 = 3; int r2 = 3, c2 = 2; int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} }; int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} }; // Mutliplying Two matrices int[][] product = new int[r1][c2]; for(int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; } } } // Displaying the result System.out.println("Multiplication of two matrices is: "); for(int[] row : product) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
45
Multiply Two Matrices using a Function
Program to Multiply Two Matrices using a Function public class MultiplyMatrices { public static void main(String[] args) { int r1 = 2, c1 = 3; int r2 = 3, c2 = 2; int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} }; int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} }; // Mutliplying Two matrices int[][] product = multiplyMatrices(firstMatrix, secondMatrix, r1, c1, c2); // Displaying the result displayProduct(product); } public static int[][] multiplyMatrices(int[][] firstMatrix, int[][] secondMatrix, int r1, int c1, int c2) { int[][] product = new int[r1][c2]; for(int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { for (int k = 0; k < c1; k++) { product[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; } } } return product; } public static void displayProduct(int[][] product) { System.out.println("Product of two matrices is: "); for(int[] row : product) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
46
Transpose of a Matrix
Program to Find Transpose of a Matrix public class Transpose { public static void main(String[] args) { int row = 2, column = 3; int[][] matrix = { {2, 3, 4}, {5, 6, 4} }; // Display current matrix display(matrix); // Transpose the matrix int[][] transpose = new int[column][row]; for(int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { transpose[j][i] = matrix[i][j]; } } // Display transposed matrix display(transpose); } public static void display(int[][] matrix) { System.out.println("The matrix is: "); for(int[] row : matrix) { for (int column : row) { System.out.print(column + " "); } System.out.println(); } } }
47
Print an Array
Print an Array using For loop public class Array { public static void main(String[] args) { int[] array = {1, 2, 3, 4, 5}; for (int element: array) { System.out.println(element); } } }
48
Frequency of Character
Find Frequency of Character public class Frequency { public static void main(String[] args) { String str = "This website is awesome."; char ch = 'e'; int frequency = 0; for(int i = 0; i < str.length(); i++) { if(ch == str.charAt(i)) { ++frequency; } } System.out.println("Frequency of " + ch + " = " + frequency); } }
49
count vowels, consonants, digits, and spaces
class Main { public static void main(String[] args) { String line = "This website is aw3som3."; int vowels = 0, consonants = 0, digits = 0, spaces = 0; line = line.toLowerCase(); for (int i = 0; i < line.length(); ++i) { char ch = line.charAt(i); // check if character is any of a, e, i, o, u if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { ++vowels; } // check if character is in between a to z else if ((ch >= 'a' && ch <= 'z')) { ++consonants; } // check if character is in between 0 to 9 else if (ch >= '0' && ch <= '9') { ++digits; } // check if character is a white space else if (ch == ' ') { ++spaces; } } System.out.println("Vowels: " + vowels); System.out.println("Consonants: " + consonants); System.out.println("Digits: " + digits); System.out.println("White spaces: " + spaces); } }
50
Sort Strings in Dictionary Order
class Main { public static void main(String[] args) { String[] words = { "Ruby", "C", "Python", "Java" }; for(int i = 0; i < 3; ++i) { for (int j = i + 1; j < 4; ++j) { if (words[i].compareTo(words[j]) > 0) { // swap words[i] with words[j[ String temp = words[i]; words[i] = words[j]; words[j] = temp; } } } System.out.println("In lexicographical order:"); for(int i = 0; i < 4; i++) { System.out.println(words[i]); } } }
51
Add Two Complex Numbers
public class Complex { double real; double imag; public Complex(double real, double imag) { this.real = real; this.imag = imag; } public static void main(String[] args) { Complex n1 = new Complex(2.3, 4.5), n2 = new Complex(3.4, 5.0), temp; temp = add(n1, n2); System.out.printf("Sum = %.1f + %.1fi", temp.real, temp.imag); } public static Complex add(Complex n1, Complex n2) { Complex temp = new Complex(0.0, 0.0); temp.real = n1.real + n2.real; temp.imag = n1.imag + n2.imag; return(temp); }
52
Calculate Difference Between Two Time Periods
public class Time { int seconds; int minutes; int hours; public Time(int hours, int minutes, int seconds) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } public static void main(String[] args) { // create objects of Time class Time start = new Time(8, 12, 15); Time stop = new Time(12, 34, 55); Time diff; // call difference method diff = difference(start, stop); System.out.printf("TIME DIFFERENCE: %d:%d:%d - ", start.hours, start.minutes, start.seconds); System.out.printf("%d:%d:%d ", stop.hours, stop.minutes, stop.seconds); System.out.printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds); } public static Time difference(Time start, Time stop) { Time diff = new Time(0, 0, 0); // if start second is greater // convert minute of stop into seconds // and add seconds to stop second if(start.seconds > stop.seconds){ --stop.minutes; stop.seconds += 60; } diff.seconds = stop.seconds - start.seconds; // if start minute is greater // convert stop hour into minutes // and add minutes to stop minutes if(start.minutes > stop.minutes){ --stop.hours; stop.minutes += 60; } diff.minutes = stop.minutes - start.minutes; diff.hours = stop.hours - start.hours; // return the difference time return(diff); } }
53
class of an object using getClass()
class Test1 { // first class } class Test2 { // second class } class Main { public static void main(String[] args) { // create objects Test1 obj1 = new Test1(); Test2 obj2 = new Test2(); // get the class of the object obj1 System.out.print("The class of obj1 is: "); System.out.println(obj1.getClass()); // get the class of the object obj2 System.out.print("The class of obj2 is: "); System.out.println(obj2.getClass()); } }
54
create an enum class
Java program to create an enum class enum Size{ // enum constants SMALL, MEDIUM, LARGE, EXTRALARGE; public String getSize() { // this will refer to the object SMALL switch(this) { case SMALL: return "small"; case MEDIUM: return "medium"; case LARGE: return "large"; case EXTRALARGE: return "extra large"; default: return null; } } public static void main(String[] args) { // call the method getSize() // using the object SMALL System.out.println("The size of Pizza I get is " + Size.SMALL.getSize()); // call the method getSize() // using the object LARGE System.out.println("The size of Pizza I want is " + Size.LARGE.getSize()); } }
55
print the object
class Test { } class Main { public static void main(String[] args) { // create an object of the Test class Test obj = new Test(); // print the object System.out.println(obj); } }
56
create custom checked exception
Java program to create custom checked exception import java.util.ArrayList; import java.util.Arrays; // create a checked exception class class CustomException extends Exception { public CustomException(String message) { // call the constructor of Exception class super(message); } } class Main { ArrayList languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript")); // check the exception condition public void checkLanguage(String language) throws CustomException { // throw exception if language already present in ArrayList if(languages.contains(language)) { throw new CustomException(language + " already exists"); } else { // insert language to ArrayList languages.add(language); System.out.println(language + " is added to the ArrayList"); } } public static void main(String[] args) { // create object of Main class Main obj = new Main(); // exception is handled using try...catch try { obj.checkLanguage("Swift"); obj.checkLanguage("Java"); } catch(CustomException e) { System.out.println("[" + e + "] Exception Occured"); } } }
57
create immutable class
// class is declared final final class Immutable { // private class members private String name; private int date; Immutable(String name, int date) { // class members are initialized using constructor this.name = name; this.date = date; } // getter method returns the copy of class members public String getName() { return name; } public int getDate() { return date; } } class Main { public static void main(String[] args) { // create object of Immutable Immutable obj = new Immutable("Programiz", 2011); System.out.println("Name: " + obj.getName()); System.out.println("Date: " + obj.getDate()); } }
58
Convert Array to Set
import java.util.*; public class ArraySet { public static void main(String[] args) { String[] array = {"a", "b", "c"}; Set set = new HashSet<>(Arrays.asList(array)); System.out.println("Set: " + set); } }
59
Sort a map by values
import java.util.*; import java.util.Map.Entry; class Main { public static void main(String[] args) { // create a map and store elements to it LinkedHashMap capitals = new LinkedHashMap(); capitals.put("Nepal", "Kathmandu"); capitals.put("India", "New Delhi"); capitals.put("United States", "Washington"); capitals.put("England", "London"); capitals.put("Australia", "Canberra"); // call the sortMap() method to sort the map Map result = sortMap(capitals); for (Map.Entry entry : result.entrySet()) { System.out.print("Key: " + entry.getKey()); System.out.println(" Value: " + entry.getValue()); } } public static LinkedHashMap sortMap(LinkedHashMap map) { List > capitalList = new LinkedList<>(map.entrySet()); // call the sort() method of Collections Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue())); // create a new map LinkedHashMap result = new LinkedHashMap(); // get entry from list to the map for (Map.Entry entry : capitalList) { result.put(entry.getKey(), entry.getValue()); } return result; } }
60
Sort ArrayList of Custom Objects By Property
import java.util.*; public class CustomObject { private String customProperty; public CustomObject(String property) { this.customProperty = property; } public String getCustomProperty() { return this.customProperty; } public static void main(String[] args) { ArrayList list = new ArrayList<>(); list.add(new CustomObject("Z")); list.add(new CustomObject("A")); list.add(new CustomObject("B")); list.add(new CustomObject("X")); list.add(new CustomObject("Aa")); list.sort((o1, o2) -> o1.getCustomProperty().compareTo(o2.getCustomProperty())); for (CustomObject obj : list) { System.out.println(obj.getCustomProperty()); } } }
61
implement LinkedList
class LinkedList { // create an object of Node class // represent the head of the linked list Node head; // static inner class static class Node { int value; // connect each node to next node Node next; Node(int d) { value = d; next = null; } } public static void main(String[] args) { // create an object of LinkedList LinkedList linkedList = new LinkedList(); // assign values to each linked list node linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); // connect each node of linked list to next node linkedList.head.next = second; second.next = third; // printing node-value System.out.print("LinkedList: "); while (linkedList.head != null) { System.out.print(linkedList.head.value + " "); linkedList.head = linkedList.head.next; } } }
62
implement Stack
// Stack implementation in Java class Stack { // store elements of stack private int arr[]; // represent top of stack private int top; // total capacity of the stack private int capacity; // Creating a stack Stack(int size) { // initialize the array // initialize the stack variables arr = new int[size]; capacity = size; top = -1; } // push elements to the top of stack public void push(int x) { if (isFull()) { System.out.println("Stack OverFlow"); // terminates the program System.exit(1); } // insert element on top of stack System.out.println("Inserting " + x); arr[++top] = x; } // pop elements from top of stack public int pop() { // if stack is empty // no element to pop if (isEmpty()) { System.out.println("STACK EMPTY"); // terminates the program System.exit(1); } // pop element from top of stack return arr[top--]; } // return size of the stack public int getSize() { return top + 1; } // check if the stack is empty public Boolean isEmpty() { return top == -1; } // check if the stack is full public Boolean isFull() { return top == capacity - 1; } // display elements of stack public void printStack() { for (int i = 0; i <= top; i++) { System.out.print(arr[i] + ", "); } } public static void main(String[] args) { Stack stack = new Stack(5); stack.push(1); stack.push(2); stack.push(3); System.out.print("Stack: "); stack.printStack(); // remove element from stack stack.pop(); System.out.println("\nAfter popping out"); stack.printStack(); } }
63
call one constructor from another
class Main { int sum; // first constructor Main() { // calling the second constructor this(5, 2); } // second constructor Main(int arg1, int arg2) { // add two value this.sum = arg1 + arg2; } void display() { System.out.println("Sum is: " + sum); } // main class public static void main(String[] args) { // call the first constructor Main obj = new Main(); // call display method obj.display(); } }
64
lambda expression
import java.util.ArrayList; class Main { public static void main(String[] args) { // create an ArrayList ArrayList languages = new ArrayList<>(); // add elements to the ArrayList languages.add("java"); languages.add("swift"); languages.add("python"); System.out.println("ArrayList: " + languages); // pass lambda expression as parameter to replaceAll() method languages.replaceAll(e -> e.toUpperCase()); System.out.println("Updated ArrayList: " + languages); } }
65
calculate the method execution time
class Main { // create a method public void display() { System.out.println("Calculating Method execution time:"); } // main method public static void main(String[] args) { // create an object of the Main class Main obj = new Main(); // get the start time long start = System.nanoTime(); // call the method obj.display(); // get the end time long end = System.nanoTime(); // execution time long execution = end - start; System.out.println("Execution time: " + execution + " nanoseconds"); } }
66
Load a Text File as InputStream
import java.io.InputStream; import java.io.FileInputStream; public class Main { public static void main(String args[]) { try { // file input.txt is loaded as input stream // input.txt file contains: // This is a content of the file input.txt InputStream input = new FileInputStream("input.txt"); System.out.println("Data in the file: "); // Reads the first byte int i = input.read(); while(i != -1) { System.out.print((char)i); // Reads next byte from the file i = input.read(); } input.close(); } catch(Exception e) { e.getStackTrace(); } } }