Square CSS

Monday, October 29, 2018

Java Multithreading : Introduction

Multithreading refers to the process of executing multiple threads simultaneously.
A thread can be considered as a smaller unit of processing.
Both multithreading and multiprocessing can be used to achieve multitasking. But in multithreading, threads use shared memory and context switching takes very less time.
Multithreading is mostly used in applications related to games and animations.

Advantages of Multithreading :


  • If any exception occurs in a thread then it doesn't block the other threads or tasks from execution.
  • Multiple tasks can be executed in parallel so it saves time.
  • It doesn't block the user to wait for a particular task to complete as threads are independent of each other.


                    In Java we can create a thread in two ways... 

Wednesday, October 24, 2018

Interface In Java

An interface can be considered as the blueprint of a class. Methods and variables are provided in an interface and its implementations are done in a class. Till java 7 no method body remained in an interface. An instance of the interface cannot be created, unlike the abstract methods.

Properties of an Interface :


Some of the common properties are as follows:

  • All methods of an interface are public static and final by default.
  • Mechanism of abstraction in Java can be achieved using abstraction.
  • The instance of an interface cannot be created, unlike the abstract class.
  • Till Java 7 method bodies were not provided in an interface.
  • Since Java 8 default and static methods can be provided in an interface.

The format for using interface:


Interfaces are declared using interface keyword. All the methods in an interface are public, static and final by default due to which total it provided abstraction in Java.

 
   interface interfaceName{ 
        /* code data */  
     }                               
        

Changes in Java 8:


Since Java 8 one can declare static and default methods in an interface. Discussion regarding this change will be done in the separate tutorial.



                    Nowadays in some office, it is required to stay on your desk and work for offi...



Sunday, October 21, 2018

Singleton Class In Java

A singleton class is a class which has one object at a time. In other words, a class having one and only one instance at a time is known as a singleton class.

This can be achieved by following :
  • Make the method which returns the object as static. In our case, the method is getInstance().
  • Make the constructor as private.
  • Check for the instance of the class in the static method. If the instance is not there then create the instance using new operator. Otherwise, return the instance.

Example :


 
   class MySingleton{

         private static MySingleton ms=null;

         public String s;

         // create a private constructor         

         private MySingleton(){
                 s="Singleton from Play Java";     
         }

         /* create a static method to return the instance     
         of the class. If the instance is not present
         then create one */
 
        public static MySingleton getInstance(){
               if(ms==null) ms=new MySingleton();
               return ms;
         }

   }                               
        

Uses Cases:

  • Singleton class are mostly used where the single data is required to create on the first call and retains its instance until the closure of application.
  • Used for logging, caching, configuration settings, thread pools, etc.


    Refer the video tutorial :







                       Nowadays in some office, it is required to stay on your desk and work for  ... 


    Saturday, October 20, 2018

    Switch Statement In Java

    The switch statement can be considered as an alternative for if-elseif statements. It is a multi-branch of conditional statements. It works by checking the equality of different cases. It can be used with byte, short, char, and int primitive data types. Since Java 7 one can use Strings also in the switch statement.


    Format :


       
       switch(condition){
            /* if condition matches case
               value code executes */
            
    case value1 :
                     // code for execution     
                     break//optional
       
            case value2 :
                     // code for execution     
                     break;  //optional         .....
             .....     
             .....
       
             default :
                     //code to execute if all cases fail   
         }                                 
            

    Example :


    Let's consider the following code.

     
       int  data=200;
       String dataString;
       switch(data){
            /* if condition matches case
               value code executes */
            
    case  100:
                     dataString = "hundred";     
                     break;  //optional
       
            case  200:
                     dataString = "two hundred";      
                     break;  //optional         .....
             .....   
             .....
       
             default :
                     dataString = "not from given cases";   
         }                                 
       
         System.out.println("The number is: " + dataString);       

    The output of the above input will be :

     
       The number is: two hundred            




                        A singleton class is a class which has one object at a time. In other wor ... 


    Friday, October 19, 2018

    If-Else Statement

    In Java, if-else statements are used to run codes on basis of boolean conditions.
    The conditions can be provided in the following ways :

    • if condition
    • if-else condition
    • if-elseif conditions
    • nested if conditions


      If Statement :


      In if condition a boolean condition is provided after if using "(" and ")".


        
        /*syntax*/
        if(booleanCondition){  
             // program to execute if booleanCondition is true 
        }
              

      Example : 

      Suppose if we have an int a whose value is 10. if we provide the boolean condition as "a==10" then it is a true statement. So if the input is :


        
        int a=10;

        if(a==10){  

            System.out.println("If part executed!") ;          
        }
            

      The output will be :


        
         If part executed!                                             



      If-else statement :


      In an if-else statement, if the condition of "if" block turns out to be false then else part is executed.
      Suppose if the input is :

        
        int a=10;

        if(a>20){  
            System.out.println("If part executed!") ;          
        } else {
            System.out.println("else part executed!") ;
        }         



      The output will be :

           
         else part executed!                                    
              


      If-elseif statement :


      In an if-elseif statement, conditions are provided in the elseif part also. We can combine if-elseif with else also. So when all the conditions will fail else part will execute. Suppose if the input is :

        
        int a=10;

        if(a>20){  
            System.out.println("If part executed!") ;          
        } elseif (a>15) {
            System.out.println("elseif part executed!") ;
        } else {
             System.out.println("else part executed!") ;
         }        



      The output will be :

           
         else part executed!                                    
              

      Nested If statements :


      If one "if condition" is provided inside the outer if statement then it is known as nested if statement.

        
        /*syntax*/
        if(condition1){  
             // program executed if condition1 is true
             if(condition2){
                  // program executed if condition2 is true    
             } 
        }
              



                          The switch statement can be considered as an alternative for if-elseif stat ... 

      Thursday, October 18, 2018

      Spring Boot : Hello World Example

      Create a Spring Boot application to print "Hello World".

      Prerequisites for Creation of Spring Boot :

      • Java with version 1.6 or above. Better to use the latest version.
      • If using Maven then 3.2 or above.
      • If using Gradle then 2.9 or above.
      • Plugin of Spring Tool Suit enabled in IDE like eclipse.
      • Basic knowledge of  Spring Framework.

      Versions Used :

      • Java 1.8
      • Spring Boot 1.5.9
      • Eclipse 4.6.9 Neon

      Create a Maven project and provide the dependency :

      • Go to File >> New >> Maven Project.
      • Provide Artifact Id as your project name. In this case, it is SpringBootTutorial.

          


      •  Provide the following dependencies in the pom.xml file.


        <parent>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-parent</artifactId>    
             <version>1.5.9.RELEASE</version>
        </parent>
        <dependencies>
            <dependency>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-starter-web</artifactId>                 
            </dependency>
        </dependencies>

      • Provide the mapping for the method to return "Hello World".

        @Controller
        @EnableAutoConfiguration
        public class SpringBootTutorial{

      @RequestMapping("/")
      @ResponseBody
      String Home() {
      return "Hello World";
      }
      public static void main(String[] args) {
      SpringApplication.run(SpringBootTutorial.class, args);    
      }

       }

      • Run as Spring Boot App.
           
      • Go to the browser and provide the URL localhost:[portNumber]/pathForMethod.

      Refer the video tutorial :




      SpringApplication

      SpringApplication is a class which has a static parametrized method called run(). Using this method any Spring Boot application can be bootstrapped by passing the class in this method.

      One can start the application by calling the static run() method of SpringApplication.


        
         public static void main(String[] args){
             SpringApplication.run(nameOfMainClass.class,args);  
         }



        Next >> Spring Boot : Hello World Example
                            Create a Spring Boot application to print "Hello Wor ...

      Spring Boot Starter

      In big projects, it becomes difficult to handle dependencies. Spring boot provides a set of dependencies which can be easily implemented.

      For providing dependency a developer can provide the artifactId as spring-boot-starter-*  where "*" is the application type in lowercase.

      For example, if JPA application needs to be developed just provide spring-boot-starter-jpa in the artifactId.


      Let's have a look over some examples :


      Security implementation using Spring Boot Starters -

        
         <dependency>
             <gropuId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-security</artifactId>    
         </dependency>


      Thymleaf implementation using Spring Boot Starters -

        
         <dependency>
             <gropuId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-thymleaf</artifactId>    
         </dependency>


        Next >> SpringApplication
                            SpringApplication is a class which has a static parametrized method ...


      Spring Boot : Introduction

      Spring Boot provides the Java developers to create a stand-alone application with an ease which the developer can just run in no time. With the minimal configuration requirement, Spring Boot is becoming popular day by day.




      Benefits of using Spring Boot :

      • Easy to use.
      • Reduction in the time of production.
      • Easy to work with data layers using annotation based configurations.
      • Increase in productivity.
      • Reduction in complexity.

          Next >> Spring Boot Starters
                             In big projects, it becomes difficult to handle dependencies. Spring boot ... 


        Monday, October 8, 2018

        String vs StringBuffer vs StringBuilder

        Let's have some basic idea about String, StringBuffer and StringBuilder.

        String in Java

        A string is immutable in Java. String class represent character strings, i.e. string class is implemented with the char array. We can create a string in two ways :

          
          String str1 = "playjavatutorials";
          String str2 = new String("playjavatutorials"); 


        When a string is created using double quotes it checks for the same value in the string pool. 
        If the value already exists in the string pool then it returns the reference else creates it's object and then places it in the string pool. In this way, JVM saves lots of memory by using the same string at many places and threads.

        When a string is created with the new operator then it explicitly creates a string in the heap memory.

        The string is a final class with its all fields as final except for 'private int hash'.

        String overrides equals() and hashCode() method to verify if given two strings are same or not. The equals() method is case sensitive so if case-sensitive checks are not required then equalsIgnoreCase() method should be used. 

        StringBuffer in Java

        A StringBuffer is like String but it can be modified because of its mutable nature. They are thread-safe and can be easily used in a multithreaded environment.

        It has two important methods append() and insert().

        The append("x") function appends "x" at the end of existing StringBuffer.
        The insert(5, "x") function inserts the string "x" at the provided index of existing StringBuffer. In this case, it is 5.

          
           StringBuffer sb=new StringBuffer("Initial");  //Initial
           sb.append("Appended");  //InitialAppended
           sb.insert(7, "Inserted");   //InitialInsertedAppended         


        To convert a StringBuffer to String we use toString() method. 


          String str = sb.toString();


        StringBuilder in Java

        Unlike String, StringBuilder is mutable in nature. The API of this class is compatible with StringBuffer except that the StringBuilder is unsafe in a multithreaded environment. It is not synchronized so should it should not be used where thread safety is of prime concern.



        The difference: String vs StringBuffer vs StringBuilder

        The main difference between String and StringBuffer/StringBuilder is the immutability. A string is immutable whereas StringBuffer/StringBuilder is mutable.
        StringBuilder is non-synchronous in nature whereas StringBuffer can be used in a multithreaded environment. 


        ☛ Next >> If-Else Statement
                              
        In Java, if-else statements are used to run codes on basis of boolean con ...

        StringBuilder in Java

        Unlike String, StringBuilder is mutable in nature. The API of this class is compatible with StringBuffer except that the StringBuilder is unsafe in a multithreaded environment. It is not synchronized so should it should not be used where thread safety is of prime concern.


        It has two important methods append() and insert().

        The append("x") function appends "x" at the end of existing StringBuilder.
        The insert(5, "x") function inserts the string "x" at the provided index of existing StringBuilder. In this case, it is 5.


          
           StringBuilder sb=new StringBuilder("Initial");  //Initial
           sb.append("Appended");  //InitialAppended
           sb.insert(7, "Inserted");   //InitialInsertedAppended         



        To convert a StringBuilder to String we use toString() method. 


          String str = sb.toString();

                                                                      


        ☛ Next >> String vs StringBuffer vs StringBuilder
                             
        Let's have some basic idea about StringStringBuffer and StringBuilder. ...

        StringBuffer in Java

        A StringBuffer is like String but it can be modified because of its mutable nature. They are thread-safe and can be easily used in a multithreaded environment.

        It has two important methods append() and insert().

        The append("x") function appends "x" at the end of existing StringBuffer.
        The insert(5, "x") function inserts the string "x" at the provided index of existing StringBuffer. In this case, it is 5.


          
           StringBuffer sb=new StringBuffer("Initial");  //Initial
           sb.append("Appended");  //InitialAppended
           sb.insert(7, "Inserted");   //InitialInsertedAppended         


        To convert a StringBuffer to String we use toString() method. 


          String str = sb.toString();

                                                                              


        ☛ Next >> StringBuilder in Java
                              
        Unlike String, StringBuilder is mutable in nature. The API of this cla ...

        String in Java

        A string is immutable in Java. String class represent character strings, i.e. string class is implemented with the char array. We can create a string in two ways :

          
          String str1 = "playjavatutorials";
          String str2 = new String("playjavatutorials"); 


        When a string is created using double quotes it checks for the same value in the string pool. 
        If the value already exists in the string pool then it returns the reference else creates it's object and then places it in the string pool. In this way, JVM saves lots of memory by using the same string at many places and threads.

        When a string is created with the new operator then it explicitly creates a string in the heap memory.

        The string is a final class with its all fields as final except for 'private int hash'.

        String overrides equals() and hashCode() method to verify if given two strings are same or not. The equals() method is case sensitive so if case-sensitive checks are not required then equalsIgnoreCase() method should be used. 


        ☛ Next >> StringBuffer in Java
                              
        A StringBuffer is like String but it can be modified because of its m ...

        Saturday, October 6, 2018

        Data Types In Java!

        It specifies the type and size of a variable. They are grouped into 2 types :

        1. Primitive data types: They are of type boolean, char, byte, short, int, float, long and double. 
        2. Non-primitive data types: They are interfaces, classes, and arrays.

        Types of primitive data types:

        Data Type Default Size  Default Value
        boolean 1 bit FALSE
        byte 8 bit 0
        char 2 byte '\u0000'
        short 2 byte 0
        int 4 byte 0
        float 4 byte 0.0f
        long  8 byte 0l
        double 8 byte 0.0d

        Note: char uses 2 bytes of java and it has \u0000 as its default value because it java uses Unicode system not the ASCII code system. Unicode system has \u0000 as the lowest range so it is assigned as the default value.

        ☛ Next >> String in Java
                              A string is immutable in Java. String class represents character str  ...

        Learn Java : Java Hello World Example!

        In this series of tutorials, we will learn java step by step.

        Main Method!


        Everything inside Java is written in class. The entry point of a Java program is public static void main(String[] args). The functions which are required to be loaded at the start of the Java application is written in the main method.

        Print Hello World!

        For printing hello world in Java user should write System.out.println("Hello World"); inside the main method. 

        Input :


           public static void main(String[] args){   
               System.out.println("Hello World");
           }


        Output :



           Hello World                                                 


        ☛ Next >> Data Types In Java!
                              It specifies the type and size of a variable. They are grouped  ...

        Some Algorithms

        Algorithm: Tower of Hanoi

        Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

        Popular Posts