Core Java Tutorials

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

Using For Each in Java

Objective:

  • How to use For Each in Java?
  • How to use advance for in Java?
  • How to use advance for loop in Java Programming Language?
  • Types of For loop in Java

 

Source Code:

[sourcecode lang=”Java”]

class ForEachExample
{
public static void main(String args[])
{
//declaring an array
int a[]={1,2,3,4,5,6};

// Old way
System.out.println("Old way");
for(int i=0; i<a.length;i++)
{
System.out.println(a[i]);
}

//New way: for-each loop
System.out.println("For each");
for(int i:a)
{
System.out.println(i);
}
}
}

[/sourcecode]

Pattern Programs in Java – Pattern 3

Pattern 3 :

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

 

Java Code for above pattern :

[sourcecode lang=”java”]

import java.util.Scanner;

&nbsp;

public class Pattern3

{

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

//Taking rows value from the user

System.out.println("How many rows you want in this pattern?");

int rows = sc.nextInt();

System.out.println("Here is your pattern….!!!");

//Printing upper half of the pattern

for (int i = 1; i <= rows; i++)

{

for (int j = 1; j <= i; j++)

{

System.out.print(j+" ");

}

System.out.println();

}

//Printing lower half of the pattern

for (int i = rows-1; i >= 1; i–)

{

for (int j = 1; j <= i; j++)

{

System.out.print(j+" ");

}

System.out.println();

}

//Closing the resources

sc.close();

}

}

[/sourcecode]

Output :

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

 

Pattern Programs in Java – Pattern 2

Pattern 2 :

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Java Program for the above pattern:

[sourcecode language=”java”]

import java.util.Scanner;

public class MainClass

{

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

//Taking rows value from the user
System.out.println("How many rows you want in this pattern?");

int rows = sc.nextInt();

System.out.println("Here is your pattern….!!!");

for (int i = 1; i <= rows; i++)

{

for (int j = 1; j <= i; j++)

{

System.out.print(i+" ");

}

System.out.println();

}

//Close the resources
sc.close();

}

}

[/sourcecode]

Pattern Programs In Java – Pattern 1

Q. Write a Java program to print given pattern.

Pattern 1 :

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7

 

Java Program:

[sourcecode language=”java”]

import java.util.Scanner;

public class MainClass

{

public static void main(String[] args)

{

Scanner sc = new Scanner(System.in);

//Taking rows value from the user

System.out.println("How many rows you want in this pattern?");

int rows = sc.nextInt();

System.out.println("Here is your pattern….!!!");

for (int i = 1; i <= rows; i++)

{

for (int j = 1; j <= i; j++)

{

System.out.print(j+" ");

}

System.out.println();

}

//Close the resources

sc.close();

}

}

[/sourcecode]

Java Program to convert Decimal values to Hexadecimal values

Objectives :

  • How to convert Decimal to Hexadecimal in Java?

 

Java Program to convert Decimal values to Hexadecimal values : 

[sourcecode lang=”java”]

import java.util.Scanner;

public class DecimalToHexadecimal {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

System.out.print("Enter decimal number you like: ");
int deci = input.nextInt();

System.out.println("The hexadecimal number for decimal "
+ deci + " is " + convert(deci));
}

public static String convert(int decimal) {
String hex = "";

while (decimal != 0) {
int hexValue = decimal % 16;
hex = toHexadecimal(hexValue) + hex;
decimal = decimal / 16;
}

return hex;
}

public static char toHexadecimal(int hexValue) {
if (hexValue <= 9 && hexValue >= 0) {
return (char) (hexValue + ‘0’);
} else {
return (char) (hexValue – 10 + ‘A’);
}
}
}

[/sourcecode]

Output :
Enter decimal number you like: 1234
The hexadecimal number for decimal 1234 is 4D2

Java Program to Convert Decimal Number to Roman Number

Objectives :

  • Convert Decimal number to Roman number
  • Convert Decimal numeral to Roman numeral
  • How to convert a decimal number to roman number
  • Write a program that converts a decimal number to Roman number.
  • Write a program that converts a decimal number to Roman number. Decimal Number is accepted using Scanner class at the time of execution.
  • Write a program that converts a decimal number to Roman number. Decimal Number is accepted as command line input at the time of execution.

 

Program : 

Java program that converts a decimal number to Roman number. Decimal Number is accepted using Scanner class at the time of execution.

[sourcecode lang=”java”]

&nbsp;

import java.util.Scanner;

public class DecimalToRoman {

private static String toRoman(int num) {
String[] romanCharacters = { "M", "CM", "D", "C", "XC", "L", "X", "IX", "V", "I" };
int[] romanValues = { 1000, 900, 500, 100, 90, 50, 10, 9, 5, 1 };
String result = "";

for (int i = 0; i < romanValues.length; i++) {
int numberInPlace = num / romanValues[i];
if (numberInPlace == 0) continue;
result += numberInPlace == 4 && i > 0? romanCharacters[i] + romanCharacters[i – 1]:
new String(new char[numberInPlace]).replace("\0",romanCharacters[i]);
num = num % romanValues[i];
}
return result;
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number : ");
int decimal = scanner.nextInt();
System.out.println(toRoman(decimal));
}

}

[/sourcecode]

Output :

Enter a number : 1234

MCCXXXIV

Java program that converts a decimal number to Roman number. Decimal Number is accepted as command line input at the time of execution.

[sourcecode lang=”java”]

public class DecimalToRoman {

private static String toRoman(int num) {
String[] romanCharacters = { "M", "CM", "D", "C", "XC", "L", "X", "IX", "V", "I" };
int[] romanValues = { 1000, 900, 500, 100, 90, 50, 10, 9, 5, 1 };
String result = "";

for (int i = 0; i < romanValues.length; i++) {
int numberInPlace = num / romanValues[i];
if (numberInPlace == 0) continue;
result += numberInPlace == 4 && i > 0? romanCharacters[i] + romanCharacters[i – 1]:
new String(new char[numberInPlace]).replace("\0",romanCharacters[i]);
num = num % romanValues[i];
}
return result;
}

public static void main(String[] args) {
if(args.length<1 || args.length>1){
System.out.println("Wrong input");
}else{
String number = args[0];
int decimal = Integer.parseInt(number);
System.out.println(toRoman(decimal));
}
}

}

[/sourcecode]

Java Program to convert Decimal to Binary

Objectives :

  • Decimal to Binary Conversion
  • Converting Decimal to Binary
  • Converting Decimal Number to Binary format
  • Write a program to convert decimal to binary
  • Write a program to convert decimal number to binary format
  • Write a program to convert positive decimal number to binary format
  • Write a program to convert decimal to binary using Scanner class
  • Write a program to convert decimal to binary, take input using Scanner class

 

Java Program to convert Decimal to Binary : 

[sourcecode lang=”java”]
public class DecimalToBinary {

public void toBinary(int number){
int binary[] = new int[25];
int n = 0;
// Convert Decimal to Binary
while(number > 0){
binary[n++] = number%2;
number = number/2;
}
// Print Binary number
for(int i = n-1;i >= 0;i–){
System.out.print(binary[i]);
}
}

public static void main(String[] args){
DecimalToBinary obj = new DecimalToBinary();
obj.toBinary(14);
}
}
[/sourcecode]

Output :

1110

 

Java Program to convert Decimal to Binary using Scanner class :

[sourcecode lang=”java”]

import java.util.Scanner;

public class DecimalToBinary {

public void toBinary(int number){
int binary[] = new int[14];
int n = 0;

// Convert Decimal to Binary
while(number > 0){
binary[n++] = number%2;
number = number/2;
}

// Print Binary Number
for(int i = n-1;i >= 0;i–){
System.out.print(binary[i]);
}
}

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num= scanner.nextInt();
DecimalToBinary obj = new DecimalToBinary();
obj.toBinary(num);

}
}

[/sourcecode]

Output :

Enter a number: 14

1110

Java Program to find prime number upto N number

Objectives :

  • Write a Java program to find prime number upto N number
  • Write a Java program to print prime number upto N number
  • Write a Java program to find prime number upto N number using Command Line Arguments
  • Write a Java Program to find prime number upto N number via Command Line Arguments
  • Write a Java program to find prime number upto N number using Scanner class

 

Java Program / Code :

Method 1 : Java Program to find Prime Number upto N number using Scanner class

[sourcecode lang=”Java”]

import java.util.Scanner;
class PrimeNumber
{
public static void main(String[] args)
{
int n,p;
Scanner s=new Scanner(System.in);
System.out.println(“Enter number : ”);
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0){
System.out.println(i);
}
}
}
}
[/sourcecode]

Method 2 : Java Program to find Prime Number upto N number using Scanner class and writing function to find prime number

Method isPrime() for checking if a number is prime or not

[sourcecode lang=”java”]
public class PrimeNumber{
public boolean isPrime(int num) {
if ( num < 2 ){
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if ( num % i == 0 ) {
return false;
}
}
return true;
}
}

// Mock Test Class to test above code
import java.util.Scanner;

public class Demo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

System.out.println("Please enter a number: ");
int num = scanner.nextInt();

if ( num < 2 ) {
System.out.println("\n There are no Prime Numbers available");
System.exit(0);
}
System.out.println("\n Prime Numbers from 1 to "+ num);
PrimeNumber primeNum = new PrimeNumber();

for (int i = 3; i <= num; i++) {
if ( primeNum.isPrime(i) ) {
System.out.print(", " + i);
}
}
}
}
[/sourcecode]

Method 3 : Java Program to find Prime Number upto N number using Command line input

[sourcecode lang=”Java”]

class PrimeNumber
{
public static void main(String[] args)
{
int n,p;
n=Integer.parseint(args[0]);
for(int i=2;i&lt;n;i++)
{
p=0;
for(int j=2;j&lt;i;j++)
{
if(i%j==0)
p=1;
}
if(p==0){
System.out.println(i);
}
}
}
}
[/sourcecode]

Steps to run above program via command line :

  1. Compilation : C:\JavaPrograms>javac PrimeNumber.java
  2. Interpretation : C:\JavaPrograms>java PrimeNumber 20

Output :

2

3

5

7

11

13

17

19