Java fundamental programs to practice: Conditional statement- switch:

               Switch is one of the conditional statements which is useful in selecting one among in multiple options.

Syntax:

Switch(Option)

{

 Case 1: statements…..

               break;

Case 2: statements…..

               break;

---------------------------

---------------------------

Case n: statements…..

               break;

}

Example for switch conditional statement is given below.

Java Program to print the month using switch case:

  • ·       Create a class SwitchMonth with main() function.
  • ·       Get the input from user. Using the switch statement,pass the input.
  • ·       Based on the input given, case statement is selected.
  • ·       The output is displayed as per the input.

//Java Program to print the month using switch case:

import java.util.Scanner;

public class SwitchMonth {

    public static void main(String[] args) {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter the number of the month:");

   int m= scanner.nextInt();

   switch (m) {

            case 1:

                System.out.println("January");

                break;

            case 2:

                System.out.println("February");

                break;

            case 3:

                System.out.println("March");

                break;

            case 4:

                System.out.println("April");

                break;

            case 5:

                System.out.println("May");

                break;

            case 6:

                System.out.println("June");

                break;

            case 7:

                System.out.println("July");

                break;

            case 8:

                System.out.println("August");

                break;

            case 9:

                System.out.println("September");

                break;

                  case 10:

                System.out.println("October");

                break;

                  case 11:

                System.out.println("November");

                break;

                  case 12:

                System.out.println("December");

                break;

            default:

                System.out.println("Invalid Month");

                break;

        }

    }

}

·       Compile and execute the program as follows…

C:\raji\blog>javac SwitchMonth.java

C:\raji\blog>java SwitchMonth

Enter the number of the month:6

June

C:\raji\blog>java SwitchMonth

Enter the number of the month:11

November

C:\raji\blog>java SwitchMonth

Enter the number of the month:3

March

C:\raji\blog>java SwitchMonth

Enter the number of the month:20

Invalid Month

This is the way of implementing switch statements to display the month name according to the user’s choice.

 

Java fundamental programs to practice: Conditional statements(if,else)

             Conditional statements are used to check the conditions. It uses the conditional statements listed below.

  • 1.       If statement
  • 2.       If else statement
  • 3.       If else if statement

Java fundamental program: To check a number is greater than five(if statement example)

              This program reads a input value. Check the value is greater than 5 or not and print the value.

import java.util.Scanner;

class great

{

 public static void main(String args[])

 {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter a number: ");

   int n = scanner.nextInt();

   if (n >5)

     System.out.println("The given number is greater than five");

 }

}

The output is given below.

C:\raji\blog>javac great.java

C:\raji\blog>java great

Enter a number: 7

The given number is greater than five

Next,if else statement example is given below.

Java fundamental program: To check your examination status pass or fail(if else statement example)

              This program reads a mark of a student. It checks the mark value is greater than 35 or not. If it is greater than 35, it prints the pass message. otherwise, it prints the fail message.

import java.util.Scanner;

class pos

{

 public static void main(String args[])

 {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter a mark: ");

   int ma = scanner.nextInt();

   if (ma > 35)

     System.out.println("You have passed in the examination");

   else

     System.out.println("sorry,you have failed in the examination");

 }

}

Here is the output.

C:\raji\blog>javac pos.java

C:\raji\blog>java pos

Enter a mark: 67

You have passed in the examination

C:\raji\blog>java pos

Enter a mark: 32

sorry,you have failed in the examination

Next program is using if else ladder.

Java fundamental program: To check your mark grade (if else if ladder statement example)

              This program reads the mark. Prints the grade according to the mark using multiple if else statement conditional statement checking.

import java.util.Scanner;

public class ifelseif

{

 public static void main(String args[])

 {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter the mark:");

   int m= scanner.nextInt();

   if(m>90)

    System.out.println("You have scored well. Your grade is A");

   else if(m<=89 && m>80)

    System.out.println("Your grade is B");

   else if(m<=79 && m>60)

    System.out.println("Your grade is C");

   else if(m<=59 && m>=35)

    System.out.println("Your grade is D");

   else

    System.out.println("Sorry. You have failed in the examination");

 }

}

The output is shown below.

C:\raji\blog>javac ifelseif.java

C:\raji\blog>java ifelseif

Enter the mark: 97

You have scored well. Your grade is A

C:\raji\blog>java ifelseif

Enter the mark: 87

Your grade is B

C:\raji\blog>java ifelseif

Enter the mark:76

Your grade is C

C:\raji\blog>java ifelseif

Enter the mark:45

Your grade is D

C:\raji\blog>java ifelseif

Enter the mark:31

Sorry. You have failed in the examination

These are the ways of using if else conditional statements in java programs in basic level. Enjoy coding.


Java fundamental programs for beginners:

     Java is a object oriented programming language. It was developed by James Gosling in sun micro systems. It is a general-purpose language. It uses classes for creating programs.

A simple program is given below.

Class greeting is used to display a message “Have a nice day” using system.out.println()

class  greeting

{

 public static void main(String args[])

{

System.out.println("Have a nice day");

}

}

Save this file as “greeting.java”. compile and execute this file to get the output.

Output:

C:\raji\blog>javac greeting.java

C:\raji\blog>java greeting

Have a nice day

Next, an arithmetic operation : Multiplication of two numbers

Here, a class arith is created. Two integer values are assigned as input. Using print statement, the two values are multiplied and displayed.

class arith

{

 public static void main(String args[])

 {

  int a = 10;

  int b = 20;

  System.out.println("The multiplication of two numbers are:"+(a*b));

 }

}

Here is the output.

C:\raji\blog>javac arith.java

C:\raji\blog>java arith

The multiplication of two numbers are:200

Note:

Use the same code except the operation(a*b) for other arithmetic operations. Replace by below code.

For addition of two numbers:

  System.out.println("The sum of two numbers are:"+(a+b));

 For subtraction of two numbers:

  System.out.println("The subtraction of two numbers are:"+(a-b));

For division of two numbers:

  System.out.println("The division of two numbers are:"+(a/b));

Next programs uses the conditional statement if,else.

Fundamental java program: Check the given number is odd or even

import java.util.Scanner;

class oddeven

{

 public static void main(String args[])

 {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");

        int no = scanner.nextInt();

        if(no % 2 == 0)

         System.out.println("This is an even number");

        else

         System.out.println("This is an odd number");

 }

}

The output is shown.

C:\raji\blog>javac oddeven.java

C:\raji\blog>java oddeven

Enter a number: 34

This is an even number

C:\raji\blog>java oddeven

Enter a number: 23

This is an odd number

These are the Java fundamental programs for beginners.

Print different patterns using java programs

    Patterns are the sequence of some shapes or numbers in some particular order. These can be created by  sequence of looping statements. Here, three programs are listed below.

part1 of these type of programs blog is linked here.

https://www.blogger.com/blog/post/edit/5251857942821229/5422820259444677124

#Java Program to print right angle triangle:

              This program creates a right angle triangle pattern.

Steps:

  • ·       Create a class sample1 with main() function.
  • ·       Get the number of lines to print the pattern.
  • ·       Using two for loops starts from value 1 to value n.
  • ·       Repeat until it reaches the ‘n’.
  • ·       Just print the * pattern.

class sample1

{

public static void main(String args[])

{

int no=7;

System.out.println("Printing right angle triangle pattern");

for(int i=1;i<=no;i++)

{

 for(int j=1;j<=i;j++)

 {

  System.out.print("*");

 }

System.out.println();

}

}

}

While you run this code, this below output will shown….

C:\raji\blog>javac sample1.java

C:\raji\blog>java sample1

Printing right angle triangle pattern

*

**

***

****

*****

******

*******

This is the output.

 #Java Program to print reverse right angle triangle:

              This program has the following logic.

  • ·       It gets the number of lines to print as input.
  • ·       Create two loops to print the pattern. Using, from a number to 1, repeat the loop.
  • ·       Print the pattern.

class sample2

{

public static void main(String args[])

{

int no=7;

for(int i=no;i>=1;i--)

{

 for(int j=1;j<=i;j++)

 {

  System.out.print("*");

 }

System.out.println();

}

}

}

The output is given below.

C:\raji\blog>javac sample2.java

C:\raji\blog>java sample2

*******

******

*****

****

***

**

*

#Java program to print a triangle:

  • ·       This program reads the number of lines to print the pattern.
  • ·       Using two loops, the space is printed first, pattern is printed after the space.
  • ·       This will be repeated until the number of lines.

public class triangle1 {

    public static void main(String[] args) {

        int no = 7;

        for (int i = 0; i < no; i++) {

            for (int j = no - i; j > 1; j--) {

                System.out.print(" ");

            }

            for (int j = 0; j <= i; j++) {

                System.out.print("* ");

            }

            System.out.println();

        }

}

}

Output:

C:\raji\blog>javac triangle1.java

C:\raji\blog>java triangle1

      *

     * *

    * * *

   * * * *

  * * * * *

 * * * * * *

* * * * * * *

These are the ways to print different patterns using java program. Enjoy coding!!!!

Base64 Encoding and Decoding in java8

     Data is everywhere. Anybody can track your data. To secure your data, it should be protected. Java8 offers you a built-in package “java.util.Base64” for security.

Base64 encoding and decoding is the process of making binary data into ASCII string data with 64 characters. Here, encoding is the process of converting normal data into Base64 encoding string.

Decoding is the process base64 encoding string into normal data.

Let us code an example.

First, encode a data into Base64 encoding format:

Steps to follow:

  • ·       Import the built in package java.util.Base64
  • ·       Create a class with main() function.
  • ·       Get the data to be encoded.
  • ·       Using the built in function encodeTostring() to encode the string. It gets the and use Base64.getEncoder() function to encode the data.
  • ·       Finally, Print the original data and encoded data.

//Java program to Base64 encoding a data

import java.util.Base64;

public class Base64Encode {

    public static void main(String[] args) {

        String originalData = "Happiness starts from you";

       // Encode the string

        String encodedData = Base64.getEncoder().encodeToString(originalData.getBytes());

        System.out.println("Original Data: " + originalData);

        System.out.println("Encoded Data: " + encodedData);

    }

}

Just compile and run the program to display the output.

C:\raji\blog>javac Base64Encode.java

C:\raji\blog>java Base64Encode

Original Data: Happiness starts from you

Encoded Data: SGFwcGluZXNzIHN0YXJ0cyBmcm9tIHlvdQ==

This is the output for encoding the data.

Next program is to decode the data.

Java Program to Base64 Decoding a data:

Steps to follow:

  • ·       Include the built in package java.util.Base64
  • ·       Create a class Base64Decode with main() function.
  • ·       Get the data to be decoded.
  • ·       Using the built in function getDecoder() to decode the string. It gets the and use decode() function to decode the data.
  • ·       Finally, Print the encoded and decoded data.

//Java Program to Base64 Decoding a data

import java.util.Base64;

public class Base64Decode {

    public static void main(String[] args) {

        String encodedData = "SGFwcGluZXNzIHN0YXJ0cyBmcm9tIHlvdQ==";

        byte[] decodedBytes = Base64.getDecoder().decode(encodedData);

        String decodedData = new String(decodedBytes);

        System.out.println("Encoded Data: " +encodedData);

        System.out.println("Decoded Data: " + decodedData);

    }

}

While running the program,the output will shown in the display is given below.

C:\raji\blog>javac Base64Decode.java

C:\raji\blog>java Base64Decode

Encoded Data: SGFwcGluZXNzIHN0YXJ0cyBmcm9tIHlvdQ==

Decoded Data: Happiness starts from you

This is the simple way of creating Base64 encoding and decoding in java programming.

How to implement CompletableFuture class in java8?

     CompletableFuture deals with asynchronous programming. It run the process asynchronously. It allows the programs to execute in parallelly.

Built in package: java.util.concurrent.

Why completableFuture class?

CompletableFuture is efficient and provide response in timely manner. It has many functions listed below.

  • supplyAsync ,runAsync : It deals with asynchronous computations to run the tasks.
  • thenApply,thenAccept,thenRun : Multiple tasks executed and linked together to perform the computation.
  • thenCombine,thenCompose,allOf : It combines the tasks.
  • Exception handling: If any error occurs, this will handle.

Let the program begins.

First, Asynchronous Computation using completableFuture Program in java is given below.

Steps:

  • ·       Create a public class CFEg with main() function.
  • ·       Next, include the lambda expression to execute the code.
  • ·       To print the output, use try and catch block to avoid errors.

//Program to implement Asynchronous computation using CompletableFuture.

import java.util.concurrent.*;

public class CFEg { 

  public static void main(String[] args) { 

              CompletableFuture<String> fu1 = CompletableFuture.supplyAsync(() -> {

        return "Hi,Asynchronous Computation is done with completableFuture";

              });

        try {

              System.out.println(fu1.get());

        } catch(Exception e)

        {

        System.out.println(e);

         }

}

}

Save,compile and execute the program to get the output.

C:\raji\blog>javac CFEg.java

C:\raji\blog>java CFEg

Hi,Asynchronous Computation is done with completableFuture

Next program is to implement the chaining tasks.

Program to implement chaining tasks using CompletableFuture:

Steps:

  • ·       Create a class and main() function.
  • ·       Create three objects for CompletabeFuture. Two for getting input as chaining tasks. Third one for combining these two.
  • ·       Print the output using try and catch block.

//Program to implement chaining tasks using CompletableFuture:

import java.util.concurrent.*;

public class CFEg1 { 

public static void main(String[] args) { 

CompletableFuture<String> fut1 = CompletableFuture.supplyAsync(() -> "Welcome to the world of");

CompletableFuture<String> fut2 = CompletableFuture.supplyAsync(() -> "CompletableFuture coding");

CompletableFuture<String> combinedFuture = fut1.thenCombine(fut2, (ts1, ts2) -> ts1 + " " + ts2);

 try {

              System.out.println(combinedFuture.get());

        } catch(Exception e)

        {

        System.out.println(e);

         }

}

}

Compile and execute the program.

C:\raji\blog>javac CFEg1.java

C:\raji\blog>java CFEg1

Welcome to the world of CompletableFuture coding

Next program is given below.

Program to implement combining future using CompletableFuture:

Steps:

  • ·       Import the built in package.
  • ·       Create a class and include main function.
  • ·       Using the system functions to print the output.

//Program to implement combining future using CompletableFuture:

import java.util.concurrent.*;

public class CFEg2 { 

  public static void main(String[] args) { 

try {

CompletableFuture<Void> fut = CompletableFuture.supplyAsync(() -> "Asynchronous")

   .thenAcceptAsync(res -> System.out.println(res + "  Programming"));

fut.get();

 } catch(Exception e)

        {

        System.out.println(e);

         }

}

}

Run the program and the output is displayed.

C:\raji\blog>javac CFEg2.java

C:\raji\blog>java CFEg2

Asynchronous  Programming

These are the different programs to implement CompletableFuture class in java8. It is useful in building efficient code.

How to Illustrate Type annotations in java8

    Annotations are the information that can be treated as supplement about the program. It is used to associate with the meta data. Generally, it contains the information about classes, methods, constructors, variables and so on…

Syntax:

@Annotation_Information

Eg: @FunctionalInterface

Built in package for annotation is java.lang.annotation

Where to use annotations??

              Mainly, annotations are used in declaration. It can declare a class, member functions, variables and so on. In java8, it deals with types. So, it is called Type annotations.

Type annotations are very useful in object creation, type casting an element, implements and thrown statements.

Some of the examples are given below.

1.       Object creation:

This is used to create an object for a class.

Eg:

new @Class1 Obj(); where new is the keyword to create an object. @Class1 is the class. Obj() is the object name.

2.       Type casting:

It is the process of converting one datatype to another.

              Eg: a = (@NonNull int) b;

3.       Using thrown:

Thrown is an exception. This can be implemented by as follows.

              Eg: void SampleMethod() throws

@Critical  MethodException()

{

---------------

}


4.       Using Implements:

        “Implements” is one of the clause used in java.

Eg: class SampleList<L> implements

      @ReadOnly List<@Readonly L>

      {

      …………

      }

          These are the ways of type annotations are used.

        Now, a java program to illustrate type annotation is given below.

Java program to illustrate Type Annotation:

              This java program has following steps to implement the type annotation.

Steps:

  • As a beginning of the program, include the built in packages.
  • Create a type annotation @Target.
  • Implement it using an interface @interface.
  • Create a public class TypeAnnotationEg and save it.
  • Inside the main function, create a type annotation with a string str. Displays the message as “It is a type annotation example” using system.out.println.
  • Call the Msg() function.
  • Inside the Msg(), print the message.

//Java program to illustrate type annotation

import java.lang.annotation.ElementType;

import java.lang.annotation.Target;

@Target(ElementType.TYPE_USE)

@interface TypeAnnoIf{}

public class TypeAnnotationEg {

              public static void main(String[] args) {

                            @TypeAnnoDemo String str = "It is a type annotation example";

                             System.out.println(str);

                             Msg();

              }

              static @TypeAnnoIf int Msg() {

              System.out.println("The return data is annotated");

              return 0;

              }

}

Compile and run the program to print the output.

C:\raji\blog>javac TypeAnnotationEg.java

C:\raji\blog>java TypeAnnotationEg

It is a type annotation example

The return data is annotated

     Sometimes annotations are alternative to XML and JMI(Java Marker Interface).Annotations 

How to run JavaScript embedded in java program using Nashorn JavaScript Engine??

 Nashorn JavaScript Engine

              It is a JavaScript engine introduced in java8. It was developed by oracle. Now, it is under the OpenJDK community.

Purpose:

This is used to run the JavaScript code in JVM (Java Virtual Machine).

Why Nashorn?

It is efficient in execution compared to previous one (Rhino Engine).

It easily integrates java and JavaScript. The user can simply use the command line.

How to run JavaScript embedded in java program using Nashorn JavaScript Engine??

              Here, java Script is a single line which displays a greetings “Happy Programming”.

Steps:

  • Import three built in packages from javax.script(.ScriptEngine,.ScriptEngineManager,.ScriptException)
  • Create a public class NashornEg and save the file as “NashornEg.java”
  • Inside the main() function,create an object for ScriptEngineManager as mgr.
  • Get the Nashorn script Engine.
  • Write a java script code.
  • Eval the script by Object result1 = engine1.eval(script);
  • Print the result.

import javax.script.ScriptEngine;

import javax.script.ScriptEngineManager;

import javax.script.ScriptException;

public class NashornEg {

    public static void main(String[] args) {

        // Create an object for ScriptEngineManager

        ScriptEngineManager mgr = new ScriptEngineManager();

       // find the Nashorn script engine

        ScriptEngine engine1 = mgr.getEngineByName("nashorn");

      // JavaScript code

        String script = "var greetings = 'Happy Programming!';";

        try {

            // create an object and call the function

            Object result1 = engine1.eval(script);

           // Print the output

            System.out.println(result1);

        } catch (ScriptException e) {

            e.printStackTrace();

        }

    }

}

  • Compile the program.
  • If the compilation is successful, run the program.

C:\raji\blog>javac NashornEg.java

C:\raji\blog>java NashornEg

Happy Programming!

Let us try some more scripting….

Java Script to display “Happy Birthday. Stay Blessed Always!!!!”.

Same program is used with java script code alone changed.

        String script = "var bMsg = 'Happy Birthday. Stay Blessed Always!!!!';";

Change the code. Execute the same program as below.

C:\raji\blog>javac NashornEg.java

C:\raji\blog>java NashornEg

Happy Birthday. Stay Blessed Always!!!!

That’s all. The java program to use JavaScript within the code is developed successfully.

Note: This JavaScript engine is used as standalone project on GitHub because it was deprecated in java11.

How to implement Static methods in interface concept in java8???

  The word “Static” is applicable for the interface. It does not be an instance of the class which implements the interface.

Why static method???

  • ·       Scope of the static methods is visible within interface.
  • ·       It belongs to interface only. So, utility methods are declared as static methods.

Simple program to implement static methods in interface:

              This program creates an interface with a static method “staticMd()” to print the static method message. Even though, a class is declared to implement the interface, the method belongs to the interface only.

//Java Program to implement static methods in interface

interface MyInter {

    static void staticMd() {

        System.out.println("This is a static method in an interface MyInter");

    }

}

public class MyCls implements MyInter {

    public static void main(String[] args) {

        MyInter.staticMd(); // Function call

    }

}

Save this file as “MyCls.java”.

Compile the program in command prompt.

C:\raji\blog>javac MyCls.java

Execute the program as follows. You will get this output.

C:\raji\blog>java MyCls

This is a static method in an interface MyInter.

 Next, a program for odd or even number checking is given below.

Java Program to implement Odd/Even number checking using static methods in interface:

              This java program has following steps to implement the concept.

  • Create an interface “MyInter1”.
  • Inside the interface, implement the static method as “static void staticOddEven(int a)”.

         Where,

        static – keyword.

        void – return type.(It doesn’t return anything)

        staticOddEven – this is the static function name.

        int a – input of a function as integer.

  • This function checks the given number is odd or even and print it.
  • Create a class “MyCls1” to implement the interface “MyInter1”.
  • Inside it,create a main function.
  • Call the static function “MyInter1.staticOddEven(6)”.

// Java Program to implement Odd/Even number checking using static methods in interface

interface MyInter1 {

    static void staticOddEven(int a) {

      if(a%2==0)

        System.out.println("The number is a even number");

      else

       System.out.println("The number is a even number");

          }

}

public class MyCls1 implements MyInter1 {

    public static void main(String[] args) {

        MyInter1.staticOddEven(6); // static method call

    }

}

Compile and run the program to get the output.

C:\raji\blog>javac MyCls1.java

C:\raji\blog>java MyCls1

The number is a even number

These are the ways to implement the static methods in interface concept in java8. Keep Coding!!!!

How to display a vehicleList using forEach in java8 programming?

              Java8 offers variety of concepts like lambda expressions, functional interfaces, streams, default methods, collectors and so on…

“Foreach” is an added feature for looping to iterate the elements. It uses lambda expression or looping.

Java Program to display the vehicle list using ForEach method using Lambda expressions:

Steps to follow:

  • ·       This program creates a vehicleList as string.
  • ·       Add the list of vehicles to vehicleList.
  • ·       Using lambda expression, ForEach method dispalys the vehicleList.

//Java Program to display the vehicle list using ForEach method using Lambda expressions:

import java.util.ArrayList; 

import java.util.List; 

public class ForEachEg { 

  public static void main(String[] args) { 

                      List<String> vehicleList = new ArrayList<String>(); 

                      vehicleList.add("Car"); 

                      vehicleList.add("Bike"); 

                      vehicleList.add("Truck"); 

                      vehicleList.add("Bus"); 

                             vehicleList.add("Auto");

                      System.out.println("------------Example of passing lambda expression--------------"); 

                      vehicleList.forEach(vehicle -> System.out.println(vehicle)); 

                  } 

              }

Compile and run the program to get the output as shown below. 

C:\raji\blog>javac ForEachEg.java

C:\raji\blog>java ForEachEg

------------Example of passing lambda expression--------------

Car

Bike

Truck

Bus

Auto

Next program is using foreach as looping.

Java Program to display the vehicle list using ForEach method using Looping:

              This program uses the looping to iterate the elements. It has steps to follow to create this program.

Steps:

  • ·       Import the built in packages java.util.ArrayList and java.util.List
  • ·       Create a public class ForEachEg1 and save the program as “ForEachEg1.java”.
  • ·       Inside the main function, create list as “vehicleList”.
  • ·       Add the vehicles to vehicleList.
  • ·       Print the list using forEach() method.

// Java Program to display the vehicle list using ForEach method using Looping

import java.util.ArrayList; 

import java.util.List; 

public class ForEachEg1 { 

    public static void main(String[] args) { 

        List<String> vehicleList = new ArrayList<String>(); 

              vehicleList.add("Car"); 

              vehicleList.add("Bike"); 

              vehicleList.add("Truck"); 

              vehicleList.add("Bus"); 

              vehicleList.add("Auto");

        System.out.println("------------Iterating by passing method reference---------------"); 

        vehicleList.forEach(System.out::println); 

    } 

} 

  • Open the command prompt. Set the path for java.
  • Compile the program .

C:\raji\blog>javac ForEachEg1.java

  • Run the program to display the output.

C:\raji\blog>java ForEachEg1

------------Iterating by passing method reference---------------

Car

Bike

Truck

Bus

Auto

These are the ways to implement ForEach method to iterate elements.