Java Program to Create a Tutorial Course Invoice

Java Program to Create a Tutorial Course Invoice

In this article you will see how to generate a tutorial course invoice by using java programming language.

Java Program to Create a Tutorial Course Invoice

As per problem statement, you have to create an tutorial course invoice. You have provided with Course details specifying course id, course name, fee of the course.

Course Details

Approach:

  • Two classes created Main class and Course class.
  • Main class is the driver class and Course class has all the properties of course.
  • In Main class, it will ask the user to enter required details like student name, course, id, course duration in months, course fee per month etc.
  • To create object of Course class we have created a constructor of it. All the course t properties are put in the constructor. This class contains two user defined methods displayFormat() and display() method to display bill details in console.

Program:

import java.util.ArrayList;  
import java.util.List;  
import java.util.Scanner;  
import java.text.SimpleDateFormat;    
import java.util.Date;    
import java.util.Calendar;  
class Course   
    {  
        //declaring variables 
        private String course_id;  
        private String course_name;  
        private int course_duration;  
        private double price;  
        private double total_price;  
           
        //constructor  
        Course(String course_id, String course_name, int course_duration, double price, double total_price)   
        {  
            this.course_id=course_id;  
            this.course_name = course_name;  
            this.course_duration = course_duration;  
            this.price = price;  
            this.total_price = total_price;  
        }  
            //getter methods  
            public String getId()   
                {  
                    return course_id;  
                }  
                public String getPname()   
                {  
                    return course_name;  
                }  
                public int getQty()   
                {  
                    return course_duration;  
                }  
                public double getPrice()   
                {  
                    return price;  
                }  
                public double getTotalPrice()   
                {  
                    return total_price;  
                }  
                //displayFormat() method to display the column names  
                public static void displayFormat()   
                {  
                    System.out.format("---------------------------------------------------------------------------------------------------------------------------");  
                    System.out.print("\nCourse ID \t\tName\t\tDuration(In Months)\t\tRate(Per Month) \tTotal Price\n");  
                    System.out.format("---------------------------------------------------------------------------------------------------------------------------\n");  
                }  
                   
                //display() method  to display the column values
                public void display()   
                {  
                    System.out.format("   %-9s             %-9s           %5d                      %9.2f           %14.2f\n" ,course_id, course_name, course_duration, price, total_price);  
                }  
    }  
public class Main 
    {  
        public static void main(String args[])   
            {  
                //variables declared and initialized
                String courseId = null;  
                String courseName = null;  
                int duration = 0;  
                double price = 0.0;  
                double total_price = 0.0;  
                double overAllPrice = 0.0;  
                double cgst, sgst, subtotal=0.0, discount=0.0;  
                char option = '\0';  
                System.out.println("\t\t\t\t--------------------BtechGeeks Course Invoice-----------------");  
                System.out.println("\t\t\t\t\t "+"               "+"Hyderabad, India");   
                System.out.println("GSTIN: 03AYJKK932M762"+"\t\t\t\t\t\t\tContact: (+91) 9876543210");  
                //format of current date and time  
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");    
                Date date = new Date();    
                Calendar calendar = Calendar.getInstance();  
                String[] days = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Frcourse_iday", "Saturday" };  
                //Printing current date and time  
                System.out.println("Date: "+formatter.format(date)+"  "+days[calendar.get(Calendar.DAY_OF_WEEK) - 1]+"\t\t\t\t\t\t (+91) 9998887770");  
                Scanner sc = new Scanner(System.in);  
                System.out.print("Enter Student Name: ");  
                String customername=sc.nextLine();  
                //create Scanner class object  
                //creating an ArrayList to store the course  
                List<Course> course = new ArrayList<Course>();  
                do   
                    {  
                        //taking input values 
                        System.out.println("Enter the Course details: "); 
                        //Asking course ID
                        System.out.print("Course ID: ");  
                        courseId = sc.nextLine();  
                        //Asking course Name
                        System.out.print("Course Name: ");  
                        courseName = sc.nextLine();  
                        //Asking course Duration in months
                        System.out.print("Duration (in month): ");  
                        duration = sc.nextInt(); 
                        //Asking course Price per month
                        System.out.print("Price (per month): ");  
                        price = sc.nextDouble();  
                        //calculating total price for a specific course  
                        total_price = price * duration;  
                        //calculating overall price  
                        overAllPrice = overAllPrice + total_price;  
                        //creating Course class object and adding it to the List  
                        course.add( new Course(courseId, courseName, duration, price, total_price) );  
                        //asking for continue with other courses?  
                        System.out.print("Want to add more courses? (y or n): ");  
                        //reading a character y or Y or N or n 
                        option = sc.next().charAt(0);  
                        //read remaining characters, don't store (no use)  
                        sc.nextLine();  
                    }   
                while (option == 'y' || option == 'Y');  
                //display all course with its properties  
                Course.displayFormat();  
                for (Course p : course)   
                {  
                    p.display();  
                }  
                //price calculation  
                System.out.println("\n\t\t\t\t\t\t\t\t\t\tTotal Amount (Rs.) " +overAllPrice);  
                //calculating discount amount 
                //Suppose we are offering 10% discount on total course fee
                discount = overAllPrice*10/100;  
                System.out.println("\n\t\t\t\t\t\t\t\t\t\t    Discount (Rs.) " +discount);  
                //calculating total amount after discount  
                subtotal = overAllPrice-discount;   
                System.out.println("\n\t\t\t\t\t\t\t\t\t\t          SubTotal "+subtotal);  
                //calculating tax amount 
                sgst=overAllPrice*12/100;  
                System.out.println("\n\t\t\t\t\t\t\t\t\t\t          SGST (%) "+sgst);  
                cgst=overAllPrice*12/100;  
                System.out.println("\n\t\t\t\t\t\t\t\t\t\t          CGST (%) "+cgst);  
                //calculating final amount to be paid
                System.out.println("\n\t\t\t\t\t\t\t\t\t\t     Invoice Total " +(subtotal+cgst+sgst));  
                System.out.println("\t\t\t\t    All the Best for Your Bright Future"); 
                System.out.println("\t\t\t\t----------------Thank You!!-----------------");  
                //Closing Scanner object
                sc.close();  
            }     
    }

Output:

Java Program to Create a Tutorial Course Invoice

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 Get the Parts of an URL

In this article you will see how to get the different components of URL by using Java programming language.

Java Program to Get the Parts of an URL

Uniform Resource Locator in short it is called as URL which is used to uniquely identify a resource on the internet. An URL has many forms but in general they follow these 4 forms.

  1. Protocol
  2. Hostname
  3. File Name
  4. Port Number(Optional)

Lets see an example.

Link: https://btechgeeks.com/java-programming-examples

Here,
Protocol: https
Host Name: btechgeeks.com
File Name: java-programming-examples

In Java we have java.net.URL class which acts as an resource locator in WWW(World Wide Web). There are many methods of URL class like-

  • public String getProtocol(): Returns the protocol of the URL
  • public String getPort(): Returns the Port Number of the URL
  • public String getHost(): Returns the host name of the URL
  • public String getFile(): Returns the file name of the URL
  • public String getDefaultPort(): Returns the default port of the URL

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

Approach:

  • Create the object of URL and pass the input URL as parameter.
  • By using the URL object call the respective inbuilt methods of URL class.
  • Get the result.

Program:

import java.net.URL;

public class Main
{
   //Driver method
   public static void main(String args[]) throws Exception 
   {
      //Input URL
      URL u = new URL("https://btechgeeks.com/java-programming-examples/#Java_Star_Pattern_Programs");
      //String representation of the URL
      System.out.println("URL is: " + u);
      //Get the Protocol
      System.out.println("Protocol is: " + u.getProtocol());
      //Get the File name
      System.out.println("File part is: " + u.getFile());
      //Get the Host name
      System.out.println("Host is: " + u.getHost());
      //Get the Path
      System.out.println("Path is: " + u.getPath());
      //Get the Port
      System.out.println("Port is: " + u.getPort());
      //Get the Default port
      System.out.println("Default port is: " + u.getDefaultPort());
   }
}

Output:

URL is: https://btechgeeks.com/java-programming-examples/#Java_Star_Pattern_Programs
Protocol is: https
File part is: /java-programming-examples/
Host is: btechgeeks.com
Path is: /java-programming-examples/
Port is: -1
Default port is: 443

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 Write Display Weekday

Java Program to Write Display Weekday

In this article we are going to see how to display weekday in Java along with suitable examples.

Java Program to Write Display Weekday

The java.text.SimpleDateFormat class provides inbuild methods to format the date and time in java.

There are 2 patterns which we can use in SimpleDateFormat to display the weekday.

  1. EEE: used for displaying weekday in short form.
  2. EEEE: used for displaying weekday in full form.

Let’s see the program to understand it clearly.

Method-1: Java Program to Write Display Weekday By Using EEEE Format

Approach:

  • Create another object of SimpleDateFormat as ‘s’ with the argument as ‘EEEE’.
  • Declare a string variable as ‘day’ and initialize it to the current date and time using an inbuild method of SimpleDateFormat as s.format(new Date())
  • Print the result.

Program:

import java.text.SimpleDateFormat;
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
    //create an object of SimpleDateFormat as ‘s’ with the argument as ‘EEEE’.
    SimpleDateFormat s = new SimpleDateFormat("EEEE");
    // Declare a string variable as ‘month’ 
    //and initialize it to the current date and time 
    //using an inbuild method of SimpleDateFormat as s.format(new Date())
    String day= s.format(new Date());
    //Print the result in fullform
    System.out.println("Weekday in fullform is "+day);
    }
}

Output:

Weekday in full form is Friday

Method-2: Java Program to Write Display Weekday By Using EEE Format

Approach:

  • Create another object of SimpleDateFormat as ‘s’ with the argument as ‘EEE’.
  • Declare a string variable as ‘day’ and initialize it to the current date and time using an inbuild method of SimpleDateFormat as s.format(new Date())
  • Print the result.

Program:

import java.text.SimpleDateFormat;
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
    //create an object of SimpleDateFormat as ‘s’ with the argument as ‘EEE’.
    SimpleDateFormat s = new SimpleDateFormat("EEE");
    // Declare a string variable as ‘month’ 
    //and initialize it to the current date and time 
    //using an inbuild method of SimpleDateFormat as s.format(new Date())
    String day= s.format(new Date());
    //Print the result in fullform
    System.out.println("weekday in fullform is "+day);
    }
}

Output:

Weekday in full form is Fri

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 Identify Two Addresses are Same or Not When Two Address Details are Separated by Comma and in Jumbled Manner

Java Program to Identify Two Addresses are Same or Not When Two Address Details are Separated by Comma and in Jumbled Manner

In this article you will see how you can identify two addresses are same or not even it they are in jumbled manner by using Java programming language.

Java Program to Identify Two Addresses are Same or Not When Two Address Details are Separated by Comma and in Jumbled Manner

As per the problem statement you have to identify two addresses are same or different where both the addresses are in jumbled manner.

Let’s understand it with an example.

Suppose you have 2 addresses.
Address-1: "PLOT-345, SAI NAGAR , MADHAPUR , HYDERABAD"
Address-2: "PLOT-345, MADHAPUR , SAI NAGAR , HYDERABAD"
If you will look both the address then both the addresses are same only difference is the addresses is jumbled.

Let’s see another example.

Address-1: "PLOT-245, SAI NAGAR , MADHAPUR , HYDERABAD"
Address-2: "PLOT-345, MADHAPUR , SAI NAGAR , HYDERABAD"
If you will look both the address then both the addresses are not same. 
Here, PLOT number of both the addresses differs.

Let’s understand it more clearly with an program.

Approach:

  • Declared two String variables and assign two addresses as values.
  • Declared two array of String and and split both the addresses based on space and store the elements in both the array respectively.
  • Compared both the array by using containsAll() method.
  • If one array contains all the elements of another array then it is sure both the addresses are same else both the addresses are not same.

Program-1: (With Same Address & in Jumbled Manner)

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        //declared two String variables and assigned two addresses as values
        String address1= new String("PLOT-345, SAI NAGAR , MADHAPUR , HYDERABAD"); 
        String address2= new String("PLOT-345, MADHAPUR , SAI NAGAR , HYDERABAD");
        //declared two array of String
        //and splited both the addresses based on space 
        //and stored the elements in both the array respectively
        String a1[] = address1.split(" ");
        String a2[] = address2.split(" ");
        //compared both the array elements by using containsAll() method
        //if one array contains all the elements of another array
        //then it is sure both the addresses are same
        if(Arrays.asList(a1).containsAll(Arrays.asList(a2))) 
        {
            System.out.print("BOTH ADDRESSES ARE SAME");
        } 
        //Else both the addresses are not same
        else 
        {
            System.out.print("BOTH ADDRESSES ARE NOT SAME");
        }
        
    }
}

Output:

BOTH ADDRESSES ARE SAME

Program-2: (With Different Address & in Jumbled Manner)

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        //declared two String variables and assigned two addresses as values
        String address1= new String("PLOT-245, SAI NAGAR , MADHAPUR , HYDERABAD"); 
        String address2= new String("PLOT-345, MADHAPUR , SAI NAGAR , HYDERABAD");
        //declared two array of String
        //and splited both the addresses based on space \
        //and stored the elements in both the array respectively
        String a1[] = address1.split(" ");
        String a2[] = address2.split(" ");
        //compared both the array by using containsAll() method
        //if one array contains all the elemnts of another array
        //then it is sure both the addresses are same
        if(Arrays.asList(a1).containsAll(Arrays.asList(a2))) 
        {
            System.out.print("BOTH ADDRESSES ARE SAME");
        } 
        //Else both the addresses are not same
        else 
        {
            System.out.print("BOTH ADDRESSES ARE NOT SAME");
        }
        
    }
}

Output:

BOTH ADDRESSES ARE NOT SAME

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 Reverse the Words of a String and after Reversal First Word First Letter should be Capital and Last Word First Letter should be Small

Java Program to Reverse the Words of a String and after Reversal First Word First Letter should be Capital and Last Word First Letter should be Small

In this article you will see how to reverse the words of a string and after reversal first word first letter should be capital and last word first letter should be small by using Java programming language.

Java Program to Reverse the Words of a String and after Reversal First Word First Letter should be Capital and Last Word First Letter should be Small

As per the problem statement you need to reverse a String but the condition is after reversal first word first letter should be capital and last word first letter should be small. So let’s understand it with an example.

Example:

Suppose the string is: I am a boy
Reverse of the original String is: boy a am I
Reverse of the original String based on condition: Boy a am i

Let’s understand it more clearly with a program.

Approach:

  • Declare a String variable and initialize the String value to which you want to reverse.
  • Split the string based on space and stored in an String array.
  • Get the first letter of original String and store it in an character variable say ‘first‘, which will be placed at last in lower case format.
  • Now reverse the original String and store it in an String variable.
  • Get the first letter of reversed String and store it in an character variable say ‘last‘, which will be placed at first in Upper case format.
  • Now print value of ‘last‘ in upper case format by using toUpperCase() method.
  • Convert the reversed string to an array of characters.
  • Then print the array characters except first and last character.
  • Now print value of ‘first‘ in lower case format by using toLowerCase() method.
  • Now you can see the result printed  in output console.

Program:

public class Main
{
    public static void main(String[] args)
    {
        //Declared a String variable 'str' and initialized the value
        String str= new String("I belong to a middle class family"); 
        System.out.println("The original String is: "+str); 
        //Splitted the string based on space and stored in an String array
        String s[] = str.split(" ");
        
        //Got the letter, which will be placed at last in lower case format
        String first=str.substring(0,1);
        
        //declared a String varible 'ans' to hold the reversed String
        String ans = "";
        //Reversing the original String String
        for (int i = s.length - 1; i >= 0; i--)
        {
            ans += s[i] + " ";
        }
        System.out.println("The reversed String is: "+ans); 
        
        //Got the letter, which will be placed at first in Upper case format
        String last=ans.substring(0,1);
        
        System.out.print("The reversed String based on condition is: "); 
        //print the first character in Upper case
        System.out.print(last.toUpperCase()); 
        //converted the reversed string to an array of characters
        char[] ch=ans.toCharArray(); 
        //print the array characters except first and last character
        for(int i=1;i<ch.length-2;i++)
        {  
            System.out.print(ch[i]);  
        }
        //print the last character in lower case
        System.out.println(first.toLowerCase()); 
    }
}

Output:

The original String is: I belong to a middle class family
The reversed String is: family class middle a to belong I 
The reversed String based on condition is: Family class middle a to belong i

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 Count and Show the Repeated Words in a String without using HashMap

Java Program to Count and Show the Repeated Words in a String without using HashMap

In the previous article, we have discussed about Java Program to Reverse Sequence of Words of a Sentence

In this article we will see how to count and show the repeated words in a string without using Hashmap in Java programming language.

Java Program to Count and Show the Repeated Words in a String without using HashMap

As per the problem statement, it requires to count and show repeated words in the String without Hashmap. So, let’s do it by using array.

For example:

If the string is "abc bca cba abc abc cba"
Then the duplicate strings are-
abc=3
cba=2

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

Method-1: Java Program to Count and Show the Repeated Words in a String without using HashMap (By Using Array) & Static Input Value

Approach:

  • Declare a string variable and initialize it’s value.
  • Convert that string value to lowercase by using toLowerCase() method, which will be easy to compare.
  • Then split the string based on space by using split() method and store the string elements in an String array.
  • Then compare each elements with other elements of string array by using equals() method and keep track on occurrence of values.
  • Then by using an if condition check the elements whose occurrence is greater than 1, those elements are repeated words.

Program:

public class Main 
{    
    public static void main(String[] args) 
    {    
        String str = "abc bca cba abc abc cba";    
        int count;    
            
        //Converting the string into lowercase which will be easy to compare 
        str = str.toLowerCase();
        //splitted string based on space
        String word[] = str.split(" ");    
            
        System.out.println("Duplicate words in a given string : ");     
        for(int i = 0; i < word.length; i++) 
        {   
           // initializing count as 1
            count = 1;  
            //comparing each word with other words till last
            for(int j = i+1; j < word.length; j++) 
            {    
                if(word[i].equals(word[j]))
                {    
                   count++;
                   //it will not print visited word
                   word[j] = "0";    
                }    
            }    
                
            //duplicate word if count is greater than 1    
            if(count > 1 && word[i] != "0")    
                System.out.println(word[i]+"="+count);    
        }    
    }    
}

Output:

Duplicate words in a given string : 
abc=3
cba=2

Method-2: Java Program to Count and Show the Repeated Words in a String without using HashMap (By Using Array) & User Input Value

import java.util.*;

public class Main {    
    public static void main(String[] args) 
    {    
        int count;    
        Scanner sc = new Scanner(System. in );
        System.out.println("Enter a string/sentence");
        String str = sc.nextLine();   
        //Converting the string into lowercase which will be easy to compare 
        str = str.toLowerCase();
        //splitted string based on space
        String word[] = str.split(" ");    
            
        System.out.println("Duplicate words in a given string : ");     
        for(int i = 0; i < word.length; i++) 
        {   
           // initializing count as 1
            count = 1;  
            //comparing each word with other words till last
            for(int j = i+1; j < word.length; j++) 
            {    
                if(word[i].equals(word[j]))
                {    
                   count++;
                   //it will not print visited word
                   word[j] = "0";    
                }    
            }    
                
            //duplicate word if count is greater than 1    
            if(count > 1 && word[i] != "0")    
                System.out.println(word[i]+"="+count);    
        }    
    }    
}

Output:

Enter a string/sentence
I love Java I love BtechGeeks BtechGeeks BtechGeeks
Duplicate words in a given string : 
i=2
love=2
btechgeeks=3

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.

Related Java Programs:

Java Program to Sort Elements of an Array in the Format Negative Numbers to Positive Numbers & Smallest to Highest

Java Program to Sort Elements of an Array in the Format Negative Numbers to Positive Numbers & Smallest to Highest

In the previous article, we have discussed about Java Program to Reverse Array Elements

In this article we are going to see how to sort elements of an array in the format negative to positive numbers and smallest to highest by using Java programming language.

Java Program to Sort Elements of an Array in the Format Negative Numbers to Positive Numbers & Smallest to Highest

As per the problem statement, there is an array having negative and positive elements, you have to sort the array so that first negative numbers then positive numbers will be there in smallest to highest order format.

For Example:

Let say there is an array arr[] = {-5, 6, -7, 3, -1, 3, 9}
Solution: {-7, -5, -1, 3, 3, 6, 9}

Let’s see different programs to understand it more clearly.

Method-1: Java Program to Sort Elements of an Array in the Format Negative Numbers to Positive Numbers & Smallest to Highest By Using Manual Sorting Approach

Approach:

  • Declare an array and take the array elements(both positive and negative numbers) as user input.
  • Then sort the array in ascending order by comparing each element by using for loop.
  • Print the result.

Program:

import java.util.*;
public class Main
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the Array Size: ");
        int size=sc.nextInt();
        
        int[] arr=new int[size];
        
        //inserting elements
        System.out.println("Enter "+size+" elements into array:");
        for(int i=0;i<size;i++)
        {
            arr[i]=sc.nextInt();
        }
        
         System.out.println("Array elements after sort:");
         
        //ascending logic
        for(int i=0;i<size;i++)
        {
            for(int j=0;j<size;j++)
            {
                if(arr[i]<arr[j])
                {
                    int temp=arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        //displaying elements
        for(int i=0;i<size;i++)
        {
            System.out.print(arr[i]+" ");
        }
    }
}

Output:

Enter the Array Size: 
6
Enter 6 elements into array:
-5 4 -3 2 -1 7
Array elements after sort:
-5 -3 -1 2 4 7

Method-2: Java Program to Sort Elements of an Array in the Format Negative Numbers to Positive Numbers & Smallest to Highest By Using Inbuilt Arrays.sort() Method

Approach:

  • Declare an array and take the array elements(both positive and negative numbers) as user input.
  • Then sort the array in ascending order by comparing each element by using for loop.
  • Print the result.

Program:

import java.util.*;

public class Main
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the Array Size: ");
        int size=sc.nextInt();
        
        int[] arr=new int[size];
        
        //inserting elements
        System.out.println("Enter "+size+" elements into array:");
        for(int i=0;i<size;i++)
        {
            arr[i]=sc.nextInt();
        }
        
        System.out.println("Array elements after sort:");
         
        //Sorting the array in ascending logic by using inbuilt sort() method 
        Arrays.sort(arr);
        
        //displaying elements
        for(int i=0;i<size;i++)
        {
            System.out.print(arr[i]+" ");
        }
    }
}

Output:

Enter the Array Size: 
6
Enter 6 elements into array:
-5 4 -3 2 -1 7
Array elements after sort:
-5 -3 -1 2 4 7

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.

Related Java Programs:

Java Program to Display Current Month in the (MMMM) Format

Java Program to Display Current Month in the (MMMM) Format

In the previous article, we have discussed about Java Program to Display Current Date and Time

In this article we are going to see how to display current month in the (MMMM) format in Java along with suitable examples.

Java Program to Display Current Month in the (MMMM) Format

Let’s see the program to understand it clearly.

Method-1: Java Program to Display Current Month in the (MMMM) Format By Using SimpleDateFormat Class

The java.text.SimpleDateFormat class provides inbuild methods to format the date and time in java.

There are 2 patterns which we can use in SimpleDateFormat to display the month.

  1. MMM – used for displaying month in 3 letters.
  2. MMMM – used for displaying month in complete abbreviation.

Approach:

  • Create an object of SimpleDateFormat as ‘s’ with the argument as ‘MMMM’.
  • Declare a string variable as ‘month’ and initialize it to the current date and time using an inbuild method of SimpleDateFormat as s.format(new Date())
  • Print the result.

Program:

import java.text.SimpleDateFormat;
import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        //create an object of SimpleDateFormat as ‘s’ with the argument as ‘MMMM’.
        SimpleDateFormat s = new SimpleDateFormat("MMMM");
        // Declare a string variable as ‘month’ and initialize it to the current date and time using an inbuild method of SimpleDateFormat as s.format(new Date())
        String month = s.format(new Date());
        //Print the result in MMMM format
        System.out.println("Month in MMMM format = "+month);
    }
}
Output:

Month in MMMM format = June

Method-2: Java Program to Display Current Month in the (MMMM) Format By Using Calendar and Formatter Class

The java.util.Formatter class provides inbuild “.format()” methods to format the month in java.

The java.util.Calendar class provides an inbuild method “.getInstance()” method to get the instant date-time-month from the system calendar.

There are 3 patterns which we can use in Formatter to display the month.

  1. %tb – used for displaying month in 3 letters.
  2. %tB – used for displaying month in complete abbreviation.
  3. %tm – used for displaying month number.

Approach:

  • Declare a variable ‘cal’ of type Calendar and initialize it to get the system date-time using Calender.getInstance() method.
  • Create object of Formatter as ‘f1’ and initialize it to ‘f1.format("%tB",cal)’ to store the month in ‘MMMM‘ format.
  • Print the result.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        //declare a variable ‘cal’ of type Calender and initialize it to get the system date time month using Calender.getInstance() method.
      	Calendar cal = Calendar.getInstance();
        //create an object of Formatter as ‘f1
      	Formatter f1 = new Formatter();
        //store the month format in f1 variable
      	f1.format("%tB",cal);
        //Print the result
      	System.out.println("Month in MMMM format ="+f1);
    }
}
Output:

Month in MMMM format =June

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.

Related Java Programs:

Java Program to Display the Current Time

Java Program to Display Current Time

In the previous article, we have discussed about Java Program to Display Current Month in the (MMMM) Format

In this article we are going to see how to display the current time in Java along with suitable examples.

Java Program to Display the Current Time

Let’s see the program to understand it clearly.

Method-1: Java Program to Display the Current Time By Using Java LocalDate Class

The java.Time.LocalDate class provides inbuild “.now()” methods to format the current time in java.

Approach:

  • Create a variable of LocalTime as ‘date’.
  • Call an inbuild method of LocalTime i.e “.now()” method to get the current time and store the result in the variable “date”.
  • Print the result.

Program:

import java.time.LocalTime;
public class Main
{
    public static void main(String[] args)
    {
        // Create a variable of LocalTime as ‘date’, call an inbuild method of LocalTime “.now()” to get the current time and store the result in the variable “date”
      	LocalTime date = LocalTime.now();
        // Print the result
     	System.out.println("The current time in 24 hour format is "+ date);
    }
}
Output:

The current time in 24 hour format is 07:52:55.654615

Method-2: Java Program to Display the Current Time By Using Java Calendar Class

The java.util.Calendar class provides an inbuild method “.getInstance()” method to get the instant date-time-month from the system calendar. We can also direct get the current time in hour format using inbuild methods of calendar class i.e. calendar.get(Calendar.HOUR_OF_DAY))  represents hours in current system.

Approach:

  • Declare a variable ‘calendar’ of type Calendar and initialize it to get the system date-time using Calender.getInstance() method.
  • Print the result using inbuild methods of calendar class i.e. calendar.get(Calendar.HOUR_OF_DAY)).

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Declare a variable ‘calendar’ of type Calendar and initialize it to get the system date-time using Calendar.getInstance() method
        Calendar calendar = Calendar.getInstance();
        // Print the result using inbuild methods of calendar class
      	System.out.println("The current time in 24hour format is "+calendar.get(Calendar.HOUR_OF_DAY));
    }
}
Output:

The current time in 24hour format is 7

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

Related Java Programs:

Java Program to Display Current Date and Time

Java Program to Display Current Date and Time

In the previous article, we have discussed about Java Program to Display Current Month in the (MMM) Format

In this article we are going to see how to display current date and time in Java along with suitable examples.

Java Program to Display Current Date and Time

Let’s see the program

Method-1:

The java.util.Formatter class provides inbuild “.format()” methods to format the hour and minute in java.

The java.util.Calendar class provides an inbuild method “.getInstance()” method to get the instant date-time-month from the system calendar Where %tc represent current date and time.

Approach:

  • Create object of Formatter as ‘f’
  • Declare a variable ‘cal’ of type Calendar and initialize it to get the system date-time using Calendar.getInstance() method.
  • Using inbuild method of formatter class .format(“%tl:%tM”, calendar, calendar) we can get the current time in hour minute format.
  • Print the result.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create object of Formatter as ‘f’
      	Formatter f = new Formatter();
        // Declare a variable ‘cal’ of type Calendar 
        //and initialize it to get the system date-time using Calender.getInstance() method
     	Calendar cal = Calendar.getInstance();
        // using inbuild method of formatter class .format("%tc", cal) we can get the current date and time format
     	f.format("%tc", cal);
        //print the result
      	System.out.println("The current date and time is: "+f);
    }
}
Output:

The current date and time is: Sun Jun 26 07:39:14 GMT 2022

Method-2:

Approach:

  • Create an object of Date class which takes the system date and time.
  • Print the result using inbuild method of Date class as ‘date.toString()’ to get the current date and time.

Program:

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        // Create an object of Date class which takes the system date and time
        Date date = new Date();
        //Print the result using inbuild method of Date class as ‘date.toString()’ to get the current date and time.
      	System.out.println("The current date and time is: "+date.toString());
    }
}
Output:

The current date and time is: Sun Jun 26 07:43:18 GMT 2022

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.

Related Java Programs: