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 😉
Köp ditt körkort online. vi erbjuder hållbarhet, exceptionell utskriftskvalitet och ett helhetsintryck av kvalitet och autenticitet. Analysera en mängd olika funktioner som streckkoder, magnetremsor, smarta chips och holografiska överlägg. De inkluderar även holografiska laminat som ger äkthet till korten.
köpa körkort
Compre su licencia de conducir en línea. ofrecemos durabilidad, calidad de impresión excepcional y una impresión general de calidad y autenticidad. Analice una variedad de funciones, como códigos de barras, bandas magnéticas, chips inteligentes y superposiciones holográficas. También incluyen laminados holográficos que añaden autenticidad a las tarjetas.
comprar licencia de conducir
Right here is the right webpage for everyone who hopes to understand this topic.
You know a whole lot its almost hard to argue
with you (not that I personally will need to…HaHa).
You certainly put a fresh spin on a subject that has been discussed for ages.
Excellent stuff, just great!
You can handle the app omly if they download the app byy way oof the Google Device Policy app.
Cherck out my webpage :: 파워볼
Superb, what a web site it is! This website presents useful facts to us,
keep it up.
The job is exchanged for caqsh and there are no
other positive aspects, such as health insurance.
Also visit myy blog post :: web site
Some nonprofits permit their fundraising directors to work remotely as
long as the cann achieve all the job duties.
Heree iss my page; web site
All Flortida MEGA MILLIONS, POWERBALL, CASH4LIFE, and Rapid Play prizes oughht to be claimed in Florida.
Also visit my site: 파워볼게임
Hello there, You have done an excellent job. I will certainly digg it and personally suggest to
my friends. I am confident they’ll be benefited from this web site.
The neew digital passenger emtry and exit form will be readilky available from November 29, 2020.
Feel free to surf to my webpage – 비트파워볼
Amongst those who have been self-employed for two years, 65% are male, oof thesse who have been self-employed
for 20 years, 71% are male.
Feel free to surf to my page :: 카페알바
Three months later, the nation elected as president Mooon Jae-in, a former student activist and human rights lawyer, who, among other items, promised
the reinstatement of KTX attendants.
Here is my webpage homepage
Verry best of all, they only take a few minutes to approve the loan so
you can get your monbey fast.
My bkog post … 신용대출
Having read this I thought it was extremely informative. I appreciate you spending some time and energy to put this short article together.
I once again find myself personally spending way too much time both reading and posting comments.
But so what, it was still worth it!
I feel this is one of the such a lot vital info for me.
And i am satisfied studying your article. However should observation on few general things, The web site style is
ideal, the articles is in reality great : D. Excellent activity, cheers
If you do seasonwl perform on a day-to-day basis, you do not apply for a
secondary tax code.
my web blog homepage
There are a wide choice of games to elect from, which
includes slots, table games, video poker, specialty
games, and reside dealer games.
Here is mmy web blog … more info
The employment rate climbed to 60.9% last
year, matching a earlier higher set in 1997, statistics workplace information showed Wednesday.
Feel free to visit my blog – 여성 알바
When you’re about to choose your preferred on line casino, you shouldn’t
blindly trust any shortlist that comes your way.
Feel free too surf to my web page; homepage
If a bet is listed with a negative quantity, you will need tto have to bet that amount to win $one hundred.
Feel free to visit my page 토토사이트검증
He estimated thwt ChatGPT can generally pull
off 80 % of the legwork, leaving him to deal with the final 20 %.
Here iis my web blog bar 알바
“I believe it’s just a complicated mix of variables,” says Stephanie Aaronson, a senior fellow
with the Brookings Institution.
Look into my page – 이지알바
Two-adult households are additional broken down into households exactly where either one particular or twwo adults
function.
Here is my web site; website
Whhen you go to the cashier section to deposit funds, you will be ppresented with a list of choices and currencies.
Here is my web blog … read more
US gambling web sites ddo not only concentrate
on poker, casino gaming, and sports betting.
Feel free tto visit my blog post :: check here
If so, the markings are most probably due to the contractor submitting an 811 request for your house foor that project.
Also visit my blog: 동행복권 스피드키노
“There’s a lot of men and women I’ve identified in my individusl life who have worked
at Walmart from four a.m.
My web site; 여성알바
If you are managing remote workers, hhow ddo you know they’re operating only for you?
Here is my site: web site
In the national survey, 70 % of mothers who had quit said
they planned to return to paid function.
My website web site
Betting annd betting culture in the UK has changed
irreversibly over the years.
My homepage – click here
Our guide will show you tthe present laws and legalities of betting on sports in South Africa.
Feel free to surf to my blog post; 토토사이트검증
For Geo Wyeth, 27, who graduated from Yale in 2007, that signifies adopting a do-it-your self strategy to his profession.
Look at my sitfe :: 여성알바
Our list only incorporates regulated and licensed on the net gambling web-sites.
My page; http://nardi.homejoa.com/bbs/board.php?bo_table=free&wr_id=146246
Most of the entries on our liwt wll credit your chedcking account in
Here iss my web site: 급전 대출
This is an fantastic query, and oone that follows oon nicely from the preceding one
particular.
Revieew my web site :: 해외토토사이트
Theyy both ggot jobs at massive law firms, tthe type that reward people today
who make partner with seven-figure spend packages.
My web site … 언니알바
At present, the average salary bracket ranges
from 49,one hndred KPW ($54.56 or £40.48) to 194,000 KPW
($215.56 or £162) a month, according to data from Salary Explorer.
Here is my website – 단란주점 알바
To start, you will have access to three jobs, but with
Joker unable to go out at night, only Triple Seven and the Rafflesia Flower Shop are
accessible to start out.
My pave :: 요정알바
Loans are offered priarily based on authorized credit, revenue, aand
identity verification.
Here is myy web-site – 대환대출
For example, thhe lender may possibly require a high stable revenue
from the borrower.
Also visit my web page – 신불자대출
The synthetic handdle evaluation reveals larger increases in vaccination rates in additional populous counties.
Feel free to surf to my blog; 동행복권 스피드키노
Guaranteed immediate approval payday loans ned you to have
a bank account, identification, and proof of revenue.
my web page – 대환대출
Our lenders specialize in providing loans for fair credit to men and women inn tight economic conditions.
Here is my web-site – 일수 대출
What tends to make this platform distinctive iss that it acts
as a lottery agent rsther than a internet site for virtual drawings.
Also visit my homepage; 스피드키노
For instance, if you run into any issues in Pennsylvania, you can file a complaintt with the Pennsylvania Gaming Control Board who oversees all gaming in thhe state.
my website; check here
As anticipated, bank card and wire transfer cashouts will tak 3-5
business enterprise days to reasch your account.
My page: web page
Премиум база для Xrumer https://dseo24.monster/premium-bazy-dlja-xrumer-seo/prodaetsja-novaja-baza-dlja-xrumer-maj-2023/
Лучшая цена и качество.
線上賭場
台灣娛樂城/線上賭場(現金網)的特殊稱呼以及其歷史:
台灣對於線上賭場的特殊稱呼是「娛樂城/線上賭場(現金網)」。這種稱呼的背後有其原因,主要是因為線上賭場在台灣架設及經營是違法的。在早期經營線上博弈被抓的風險非常高,因此業者採用了「娛樂城」這樣的模糊代稱,以規避警方的注意。當時的網絡搜尋引擎尚未普及,這樣的代稱在一定程度上能夠達到避免被發現的效果。
台灣娛樂城/線上賭場的歷史可以分為幾個時期:
1. 網路未興盛時代:
– 現場賭場時期(1980年代):賭博活動主要發生在實體賭場,包括家庭電話上的BB CALL呼叫器、六合彩、大家樂等方式。
– 電銷賭場時期(21世紀):隨著手機的普及,人們開始使用手機進行博弈,主要包括中華職棒簽賭和六合彩等。
2. 線上博弈時期(2013年開始):
– 網際網路普及後,原本的信用版博弈業者開始轉戰線上賭場(娛樂城),開啟了線上博弈的時代。
– 由於在台灣,線上賭場架設和經營是違法的,合法的線上賭場通常選擇在合法的國家進行架設。
– 開設線上賭場主要採用「現金儲值」的方式,以規避法律風險。玩家將現金兌換成賭資,進行投注。
3. 娛樂城商業模式的轉變:
– 早期的娛樂城業者往往將客服人員與金流(出入款)的職責綁在一起,
容易成為執法機關定罪的基礎。
– 現代的娛樂城業者開始將客服人員、金流服務商以及廣告行銷外包,以降低定罪風險。
– 由於遠端工作的普及以及區塊鏈技術的應用,未來娛樂城業者可能更加難以被追查,這也凸顯了博弈產業合法化的必要性。
娛樂城業者面臨的風險主要來自以下幾個方面:
– 架站主機:娛樂城業者通常在合法的國家進行架設,使執法機關難以從此方面下手追查。
– 客服人員:娛樂城業者可能在台灣設立辦公室提供客服服務,這也是執法機關可能進行搜索的目標之一。
– 金流(出入款):娛樂城業者使用人頭帳戶進行金流操作,以規避監管機構的追蹤,但也存在風險。
– 行銷推廣:娛樂城業者需要進行廣告推廣來吸引玩家,行銷推廣方式也可能成為執法機關追查的一環。
娛樂城業者商業模式的轉變也反映了博弈產業的發展趨勢。隨著網路技術的成熟和商業模式的創新,博弈產業可能朝著合法化和監管的方向發展,以確保公信力、保護玩家權益並徵收相應的稅收。
http://for-css.ucoz.ae/go?https://rg8888.org/娛樂城大解析/
We would under no circumstances propose you join an offshore casino for playing slots.
Feel free to surf to my webpage … 토토사이트추천
Market your app on social media channels, like Facebook, Instagram, Twitter, and LinkedIn.
Feel free to visit my homepage … 파워볼중계