Java Full Stack Trainer

Java program to generate random numbers

Objectives:

  • Write a Java program to to generate random numbers and print the same
  • Write a program to generate random numbers
  • Write a program to generate random numbers in Java

Java Program:

[sourcecode lang="java"]

import java.util.Scanner;
import java.util.Random;

class GenerateRandomNumber
{
public static void main(String[] args)
{
int maxRange;

//create objects
Scanner SC = new Scanner(System.in);
Random rand = new Random();

System.out.print("Please enter maximum range: ");
maxRange=SC.nextInt();

for(int i=1; i<=10; i++)
{
System.out.println(rand.nextInt(maxRange));
}
}
}

[/sourcecode]

Output:

Please enter maximum range: 500
467
61
100
449
68
316
445
224
54
498

Find duplicate characters in string

Objectives:

  • Write a Java program to find duplicate characters in the string and print the duplicate characters
  • Write a program to find duplicate characters in String

Java Program:

[sourcecode lang="java"]
public class DuplicateCharacters {
    public static void main(String args[]) {

        String str = "NITIN";
        int count = 0;

        char input[] = str.toCharArray();
        System.out.println("Duplicate Characters are:");

        for (int i = 0; i &amp;lt; str.length(); i++) {
            for (int j = i + 1; j &amp;lt; str.length(); j++) {
                if (input[i] == input [j]) {
                    System.out.println(input[j]);
                    count++;
                    break;
                }
           }
        }
    }
}
[/sourcecode]

Output:

Duplicate Characters are: N I

Passing String in Switch Case in Java

Objectives:

  • How to use switch case in Java?
  • How to use switch case with string in Java?
  • How to pass string literals in switch case in Java?

 

Source Code:

[sourcecode lang=”java”]

public class SwitchWithStringExample

{
public static void main(String[] args)
{
String str = "two";
switch(str)
{
case "one":
System.out.println("one");
break;
case "two":
System.out.println("two");
break;
case "three":
System.out.println("three");
break;
default:
System.out.println("no match");
} // switch close
} // main close
} // class close

[/sourcecode]

 

Steps to run above Java code:

Consider that we have saved code at C drive (c:\>) and the file is saved as SwitchWithStringExample.java

  1. Compilation : c:\> javac SwitchWithStringExample.java
  2. Interpretation : c:\> java SwitchWithStringExample

 

Output:

two

 

We conduct Java Training and Workshop for Corporates and College Students, if interested, please write to us on kloudsancyber@gmail.com

 

Aatul Palandurkar
International Trainer, and Author, NetBeans Dream Team Member

https://www.facebook.com/aatulpalandurkar
https://www.instagram.com/aatulpalandurkar/