Operador ternario ?: en Java

Nos empezamos a adentrar a las estructuras de control o condicionales (if, if else, for…) como introducción vamos a comenzar mostrando el funcionamiento del poco conocido operador ternario.

Vamos a dividir la explicación en dos partes la teórica, donde explicamos el funcionamiento de operador ternario y finalmente la parte práctica.

Teoría de operador ternario ?: en Java

Las estructuras de control nos permiten modificar el flujo de ejecución de las instrucciones de un programa en Java. Esto realmente significa que tenemos varios caminos por donde mandar al programa según unas condiciones y que estos caminos tendrán resultados diferentes.

Bien imaginaros que sois un portero en una discoteca (aunque ya sé que preferís la programación) y vuestro jefe os dice que en la discoteca solo pueden entrar personas que sean mayores de edad (por tanto nos está especificando una condición: edad >=18). Os empiezan a venir niños de entre 16 y 25 años intentado acceder a vuestra discoteca. El operador ternario, se caracteriza por tener dos caminos Verdadero y Falso. Si los jóvenes son mayores de edad, la condición es verdadera, los dejaréis pasar a la discoteca, en el caso del programa, nos mostrará el primer resultado (el que tiene ? al principio) que nos indica que somos mayores de edad. Si la condición es Falsa, nos mostrará el segundo resultado (el que tiene : al principio), el que nos indica que somos menores de edad.

Una vez analizado, ya habéis podido comprobar que esto no tiene ni trampa ni cartón. Y que con un simple ejemplo cotidiano hemos hecho lo mismo que con el operador ternario.

Para realizar una operación con un operador ternario utilizamos:

  • Una condición que comparará los valores. En este caso la condición tiene al lado izquierdo la variable edad de tipo (int) y al lado derecho un valor numérico. Más adelante incluso podremos interactuar con el usuario desde la consola solicitando que nos introduzca un valor por la consola (lo veremos en próximas clases).

  • 2 caminos por los que puedan continuar dependiendo del resultado de la comprobación que hemos hecho. Una cosa a matizar es que una de las características de este operador es que solo puede tener 2 caminos NO más.
  • Un System.out.print para mostrarlo por la consola de Java.
  • La utilización del operador ?: donde ? irá delante de la primera condición y : delante de la segunda condición (no hace falta poner ni símbolos de más de concatenar ni nada a excepción de que queramos concatenar variables con texto en uno de los caminos).

Os dejo el código como siempre por aquí:

46 comentarios

  1. Hello to all, as I am truly eager of reading this
    web site’s post to be updated daily. It carries fastidious material.

  2. You can certainly see your expertise in the article you write.
    The arena hopes for even more passionate writers such as
    you who are not afraid to say how they believe. Always go
    after your heart.

  3. Good day very nice site!! Man .. Excellent .. Wonderful ..
    I will bookmark your blog and take the feeds additionally?
    I am glad to search out numerous helpful info here within the
    post, we need work out more techniques on this regard, thank you for sharing.

    . . . . .

  4. Very soon this web page will be famous amid all blogging
    visitors, due to it’s pleasant articles or reviews

  5. Hi there! This blog post could not be written any better!
    Going through this article reminds me of my previous roommate!
    He always kept talking about this. I am going
    to send this information to him. Fairly certain he’ll have a great read.
    Thank you for sharing!

  6. I’m not sure where you are getting your information, but great topic.
    I needs to spend some time learning more or understanding more.
    Thanks for fantastic info I was looking for this information for my mission.

  7. Hi! I could have sworn I’ve visited this site before but after looking at
    some of the articles I realized it’s new to me. Regardless, I’m
    definitely pleased I stumbled upon it and I’ll be book-marking
    it and checking back frequently!

  8. This is very interesting, You are a very skilled blogger.
    I’ve joined your rss feed and look forward to seeking
    more of your fantastic post. Also, I’ve shared your website in my social networks!

  9. Hello, Neat post. There is an issue with your site in web explorer,
    could check this? IE still is the market leader and
    a huge component of other folks will omit your magnificent writing due to this problem.

  10. It’s enormous that you are getting ideas from this
    piece of writing as well as from our dialogue made at this time.

  11. I love it when people get together and share views.

    Great blog, stick with it!

  12. Why visitors still use to read news papers when in this technological
    world everything is accessible on web?

  13. It is actually a nice and helpful piece of information. I am glad that
    you shared this useful information with us.
    Please keep us up to date like this. Thank you for sharing.

  14. Do you have any video of that? I’d care to find out some additional information.

  15. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your
    point. You clearly know what youre talking about,
    why waste your intelligence on just posting videos to your weblog when you could be giving us something enlightening to read?

  16. Thanks for sharing your thoughts about website.

  17. It’s awesome for me to have a web page, which is beneficial
    for my knowledge. thanks admin

  18. I visited many websites but the audio feature for audio songs present at this site is genuinely superb.

  19. Excellent post. I was checking continuously this
    blog and I’m impressed! Extremely helpful info specifically the last part :
    ) I care for such information much. I was looking for this particular
    information for a long time. Thank you and good luck.

  20. Hi! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked
    hard on. Any suggestions?

  21. If some one wishes to be updated with most up-to-date technologies afterward
    he must be visit this site and be up to date daily.

  22. amazingly good research. I hope you are able to continue to work so that
    you can put insight created for the readers with this website.

    Too visit my very own site to get all of the latest content material or websites about
    lisonjero togel.

  23. Attractive blog! I stumbled upon it even though surfing around in Yahoo
    Files. Do you have just about any tips on how to obtain listed in Aol News?
    We possess been intending for a while on the other hand I for no reason seem to create it
    happen! Many thanks

  24. Hi there! This blog post couldn’t be written much
    better! Going through this article reminds me of my
    previous roommate! He constantly kept preaching about this.
    I will forward this post to him. Pretty sure he will have a
    very good read. Thank you for sharing!

  25. Hi there, I enjoy reading through your article.

    I like to write a little comment to support you.

  26. Thanks for one’s marvelous posting! I actually enjoyed reading it, you happen to be a great author.
    I will be sure to bookmark your blog and will often come
    back very soon. I want to encourage yourself to continue your
    great job, have a nice weekend!

  27. Hi there to every body, it’s my first go to see of this blog; this webpage includes remarkable and genuinely excellent material in favor
    of visitors.

  28. Do you have a spam problem on this blog; I also am a blogger, and
    I was wondering your situation; many of us have developed some nice practices and we are looking to exchange techniques with other folks, be
    sure to shoot me an e-mail if interested.

  29. Simply want to say your article is as amazing.

    The clarity in your submit is simply spectacular and that i can assume you are a professional in this subject.
    Fine along with your permission let me to clutch your feed
    to stay updated with approaching post. Thanks a million and please keep up the rewarding work.

  30. It’s genuinely very difficult in this busy life to listen news on TV, thus I just use web for that purpose, and obtain the newest information.

  31. That is a great tip especially to those new to the blogosphere.

    Short but very accurate information? Many thanks for sharing this one.
    A must read post!

    Here is my homepage – quality treatment

  32. Paragraph writing is also a excitement, if you be acquainted with afterward you can write otherwise it
    is difficult to write.

    Also visit my homepage

  33. Great write-up, I’m regular visitor of one’s blog, maintain up the
    excellent operate, and It’s going to be a regular visitor for a
    long time.

    My homepage; best muscle building supplement

  34. Excellent article. I will be dealing with a few of these issues as well..

  35. What a information of un-ambiguity and preserveness of precious familiarity
    about unexpected feelings.

  36. Great post. I will be dealing with many of these issues as well..

    Here is my web blog … low carb recipes

  37. Pretty section of content. I just stumbled upon your website and in accession capital to
    assert that I get actually enjoyed account your blog posts.

    Anyway I’ll be subscribing to your augment and
    even I achievement you access consistently quickly.

  38. There is visibly a lot to know about this. I consider you made certain nice points in features also.

    My web page – http://www.hjzzj.com

  39. I always spent my half an hour to read this weblog’s content everyday along with a
    mug of coffee.

  40. Link exchange is nothing else however it is only placing the
    other person’s website link on your page at proper place and other person will also do similar for you.

  41. Having read this I believed it was rather informative.
    I appreciate you finding the time and effort to put this content together.
    I once again find myself personally spending a lot of time both reading and
    posting comments. But so what, it was still worthwhile!

  42. Hey I know this is off topic but I was wondering if you knew of
    any widgets I could add to my blog that automatically tweet my newest twitter updates.
    I’ve been looking for a plug-in like this for quite some
    time and was hoping maybe you would have some experience with something like this.

    Please let me know if you run into anything. I truly enjoy reading your blog and I look
    forward to your new updates.

  43. Greetings! Very helpful advice within this post! It is the little changes that will make the largest
    changes. Thanks for sharing!

    Also visit my new website in here <a href="https://adoptioninstitute.org/&quot;

  44. Greetings from Colorado! I’m bored to death at work so I decided to browse your blog on my iphone during lunch break.

    I love the info you present here and can’t wait to take a look when I get home.
    I’m amazed at how fast your blog loaded on my phone .. I’m not even using WIFI, just 3G ..
    Anyhow, excellent blog!

  45. Thanks a lot for the article post.Really thank you! Fantastic.

    Feel free to visit my new site
    Situs Judi Slot Online

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.