Java LocalDate from() Method with Examples

In this article we are going to see the use of Java LocalDate class from() method with suitable examples.

Java LocalDate from() Method with Examples

This java.time.LocalDate.from(TemporalAccessor temporal) method is used to obtain an instance of LocalDate from a temporal object to create a LocalDate Time. It returns the local date.

Syntax:

public static LocalDate from(TemporalAccessor temporal)

Where,

  • temporal refers to the Temporal object that to be concverted.

Let’s see an program to understand it more clearly.

Approach:

  • Create an object of localDate class.
  • By using that LocalDate class object call from() method and use ZonedDateTime.now() method to get the value.
  • Print the final LocalDate as result.

Program:

import java.time.LocalDate;
import java.time.ZonedDateTime;
public class Main
{
    public static void main(String[] args)
    {
        //create an object of localDate class
        //pass ZonedDateTime.now() in from() method.
      	LocalDate date = LocalDate.from(ZonedDateTime.now());
        //Print the result
      	System.out.println("Local date: "+date);  
   }
}
Output:

Local date: 2022-05-25

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Java LocalDate get() Method with Examples

In this article we are going to see the use of Java LocalDate class get()  method with suitable examples.

Java LocalDate get() Method with Examples

Explanation:

This java.time.LocalDate.get(TemporalField field) method is used to get the value of the specified field from this date as an integer. It returns the value for field.

Exceptions:

  • DateTimeException –it occurs when the value is outside the range of valid values for the field.
  • UnsupportedTemporalTypeException − it occurs if the field is not supported or the range of values exceeds an integer value.
  • ArithmeticException − it occurs when the numeric overflow occurs.

Syntax:

public int get(TemporalField field)

Let’s see a program to understand it more clearly.

Approach:

  • Create an object of LocalDate class.
  • Then use the get method followed by specific command to get the required result.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class Main
{
    public static void main(String[] args)
    {
        //Create an object of LocalDate class and assign a date to it
        //here it parses the local date
        LocalDate date = LocalDate.parse("2022-05-10");
        //print the result by mentioning the specific item
      	System.out.println("Result: "+date.get(ChronoField.DAY_OF_MONTH)); 
   }
}
Output:

Result: 10

Let’s see an instance of exception with a program.

Approach:

  • Create an objects of LocalDate class which will hold the parsed dates.
  • Here we pass an invalid date for testing.
  • Then use the get method followed by specific command to get the required result.
  • Put all those code inside the try block and in catch block to check the exception.
  • Then print the final result.

Program:

import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class Main
{
    public static void main(String[] args)
    {
        try
        {
            //Create an object of LocalDate class and assign a date to it
            //here it parses the local date
            LocalDate date = LocalDate.parse("2022-02-31");
            //print the result by mentioning the specific item
      	    System.out.println("Result: "+date.get(ChronoField.DAY_OF_MONTH));
        }
        catch(Exception excp)
        {
            //print the exception as result
            System.out.println(excp);
        } 
    }
}
Output:

java.time.format.DateTimeParseException: Text '2022-02-31' could not be parsed: Invalid date 'FEBRUARY 31'

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples.

Java LocalDate atStartOfDay( ) Method with Example

In this article we are going to see the use of Java LocalDate class atStartOfDay( ) method with suitable examples.

Java LocalDate atStartOfDay( ) Method with Example

This java.time.LocalDate.atStartOfDay() method is used to combine the date with the time of midnight to create a LocalDate Time. It returns the local date’s time of midnight at the start of the day.

Syntax:

public LocalDateTime atStartOfDay()

Let’s see the use of atStartOfDay( ) method with 2 different format.

Method-1: without parameters

Approach:

  1. Create an object of LocalDate class which will hold the parsed date.
  2. By using that LocalDate class object call atStartOfDay() method and assign the result to an object of LocaldateTime class.
  3. Then print the final LocalDateTime as result.

Program:

import java.time.LocalDate;
import java.time.LocalDateTime;
public class Main
{
    public static void main(String[] args)
    {
    //Create an object of LocalDate class and assign a date to it
    //here it parses the local date
    LocalDate date = LocalDate.parse("2022-05-10");
    System.out.println("Specific date: "+date);  
    //Create an object of LocalDateTime
    //call the atStartOfDay() method by using object of LocalDate class
    LocalDateTime startTime = date.atStartOfDay();
    System.out.println("Start Time: "+startTime);  
   }
}
Output:

Specific date: 2022-05-10
Start Time: 2022-05-10T00:00

Method-2: with parameters

Approach:

  1. Create an object of LocalDate class which will hold the parsed date.
  2. By using that LocalDate class object call atStartOfDay() method and by passing ZoneId.systemDefault() as parameter and assign the result to an object of ZoneddateTime class.
  3. Here we pass the ZoneId which is already defined by system so that it will take a particular zone and represent that zone’s start time.
  4. Then print the final ZonedDateTime as result.

Program:

import java.time.*;
public class Main
{
    public static void main(String[] args)
    {
    //Create an object of LocalDate class and assign a date to it
    //here it parses the local date
    LocalDate date = LocalDate.parse("2022-05-10");
    System.out.println("Specific date: "+date);  
    //Create an object of LocalDateTime
    //call atStartOfDay() method by passing the ZoneId.systemDefault() as parameter
    ZonedDateTime startTime = date.atStartOfDay(ZoneId.systemDefault());
    System.out.println("Start Time: "+startTime);  
   }
}
Output:

Specific date: 2022-05-10
Start Time: 2022-05-10T00:00Z[GMT]

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding.

What is Hashing and Hash Table?

What is Hashing and Hash Table

Hashing and Hash Table

1)Hashing

Hashing is the process of mapping object data to a representative integer value using a function or algorithm.

This hash code (or simply hash) can then be used to narrow our quest when searching for the item on the map.

These hash codes are usually used to create an index at which the value is stored.

2)Hash Table

A hash table is a data structure that stores data associatively. Data is stored in an array format in a hash table, with each data value having its own unique index value. When we know the index of the desired data, we can access it very quickly.

As a result, it becomes a data structure in which insertion and search operations are extremely quick, regardless of the size of the data. Hash Tables use an array as a storage medium and use the hash technique to produce an index from which an element is to be inserted or located.

3)Features of HashTable

  • It works in the same way as HashMap, but it is synchronised.
  • In a hash table, a key/value pair is stored.
  • In Hashtable, we define an object that will be used as a key, as well as the value that will be associated with that key. The key is then hashed, and the resulting hash code serves as the index for storing the value in the table.
  • The default capacity of the Hashtable class is 11, and the loadFactor is 0.75.
  • HashMap does not support Enumeration, while Hashtable does not support fail-fast Enumeration.

4)Adding element in HashTable

When an entity is inserted into a Hash Table, its hash code is measured first, and the bucket in which it will be stored is determined based on that hash code.

Let us illustrate this with an example.

For instance, suppose we want to store some numbers in a Hash Table, i.e.

32 , 45 , 64 , 92 , 57 , 88 , 73

Internally, this Hash Table can use 10 buckets, i.e.

The Hash Code will be returned by our Hash Function.

HashCode=Element_value%10

This Hash code for,

32 will be 2

45 will be 5

64 will be 4

92 will be 2

57 will be 7

88 will be 8

73 will be 3

Now, each element’s hash code will be used to determine where that element will be stored, for example, 45 will be stored in bucket 5 since its hash code is 5. In the same way, all elements will be stored in the bucket that corresponds to their hash code.

5)Hashing Collisions

As we can see, the hash code for both 32 and 92 is the same, which is 2. In Hashing, this is referred to as Collision. Both components would be deposited in the same bucket if they collide.

6)Searching element in Hash Table

If we want to check for an element in a hash table, we must first calculate the hash code for that element. Then, using the hash code, we’ll go straight to the bucket where this element will be saved. Now, there may be several elements in that bucket; in that case, we’ll look for our element only in those elements.

Assume we want to find 45 in the hash table in the previous case.

Then we’ll measure the hash code, which will be 45 %10 = 5.

Then we’ll go straight to bucket no. 5 and search for the factor there.

7)Best Case Time Complexity in Hashing

From the viewpoint of searching, each bucket containing only one element in the Hash table is the best case scenario. In such a case, searching time would require the following effort:

The complexity of calculating hash codes is O(1)

If the bucket only contains one element, choosing that element from the bucket is a complex task O(1)

Consequently In the best case scenario, finding an element would be difficult O(1)

While the complexity of a collision, i.e. several elements in a bucket, will be O(no. of elements in bucket), it will be much less than the complexity of searching an element from a List, which will be O(n).

8)Worst Case Time Complexity in Hashing

The worst case scenario in hashing is when the Hash Function is not correctly implemented, resulting in the same hash code for several elements.

Assume the following is our hash function:

Hash code = given_element / 100

Then, in the preceding case, the hash code for all elements ( 32 , 45 , 64 , 92 , 57 , 88 , 73 ) will be 0. As a result, all elements will be saved in bucket 0.

Since all components are in the same bucket, complexity is at its highest in this case. As a result, the complexity will be O(n) since it must check for the appropriate element among all elements.

Related Programs:

Java LocalDate equals( ) Method with Example

In this article we are going to see the use of Java LocalDate class equals( ) method with suitable examples.

Java LocalDate equals( ) Method with Example

This java.time.LocalDate.equals(Object obj) method is used to check a date with another date whether both the dates are equal or not. It returns Boolean value, returns true if equal, false if not equal.

Syntax:

public boolean equals(Object obj)

Where,

  • obj refers to the date which will be passed as parameter to check it is equal with another date or not.

Let’s see the program to understand it more clearly.

Approach:

  • Create two objects of LocalDate class which will hold the parsed dates, here we have taken date1 and date2.
  • Then by using equal() method check both dates are equal or not like date2.equals(date1).
  • Print the final result.

Program:

CASE-1: When both the dates are not equal

import java.time.LocalDate;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it.
     	LocalDate date1 = LocalDate.parse("2022-04-25");
      	System.out.println("date-1: "+date1);
      	//Create an object of LocalDate class and assign a date to it..
      	LocalDate date2 = LocalDate.parse("2022-05-08");
      	System.out.println("date-2: "+date2);
      	//check both the values equal or not and print the final result.
      	System.out.println("Result: "+date2.equals(date1)); 
   	}
}
Output:

date-1: 2022-04-25
date-2: 2022-05-08
Result: false

CASE-2: When both the dates are equal

import java.time.LocalDate;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it.
         LocalDate date1 = LocalDate.parse("2022-05-18");
          System.out.println("date-1: "+date1);
          //Create an object of LocalDate class and assign a date to it..
          LocalDate date2 = LocalDate.parse("2022-05-18");
          System.out.println("date-2: "+date2);
          //check both the values equal or not and print the final result.
          System.out.println("Result: "+date2.equals(date1)); 
       }
}
Output:

date-1: 2022-05-18
date-2: 2022-05-18
Result: true

Enhancing programming skills is very important no matter what language you have chosen. So, practice frequently with these simple java programs examples and excel in coding the complex logic.

Java LocalDate atTime( ) Method with Example

In this article we are going to see the use of Java LocalDate class atTime() method with suitable examples.

Java LocalDate atTime( ) Method with Example

This java.time.LocalDate.atTime(LocalTime time) method is used to combine a date with time to create LocalDateTime. It returns the local date-time formed by the specified date and time.

Syntax:

public LocalDateTime atTime(LocalTime time)

Where,

  • time refers to the actual time to be combined with the date.

Let’s see the use of atTime() method.

Method-1: Java LocalDateTime class atTime(int hour, int minute)

The LocalDate.atTime(int hour, int minute) method creates a LocalDateTime by combining the date with a specified time. Here hour and minute are passed as the parameter to the atTime() method.

It returns the formed local date-time but if any value is out of range then it gives DateTimeException.

Syntax:

public LocalDateTime atTime(int hour, int minute)

Where,

  • hour refers to the hour of the day, its value ranges from 0 to 23.
  • minute refers to the minute of the hour, its value ranges from 0 to 59.

Approach:

  • Create an object of LocalDate class which will hold the parsed date.
  • Then pass a time as parameter in (int hour, int minute) format to atTime() method which will add the specified time with the provided date and the final local date-time result will be hold by an object of LocalDateTime class.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.LocalDateTime;
public class Main
{
   public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it
        LocalDate date = LocalDate.parse("2017-02-03");
        System.out.println("Specified date: "+date);  
        //Create an object of LocalDateTime class 
        //By using the object of LocalDate class and atTime() method create the local date-time
        LocalDateTime dateWithTime = date.atTime(1,20);
        //Print the result
        System.out.println("Final Date and Time: "+dateWithTime);  
    }
}
Output:

Specified date: 2017-02-03
Final Date and Time: 2017-02-03T01:20

Method-2: Java LocalDateTime class atTime(int hour, int minute, int second)

The LocalDate.atTime(int hour, int minute, int second) method creates a LocalDateTime by combining the date with a specified time. Here hour, minute and second are passed as the parameter to the atTime() method.

It returns the formed local date-time but if any value is out of range then it gives DateTimeException.

Syntax:

public LocalDateTime atTime(int hour, int minute, int second)

Where,

  • hour refers to the hour of the day, its value ranges from 0 to 23.
  • minute refers to the minute of the hour, its value ranges from 0 to 59.
  • second refers to the seconds of the minute, its value ranges from 0 to 59.

Approach:

  • Create an object of LocalDate class which will hold the parsed date.
  • Then pass a time as parameter in (int hour, int minute, int second) format to atTime() method which will add the specified time with the provided date and the final local date-time result will be hold by an object of LocalDateTime class.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.LocalDateTime;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it
        LocalDate date = LocalDate.parse("2017-02-03");
        System.out.println("Specified date: "+date);  
        //Create an object of LocalDateTime class 
        //By using the object of LocalDate class and atTime() method create the local date-time
        LocalDateTime dateWithTime = date.atTime(1,20,25);
        //Print the result
        System.out.println("Final Date and Time: "+dateWithTime);  
    }
}
Output:

Specified date: 2017-02-03
Final Date and Time: 2017-02-03T01:20:25

Method-3: Java LocalDateTime class atTime(int hour, int minute, int second, int nanoOfSecond)

The LocalDate.atTime(int hour, int minute, int second, int nanoOfSecond) method creates a LocalDateTime by combining the date with a specified time. Here hour, minute, second and Nano second are passed as the parameter to the atTime() method.

It returns the formed local date-time but if any value is out of range then it gives DateTimeException.

Syntax:

public LocalDateTime atTime(int hour, int minute, int second, int nanoOfSecond)

Where,

  • hour refers to the hour of the day, its value ranges from 0 to 23.
  • minute refers to the minute of the hour, its value ranges from 0 to 59.
  • second refers to the seconds of the minute, its value ranges from 0 to 59.
  • nanoOfSecond refers to the Nano seconds of the second, its value ranges from 0 to 999999999.

Approach:

  • Create an object of LocalDate class which will hold the parsed date.
  • Then pass a time as parameter in (int hour, int minute, int second, int nanoOfSecond) format to atTime() method which will add the specified time with the provided date and the final local date-time result will be hold by an object of LocalDateTime class.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.LocalDateTime;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it
        LocalDate date = LocalDate.parse("2017-02-03");
        System.out.println("Specified date: "+date);  
        //Create an object of LocalDateTime class 
        //By using the object of LocalDate class and atTime() method create the local date-time
        LocalDateTime dateWithTime = date.atTime(1,20,25,345);
        //Print the result
        System.out.println("Final Date and Time: "+dateWithTime);  
    }
}
Output:

Specified date: 2017-02-03
Final Date and Time: 2017-02-03T01:20:25.000000345

Method-4: Java LocalDateTime class atTime(LocalTime time)

The LocalDate.atTime(LocalTime time) method creates a LocalDateTime by combining the date with a specified time. Here specific time is passed as the parameter to the atTime() method.

It returns the formed local date-time but if any value is out of range then it gives DateTimeException.

Syntax:

public LocalDateTime atTime(LocalTime time)

Where,

  • time refers to the time in LocalTime format.

Approach:

  • Create an object of LocalDate class which will hold the parsed date.
  • Create an object of LocalTime class which will hold the parsed time.
  • Then pass a time as parameter in (LocalTime time) format to atTime() method which will add the specified time with the provided date and the final local date-time result will be hold by an object of LocalDateTime class.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it
        LocalDate date = LocalDate.parse("2017-02-03");
        System.out.println("Specified date: "+date);
        //Create an object of LocalTime class and pass a parse value of time 
        LocalTime time = LocalTime.parse("09:20:45");
        //Create an object of LocalDateTime class 
        //By using the object of LocalDate class and atTime() method create the local date-time
        LocalDateTime dateWithTime = date.atTime(time );
        //Print the result
        System.out.println("Final Date and Time: "+dateWithTime);  
    }
}
Output:

Specified date: 2017-02-03
Final Date and Time: 2017-02-03T09:20:45

Method-5: OffsetDateTime atTime(OffsetTime time)

The OffsetDateTime atTime(OffsetTime time) method creates a OffsetDateTime by combining the date with a offset time. Here specific time is passed as the parameter to the atTime() method.

It returns the formed local date-time but if any value is out of range then it gives DateTimeException.

Syntax:

public OffsetDateTime atTime(OffsetTime time)

Where,

  • time refers to the time in OffsetTime format.

Approach:

  • Create an object of LocalDate class which will hold the parsed date.
  • Create an object of OffsetTime class which will hold the offset time.
  • Then pass a time as parameter in (OffsetTime time) format to atTime() method which will add the specified time with the provided date and the final local date-time result will be hold by an object of LocalDateTime class.
  • Print the final result.

Program:

import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
public class Main
{
    public static void main(String[] args) 
    {
        //Create an object of LocalDate class and assign a date to it
        LocalDate date = LocalDate.parse("2017-02-03");
        System.out.println("Specified date: "+date);
        //Create an object of OffsetTime class 
        OffsetTime time = OffsetTime.now();
        //Create an object of LocalDateTime class 
        //By using the object of OffsetDateTime class and atTime() method create the local date-time
        OffsetDateTime dateWithTime = date.atTime(time );
        //Print the result
        System.out.println("Final Date and Time: "+dateWithTime);  
    }
} 
Output:

Specified date: 2017-02-03
Final Date and Time: 2017-02-03T14:17:35.166418Z

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Java Program to Remove Duplicate Elements from a Singly Linked List

In this article we are going to see how we remove duplicate elements from a singly linked list by using Java programming language.

Java Program to Remove Duplicate Elements from a Singly Linked List

Approach:

  • Create a linked list.
  • Add some elements(with duplicates) to it.
  • Print the list.
  • Call the user defined method removeDup( ) that iterates the whole list repeatedly and removes all the duplicate nodes from the list.
  • Display the new list.

Program:

import java.util.*;
// Main class
public class Main
{
    // Class Node that defines the two linked list variables
    class Node
    {
        int data;
        Node nextNode;
        // constructor to create a node
        public Node(int data) 
        {    
            this.data = data;    
            this.nextNode = null;    
        }    
    }

    // Setting the head and end of the node as NULL  
    public Node head = null;    
    public Node tail = null;  

    // Method to remove duplicate elements from a linked list
    public void removeDup() 
    {  
        Node curr = head, index = null, temp = null;  
        if(head == null) 
        {  
            System.out.println("THe linked list is empty");
            return;  
        }  
        else 
        {  
            while(curr != null)
            {  
                //Node temp points to previous node to index.  
                temp = curr;  
                //Index points to the next node
                index = curr.nextNode;  
                while(index != null) 
                {  
                    //If curr node's data is equal to index node's data  
                    if(curr.data == index.data) 
                    {  
                        //If we find a duplicate node it skips the duplicate node by pointing to nextNode node  
                        temp.nextNode = index.nextNode;  
                    }  
                    else 
                    {  
                        //Temp points to the previous node in the index
                        temp = index;  
                    }  
                    index = index.nextNode;  
                }  
                curr = curr.nextNode;  
            }  
        }  
    }

    // method to add a node to the end of the linked list
    public void add(int data)
    {
        Node newNode = new Node(data);
        // Checks if there was any previous node
        if(head==null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail.nextNode = newNode;
            tail = newNode;
        }
    }
    
    // Method to display all the nodes of the linked list
    public void show()
    {
        Node curr = head;
        // If the head is pointing to no node then the linked list is empty
        if(head==null)
            System.out.println("Linked List is empty");
        else
        {
            System.out.println("The nodes are:");
            while(curr!=null)
            {
                System.out.print(curr.data+",");
                curr = curr.nextNode;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) 
    {
        // create an object of the main class
        Main ll = new Main();
        // add elements to the linked list
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);
        ll.add(20);
        ll.add(40);
        // display the nodes
        ll.show();
        System.out.println("Removing the duplicate nodes...");
        ll.removeDup();
        // display the nodes
        ll.show();
    }
}
Output:

The nodes are:
10,20,30,40,50,20,40,
Removing the duplicate nodes...
The nodes are:
10,20,30,40,50,

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

Java Program to Search for an Element in a Singly Linked List

In this article we are going to see how we can search for an element in a singly linked list by using Java programming language.

Java Program to Search for an Element in a Singly Linked List

Approach:

  • Create a linked list.
  • Add elements to it.
  • Display the list.
  • Ask the user to enter an element to search.
  • Pass the element into our user defined method search( ) method. The method iterates the whole list, compares the value.
  • Then prints the result.

Program:

import java.util.*;
// Main class
public class Main
{
    // Class Node that defines the two linked list variables
    class Node
    {
        int data;
        Node nextNode;
        // constructor to create a node
        public Node(int data) 
        {    
            this.data = data;    
            this.nextNode = null;    
        }    
    }

    // Setting the head and end of the node as NULL  
    public Node head = null;    
    public Node tail = null;  

    // method to search for a value in a linked list
    public void search(int data) 
    {  
        Node curr = head;  
        // iterator
        int i = 1;  
        // Flag to check the condition
        boolean flag = false;  
        if(head == null) 
        {  
            System.out.println("Linked list is empty");  
        }
        else 
        {  
            // Iterates the whole list
            while(curr != null)
            {  
                // compares the value with the data at each node
                if(curr.data == data) 
                {
                    // If a match is found breaks out of the loop  
                    flag = true;  
                    break;  
                }  
                i++;  
                curr = curr.nextNode;  
            }  
        }  
        if(flag)  
            System.out.println("Element is at location : " + i);  
        else  
            System.out.println("Element could not be found");  
    }  

    // method to add a node to the end of the linked list
    public void add(int data)
    {
        Node newNode = new Node(data);
        // Checks if there was any previous node
        if(head==null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail.nextNode = newNode;
            tail = newNode;
        }
    }
    
    // Method to display all the nodes of the linked list
    public void show()
    {
        Node curr = head;
        // If the head is pointing to no node then the linked list is empty
        if(head==null)
            System.out.println("Linked List is empty");
        else
        {
            System.out.println("The nodes are:");
            while(curr!=null)
            {
                System.out.print(curr.data+",");
                curr = curr.nextNode;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) 
    {
        // create an object of the main class
        Main ll = new Main();
        // add elements to the linked list
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);
        // display the nodes
        ll.show();
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a value to search");
        int val = sc.nextInt();
        ll.search(val);
    }
}
Output:

The nodes are:
10,20,30,40,50,
Enter a value to search
50
Element is at location : 5

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language.

Java Program to Find the Max and Min Values in a Linked List

In this article we are going to see how we can find the max and min values in a linked list by using Java programming language.

Java Program to Find the Max and Min Values in a Linked List

Approach:

  • Create a linked list.
  • Add elements to the list.
  • Display the elements.
  • Call the user defined method minVal() and maxVal() method to find the min and max value from the list. The method stores the head element in variable and compares it with the data from the rest of the list and prints the min/max value.

Program:

import java.util.*;
// Main class
public class Main
{
    // Class Node that defines the two linked list variables
    class Node
    {
        int data;
        Node nextNode;
        // constructor to create a node
        public Node(int data) 
        {    
            this.data = data;    
            this.nextNode = null;    
        }    
    }

    // Setting the head and end of the node as NULL  
    public Node head = null;    
    public Node tail = null;  

    // method to find the minimum value in the linked list  
    public void minVal() 
    {  
        Node curr = head;  
        int min;  
        if(head == null)
        {  
            System.out.println("Linked list is empty");  
        }  
        else 
        {  
            //Store the first node data
            min = head.data;  
            while(curr != null)
            {  
                //compare min with each node and if any value is smaller than min replace min with it.
                if(min > curr.data) 
                {  
                    min = curr.data;  
                }  
                curr= curr.nextNode;  
            }  
            System.out.println("Minimum value in the list is "+ min);  
        }  
    }  

    // method to find the maximum value in the linked list  
    public void maxVal() 
    {  
        Node curr = head;  
        int max;  
        if(head == null) 
        {  
            System.out.println("Linked list is empty");  
        }  
        else 
        {  
            //Storing the first node data in max  
            max = head.data;  
            while(curr != null)
            {  
                //compare max with each node and if any value is bigger than max replace min with it.  
                if(max < curr.data) 
                {  
                    max = curr.data;  
                }  
                curr = curr.nextNode;  
            }  
            System.out.println("Maximum value in the list is "+ max);  
        }  
    }  

    // method to add a node to the end of the linked list
    public void add(int data)
    {
        Node newNode = new Node(data);
        // Checks if there was any previous node
        if(head==null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail.nextNode = newNode;
            tail = newNode;
        }
    }
    
    // Method to display all the nodes of the linked list
    public void show()
    {
        Node curr = head;
        // If the head is pointing to no node then the linked list is empty
        if(head==null)
            System.out.println("Linked List is empty");
        else
        {
            System.out.println("The nodes are:");
            while(curr!=null)
            {
                System.out.print(curr.data+",");
                curr = curr.nextNode;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) 
    {
        // create an object of the main class
        Main ll = new Main();
        // add elements to the linked list
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);
        // display the nodes
        ll.show();
        ll.minVal();
        ll.maxVal();
    }
}
Output:

The nodes are:
10,20,30,40,50,
Minimum value in the list is 10
Maximum value in the list is 50

Grab the opportunity to learn all effective java programming language concepts from basic toadvance levels by practicing these Java Program Examples with Output.

Java Program to Add a Node to a Singly Linked List

In this article we are going to see how we can add a node to a singly linked list by using Java programming language.

Java Program to Add a Node to a Singly Linked List

In a linked list each element is called as a node which is having the actual element and a pointer to next element. You can add a new node at any position of the linked list.

Approach:

  • Create a linked list add some elements.
  • Display the list.
  • Add elements at the beginning by using the addBeg() user defined method that points the head to the new node and links the node to the rest of the list.
  • Display the list.
  • Ask the user to enter the position and data to insert.
  • Pass the values with head to the addPos( ) user defined method. The method iterates to the position and adds the node to the rest of the list.
  • Display the list.
  • Insert elements at the end by using insertEnd( ) user defined method. The method updates the tail and links the new node.
  • Display the list.

Program:

import java.util.*;
// Main class
public class Main
{
    // Class Node that defines the two linked list variables
    class Node
    {
        int data;
        Node nextNode;
        // constructor to create a node
        public Node(int data) 
        {    
            this.data = data;    
            this.nextNode = null;    
        }    
    }

    // Setting the head and end of the node as NULL  
    public Node head = null;    
    public Node tail = null;  

    // Method to add a node to the start of a linked list
    public void addBeg(int data)
    {  
        //Create a new node  
        Node newNode = new Node(data);  
        //Checks if the list is empty  
        if(head == null)
        {  
            // makes the head and tail point to the first node
            head = newNode;  
            tail = newNode;  
        }  
        else
        {
            Node temp = head;  
            //The newNode becomes the head of the linked list
            head = newNode;  
            //the head node now points to the previous head node
            head.nextNode = temp;  
        }  
    }

    // Method to add a node at a specified position
    public void addPos(Node headNode, int pos, int data) 
    {
        Node curr = headNode;
        // Position should be always greater than equals to 1
        if (pos < 1)
            System.out.print("Wrong input");
 
        // if position is 1 then the insertion happens at head
        if (pos == 1) 
        {
            // Setting the newNode as head
            Node newNode = new Node(data);
            newNode.nextNode = headNode;
            curr = newNode;
        } 
        else 
        {
            while (pos-- != 0) 
            {
                if (pos == 1) 
                {
                    Node newNode = new Node(data);
                    // Set the new node to point to the previously existing node
                    newNode.nextNode = headNode.nextNode;
                    headNode.nextNode = newNode;
                    break;
                }
                headNode = headNode.nextNode;
            }
            if (pos != 1)
                System.out.print("Wrong input");
        }
        head = curr;
    }

    // method to add a node to the end of the linked list
    public void add(int data)
    {
        Node newNode = new Node(data);
        // Checks if there was any previous node
        if(head==null)
        {
            head = newNode;
            tail = newNode;
        }
        else
        {
            tail.nextNode = newNode;
            tail = newNode;
        }
    }
    
    // Method to display all the nodes of the linked list
    public void show()
    {
        Node curr = head;
        // If the head is pointing to no node then the linked list is empty
        if(head==null)
            System.out.println("Linked List is empty");
        else
        {
            System.out.println("The nodes are:");
            while(curr!=null)
            {
                System.out.print(curr.data+",");
                curr = curr.nextNode;
            }
            System.out.println();
        }
    }

    public static void main(String[] args) 
    {
        // create an object of the main class
        Main ll = new Main();
        // add elements to the linked list
        ll.add(10);
        ll.add(20);
        ll.add(30);
        ll.add(40);
        ll.add(50);
        // display the nodes
        ll.show();
        // add a node at beginning
        System.out.println("Adding 11 at beginning");
        ll.addBeg(11);
        // Display the nodes
        ll.show();
        // Add a node at a position
        // Taking user input
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the position to enter a node and the data");
        int pos = sc.nextInt(), data = sc.nextInt();
        ll.addPos(ll.head,pos,data);
        // display the nodes
        ll.show();
        // Add a node at the end
        System.out.println("Adding 99 at end");
        ll.add(99);
        // display the nodes
        ll.show();
    }
}
Output:

The nodes are:
10,20,30,40,50,
Adding 11 at beginning
The nodes are:
11,10,20,30,40,50,
Enter the position to enter a node and the data
5 50
The nodes are:
11,10,20,30,50,40,50,
Adding 99 at end
The nodes are:
11,10,20,30,50,40,50,99,

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.