Friday, 1 January 2016

Examples to concatenate strings in Java

In this post, I am going to show how to concatenate two strings in different ways.


1. By using concatenate operator (+)
public class StringConcatenateDemo {
    public static void main(String args[]) {
        String str1 = "PTR";
        String str2 = "Nayan";

        String result = str1 + str2;

        System.out.println("result = " + result);
    }
}

Output
result = PTRNayan

2. By using String concat method

Return a string that represents the concatenation of this object's characters followed by the string argument's characters.
public class StringConcatenateDemo {
    public static void main(String args[]) {
        String str1 = "PTR";
        String str2 = "Nayan";

        String result = str1.concat(str2);

        System.out.println("result = " + result);
    }
}


Output
result = PTRNayan

3. By using String join method
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.

public class StringConcatenateDemo {
    public static void main(String args[]) {
        String str1 = "PTR";
        String str2 = "Nayan";
        String str3 = "ABC";

        String result = String.join(",", str1, str2, str3);

        System.out.println("result = " + result);
    }
}


Output
result = PTR,Nayan,ABC

4. By using String format method
Returns a formatted string using the specified locale, format string, and arguments.

Returns a formatted string using the specified format string and arguments.

public class StringConcatenateDemo {
    public static void main(String args[]) {
        String str1 = "PTR";
        String str2 = "Nayan";
        String str3 = "ABC";

        String result = String.format("%s, %s, %s", str1, str2, str3);

        System.out.println("result = " + result);

    }
}


Output
result = PTR, Nayan, ABC

5. By using StringBuilder
Following link explains the difference between StringBuffer and StringBuilder.

public class StringConcatenateDemo {
    public static void main(String args[]) {
        String firstName = "Hari Krishna";
        String lastName = "Gurram";
        int age = 26;
        String city = "Bangalore";

        StringBuilder builder = new StringBuilder();

        String result = builder.append("(").append("firstName = ")
                .append(firstName).append(", ").append("lastName = ")
                .append(lastName).append(", ").append("age = ").append(age)
                .append(", ").append("city = ").append(city).append(")")
                .toString();

        System.out.println("result : " + result);
    }
}


Output
result : (firstName = Hari Krishna, lastName = Gurram, age = 26, city = Bangalore)

6. By using StringBuffer
public class StringConcatenateDemo {
    public static void main(String args[]) {
        String firstName = "Hari Krishna";
        String lastName = "Gurram";
        int age = 26;
        String city = "Bangalore";

        StringBuffer buffer = new StringBuffer();

        String result = buffer.append("(").append("firstName = ")
                .append(firstName).append(", ").append("lastName = ")
                .append(lastName).append(", ").append("age = ").append(age)
                .append(", ").append("city = ").append(city).append(")")
                .toString();

        System.out.println("result : " + result);
    }
}


Output
result : (firstName = Hari Krishna, lastName = Gurram, age = 26, city = Bangalore)

7. By using StringJoiner
StringJoiner class is added in Java8, used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
import java.util.StringJoiner;

public class StringConcatenateDemo {
    public static void main(String args[]) {
        String firstName = "Hari Krishna";
        String lastName = "Gurram";
        int age = 26;
        String city = "Bangalore";

        StringJoiner joiner = new StringJoiner("", "(", ")");

        String result = joiner.add("firstName = ").add(firstName).add(", ")
                .add("lastName = ").add(lastName).add(", ").add("age = ")
                .add("" + age).add(", ").add("city = ").add(city).toString();

        System.out.println("result : " + result);
    }
}


Output
result : (firstName = Hari Krishna, lastName = Gurram, age = 26, city = Bangalore)


You may like



                                                 Home

Python: formatters

Formatters are used to format log records. ‘logging’ module provides Formatter class to initialize formatter.

logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
Argument
Description
fmt
Specify the format of log record.
For example,
fmt='[%(levelname)s] %(message)s'
datefmt
If there is no date format string, the default date format is: '%Y-%m-%d %H:%M:%S'
style
The style is one of %, ‘{‘ or ‘$’. If one of these is not specified, then ‘%’ will be used.

If the style is ‘%’, the message format string uses %(<dictionary key>)s styled string substitution.

If the style is ‘{‘, the message format string is assumed to be compatible with str.format().

If the style is ‘$’ then the message format string should conform to what is expected by string.Template.substitute().


Following are different format attributes supported by python.

Format
Description
%(asctime)s
Displays the time of log record creation in human readable format. The format is of the form '2015-10-22 22:55:19,096'. The numbers after the comma (,) represents milli seconds.
%(created)f
Represents the time when the LogRecord was created.
%(filename)s
File name portion of the pathname.
%(funcName)s
Name of the function is logged
%(levelname)s
Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').
%(levelno)s
Numeric logging level for the message.
%(lineno)d
Line number, from where the logging call was issued.
%(module)s
Module name
%(msecs)d
Millisecond portion of the time when the LogRecord was created.
%(message)s
The logged message, computed as msg % args.
%(name)s
Name of the logger used to log the call.
%(pathname)s
Full pathname of the source file where the logging call was issued
%(process)d
Process Id
%(processName)s
Process Name
%(relativeCreated)d
Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
%(thread)d
Thread ID.
%(threadName)s
Thread name

import logging
import logging.handlers
import time

#Define logger
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s')

LOG_FILENAME="temp.log"
#Define handler to write to standard output
handler = logging.FileHandler(LOG_FILENAME)

formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)

#Adding handler to logger
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

def logMessages():
    logger.debug("Debug message")
    logger.info("Information Message")
    logger.warn("Warning Message")
    logger.error("Error Message")
    logger.critical("Critical Message")

if(__name__=="__main__"):
    logMessages()


Run above program, you will get following output in console.
2015-10-24 09:26:07,783 __main__     DEBUG    Debug message
2015-10-24 09:26:07,783 __main__     INFO     Information Message
2015-10-24 09:26:07,783 __main__     WARNING  Warning Message
2015-10-24 09:26:07,783 __main__     ERROR    Error Message
2015-10-24 09:26:07,784 __main__     CRITICAL Critical Message


You will get following output in temp.log file.
2015-10-24 09:28:08,914 - DEBUG - Debug message
2015-10-24 09:28:08,914 - INFO - Information Message
2015-10-24 09:28:08,914 - WARNING - Warning Message
2015-10-24 09:28:08,914 - ERROR - Error Message
2015-10-24 09:28:08,914 - CRITICAL - Critical Message









Previous                                                 Next                                                 Home