Friday, 18 October 2019

Convert String to float in Python

In this post we’ll see how to convert String to float in Python.

If you have a float represented as String literal then you need to convert it to float value if you have to use it in any arithmetic operation.

For example-

num1 = "50.56"
num2 = 20.45
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 14, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "float") to str

As you can see num1 variable is of type string so Python tries to concatenate num2 to num1 rather than adding them. In such scenario you need to convert string to float.

Python program - convert String to float

To convert a Python String to a float pass that String to float() function which returns a float object constructed from the passed string.

num1 = "50.56"
num2 = 20.45
result = float(num1) + num2
print("Sum is-", result)

Output

Sum is- 71.01

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to float, ValueError is raised. If you are not sure about the passed number it is better to use try and except for exception handling.

For example in the following Python function string ‘abc’ is passed as one of the argument value which results in ValueErorr being raised while converting it.

def add(num1, num2):
    try:
        result = float(num1) + float(num2)
        print("Sum is-", result)
    except ValueError as error:
        print('Error while conversion:', error)


add('abc', 10)

Output

Error while conversion: could not convert string to float: 'abc'

Getting integer part of the decimal number

If there is a decimal number stored as a string and you want only the integer part then directly using int() function results in error. You have to first convert string to float and then to int.

num = "50.56"
# Causes error
int_num = int(num) 
print("Integer part is-", int_num)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 10, in <module>
    int_num = int(num)
ValueError: invalid literal for int() with base 10: '50.56'

Correct way

num = "50.56"
int_num = int(float(num))
print("Integer part is-", int_num)

Output

Integer part is- 50

That's all for this topic Convert String to float in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Convert String to int in Python
  2. Python Program to Count Number of Words in a String
  3. Python String isnumeric() Method
  4. Operator Overloading in Python
  5. Check String Empty or Not in Python

You may also like -

  1. Name Mangling in Python
  2. Magic Methods in Python With Examples
  3. Passing Object of The Class as Parameter in Python
  4. Inheritance in Python
  5. Converting String to float in Java
  6. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  7. intern() Method in Java String
  8. Java Exception Handling Tutorial

Thursday, 17 October 2019

Convert String to int in Python

In this post we’ll see how to convert String to int in Python.

If you have an integer represented as String literal then you need to convert it to integer value if you have to use it in any arithmetic operation.

For example-

num1 = "50"
num2 = 20
result = num1 + num2
print("Sum is-", result)

Output

Traceback (most recent call last):
  File "F:/NETJS/NetJS_2017/Python/Programs/Test.py", line 3, in <module>
    result = num1 + num2
TypeError: can only concatenate str (not "int") to str

As you can see since the first operand is string so Python tries to concatenate the second operand to the first rather than adding them. In such scenario you need to convert string to int.

Python program - convert String to int

To convert a Python String to an int pass that String to int() function which returns an integer object constructed from the passed string.

num1 = "50"
num2 = 20
# converting num1 to int
result = int(num1) + num2
print("Sum is-", result)

Output

Sum is- 70

ValueError while conversion

If the string doesn’t represent a valid number that can be converted to int, ValueError is raised. While doing such conversions it is better to use try and except for exception handling.

def add():
    try:
        num1 = "abc"
        num2 = 20
        # converting num1 to int
        result = int(num1) + num2
        print("Sum is-", result)
    except ValueError as error:
        print('Error while conversion:', error)


add()

Output

Error while conversion: invalid literal for int() with base 10: 'abc'

Converting String with commas to int

If String variable is storing a number with commas (as example str_num=”6,00,000”) then one of the option is to use replace method of the str class t remove commas before converting string to int.

def add():
    try:
        num1 = "6,45,234"
        num2 = 230000
        # converting num1 to int
        result = int(num1.replace(',', '')) + num2
        print("Sum is-", result)
    except ValueError as error:
        print('Error while conversion:', error)


add()

Output

Sum is- 875234

That's all for this topic Convert String to int in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Convert String to float in Python
  2. Python Program to Display Fibonacci Series
  3. Python String isdigit() Method
  4. Operator Overloading in Python
  5. Removing Spaces From String in Python

You may also like -

  1. Comparing Two Strings in Python
  2. Python Functions : Returning Multiple Values
  3. Python Exception Handling Tutorial
  4. Local, Nonlocal And Global Variables in Python
  5. Converting String to int in Java
  6. ArrayList in Java With Examples
  7. Lambda Expressions in Java 8
  8. Interface Default Methods in Java 8

Wednesday, 16 October 2019

Python Functions : Returning Multiple Values

In Python a function can return multiple values, that is one of the difference you will find in a Python function and function (or method) in a language like C or Java.

Returning multiple values in Python

If you want to return multiple values from a function you can use return statement along with comma separated values. For example

return x, y, z

When multiple values are returned like this, function in Python returns them as a tuple. When assigning these returned values to a variable you can assign them to variables in sequential order or in a tuple. Let’s try to clarify it with examples.

Python function returning multiple values example

In the example there is a function that adds and multiplies the passed numbers and returns the two results.

def return_mul(a, b):
    add = a + b
    mul = a * b
    # returning two values
    return add, mul


# calling function
a, m = return_mul(5, 6)
print('Sum is', a)
print('Product is', m)

Output

Sum is 11
Product is 30

As you can see in the function two values are returned which are assigned to two variables in sequential order

a, m = return_mul(5, 6)

value of add to a and value of mul to m.

You can also assign the returned values into a tuple.

def return_mul(a, b):
    add = a + b
    mul = a * b
    # returning two values
    return add, mul


# calling function
t = return_mul(5, 6)
# getting values from tuple
print('Sum is', t[0])
print('Product is', t[1])

Output

Sum is 11
Product is 30

That's all for this topic Python Functions : Returning Multiple Values. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Global Keyword in Python With Examples
  2. Namespace And Variable Scope in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Passing Object of The Class as Parameter in Python
  5. pass Statement in Python

You may also like-

  1. Multiple Inheritance in Python
  2. Python String split() Method
  3. User-defined Exceptions in Python
  4. Python Program to Find Factorial of a Number
  5. Java BufferedWriter Class With Examples
  6. How to Reverse a Doubly Linked List in Java
  7. How to Create Immutable Class in Java
  8. Spring Boot StandAlone (Console Based) Application Example

Tuesday, 15 October 2019

Functions in Python

In this post we’ll see what are functions, what are the advantages of creating functions, how to define functions in Python and how to execute functions in Python and return result, if any.

What are functions

A function is a block of code that is usually written to perform a specific functionality. A function is executed only when you call it and you can pass data to a function (known as function parameters) and return a result from a function.

Advantages of using functions

  1. Functions help you in writing modular code as you can write different functions for different functionality. So. Functions help you in dividing application into smaller chunks.
  2. Functions help in making your code reusable as you can call functions when required and use them in different applications too.
  3. Functions also avoid repetition of code as the functionality which is required at several places can be written as a separate function and that function can be called as and when required.
  4. Functions make your code easy to maintain as any extra functionality can be written as an extra function without disturbing the existing code base.
  5. Functions make it easy to debug code, since different functions are written for different tasks so it easy to pin-point which function has a problem.

Python function syntax

In Python there are many inbuilt functions for performing various tasks like print() to display output, len() which returns the length (the number of items) of an object. But user can also define ‘user defined functions’ for performing specific tasks.

Syntax for defining a function in Python is as given below-

def function_name(param1, param2, ..) :
 """function doc string"""
 function suite
  1. For defining a function ‘def’ keyword is used followed by the function name.
  2. Function name is followed by a parenthesis where you specify the parameters for passing values to a function. Note that parameters are optional. In case there are no parameters then you have an empty parenthesis after function name.
  3. After parentheses there is a colon (:) which marks the end of function header and beginning of function body (indented code block also known as function suite).
  4. There is also an optional doc string that describes what a function does.
  5. There is also an optional return statement to return a value from a function.

Example of creating function in Python

In the example a function sum is created with two parameters. In the function those two parameters are added and the added value is returned.

def sum(a, b):
    """This function adds the passed values"""
    sum = a + b
    return sum

Calling a function

To execute a function you have to call it. You can call a function using its name passing values for the parameters if there are parameters.

def sum(a, b):
    """This function adds the passed values"""
    sum = a + b
    return sum


# calling function
result = sum(5, 6)
print('Sum is', result)

Output

Sum is 11

Return value from a function

Using return statement a function in Python can return a value. If there is no value to be returned from a function then you don’t need to write a return statement in your function. If there is no return statement in a function then a Python function returns ‘None’ implicitly.

If a function just performs some action rather than calculating and returning a result, such functions are also known as procedures.

Here is the sum function rewritten so that result is printed with in the function itself and no value is returned from the function.

def sum(a, b):
    """This function adds the passed values"""
    result = a + b
    print('Sum is', result)


# calling function
print(sum(5, 6))

Output

Sum is 11
None

As you can see now trying to print the returned value displays ‘None’ as that is the value returned for a void function in Python.

That's all for this topic Functions in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Global Keyword in Python With Examples
  2. Namespace And Variable Scope in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Passing Object of The Class as Parameter in Python
  5. pass Statement in Python

You may also like-

  1. Multiple Inheritance in Python
  2. Python String split() Method
  3. User-defined Exceptions in Python
  4. Python Program to Find Factorial of a Number
  5. Java BufferedWriter Class With Examples
  6. How to Reverse a Doubly Linked List in Java
  7. How to Create Immutable Class in Java
  8. Spring Boot StandAlone (Console Based) Application Example

Monday, 14 October 2019

Spring Boot spring-boot-starter-parent

In the Spring Boot Hello World Web Application Example you would have seen that spring-boot-starter-parent has been added as a parent dependency in the pom.xml. In this post we’ll discuss this spring-boot-starter-parent dependency in detail.

Dependency management in Spring Boot

Each release of Spring Boot provides a curated list of dependencies that it supports. So, you don't need to provide version number for any of the required dependencies in your build configuration, as Spring Boot manages that for you. When you upgrade Spring Boot itself, these dependencies are upgraded as well in a consistent way.

The list is available as a standard BOM (Bills of Materials), dependency for it is spring-boot-dependencies that can be used with both Maven and Gradle.

spring-boot-starter-parent in Spring Boot

Spring Boot users using Maven as build tool can inherit from the spring-boot-starter-parent project to obtain sensible defaults. This parent dependency can be added in the pom.xml as given below-

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.9.RELEASE</version>
</parent>

spring-boot-starter-parent provides the following features-

  • Java 1.8 as the default compiler level. Note that Spring Boot 2.x requires Java 8 as the minimum Java version
  • UTF-8 source encoding.
  • A Dependency Management section which is inherited from the spring-boot-dependencies pom, that manages the versions of common dependencies. This dependency management lets you omit <version> tags for those dependencies when used in your own pom.
  • An execution of the repackage goal (spring-boot:repackage) with a repackage execution id.
  • Sensible resource filtering.

spring-boot-starter-parent pom

If you look at the pom.xml of spring-boot-starter-parent (Available here) you will see that it inherits from spring-boot-dependencies itself. In the properties section you can also see the configuration for Java version and UTF encoding.

Relevant section of the pom.xml is shown here.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>${revision}</version>
        <relativePath>../../spring-boot-dependencies</relativePath>
    </parent>
    <artifactId>spring-boot-starter-parent</artifactId>
    <packaging>pom</packaging>
    <name>Spring Boot Starter Parent</name>
    <description>Parent pom providing dependency and plugin management for applications
        built with Maven</description>
    <properties>
        <main.basedir>${basedir}/../../..</main.basedir>
        <java.version>1.8</java.version>
        <resource.delimiter>@</resource.delimiter> <!-- delimiter that doesn't clash with Spring ${} placeholders -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>
    </properties>

The curated list of dependencies is configured in spring-boot-dependencies. You can see its pom.xml here

Compatible dependencies are enclosed with in the properties tag.

<properties>
    <main.basedir>${basedir}/../..</main.basedir>
    <!-- Dependency versions -->
    <activemq.version>5.15.10</activemq.version>
    <antlr2.version>2.7.7</antlr2.version>
    <appengine-sdk.version>1.9.76</appengine-sdk.version>
    <artemis.version>2.10.1</artemis.version>
    <aspectj.version>1.9.4</aspectj.version>
    ...
    ...

Using Spring Boot without the Parent POM

If you do not want to use the spring-boot-starter-parent, you can still keep the benefit of the dependency management (but not the plugin management) by using a scope=import dependency, as follows-

<dependencyManagement>
    <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.6.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

Customizing managed versions

To customize a managed version you set its corresponding property. For example, to customize the version of Jersey which is controlled by the jersey.version property:

<properties>
    <jersey.version>2.28</jersey.version>
</properties>

Then add dependency-

<dependency>
    <groupId>org.glassfish.jersey.core</groupId>
    <artifactId>jersey-client</artifactId>
</dependency>

That's all for this topic Spring Boot spring-boot-starter-parent. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Boot Spring Initializr
  2. Spring Boot StandAlone (Console Based) Application Example
  3. Spring MVC @RequestParam Annotation Example
  4. Spring MVC Pagination Example Using PagedListHolder
  5. How to Read Properties File in Spring Framework

You may also like-

  1. Using util-namespace For Wiring Collection in Spring
  2. Spring Asynchronous Method Execution Support Using @Async Annotation
  3. @Required Annotation in Spring Framework
  4. Spring JdbcTemplate Insert, Update And Delete Example
  5. Buffered Streams in Java IO
  6. Switch Expressions in Java 12
  7. Creating Temporary File in Java
  8. Java String Interview Questions And Answers

Friday, 11 October 2019

Switch Expressions in Java 12

In Java 12 Switch statement has been extended to be used as either a statement or an expression. In this article we’ll see with some examples how to use this new feature switch expressions.


Java Switch expressions

A new form of switch label, written "case L ->" has been added in Java 12 that allows the code to the right of the label to execute only if the label is matched.

We’ll try to understand this switch expression with an example, initially let’s use traditional switch statement to write a conditional switch-case branch and then use switch expression to see how it simplifies it.

For example if you want to display the quarter, passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1:    
   case 2:    
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4:   
   case 5:     
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:   
   case 8:  
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:     
   case 11:   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }
 }
}

Consider some of the pain areas here-

  1. Even if multiple cases have the same end value still you need to write them in the separate lines.
  2. Use of many break statements make it unnecessarily verbose.
  3. Missing a break statement results in an accidental fall-through.

Now let’s write the same example using switch expressions.

public class SwitchCaseDemo {

    public static void main(String[] args) {
        int month = 4;        
        switch(month){
            case 1, 2, 3 -> System.out.println("Quarter 1");         

            case 4, 5, 6 -> System.out.println("Quarter 2");     
        
            case 7, 8, 9 -> System.out.println("Quarter 3");             
             
            case 10, 11, 12 -> System.out.println("Quarter 4");              
            
            default -> System.out.println("Invalid month value passed");
        }
    }
}

Note the changes here-

  1. Multiple case labels can be grouped together now.
  2. Break statement is not required any more. If a label is matched, then only the expression or statement to the right of an arrow label is executed; there is no fall through.
  3. This new switch form uses the lambda-style syntax introduced in Java 8 consisting of the arrow between the label and the code that returns a value.

Note that to use switch expressions feature make sure you have JDK 12 installed. To enable this feature, you’ll need to use the flags --enable-preview and --release 12 when you compile your code.

javac --enable-preview --release 12 SwitchCaseDemo.java

To run the generated class file, you’ll need to pass the --enable-preview flag to the Java launcher.

java --enable-preview SwitchCaseDemo

From Java 12 you can use colon syntax (:) too with multiple case labels but in that case break statement has to be used to avoid fall-through.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1, 2, 3 : System.out.println("Quarter 1"); 
         break;

   case 4, 5, 6 : System.out.println("Quarter 2");  
       break;
   case 7, 8, 9 : System.out.println("Quarter 3");    
       break;
   case 10, 11, 12 : System.out.println("Quarter 4");     
       break;
   default : System.out.println("Invalid month value passed");
  }
 }
}

Why is it called Switch expression

Now the more pertinent question is why this new feature is called switch expression. As you must be knowing; Statements are essentially “actions” that have to be executed. Expressions, however, are “requests” that produce a value. Same difference applies to switch statement and switch expressions too.

Here is an example showing returning a value from a traditional switch statement.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  String message = "No event to log";
  switch (event) {
      case "Start":
          message = "User started the event";
          break;
      case "Stop":
          message = "User stopped the event";
          break;
  }
  return message;
 }
}

Output

User started the event

Same thing with Java Switch expressions. Since expression itself produces a value so it can be assigned to a variable directly.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
      case "Start" ->  "User started the event";
      case "Stop" -> "User stopped the event";
      default -> "No event to log";
  };
  return msg;
 }
}

Output

User started the event

If you want to use colon syntax then you can assign the value directly after break.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
      case "Start" : break  "User started the event";
      case "Stop" : break "User stopped the event";
      default : break "No event to log";
  };
  return msg;
 }
}

Writing statement blocks

If you need to have multiple statements with in a case you can use a statement block enclosed in curly braces.

public class SwitchCaseDemo {

    public static void main(String[] args) {
        int month = 4;        
        var value =switch(month){
             case 1, 2, 3 ->{
                System.out.println("Quarter 1");     
                break "Quarter 1";
            }
            case 4, 5, 6 -> {
                System.out.println("Quarter 2"); 
                break "Quarter 2";
            }
        
            case 7, 8, 9 ->{
                System.out.println("Quarter 3");     
                break "Quarter 3";
            }
             
            case 10, 11, 12 -> {
                System.out.println("Quarter 4");  
                break "Quarter 4";
            
            }
            
            default -> {
                System.out.println("Invalid month value passed");
                break "Invalid month value";
            }
        };
        System.out.println("Value- " + value);
    }
}

That's all for this topic Switch Expressions in Java 12. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. break Statement in Java
  2. Type Wrapper Classes in Java
  3. Ternary Operator in Java
  4. Type Casting in Java
  5. Core Java Basics Interview Questions And Answers

You may also like -

  1. Private Methods in Java Interface
  2. Multi-Catch Statement in Java Exception Handling
  3. Creating a Thread in Java
  4. How HashMap Works Internally in Java
  5. Byte Streams in Java IO
  6. Check if Given String or Number is a Palindrome - Java Program
  7. Spring Boot Hello World Web Application Example
  8. Connection Pooling With Apache DBCP Spring Example

Wednesday, 9 October 2019

Spring Boot StandAlone (Console Based) Application Example

In the post Spring Boot Hello World Web Application Example we have already seen an example of creating web application using Spring Boot. In this post we’ll see how to create a stand alone (non-web) application using Spring Boot. If you want this stand alone application to be console based where you can pass arguments to the application you can use CommandLineRunner interface.

Another option for the Spring Boot stand alone application is to get bean from the ApplicationContext the usual way.


Maven Dependencies

To see how to create a Maven project refer this post- Creating Maven Project in Eclipse

For stand alone required starter dependency is spring-boot-starter.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.netjs</groupId>
    <artifactId>SpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringBootApp</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
    </parent>
    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Service class

There is a GreetingService class that returns a greeting. This is the class that is called from the application class.

import org.springframework.stereotype.Service;

@Service
public class GreetingService {
    public String greet(String name) {
        return "Hello " + name;
    }
}

Application class implementing CommandLineRunner

Here is the Application class annotated with @SpringBootApplication that bootstraps the spring boot application. For the console based Spring Boot application, Application class implements CommandLineRunner which has a run method. In the application class run method of this interface has to be implemented which is the callback used to run the bean.

In the application class GreetingService is injected as a bean dependency as the property is annotated with @Autowired annotation.

import org.netjs.SpringBootApp.service.GreetingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAppApplication  implements CommandLineRunner {
    @Autowired
    GreetingService greetingService;
 public static void main(String[] args) {
  SpringApplication.run(SpringBootAppApplication.class, args);
 }

 @Override
 public void run(String... args) throws Exception {
  System.out.println(greetingService.greet(args[0]));
  
 }
}

Now you can run this Spring Boot application directly from Eclipse IDE by right clicking the application class and select Run As – Run Configurations. In the Run Configurations window provide Program arguments for the application.

Output

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.9.RELEASE)

2019-10-09 12:27:11.916  INFO 9272 --- [           main] o.n.S.SpringBootAppApplication           : Starting SpringBootAppApplication on user with PID 9272
2019-10-09 12:27:11.920  INFO 9272 --- [           main] o.n.S.SpringBootAppApplication           : No active profile set, falling back to default profiles: default
2019-10-09 12:27:13.154  INFO 9272 --- [           main] o.n.S.SpringBootAppApplication           : Started SpringBootAppApplication in 2.134 seconds 
                                                                                                   (JVM running for 3.318)
Hello netjs

Getting bean from Application Context

Another way to execute Spring Boot standalone application is to get the bean from Application Context and then call the method. Application class in that scenario looks as given below-

import org.netjs.SpringBootApp.service.GreetingService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class SpringBootAppApplication {
 public static void main(String[] args) {
  ApplicationContext ctx = SpringApplication.run(SpringBootAppApplication.class, args);
  GreetingService greetingService = ctx.getBean(GreetingService.class);
  System.out.println(greetingService.greet("netjs"));
 }
}

That's all for this topic Spring Boot StandAlone (Console Based) Application Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring Boot Spring Initializr
  2. Difference Between @Controller And @RestController Annotations in Spring
  3. Spring MVC Form Example With Bean Validation
  4. Spring Batch Processing With List of Objects in batchUpdate() Method
  5. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

You may also like-

  1. Spring Profiles With Examples
  2. Different Bean Scopes in Spring
  3. Spring Expression Language (SpEL) With Examples
  4. Java Multithreading Interview Questions And Answers
  5. How to Convert Date And Time Between Different Time-Zones in Java
  6. Heap Memory Allocation in Java
  7. static Keyword in Java With Examples
  8. Constructor in Python - __init__() function