how do you shorten system.out.println in java

Viewed 8601

what is the absolute shortest possible shortcut to call System.out.println that makes it callable via the shortest possible number of characters (like print())

10 Answers

Here's a workable example of the answers on this page, and also the related question. I'm not sure if any of these shortcuts is recommended for readable, reusable code.

import static java.lang.System.out; // only for method of minichate&Tim Cooper
import java.io.PrintWriter;// only for method of Stephan Paul

public class PrintExample{
    public static void main(String[] args){
        out.println("Typing of 7 characters saved!");
        p.pl("shortened System.out.println, 14 characters saved.");
        p.pl(77); // takes non-strings
        p.out(88); // also takes non-strings
        p.print("sorry, I only take strings!");
        //p.print(99); compilation error, int cannot be converted to String
        PrintWriter pr = new PrintWriter(System.out, true);
        pr.println(33); // method of Stephan Paul
    }
}

class p{
    // using generics (Java 5.0 onwards), by carlos_lm
    public static <T> void pl (T obj){
        System.out.println(obj);
    }
    // method by Neji3971 & bakkal, seems to work for all objects
    public static void out(Object o){
        System.out.println(o.toString());
    }
    // method by Jesus Ramos & rup. Only accepts strings!!
    public static void print(String s) {
        System.out.println(s);
    }
}

You might wanna try this

package com.company;

class Database {

    // SOP to print function
    public static void print(String inp) { 
        System.out.println(inp);
    }

    public static void print(int inp) {
        System.out.println(inp);
    }

    public static void print(double inp) {
        System.out.println(inp);
    }

    public static void print(float inp) {
        System.out.println(inp);
    }

    public static void print(boolean inp) {
        System.out.println(inp);
    }

    // SOPLN to printLN function

    public static void printLN(String inp) {
        System.out.println(inp);
    }

    public static void printLN(int inp) {
        System.out.println(inp);
    }

    public static void printLN(double inp) {
        System.out.println(inp);
    }

    public static void printLN(float inp) {
        System.out.println(inp);
    }

    public static void printLN(boolean inp) {
        System.out.println(inp);
    }

    public static void main(String[] args) {
        
        printLN("Hello");
        printLN(1);
        printLN(2.123);
        printLN(2.2);
        printLN(false);
        printLN(1+2);
        int x = 323;
        int y = 342;
        int z = x+y;
        printLN(x+y);
        printLN(z);
        printLN("Hello" + z);
        printLN("You can print anything.");

    }
}
Related