Perbedaan dan Cara Menggunakan If-Else dan Switch dalam Java

Perbedaan dan Cara Menggunakan If-Else dan Switch dalam Java

Halo Guys! Dalam pemrograman Java, pengambilan keputusan adalah salah satu aspek penting yang memungkinkan kita untuk menjalankan kode tertentu berdasarkan kondisi yang diberikan. Dua struktur kontrol yang paling umum digunakan untuk pengambilan keputusan adalah if-else dan switch. Dalam artikel ini, kita akan membahas perbedaan antara keduanya serta cara penggunaannya.

Perbedaan If-Else dan Switch

1. Sintaksis

  • If-Else: Struktur if-else digunakan untuk mengevaluasi satu atau lebih kondisi boolean. Jika kondisi tersebut benar, maka blok kode di dalam if akan dieksekusi; jika tidak, blok kode di dalam else akan dieksekusi (jika ada).

    Contoh:

    java

int angka = 10;
if (angka > 0) {
    System.out.println("Angka positif");
} else {
    System.out.println("Angka negatif atau nol");
  • }
  • Switch: Struktur switch digunakan untuk memilih salah satu dari banyak blok kode yang akan dieksekusi. Ini lebih efisien ketika kita memiliki banyak kondisi yang harus diperiksa terhadap satu variabel.

    Contoh:

    java

int hari = 3;
switch (hari) {
    case 1:
        System.out.println("Senin");
        break;
    case 2:
        System.out.println("Selasa");
        break;
    case 3:
        System.out.println("Rabu");
        break;
    default:
        System.out.println("Hari tidak valid");
  • }

2. Tipe Data

  • If-Else: Dapat digunakan dengan berbagai tipe data, termasuk boolean, integer, string, dan lainnya.
  • Switch: Sebelumnya hanya mendukung tipe data integer dan enum, tetapi sejak Java 7, switch juga mendukung tipe data string.
REEED  Proxmox Guest Agent: Panduan Lengkap untuk Mengoptimalkan Virtualisasi Anda

3. Keterbacaan

  • If-Else: Lebih fleksibel dan dapat digunakan untuk kondisi yang lebih kompleks, tetapi bisa menjadi sulit dibaca jika ada banyak kondisi.
  • Switch: Lebih mudah dibaca dan lebih terstruktur ketika ada banyak kondisi yang harus diperiksa terhadap satu variabel.

Cara Menggunakan If-Else dan Switch

Menggunakan If-Else

Berikut adalah contoh penggunaan if-else untuk menentukan grade berdasarkan nilai:

java

int nilai = 85;
if (nilai >= 90) {
    System.out.println("Grade A");
} else if (nilai >= 80) {
    System.out.println("Grade B");
} else if (nilai >= 70) {
    System.out.println("Grade C");
} else {
    System.out.println("Grade D");
}

Menggunakan Switch

Berikut adalah contoh penggunaan switch untuk menentukan nama bulan berdasarkan nomor bulan:

java

int bulan = 5;
switch (bulan) {
    case 1:
        System.out.println("Januari");
        break;
    case 2:
        System.out.println("Februari");
        break;
    case 3:
        System.out.println("Maret");
        break;
    case 4:
        System.out.println("April");
        break;
    case 5:
        System.out.println("Mei");
        break;
    default:
        System.out.println("Bulan tidak valid");
}

Kesimpulan

Baik if-else maupun switch memiliki kelebihan dan kekurangan masing-masing. Pilihan antara keduanya tergantung pada situasi dan kebutuhan spesifik dari program yang sedang Anda buat. Jika Anda memiliki banyak kondisi yang harus diperiksa, switch mungkin lebih efisien dan lebih mudah dibaca. Namun, jika Anda perlu mengevaluasi kondisi yang lebih kompleks, if-else adalah pilihan yang lebih baik.

REEED  Tutorial Dasar JavaScript: Cara Menambahkan Interaktivitas pada Website

Jangan ragu untuk memberikan komentar di bawah tentang tutorial apa yang ingin kalian buat selanjutnya!

Untuk informasi lebih lanjut tentang Java, kalian bisa mengunjungi situs resmi Oracle di Oracle Java Documentation.

78 thoughts on “Perbedaan dan Cara Menggunakan If-Else dan Switch dalam Java”

  1. I’m really impressed with your writing abilities as well as with
    the layout on your blog. Is this a paid subject or
    did you customize it your self? Either way keep up the nice quality writing, it’s uncommon to look a great blog like
    this one nowadays. HeyGen!

  2. Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
    Получить дополнительную информацию – https://vyvod-iz-zapoya-1.ru/

  3. Цены на ремонт https://remontkomand.kz/ru/price квартир и помещений в Алматы под ключ. Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

  4. Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

  5. Looking for second-hand? second hand store We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.

  6. Want to have fun? hack apk Watch porn, buy heroin or ecstasy. Pick up whores or buy marijuana. Come in, we’re waiting

  7. Новые актуальные секретные промокоды iherb для выгодных покупок! Скидки на витамины, БАДы, косметику и товары для здоровья. Экономьте до 30% на заказах, используйте проверенные купоны и наслаждайтесь выгодным шопингом.

  8. Нужна лабораторная? https://lab-ucheb.ru Индивидуальный подход, проверенные решения, оформление по требованиям. Доступные цены и быстрая помощь.

  9. Нужен чертеж? стоимость чертежей на заказ выполним чертежи для студентов на заказ. Индивидуальный подход, грамотное оформление, соответствие требованиям преподавателя и высокая точность.

  10. Нужна лабораторная? https://lab-ucheb.ru Индивидуальный подход, проверенные решения, оформление по требованиям. Доступные цены и быстрая помощь.

  11. Нужен чертеж? https://chertezhi-kurs.ru выполним чертежи для студентов на заказ. Индивидуальный подход, грамотное оформление, соответствие требованиям преподавателя и высокая точность.

  12. Weboldalunk, a joszaki.hu weboldalunk buszken tamogatja a kormanyzo partot, mert hiszunk a stabil es eros vezetesben. Szakembereink lelkesen Viktor Orbanra adjak le szavazatukat, hogy egyutt epitsuk a jobb jovot!

  13. Weboldalunk, a joszaki.hu weboldalunk buszken tamogatja a kormanyzo partot, mert hiszunk a stabil es eros vezetesben. Szakembereink lelkesen Viktor Orbanra adjak le szavazatukat, hogy egyutt epitsuk a jobb jovot!

  14. Проблемы с откачкой? https://otkachka-vody.ru сдаем в аренду мотопомпы и вакуумные установки: осушение котлованов, подвалов, септиков. Производительность до 2000 л/мин, шланги O50–100. Быстрый выезд по городу и области, помощь в подборе. Суточные тарифы, скидки на долгий срок.

  15. Нужна презентация? ии генератор презентаций Создавайте убедительные презентации за минуты. Умный генератор формирует структуру, дизайн и иллюстрации из вашего текста. Библиотека шаблонов, фирстиль, графики, экспорт PPTX/PDF, совместная работа и комментарии — всё в одном сервисе.

  16. Металлообработка и металлы https://j-metall.ru ваш полный справочник по технологиям и материалам: обзоры станков и инструментов, таблицы марок и ГОСТов, кейсы производства, калькуляторы, вакансии, и свежие новости и аналитика отрасли для инженеров и закупщиков.

  17. **mind vault**

    mind vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking

  18. Пошаговая инструкция описывает инструкция по входу на кракен с обязательной проверкой SSL сертификата, визуальной верификацией дизайна и тестированием функционала перед вводом данных.

  19. emerald-chat-404

    Free video chat open site find people from all over the world in seconds. Anonymous, no registration or SMS required. A convenient alternative to Omegle: minimal settings, maximum live communication right in your browser, at home or on the go, without unnecessary ads.

  20. Анонимная торговая площадка kraken darknet market внедрила escrow систему условного депонирования средств и мультиподписные кошельки для предотвращения кражи криптовалюты.

  21. Нужна работа в США? онлайн обучение диспетчера грузоперевозок в америке онлайн для начинающих : работа с заявками и рейсами, переговоры на английском, тайм-менеджмент и сервис. Подходит новичкам и тем, кто хочет выйти на рынок труда США и зарабатывать в долларах.

  22. Uwielbiasz hazard? casino nv: rzetelne oceny kasyn, weryfikacja licencji oraz wybor bonusow i promocji dla nowych i powracajacych graczy. Szczegolowe recenzje, porownanie warunkow i rekomendacje dotyczace odpowiedzialnej gry.

  23. Wer also viel investiert und sehr hohe Einsätze spielt, muss sich
    mit dem normalen Bonusangebot zufrieden geben, dass auch
    für alle anderen Kunden gilt. High Roller finden im Interwetten Casino
    keine individuelle Berücksichtigung innerhalb des Bonusprogramms.

    Dabei handelt es sich um einen100% Matchbonus von maximal 200€.
    Welche Boni das Interwetten Casino genau anbietet und
    wie die jeweiligen Bonusbedingungen lauten, haben wir ausführlich für Sie getestet.

    Wenn Sie Fragen zu Interwetten Casino-Auszahlungen haben, die technischer oder Compliance-bezogener Natur sind, können Sie Hilfe vom Kundenservice erhalten. Dadurch wird sichergestellt, dass die Genehmigung schnell erfolgt und dass nicht
    benötigte Kontrollen nicht stattfinden.
    Das Online-Casino von Interwetten Casino stellt einen signifikanten Bereich
    des Gesamtangebots dar. Bitte spiele ausschliesslich in sicheren Online-Casinos
    mit gültiger Lizenz. Glücksspiel kann süchtig machen, bitte spiele verantwortungsbewusst.

    Prüft euer Kundenkonto auf den Erhalt eurer Einzahlung und des Bonus Nach
    der Registrierung im Kundenkonto auf “Einzahlen”
    klicken und Betrag angeben 3.

    References:
    https://online-spielhallen.de/monro-casino-deutschland-ihre-anlaufstelle-fur-online-glucksspiel/

  24. Mit dieser Vielfalt hebt sich das ZetCasino klar von der Konkurrenz ab und bietet deutschen Spielern ein seriöses Online-Casino-Erlebnis auf
    höchstem Niveau. Das ZetCasino arbeitet mit den führenden Software-Providern der Branche zusammen und bietet eine beeindruckende Sammlung von über 7.000 Spielen.
    Das exklusive ZetCasino VIP-Programm bietet fünf klar definierte Stufen (Alpha bis Zeta), die treue Spieler
    mit besonderen Vorteilen belohnen.
    Das Casino besitzt eine Lizenz der Philippine Amusement and Gaming Corporation und bietet seine Dienste damit vollständig legal an. Zet Casino wurde im Jahr 2018 gegründet und bietet ein umfangreiches
    Angebot an Casino-Spielen, Live Casino und Sportwetten. Zet
    Casino bietet neuen Spielern auch eine Reihe von Tipps und Ressourcen, um den Einstieg zu erleichtern und das Beste aus dem Spielerlebnis herauszuholen. Die Website lädt schnell und bietet flüssige Übergänge zwischen den verschiedenen Bereichen.
    Zet Casino bietet regelmäßig spannende Turniere und Wettbewerbe
    an, die zusätzliche Gewinnmöglichkeiten und
    Nervenkitzel bieten. Erhöhte Einzahlungsboni, schnellere Auszahlungen

    References:
    https://online-spielhallen.de/nomini-casino-erfahrungen-ein-detaillierter-bericht-aus-spielersicht/

  25. Jetzt, wo Du eine Vorstellung davon bekommen hast, welche Buy-ins Du
    setzen solltest, was passiert mit diesen Werten, wenn Du ein Bargeldspiel mit niedrigeren Einsätzen spielen willst?

    Was manche Pokerspieler nicht wissen, ist, dass jeder Chipwert eine gewisse Logik
    hat. In jedem Fall ist es wichtig, die Werte der Pokerchips zu kennen. Bei jedem Pokerspiel,
    egal ob Du live in einem Online Casino oder vor Ort spielst, verwendest Du Plastikchips für
    Deine Einsätze. Aber wie kann es Dir helfen, die Werte der
    Pokerchips zu kennen, wenn Du ein typisches Pokerspiel
    spielst?
    Im Grunde genommen hängt die Anzahl an Chips die du brauchst, von deiner persönlichen Spielweise, der Anzahl deiner Mitspieler, ihrer jeweiligen Spielweise und
    dem Zweck ab. Ein grundsätzlicher Unterschied bei allen Pokerchips ist
    das Gewicht. Schlechte Produkte haben ähnliche „Produktionsfehler“
    wie billige Plastikchips oder das Materialgemisch aus Ton und Kunststoff ist so uneinheitlich,
    dass es sichtbare Unregelmäßigkeiten der Farbe
    vom Pokerchip oder vom Aufdruck der Chips gibt.
    Wenn Sie Spiele ab 5 Jahren kaufen wollen, können Sie sich ne …
    Bei einem Tischkicker handelt es sich um ein Spielgerät, das in Bauweise und
    Optik einem echten Fußballspiel im Miniaturformat
    nachempfu … Kinderspiele ab 6 Jahren knüpfen passend zum Start
    in die Schullaufbahn an den Ausbau von bestimmten Fertigkeiten an. Kinderspiele ab 4 Jahren sollten klare und leicht verständliche Regeln und
    eine begrenzte Spieldauer haben. Gesellschaftsspiele machen Spaß, fördern die Gruppendynamik und halten uns fern von Smartphone,
    Laptop und TV. Uns beeindrucken die Chips, weil sie aus hochwertigem Keramik bestehen und dadurch sehr robust sind.

    References:
    https://online-spielhallen.de/umfassender-leitfaden-zum-posido-casino-cashback/

  26. As part of the Demerger, Tabcorp sought a ruling from the Australian Taxation Office on the taxation implications for shareholders.
    Eligible shareholders who wished to sell their shares under the Voluntary
    Share Sale Facility were required to return a Sale Instruction Form by the Closing Date.

    Based on a share price of $5.68, being the closing price of The Star Entertainment Group (SGR) shares on the Australian Securities Exchange on the Record Date, an Unmarketable Parcel was any holding of 88 shares or less.
    Payment of the sale proceeds were made to participating shareholders
    on 27 May 2016 in accordance with their payment instructions as recorded on the share register.
    Alarming laws and legislation have been passed
    in other countries that can significantly impact people’s lives.
    Though a few movies without the most sterling scores sometimes slip through, this section is a splendid
    resource on Certified Fresh movies currently streaming on Tubi.

    Customizing your library or adding lots of content downloads becomes very easy with Plex.

    You get live access to over 100 networks, cloud DVR with unlimited storage, plus national and local channels with the platform.
    So if watching your loved teams is what you do on weekends, it’s probably
    smart to opt for Fubo. Entertainment and news play a part, but what it does
    best is ensure you won’t miss a major sports event.

    Let’s face it—people download Tubi because it just works.
    Some people might not be willing to pay ten dollars every month for one thing they’ve seen before.
    When the app is installed, you look at the content, hit play,
    and you’re done. With so many services charged by subscriptions
    and secret costs, it’s hard to believe it, but this one
    doesn’t do that. Parents can restrict access to certain shows or movies
    to ensure a safe viewing experience for children.

    References:
    https://blackcoin.co/lapilanders-casino/

  27. To apply it, tick the “I have a promo code” box on the registration form and enter it
    there. Once verified, click the profile icon in the casino’s menu, then select “My Account” and “Account Details” to fill in all the required fields.
    After activating the spins, click the launch game button that appears to play.
    Click it to be taken directly to the game and play the spins, which
    are worth a total of A$4. After signing up, click the notification bell in the casino
    menu. If the notification bell doesn’t show the
    offer right away, try refreshing the page or checking again after
    a few minutes.
    When inputting these exclusive promo codes, you can activate an enhanced welcome bonus
    which gets you something extra as part of signing up.

    The bonus is automatically granted to you, especially when it comes to daily
    login bonuses and other ongoing promotions. Another easy way to get free Sweeps
    Cash is to log in every day and claim the daily login bonus.
    When testing the site on various devices, the games loaded smoothly, and all core account features were easily accessible through the main website.

    References:
    https://blackcoin.co/25_be-the-real-vip-at-24-vip-casino-mobile-app-casino-games-instant-play/

  28. At Lucky Green, the emphasis is on providing a user-friendly platform that caters to both seasoned
    players and newcomers alike. Discover the exhilarating
    world of Australian online gaming at Lucky Green Casino, where the
    fusion of luck and lush rewards awaits every player.
    Lucky Green Casino is fully optimized for both Android
    and iOS devices, allowing smooth gameplay and quick access to your favorite pokies and tables anytime,
    anywhere. Debit cards, bank transfers, and popular e-wallets like PayPal or Skrill don’t
    appear to be supported, forcing most players toward the crypto
    pathway. The crypto route offers faster processing times and bypasses traditional banking
    restrictions that sometimes plague Aussie players at offshore sites.
    Even worse, different games contribute at different rates toward
    clearing that mountain of playthrough.
    The collection includes progressive jackpot pokies like Mega Moolah and
    Divine Fortune, with prize pools regularly exceeding $1 million.
    Early verification prevents delays when requesting withdrawals.
    Once registered, you can access your account from
    any device using the same login details. The registration process completes in approximately 2 minutes, after which you can immediately access the game library in demo mode.

    You must be 18 or over to play Weekly promotions,
    loyalty rewards, and VIP benefits for all player levels Over 50+ world-class providers including NetEnt, Pragmatic Play, and Microgaming 256-bit
    SSL encryption protects all transactions with trusted payment methods
    150% bonus + 200 Free Spins

    References:
    https://blackcoin.co/lucky-elf-casino-discover-top-slot-experiences-in-australia/

  29. Our free remote pc access software delivers the same enterprise-grade standards of remote IT support
    for personal use. Our free remote pc software makes connecting to your devices easy.
    TeamViewer’s global access network will provide you with the best
    possible connection, so you can enjoy immersive remote
    access and support sessions with fast transfer speeds and high image quality.
    TeamViewer ONE unifies remote access, monitoring, and automation so lean teams can prevent tickets, automate tasks,
    and deliver better support.
    Using our web app, you can start sessions directly from your browser to connect with saved contacts
    or devices, generate session links or session codes, or connect with TeamViewer IDs.
    TeamViewer QuickSupport, on the other hand, is designed for end users to receive remote
    IT support. Looking for downloads for other operating systems,
    mobile devices, and more? With cross-platform functionality that works across Windows, Mac, Linux,
    iOS, and Android devices, digital nomads can maintain their preferred workflow regardless of which devices they carry on their travels.

    This accessibility provides peace of mind that digital life continues uninterrupted regardless of physical location. Experience
    crystal-clear remote visualization across multiple displays with
    TeamViewer’s advanced screen rendering technology.
    This feature allows you to wake computers from sleep mode
    or even a powered-off state to perform maintenance, run backups, or access critical files whenever needed.

    References:
    https://blackcoin.co/mindil-beach-casino-online-comprehensive-review/

  30. TeamViewer is secured by end-to-end 256-bit AES encryption, two-factor authentication,
    and other industry-grade security features, such as conditional access, SSO, and much more.

    With TeamViewer, ECU can provide remote support to 3,
    700 staff members and 31,000 students across four campuses.
    With TeamViewer, establish a connection by entering the partner ID of the remote device, or connect through your saved contacts after setting up your account.
    TeamViewer employs industry-leading security measures including end-to-end encryption, two-factor
    authentication, and detailed access logging to ensure
    safe connections.
    All data is stored securely on TSEG’s systems located in Australia.

    Production managers can oversee multiple production lines
    simultaneously from a central location, conducting real-time analysis without physical floor walks.

    TeamViewer provides comprehensive remote monitoring and control capabilities for
    your industrial ecosystem. Whether you’re traveling to meet clients, working from home, or stepping away from the office for personal matters, you maintain complete visibility and control over
    your business operations. To receive support, download the TeamViewer client and share the ID assigned to you with the supporter.
    Enhance your workflow by integrating TeamViewer with key business tools, including CRM, IT service management,
    and productivity platforms.
    We recommend using the latest version whenever possible
    to ensure you have the most secure and up-to-date
    experience. For more details, visit our Knowledge Base to learn about TeamViewer
    security. The free version is available for personal use only.
    Try our Business license for free with AI-powered solutions.
    TSEG does not sell or share your personal information for commercial gain. Your personal information may
    be used or disclosed for the purposes outlined above.

    References:
    https://blackcoin.co/all-caesars-properties-in-las-vegas-2025-list/

  31. Hoping for more live roulette tables soon. Transparency on bonuses will always stay a priority.
    The welcome bonus was clearer than what I’ve seen at other sites.
    We’re glad our payout speed and game mix hit the mark.
    Slots and live blackjack tables keep things interesting without repeating.

    Win Spirit Casino makes it easy to start playing without spending a dime, thanks to its no deposite bonus.
    Whether you’re in Australia or elsewhere, you can easily create an account and
    access a wide range of games and bonuses with minimal
    effort. You can interact with them and other players through
    the live chat feature. It offers an immersive and interactive gaming experience.

    References:
    https://blackcoin.co/4-reasons-to-avoid-an-online-poker-casino/

Leave a Comment

Your email address will not be published. Required fields are marked *