Notes

My latest writings


Tuesday, September 20, 2016

Top 10 Computer Programming Languages in 2016

1. Java

  • Learning Curve: Medium
  • Java is one of the top programming language right now and most of its success goes to the Android Operating System that has captured more than 80% of the mobile OS market.
  • Java is a versatile language, providing OOP, functional programming out of the box. It also follows all the modern programming methodologies and try to enhance Object Oriented Methodology.
  • Java Technologies can also be used for creating awesome websites and enterprise-level web applications that solve the problems of the future. The apps created using the Java Programming language are scalable and is supported by Google App Engine for hosting purposes.
  • Features of Java:
    • Easy to write and debug
    • Pure Object Oriented Language
    • Robust, Multithread and Architecture neutral
  • Homepage: Java Oracle


2. Python

  • Learning Curve: Easy
  • Python is one of the succinct programming languages that yields from the basic philosophy of minimum and clean code.
  • There are tons of courses online from Udacity, Coursera, and other Massive Open Online Course platform that improves on the premises of starting with the simplest yet the most powerful programming language of all time.
  • Python is a multi-purpose programming language and can be used to build almost anything. Another staggering fact about python is its use in data science and other scientific endeavors.
  • Features of Python:
    • Simple and Easy to learn
    • Used as introductory language to newbie programmers
    • Great Programming language for Scientists
    • Supports OPPs and Functional Programming
  • HomePage: Python

3. C#

  • Learning Curve: Medium, Easy Only if already know Java
  • C# is one of the close brothers of Java but works on Windows platforms only. When I started learning C#, the similarities between C# and Java was way beyond my likings.
  • C# is one of the top languages as it helps the programmers to build modern web applications with ‘.NET’ framework and Azure.
  • You can also choose to create apps that work on the desktop, as well as portable Windows devices. The recent release of Windows 10 have made prospects of this programming language way better than other programming languages.
  • For gaming, a popular gaming development engine, Unity is all created using C# as its primary language.
  • Recent News of .NET framework becoming open source has also changed the prospects and growth of Microsoft and the C# programming language.
  • Features of C#:
    • Similar to JAVA
    • Pure Object Oriented
    • Can be used to do almost anything including web programming, game programming.
  • Homepage: Resources and More Information

4. C++

  • Learning Curve: Hard
  • If you are interested in low-level programming, then look no further than C++. C++ is famous for its system call libraries and can be used to control every aspect of the Operating System. The reason behind such control is the fact that it can call hardware related operations and ultimately gives the control in the hands of the programmer.
  • The current generation Direct X are all developed in C++ programming language as C++ is scalable, less memory hogger and works perfectly on the different set of devices, i.e. completely portable.
  • Features of C++:
    • Build upon the most popular language, C
    • Supports OOPs
    • Supports functional programming
  • Homepage: ISOCPP

5. PHP

  • Learning Curve: Easy
  • PHP(Hypertext Preprocessor) is one of the world’s most used server-side scripting language. All the magic that happens behind the door of the server is performed by a server-side scripting language such as PHP.
  • PHP oriented CMS are already popular in the market. Some of the popular CMS that uses PHP as its core languages are WordPress, Magento, Joomla and more.
  • PHP also offers a great deal of frameworks to work with. Some of the popular PHP frameworks are Yii, CodeIgniter, CakePHP, Symphony, Larval and more.
  • PHP works great with database oriented applications and can harness a lot, if properly used. Facebook has also launched a modified version of PHP, known as HACK programming languages.
  • Features of PHP:
    • Supports OOP
    • Works great with HTTP
    • Handles Data and forms efficiently
    • Works for Persistent Connection and more
  • Homepage: PHP

6. JavaScript

  • Learning Curve: Easy-Medium
  • JavaScript is the lingua franca of the web and also the no.2 programming language in our top programming language list. Without JavaScript, we would never have been able to manipulate those HTML DOM elements and create some amazing front-end interaction with the user.
  • JavaScript has evolved a lot in the past 10 years and now-a-days, a lot of JavaScript frameworks are linked to its success. Frameworks such as Angular.js, Ember.js and other provide more value to the programming language.
  • A great tool for the front-end developer.
  • Features of JavaScript:
    • Similar to C
    • Detects browser and loads browser specific information
    • Support functional and OOP
    • Can be used to validate user’s input
  • Learn more about JavaScript: MDN JavaScript

7. Swift

  • Learning Curve: Depends
  • There is no doubt in my mind that Swift is here to stay. Just a year old, the programmming language has brough a lot of oppurtunity to the iOS develoeprs in term of new features, which might include writing less code and developing faster codes.
  • An interesting article shows the recreation of one of the most notorious(read popular games) Flappy Bird using the swift programming language.
  • Features of Swift:
    • Modern
    • Designed for safety
    • Fast and Powerful
  • Homepage: Swift

8. R

  • Learnign Curve: Medium
  • R is not really a programming language, but it is one of the most popular stastical language used by scientist all over the world. You can learn more about R here.
  • Features of R:
    • Supports Input/Output files
    • Object Oriented Programming
    • Distributed Computing
    • Supports tons of R packages for array of tasks
  • Homepage: R

9. Ruby

  • Learning Curve: Easy-Medium
  • Ruby hails from the land of fast protoyping and agile development. If you are looking to get started with any project that require agile development and also needs to be develop prototypes faster, then Ruby is for you.
  • Web applications can be built using Ruby on Rails framework with tons of learning resources available online for both free and paid.
  • Also, online learning platform such as Udacity, Coursera and others provide tons of resources for learning Ruby and its framework Ruby on Rails.
  • Features of Ruby:
    • Supports OOP and functional programming
    • Great for Prototyping and Agile Development
    • Easy to learn for newbie programmers.
    • Bonus: A great resource that compares Ruby programming language with other programming languages. Must read for Ruby enthusiast.
  • Homepage: Ruby

10. Objective-C

  • Learning Curve: Depends
  • Objective C is the predecessor of the newest entrant of iOS programming language Swift that created ripples last year. Still, the frontier of iOS programming is still hot and can be learned.
  • Apple has released both XCode and Objective-C that works in tandem to create wonderful apps for their operating system.
  • Features of Objectve-C:
    • Creates app for iOS operating System
    • Large Community
  • Homepage: Objective-C


images: statisticstimes.com

Friday, March 4, 2016

Java Error Handling Mechanism !!!

Errors: 

When a dynamic linking failure or some other “hard” failure in the virtual machine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors. In addition, it’s unlikely that typical Java programs will ever throw Errors either.

Exceptions: 

Most programs throw and catch objects that derive from the Exception class. Exceptions indicate that a problem occurred but that the problem is not a serious JVM problem. An Exception class has many subclasses. These descendants indicate various types of exceptions that can occur. For example, NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One exception subclass has special meaning in the Java language: RuntimeException.

All the exceptions except RuntimeException are compiler checked exceptions. If a method is capable of throwing a checked exception it must declare it in its method header or handle it in a try/catch block. Failure to do so raises a compiler error. So checked exceptions can, at compile time, greatly reduce the occurrence of unhandled exceptions surfacing at runtime in a given application at the expense of requiring large throws declarations and encouraging use of poorly constructed try/catch blocks. Checked exceptions are present in other languages like C++, C#, and Python.


Runtime Exceptions (unchecked exception):

A RuntimeException class represents exceptions that occur within the Java virtual machine (during runtime). An example of a runtime exception is NullPointerException. The cost of checking for the runtime exception often outweighs the benefit of catching it. Attempting to catch or specify all of them all the time would make your code unreadable and unmaintainable. The compiler allows runtime exceptions to go uncaught and unspecified. If you like, you can catch these exceptions just like other exceptions. However, you do not have to declare it in your “throws" clause or catch it in your catch clause. In addition, you can create your own RuntimeException subclasses and this approach is probably preferred at times because checked exceptions can complicate method signatures and can be difficult to follow.

What are the exception handling best practices: 

Q. Why is it not advisable to catch type “Exception”?

Exception handling in Java is polymorphic in nature. For example if you catch type Exception in your code then it can catch or throw its descendent types like IOException as well. So if you catch the type Exception before the type IOException then the type Exception block will catch the entire exceptions and type IOException block is never reached. In order to catch the type IOException and handle it differently to type Exception, IOException should be caught first (remember that you can’t have a bigger basket above a smaller basket).


The diagram above is an example for illustration only. In practice it is not recommended to catch type
“Exception”. We should only catch specific subtypes of the Exception class. Having a bigger basket (i.e. Exception) will hide or cause problems. Since the RunTimeException is a subtype of Exception, catching the type Exception will catch all the run time exceptions (like NullPointerException, ArrayIndexOutOfBoundsException) aswell.

Example: The FileNotFoundException is extended (i.e. inherited) from the IOException. So (subclasses have to be caught first) FileNotFoundException (small basket) should be caught before IOException (big basket).

Q. Why should you throw an exception early?

The exception stack trace helps you pinpoint where an exception occurred by showing you the exact sequence of method calls that lead to the exception. By throwing your exception early, the exception becomes more accurate and more specific. Avoid suppressing or ignoring exceptions. Also avoid using exceptions just to get a flow control.

Instead of:
// assume this line throws an exception because filename == null.
InputStream in = new FileInputStream(fileName);

Use the following code because you get a more accurate stack trace:

if(filename == null) {
throw new IllegalArgumentException(“file name is null”);
}
InputStream in = new FileInputStream(fileName);

Q. Why should you catch a checked exception late in a catch {} block?

You should not try to catch the exception before your program can handle it in an appropriate manner. The natural tendency when a compiler complains about a checked exception is to catch it so that the compiler stops reporting errors. It is a bad practice to sweep the exceptions under the carpet by catching it and not doing anything with it.

The best practice is to catch the exception at the appropriate layer (e.g. an exception thrown at an integration layer can be caught at a presentation layer in a catch {} block), where your program can either meaningfully recover from the exception and continue to execute or log the exception only once in detail, so that user can identify the cause of the exception. 

Q. When should you use a checked exception and when should you use an unchecked exception?

Due to heavy use of checked exceptions and minimal use of unchecked exceptions, there has been a hot debate in the Java community regarding true value of checked exceptions. Use checked exceptions when the client code can take some useful recovery action based on information in exception. Use unchecked exception when client code cannot do anything. For example Convert your SQLException into another checked exception if the client code can recover from it. Convert your SQLException into an unchecked (i.e. RuntimeException) exception, if the client code can not recover from it. (Note: Hibernate 3 & Spring uses RuntimeExceptions prevalently).

Important: throw an exception early and catch an exception late but do not sweep an exception under the carpet by catching it and not doing anything with it. This will hide problems and it will be hard to debug and fix. 

A note on key words for error handling:

throw / throws – used to pass an exception to the method that called it.
try – block of code will be tried but may cause an exception.
catch – declares the block of code, which handles the exception.
finally – block of code, which is always executed (except System.exit(0) call) no matter what program flow, occurs when dealing with an exception.
assert – Evaluates a conditional expression to verify the programmer’s assumption.

Friday, June 28, 2024

50 Java 8 Interview Programs with Solutions

This blog post presents 50 Java 8 interview programs along with their solutions. These examples demonstrate various features and concepts introduced in Java 8, particularly focusing on streams, lambdas, and functional programming.

1. Find the sum of all numbers in a list using streams

import java.util.Arrays;
import java.util.List;

public class SumOfNumbers {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        int sum = numbers.stream().mapToInt(Integer::intValue).sum();
        System.out.println("Sum: " + sum);
    }
}
    

2. Find the average of numbers in a list using streams

import java.util.Arrays;
import java.util.List;

public class AverageOfNumbers {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
        System.out.println("Average: " + average);
    }
}
    

3. Count the number of strings in a list with length greater than 3

import java.util.Arrays;
import java.util.List;

public class CountStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("a", "ab", "abc", "abcd", "abcde");
        long count = strings.stream().filter(s -> s.length() > 3).count();
        System.out.println("Count: " + count);
    }
}
    

4. Remove all empty strings from a list

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveEmptyStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List filtered = strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        System.out.println("Filtered List: " + filtered);
    }
}
    

5. Convert a list of strings to uppercase

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class UppercaseStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("a", "b", "c", "d", "e");
        List uppercase = strings.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("Uppercase: " + uppercase);
    }
}
    

6. Find the maximum value in a list of integers

import java.util.Arrays;
import java.util.List;

public class MaxValue {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 5, 3, 8, 2);
        int max = numbers.stream().max(Integer::compare).orElse(0);
        System.out.println("Max value: " + max);
    }
}
    

7. Sort a list of strings in alphabetical order

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SortStrings {
    public static void main(String[] args) {
        List strings = Arrays.asList("d", "b", "a", "c", "e");
        List sorted = strings.stream().sorted().collect(Collectors.toList());
        System.out.println("Sorted: " + sorted);
    }
}
    

8. Find the first non-repeated character in a string

import java.util.LinkedHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstNonRepeatedChar {
    public static void main(String[] args) {
        String input = "aabbcdeeff";
        Character result = input.chars()
                .mapToObj(ch -> Character.toLowerCase((char) ch))
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
                .entrySet()
                .stream()
                .filter(entry -> entry.getValue() == 1L)
                .map(entry -> entry.getKey())
                .findFirst()
                .orElse(null);
        System.out.println("First non-repeated character: " + result);
    }
}
    

9. Check if a number is prime

import java.util.stream.IntStream;

public class PrimeNumber {
    public static void main(String[] args) {
        int number = 17;
        boolean isPrime = number > 1 && IntStream.rangeClosed(2, (int) Math.sqrt(number)).noneMatch(i -> number % i == 0);
        System.out.println(number + " is prime: " + isPrime);
    }
}
    

10. Generate Fibonacci series up to n terms

import java.util.stream.Stream;

public class FibonacciSeries {
    public static void main(String[] args) {
        int n = 10;
        Stream.iterate(new int[]{0, 1}, f -> new int[]{f[1], f[0] + f[1]})
              .limit(n)
              .map(f -> f[0])
              .forEach(i -> System.out.print(i + " "));
    }
}
    

11. Find all pairs of elements in an array whose sum is equal to a given number

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class PairSum {
    public static void main(String[] args) {
        int[] numbers = {2, 4, 3, 5, 7, 8, 9};
        int targetSum = 7;
        
        List pairs = Arrays.stream(numbers)
            .boxed()
            .flatMap(i -> Arrays.stream(numbers)
                .filter(j -> i + j == targetSum && i <= j)
                .mapToObj(j -> i + "," + j))
            .collect(Collectors.toList());
        
        System.out.println("Pairs with sum " + targetSum + ": " + pairs);
    }
}
    

12. Check if a string is a palindrome

import java.util.stream.IntStream;

public class Palindrome {
    public static void main(String[] args) {
        String str = "racecar";
        boolean isPalindrome = IntStream.range(0, str.length() / 2)
            .allMatch(i -> str.charAt(i) == str.charAt(str.length() - 1 - i));
        
        System.out.println(str + " is palindrome: " + isPalindrome);
    }
}
    

13. Find the factorial of a number using streams

import java.util.stream.LongStream;

public class Factorial {
    public static void main(String[] args) {
        int n = 5;
        long factorial = LongStream.rangeClosed(1, n)
            .reduce(1, (long x, long y) -> x * y);
        
        System.out.println("Factorial of " + n + " is: " + factorial);
    }
}
    

14. Find the second largest number in an array

import java.util.Arrays;

public class SecondLargest {
    public static void main(String[] args) {
        int[] numbers = {5, 9, 11, 2, 8, 21, 1};
        
        int secondLargest = Arrays.stream(numbers)
            .boxed()
            .sorted((a, b) -> b.compareTo(a))
            .skip(1)
            .findFirst()
            .orElse(-1);
        
        System.out.println("Second largest number: " + secondLargest);
    }
}
    

15. Remove duplicates from a list

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDuplicates {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
        
        List distinctNumbers = numbers.stream()
            .distinct()
            .collect(Collectors.toList());
        
        System.out.println("List without duplicates: " + distinctNumbers);
    }
}
    

16. Find the longest string in a list

import java.util.Arrays;
import java.util.List;

public class LongestString {
    public static void main(String[] args) {
        List strings = Arrays.asList("Java", "Python", "JavaScript", "C++", "Ruby");
        
        String longest = strings.stream()
            .reduce((s1, s2) -> s1.length() > s2.length() ? s1 : s2)
            .orElse("");
        
        System.out.println("Longest string: " + longest);
    }
}
    

17. Count occurrences of each character in a string

import java.util.Map;
import java.util.stream.Collectors;

public class CharacterCount {
    public static void main(String[] args) {
        String str = "programming";
        
        Map charCount = str.chars()
            .mapToObj(ch -> (char) ch)
            .collect(Collectors.groupingBy(ch -> ch, Collectors.counting()));
        
        System.out.println("Character count: " + charCount);
    }
}
    

18. Join a list of strings with a delimiter

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class JoinStrings {
    public static void main(String[] args) {
        List fruits = Arrays.asList("apple", "banana", "cherry", "date");
        
        String joined = fruits.stream()
            .collect(Collectors.joining(", "));
        
        System.out.println("Joined string: " + joined);
    }
}
    

19. Check if all elements in a list are even

import java.util.Arrays;
import java.util.List;

public class AllEven {
    public static void main(String[] args) {
        List numbers = Arrays.asList(2, 4, 6, 8, 10);
        
        boolean allEven = numbers.stream()
            .allMatch(n -> n % 2 == 0);
        
        System.out.println("All numbers are even: " + allEven);
    }
}
    

20. Find the sum of squares of all odd numbers in a list

import java.util.Arrays;
import java.util.List;

public class SumOfSquaresOfOdd {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        
        int sumOfSquaresOfOdd = numbers.stream()
            .filter(n -> n % 2 != 0)
            .mapToInt(n -> n * n)
            .sum();
        
        System.out.println("Sum of squares of odd numbers: " + sumOfSquaresOfOdd);
    }
}
    

21. Convert a list of integers to an array

import java.util.Arrays;
import java.util.List;

public class ListToArray {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        int[] array = numbers.stream()
            .mapToInt(Integer::intValue)
            .toArray();
        
        System.out.println("Array: " + Arrays.toString(array));
    }
}
    

22. Find the most frequent element in an array

import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostFrequentElement {
    public static void main(String[] args) {
        Integer[] numbers = {1, 2, 3, 2, 4, 2, 5, 3};
        
        Map.Entry mostFrequent = Arrays.stream(numbers)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
            .entrySet()
            .stream()
            .max(Map.Entry.comparingByValue())
            .orElse(null);
        
        System.out.println("Most frequent element: " + (mostFrequent != null ? mostFrequent.getKey() : "None"));
    }
}
    

23. Check if a string contains only digits

public class OnlyDigits {
    public static void main(String[] args) {
        String str = "12345";
        
        boolean onlyDigits = str.chars()
            .allMatch(Character::isDigit);
        
        System.out.println("String contains only digits: " + onlyDigits);
    }
}
    

24. Find the sum of all even numbers in a range

import java.util.stream.IntStream;

public class SumOfEvenInRange {
    public static void main(String[] args) {
        int start = 1;
        int end = 100;
        
        int sum = IntStream.rangeClosed(start, end)
            .filter(n -> n % 2 == 0)
            .sum();
        
        System.out.println("Sum of even numbers from " + start + " to " + end + ": " + sum);
    }
}
    

25. Reverse the order of words in a sentence

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ReverseSentence {
    public static void main(String[] args) {
        String sentence = "Hello World Java Programming";
        
        List words = Arrays.asList(sentence.split("\\s+"));
        Collections.reverse(words);
        
        String reversed = words.stream()
            .collect(Collectors.joining(" "));
        
        System.out.println("Reversed sentence: " + reversed);
    }
}
    

26. Find the intersection of two lists

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ListIntersection {
    public static void main(String[] args) {
        List list1 = Arrays.asList(1, 2, 3, 4, 5);
        List list2 = Arrays.asList(4, 5, 6, 7, 8);
        
        List intersection = list1.stream()
            .filter(list2::contains)
            .collect(Collectors.toList());
        
        System.out.println("Intersection: " + intersection);
    }
}
    

27. Calculate the product of all numbers in a list

import java.util.Arrays;
import java.util.List;

public class ProductOfList {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        int product = numbers.stream()
            .reduce(1, (a, b) -> a * b);
        
        System.out.println("Product: " + product);
    }
}
    

28. Find all strings that start with a specific letter

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StringsStartingWith {
    public static void main(String[] args) {
        List words = Arrays.asList("apple", "banana", "avocado", "cherry", "apricot");
        char startLetter = 'a';
        
        List filteredWords = words.stream()
            .filter(w -> w.toLowerCase().startsWith(String.valueOf(startLetter).toLowerCase()))
            .collect(Collectors.toList());
        
        System.out.println("Words starting with '" + startLetter + "': " + filteredWords);
    }
}
    

29. Calculate the average length of strings in a list

import java.util.Arrays;
import java.util.List;

public class AverageStringLength {
    public static void main(String[] args) {
        List words = Arrays.asList("Java", "Python", "C++", "JavaScript", "Ruby");
        
        double averageLength = words.stream()
            .mapToInt(String::length)
            .average()
            .orElse(0.0);
        
        System.out.println("Average length: " + averageLength);
    }
}
    

30. Find the smallest number in a list that is greater than a given number

import java.util.Arrays;
import java.util.List;

public class SmallestGreaterThan {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 3, 5, 7, 9, 11, 13);
        int target = 6;
        
        int result = numbers.stream()
            .filter(n -> n > target)
            .min(Integer::compare)
            .orElse(-1);
        
        System.out.println("Smallest number greater than " + target + ": " + result);
    }
}
    

31. Group a list of objects by a property

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

class Person {
    String name;
    int age;
    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class GroupByAge {
    public static void main(String[] args) {
        List people = Arrays.asList(
            new Person("Alice", 25),
            new Person("Bob", 30),
            new Person("Charlie", 25),
            new Person("David", 30)
        );
        
        Map> groupedByAge = people.stream()
            .collect(Collectors.groupingBy(p -> p.age));
        
        System.out.println("Grouped by age: " + groupedByAge);
    }
}
    

32. Find the length of the longest word in a sentence

public class LongestWordLength {
    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog";
        
        int maxLength = sentence.split("\\s+").length > 0 ?
            sentence.split("\\s+")
                .stream()
                .mapToInt(String::length)
                .max()
                .orElse(0) : 0;
        
        System.out.println("Length of longest word: " + maxLength);
    }
}
    

33. Check if a list contains any element starting with a specific prefix

import java.util.Arrays;
import java.util.List;

public class ContainsPrefix {
    public static void main(String[] args) {
        List words = Arrays.asList("apple", "banana", "cherry", "date");
        String prefix = "ba";
        
        boolean containsPrefix = words.stream()
            .anyMatch(w -> w.startsWith(prefix));
        
        System.out.println("Contains word with prefix '" + prefix + "': " + containsPrefix);
    }
}
    

34. Convert a list of strings to lowercase

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ToLowerCase {
    public static void main(String[] args) {
        List words = Arrays.asList("HELLO", "World", "JAVA", "Programming");
        
        List lowercaseWords = words.stream()
            .map(String::toLowerCase)
            .collect(Collectors.toList());
        
        System.out.println("Lowercase words: " + lowercaseWords);
    }
}
    

35. Find the sum of digits of a number

public class SumOfDigits {
    public static void main(String[] args) {
        int number = 12345;
        
        int sum = String.valueOf(number)
            .chars()
            .map(Character::getNumericValue)
            .sum();
        
        System.out.println("Sum of digits: " + sum);
    }
}
    

36. Check if a list is sorted

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class IsSorted {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        boolean isSorted = numbers.stream()
            .sorted()
            .collect(Collectors.toList())
            .equals(numbers);
        
        System.out.println("Is list sorted: " + isSorted);
    }
}
    

37. Find the kth largest element in an array

import java.util.Arrays;

public class KthLargest {
    public static void main(String[] args) {
        int[] numbers = {3, 2, 1, 5, 6, 4};
        int k = 2;
        
        int kthLargest = Arrays.stream(numbers)
            .boxed()
            .sorted((a, b) -> b.compareTo(a))
            .skip(k - 1)
            .findFirst()
            .orElse(-1);
        
        System.out.println(k + "th largest element: " + kthLargest);
    }
}
    

38. Remove all vowels from a string

public class RemoveVowels {
    public static void main(String[] args) {
        String str = "Hello World";
        
        String result = str.replaceAll("[aeiouAEIOU]", "");
        
        System.out.println("String without vowels: " + result);
    }
}
    

39. Find the common elements between two arrays

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CommonElements {
    public static void main(String[] args) {
        Integer[] arr1 = {1, 2, 3, 4, 5};
        Integer[] arr2 = {4, 5, 6, 7, 8};
        
        List common = Arrays.stream(arr1)
            .filter(Arrays.asList(arr2)::contains)
            .collect(Collectors.toList());
        
        System.out.println("Common elements: " + common);
    }
}
    

40. Calculate the factorial of a number using reduce

import java.util.stream.LongStream;

public class FactorialUsingReduce {
    public static void main(String[] args) {
        int n = 5;
        
        long factorial = LongStream.rangeClosed(1, n)
            .reduce(1, (long x, long y) -> x * y);
        
        System.out.println("Factorial of " + n + ": " + factorial);
    }
}
    

41. Find the longest palindrome in a string

import java.util.stream.IntStream;

public class LongestPalindrome {
    public static void main(String[] args) {
        String str = "babad";
        
        String longest = IntStream.range(0, str.length())
            .boxed()
            .flatMap(i -> IntStream.rangeClosed(i + 1, str.length())
                .mapToObj(j -> str.substring(i, j)))
            .filter(s -> s.equals(new StringBuilder(s).reverse().toString()))
            .max((s1, s2) -> s1.length() - s2.length())
            .orElse("");
        
        System.out.println("Longest palindrome: " + longest);
    }
}
    

42. Convert a list of integers to a comma-separated string

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ListToString {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5);
        
        String result = numbers.stream()
            .map(String::valueOf)
            .collect(Collectors.joining(", "));
        
        System.out.println("Comma-separated string: " + result);
    }
}
    

43. Find the sum of squares of even numbers in a list

import java.util.Arrays;
import java.util.List;

public class SumOfSquaresOfEven {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        
        int sum = numbers.stream()
            .filter(n -> n % 2 == 0)
            .mapToInt(n -> n * n)
            .sum();
        
        System.out.println("Sum of squares of even numbers: " + sum);
    }
}
    

44. Check if a number is a perfect square

import java.util.stream.IntStream;

public class PerfectSquare {
    public static void main(String[] args) {
        int number = 16;
        
        boolean isPerfectSquare = IntStream.rangeClosed(1, (int) Math.sqrt(number))
            .anyMatch(i -> i * i == number);
        
        System.out.println(number + " is a perfect square: " + isPerfectSquare);
    }
}
    

45. Find the first repeating element in an array

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FirstRepeatingElement {
    public static void main(String[] args) {
        Integer[] numbers = {1, 2, 3, 4, 2, 1, 5, 6};
        
        Integer firstRepeating = Arrays.stream(numbers)
            .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()))
            .entrySet()
            .stream()
            .filter(entry -> entry.getValue() > 1)
            .map(Map.Entry::getKey)
            .findFirst()
            .orElse(null);
        
        System.out.println("First repeating element: " + firstRepeating);
    }
}
    

46. Calculate the product of all odd numbers in a list

import java.util.Arrays;
import java.util.List;

public class ProductOfOdd {
    public static void main(String[] args) {
        List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
        
        int product = numbers.stream()
            .filter(n -> n % 2 != 0)
            .reduce(1, (a, b) -> a * b);
        
        System.out.println("Product of odd numbers: " + product);
    }
}
    

47. Find the difference between the largest and smallest numbers in a list

import java.util.Arrays;
import java.util.List;

public class LargestSmallestDifference {
    public static void main(String[] args) {
        List numbers = Arrays.asList(5, 2, 8, 1, 9, 3);
        
        int difference = numbers.stream()
            .reduce((a, b) -> Math.max(a, b) - Math.min(a, b))
            .orElse(0);
        
        System.out.println("Difference between largest and smallest: " + difference);
    }
}
    

48. Check if a string contains only unique characters

public class UniqueCharacters {
    public static void main(String[] args) {
        String str = "abcdefg";
        
        boolean hasUniqueChars = str.chars()
            .distinct()
            .count() == str.length();
        
        System.out.println("String has only unique characters: " + hasUniqueChars);
    }
}
    

49. Find the sum of all numbers in a string

public class SumOfNumbersInString {
    public static void main(String[] args) {
        String str = "ab12c3d4ef5";
        
        int sum = str.replaceAll("\\D+", " ")
            .trim()
            .split(" ")
            .length > 0 ?
            str.replaceAll("\\D+", " ")
                .trim()
                .split(" ")
                .stream()
                .mapToInt(Integer::parseInt)
                .sum() : 0;
        
        System.out.println("Sum of numbers in string: " + sum);
    }
}
    

50. Implement a custom Collector to join strings with a delimiter

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collector;

public class CustomCollector {
    public static void main(String[] args) {
        List fruits = Arrays.asList("apple", "banana", "cherry", "date");
        
        String result = fruits.stream()
            .collect(Collector.of(
                StringBuilder::new,
                (sb, str) -> {
                    if (sb.length() > 0) sb.append(", ");
                    sb.append(str);
                },
                StringBuilder::append,
                StringBuilder::toString
            ));
        
        System.out.println("Joined string: " + result);
    }
}
    
These 50 Java 8 interview programs cover a wide range of concepts and techniques. Practice these examples to improve your understanding of Java 8 features and prepare for Java interviews.

If you need any further assistance, such as explanations of specific programs, modifications to the code, or help with implementing these examples, please don't hesitate to ask. Good luck with your Java programming endeavors!

Works

What can I do


Branding

Social media Branding is far and away the best technique a company has to boost engagement with its customer base. Even a minimum of involvement, such as making one post a day.

Web Design

Web design is the process of creating websites. It encompasses several different aspects, including webpage layout, content production, and graphic design.

Development

Web Development refers to building, creating, and an maintaining websites. It includes aspects such as web design, web publishing, web programming and database management.

Graphic Design

Graphic design is the process of visual communication and problem-solving through the use of typography, photography, and illustration. The field is considered a subset of visual communication and communication design.

Photography

Photography is the art, application and practice of creating durable images by recording light or other electromagnetic radiation, either electronically by means of an image sensor, or chemically by means of a light-sensitive material such as photographic film.

User Experience

User experience (UX) design is the process design teams use to create products that provide meaningful and relevant experiences to users. This involves the design of the entire process of acquiring and integrating the product, including aspects of branding, design.

Contact

Get in touch with me


Adress/Street

Bangalore, India