Skip to main content

Posts

Java forEach

  Java, forEach is a method introduced in Java 8 in the Iterable interface. It's a part of the Stream API and provides a way to iterate over elements of a collection and perform an action on each element. It takes a functional interface as an argument, typically a lambda expression or a method reference, which represents the action to be performed on each element. Here's the syntax of forEach method: void forEach (Consumer<? super T> action) Where: action is the action to be performed for each element. Consumer is a functional interface from the java.util.function package. It represents an operation that accepts a single input argument and returns no result. Let's see some examples: Example 1: Basic usage with ArrayList import java.util.ArrayList; public class ForEachExample { public static void main (String[] args) { ArrayList<String> names = ArrayList<String> names = new ArrayList <>(); names.add( ...

Java Type Casting

  Type casting in Java refers to converting a value of one data type to another. This is often necessary when you're working with different types of variables or objects in your program. Java supports two types of casting: Implicit Casting (Widening Conversion) : This is when you convert a smaller data type into a larger one, as it can be done automatically by the Java compiler without loss of information. For example: int numInt = 100 ; double numDouble = numInt; // Implicit casting from int to double System.out.println(numDouble); // Output: 100.0 Explicit Casting (Narrowing Conversion) : This is when you convert a larger data type into a smaller one, which may result in loss of data. It requires explicit declaration and is done by placing the type in parentheses before the value. For example: double numDouble = 100.55 ; int numInt = ( int ) numDouble; // Explicit casting from double to int System.out.println(numInt); // Output: 100 Here are a few more examples demon...