Desvendando o método main do Java

Desvendando o método main do Java

Fala galera blz 😀

Hoje vamos falar sobre um método que sempre usamos e é praticamente o primeiro método que executamos quando estamos aprendendo a linguagem Java. Sim, estou falando do método main, aquele onde executamos o famoso “Hello World” – “Olá Mundo” quando entramos nesse mundo da programação.

Porque falar sobre ele? Porque eu me “toquei” que nunca tinha visto artigo sobre o main e achei isso meio triste rsrsrsr.

Ele tem alguns pontos interessantes e curiosos você sabia?

O método main é o ponto de entrada de qualquer programa Java e desde a primeira versão, ele tinha a seguinte assinatura:

public static void main(String[] args) {}

Mas, você sabia que temos outras formas de usar o método main?

A partir do Java 8, podemos usar a interface funcional Consumer para nos dar mais “poder” com o método:

public static void main(String[] args, Consumer<String[]> consumer) {}

Com essa alteração, podemos criar um Consumer que processe um ou mais argumentos passados para o programa.

Suponha que você tem um programa Java que faz alguma manipulação qualquer em um array de strings. Então você deseja permitir que o usuário forneça o array de entrada a partir da linha de comando. Você pode usar o Consumer<String[]> para aceitar esse array de entrada, como mostrado no exemplo abaixo:

public class MeuPrograma {
    public static void main(String[] args, Consumer<String[]> consumer) {
        // Chama a função fornecida pelo usuário com o array de argumentos da linha de comando
        consumer.accept(args);
      
       // Faz alguma manipulação no array de entrada
    }
}

Em seguida, o usuário pode fornecer uma função para manipular o array de entrada, como mostrado abaixo:

public class Teste {
    public static void main(String[] args) {
        MeuPrograma.main(args, (input) -> {
            // Imprime o array de entrada (input) 
            System.out.println("Array de entrada: " + Arrays.toString(input));
        });
    }
}

O método main do programa MeuPrograma é chamado a partir do método main do programa Teste, e é passado um lambda como o segundo parâmetro.

        //lambda que imprime o array
        (input) -> {
            // Imprime o array de entrada (input) 
            System.out.println("Array de entrada: " + Arrays.toString(input));
        }

O lambda simplesmente imprime o array de entrada fornecido pelo usuário. Quando o método MeuPrograma.main é chamado, ele chama a função fornecida pelo usuário com o array de argumentos da linha de comando e, em seguida, faz alguma manipulação no array de entrada.

/> java Teste argumento1 argumento2

Array de entrada: [argumento1, argumento2]

Bacana né? Sabia dessa?

A título de curiosidade, podemos também a partir do Java 9, “omitir” o método main em determinadas situações, se o programa não tiver uma carga de inicialização específica . Nesse caso, podemos usar a opção -m do comando java para especificar o módulo que deve ser executado.

É necessário para isso, que o programa seja organizado em um módulo e que esse módulo especifique a classe que deve ser executada, por meio de um arquivo de configuração module-info.java, dessa forma o metodo main será inferido a partir do arquivo module-info.java.

Essa abordagem pode ser útil em projetos grandes que utilizam módulos para organizar o código e reduzir as dependências entre as classes. Com essa opção, podemos especificar qual classe deve ser executada de forma mais clara e legível.

Porém, não quero entrar nesse ponto, pois quero mostrar a mudança na assinatura do método, então voltemos ao main 😀

Olha o tanto de coisa que envolve um simples método main, não é ?

//primeira variante, versão tradicional e mais usada
public static void main(String[] args) {}

//segunda variante, a partir do Java 8
public static void main(String[] args, Consumer<String[]> consumer) {}

E ai gostou de saber mais sobre o método main? Sabia dessas variantes? Já usou alguma?

Eu particularmente uso o que normalmente a IDE me entrega/gera, então estou na primeira opção rsrsr,. Enfim, independente do qual você utiliza e a forma que utiliza, o importante é entender o que está fazendo.

Até a próxima 😉

244 Comments on “Desvendando o método main do Java

  1. Азино777 предлагает первоклассный лицензионный софт от основных создателей. Здесь представлены традиционные игровые автоматы различных тематик, рулетки, известные карточные и настольные игры в огромном разнообразии от разных разработчиков.

    Сайт казино – азино777 играть онлайн бесплатно без регистрации

  2. TEST Engaging with a marriage planner for the having an experienced caterer, event designing, as well as corporate events isn’t only important but additionally beneficial, particularly for ethnic and Indian wedding ceremonies in Boston. Preparing a meeting could be complicated, time-eating, and upsetting, but a specialist planner can relieve the duty by carrying their abilities, knowledge, and understanding towards the table. In terms of ethnic and Indian wedding parties, there are lots of personal heritages and customs that need to be taken into account, and a wedding planner that is knowledgeable about these customs will help make certain that they’ve been included in the event. A marriage planner will help find a very good vendors, consult prices, and produce a schedule and plan for the big event, all whilst staying the ethnic importance in your mind. This will probably save the couple money and time, as well as provide them with peace of mind realizing that their event is within capable hands.

    For providing, a skilled wedding adviser can help with menus planning, making sure the bathroom are authentic and meet up with the couple’s dietary requirements. They are able to also assistance with seating arrangements and making sure there is enough food for many guests, in addition to coordinating using the catering staff to ensure that the foodstuff is served on some time to the couple’s liking. With regards to event planning, a marriage planner can deal with all facets for the event, from seeking the venue to organizing with vendors and making sure the function runs smoothly. They are able to assistance with accents, illumination, and sound, in addition to creating a schedule when it comes to event to ensure it all happens on time. This could be especially helpful for Indian weddings, which regularly have a number of events and events over a number of days. For corporate and business events, a marriage planner can deal with all facets associated with the event, from choosing the venue to coordinating with sellers and making sure the big event runs smoothly. They could assistance with decorations, lighting, and sound, along with adding a schedule when it comes to event to ensure every single thing happens on time. They may be able also help with product branding and marketing, making certain the function meets the business’s plan and endeavours. Hiring a marriage planner for hospitality, event preparation, and executive events could be incredibly handy and favourable, specifically for ethnic plus Indian wedding receptions in Boston. An expert wedding ceremony planner might help make sure the big event is culturally significant, authentic, and significant while also supplying the couple with tranquility of thoughts and preserving them time and money. Using their knowledge and experience, a wedding planner might help create an memorable event that fits the couple’s dream and goes beyond their goals.

    If you wish to read more info on this article focus take a look at my very own internet site:

    Boston Ethic wedding planner

  3. 57 In this randomized, double blind, phase III trial to evaluate the optimal treatment strategy, 6182 patients were randomly assigned to the following treatment groups 5 years of tamoxifen; 5 years of letrozole; letrozole for 2 years followed by tamoxifen for 3 years; and tamoxifen for 2 years followed by letrozole for 3 years clomid 100 mg

  4. ChatCrypto is building a high performance AI Bot which is CHATGPT of CRYPTO.
    We are launching the Worlds first deflationary Artificial Intelligence token (CHATCRYPTOTOKEN) which will be used as a payment gateway to license
    Join the Chatcrypto community today with peace of mind and happiness, as registering for an account will reward you with 1600 Chatcrypto tokens (CCAIT) for free
    Project link https://bit.ly/41Fp0jc
    Not only that, for every person you refer to Chatcrypto, you’ll earn an additional 1600 tokens for free.
    q1w2e19z

  5. Drunk driving is a significant crime and will result in dangerous charges, including jailhouse time, fines, furthermore a criminal history. If you or a loved one has been faced with drunk driving, it is important to take into account employing a criminal DUI personal injury attorney. In this specific article, we’re going to talk about the advantages of choosing a criminal DUI attorney in court.

    Legal Expertise: DUI lawyers are knowledgeable within the legal facets of driving while intoxicated cases. They could navigate the complex legal system and now have a deeper comprehension of what the law states and court processes. This talent could be invaluable in making certain your proper rights are protected and therefore you obtain the best possible outcome.

    Fighting Plea bargains: dwi attorneys have the ability and negotiation skills to negotiate plea deals in your stead. They could negotiate with prosecutors to lessen the charges against you or even to secure an even more lenient sentence. This will probably save you time, money, and stress.

    Evidence Review: DRIVING UNDER THE INFLUENCE attorney at law can review the data against one to see whether it had been obtained legally. If the evidence was obtained illegally, it may be left out from the court room proceedings, that may considerably boost your likelihood of a good outcome.

    Cross-Examine Witnesses: law firms are skilled in cross-examination, which will help to discredit the testimony of witnesses against you. This will probably weaken the prosecution’s case while increasing the chances of a confident outcome.

    Sentencing Alternatives: DUI attorneys can negotiate for alternative sentences, such as for example community service or drug abuse programs, in the place of jail time. This might provide an even more good end result for you personally and may allow you to prevent the stigma of having a criminal track record.

    Court Experience: DUI attorneys have extensive experience with court and therefore are acquainted with court procedures and protocols. They understand how to argue well on your behalf and will produce a solid protection. This will raise your likelihood of a great result.

    Representation in Hearings: DUI legal representatives can portray you in administrator proceedings, such as for example license suspension proceedings, which will help to save your driving privileges. This might prevent you from losing your license and certainly will ensure it is easier for you to make it to work, school, and other essential areas.

    Protection of Constitutional Rights: DUI attorneys make sure your constitutional rights are protected for the court process. This can include the ability to a fair trial, the right to remain silent, as well as the directly to get rid unreasonable searches and seizures.

    In summary, selecting a criminal DUI law firm can offer numerous importance in the court room. From legal expertise and negotiating due process deals to shielding your constitutional privileges, a legal professional can provide a very good defense while increasing your odds of a great outcome in driving under the influence case. In the event that you or a family member has been faced with drunk driving, you will need to consider hiring a criminal DUI attorney to make sure that your legal rights are protected and therefore you obtain the perfect end result.

    if you’d like to find out more info on all of this matter stop by some business: top dui attorney in Ohio

  6. На сайте https://venttehnica.ru/ ведется продажа кондиционеров, инфракрасных обогревателей, промышленных кондиционеров, тепловых завес, конвекторов и многого другого. На определенные товары всегда действует акция, которая позволит совершить приобретение по наименьшей стоимости, сэкономив семейный бюджет. Ознакомьтесь с полным каталогом продукции, чтобы совершить выгодное приобретение. Есть раздел с популярными товарами, которые приобретает большинство. В магазине установлены доступные расценки, действует быстрая доставка.

  7. Разрешение на строительство – это официальный документ, который выдается уполномоченным органом государственной власти для разрешения строительства объекта. РНС предполагает наличие статуса земельного участка и условий строительства, включая требования к проектной документации, меры безопасности, соблюдение экологических и архитектурных норм и другие ограничения, установленные за необходимость. Разрешение на начало строительства необходимо для работ по реконструкции зданий и сооружений, а также для получения документации по эксплуатации.

  8. На сайте https://urrobot.net вы сможете воспользоваться системой автоматизации взысканий. Так каждый клиент получает возможность автоматизировать работу с дебиторской задолженностью и сократить расходы в несколько раз. Воспользуйтесь комплексным программным решением, которое идеально подходит для юридических лиц. В настоящий момент проходит акция, которая позволяет протестировать программу в течение 30 дней абсолютно бесплатно. Особенностью программы является то, что при работе с должниками применяется искусственный интеллект.

  9. Myself desired to seize a moment to articulate my gratitude towards this astounding write-up you lately shared in your webpage. As a reader who is deeply curious, I found the write-up being a precious tool that has greatly improved the comprehension on the topic.

    The thing caught my attention primarily about the piece is the depth of research and knowledge that you demonstrated throughout. You evidently are deeply passionate about this topic and have taken careful consideration to gather facts from several references to present an all-encompassing overview. The consequence is a write-up which doesn’t only educates, but as well encourages further study and study.

    The configuration of the piece was likewise striking. I liked how you launched with a extensive overview of the subject before diving into additional particular aspects. This enabled me to understand more readily the background and relevance of the facts provided afterwards. The utilization of subdivisions and distinct breaks made it easy to pursue the sequence of the text and find the facts I required.

    One’s approach of authorship is apparent, succinct, still captivating and approachable. You have a skill for explicating complicated notions in a manner that is easily understood and relatable. The employment of examples and stories to show your views was notably forceful and helped me to better retain the data presented.

    I also esteem that you took the time to reference your sources throughout the article. This displays a dedication to accuracy and integrity in your writing that is all too infrequent these days. I have already commenced looking into some of the sources you discussed and have found them to be incredibly beneficial in expanding my understanding of the topic.

    But what I valued about your article was the practical counsel and actionable insights that you presented. It is clear that you have a deep comprehension of the difficulties and chances associated with article, and you have offered a plenty of information that will be helpful to anyone seeking to find out more about this subject. I distinctly esteemed the pointers and tactics that you offered for aspect of topic], as well as the resources and devices that you recommended.

    Overall, I cannot fully express enough the effort that you have dedicated in creating this article. It is an remarkable piece of writing that was written with careful precision. It has undoubtedly had a notable impact on my understanding, and I have no doubt that it will be a helpful resource for anyone interested in this subject in the time ahead.

    If you’re in search of a beneficial asset that delivers interesting and knowledgeable content, I greatly urge examining
    my online platform https://www.twitch.tv/vikaletova . Pledged to giving practical information and relevant recommendations, you are certain to find something that will increase your life and aid you in accomplishing your targets. Don’t think twice, drop in and find out what you might obtain.

    Thank you once again for your dedication to excellent writing and research. Your efforts are truly appreciated, and we are indebted for the worth you bring to the field.

  10. Вы ищете надежный и доступный способ обеспечить прохладу в вашем доме этим летом? Обратите внимание на компанию «Теххолод» в Ростове-на-Дону. Они предлагают широкий выбор сплит-систем, которые идеально подходят для поддержания комфорта в вашем доме в течение всего сезона: купить настенную сплит систему цена. Сплит-системы энергоэффективны, экономичны и просты в установке. Благодаря компетентному персоналу компании techolod вы можете быть уверены, что получите лучший продукт для ваших нужд. Кроме того, их цены конкурентоспособны, и они предлагают бесплатную доставку в Ростове-на-Дону.
    В techolod удовлетворение потребностей клиентов является их главным приоритетом. Их дружелюбный персонал всегда готов ответить на любые вопросы и проблемы, которые могут возникнуть у вас при выборе подходящей системы для вашего дома.

  11. Сайт https://generator-utm-metok.ru/ представляет собой инструмент, который необходим для создания ссылок. Для того чтобы им воспользоваться, необходимо вбить адрес ссылки в специальную строку. Далее следует определить источник трафика. Есть как обязательные, так и необязательные параметры. На портале также представлена и другая важная информация, которая касается того, что представляет собой UTM-метка, о структуре тега. Будете в курсе того, как создать такую метку в режиме реального времени.

  12. Chat GPT Online
    Revolutionizing Conversational AI

    ChatGPT is a groundbreaking conversational AI model that boasts open-domain capability, adaptability, and impressive language fluency. Its training process involves pre-training and fine-tuning, refining its behavior and aligning it with human-like conversational norms. Built on transformer networks, ChatGPT’s architecture enables it to generate coherent and contextually appropriate responses. With diverse applications in customer support, content creation, education, information retrieval, and personal assistants, ChatGPT is transforming the conversational AI landscape.

  13. Try ChatGPT
    Revolutionizing Conversational AI

    ChatGPT is a groundbreaking conversational AI model that boasts open-domain capability, adaptability, and impressive language fluency. Its training process involves pre-training and fine-tuning, refining its behavior and aligning it with human-like conversational norms. Built on transformer networks, ChatGPT’s architecture enables it to generate coherent and contextually appropriate responses. With diverse applications in customer support, content creation, education, information retrieval, and personal assistants, ChatGPT is transforming the conversational AI landscape.

  14. GcashLive Register Get Free 148PHP
    Gcash Online Casino Games!
    Best JILIBonus, PlayStar, CQ9 Betting Games!
    #gcashlive #livegcash #gcashapp #gcashlivegame #gcashlivecasino
    Subukan ang aming 1000+ Games
    Legit master agent l Self service na dito
    http://www.gcashlive.com

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *

*

Esse site utiliza o Akismet para reduzir spam. Aprenda como seus dados de comentários são processados.