Free Java Source Code

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/

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 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

Program to find Sum of Digits in Java

Objectives :

  • Write a program to compute sum of digits of a given number.
  • Write a program to find sum of digits of a given number.
  • Write a program to calculate sum of digits of a given number.
  • Write a program to compute sum of digits of a given integer number.
  • Write a program to compute sum of digits of a number entered via Command Line.
  • Write a program to compute sum of digits of a given number. Take input from Command Line.
  • Write a program to compute sum of digits of a given number. Take input using Scanner class.

Following is the Java Program to compute Sum of Digits of a given integer number;

Method 1 : Java Program to find Sum of Digits when number is entered from command line

[sourcecode lang=”java”]

class SumOfDigits
{
public static void main(String args[])
{
int n;
int a=0;
int sum=0;

//taking integer number from command line and parsing the same
n=Integer.parseInt(args[0]);

while(n!=0)
{
a=n%10;
n=n/10;
sum=sum+a;
}
System.out.println("Sum of digits: " + sum);
}
}

[/sourcecode]

Steps to run above program via command line :

  1. Compilation : C:\JavaPrograms>javac SumOfDigits.java
  2. Interpretation : C:\JavaPrograms>java SumOfDigits 12345

Output : Sum of digits: 15

Method 2 : Java Program to find Sum of Digits if input is taken using Scanner class

[sourcecode lang=”java”]

import java.util.Scanner;

public class SumOfDigits {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n;
int a=0;
System.out.print("Enter a positive number: ");
n = in.nextInt();

if (n <= 0)
System.out.println("You have entered a negative number.");
else {
int sum = 0;

while (n != 0) {

a=n%10;
n=n/10;
sum=sum+a;
}
System.out.println("Sum of digits: " + sum);
}
}
}

[/sourcecode]

Steps to run above program via command line :

  1. Compilation : C:\JavaPrograms>javac SumOfDigits.java
  2. Interpretation : C:\JavaPrograms>java SumOfDigits 12345

Output :

Trial 1 : With positive number

Enter a positive number: 12345

Sum of digits: 15

Trial 2 : With negative number

Enter a positive number: -12345

You have entered a negative number.

Get MAC Address using Java

Free Source Code

Free Source Code

Objective :

* How to get the MAC Address of a computer?
* How to get the MAC Address of a computer using Java?
* How to get the MAC Address of a computer via programming?

[sourcecode language=”java”]
import java.net.*;

class GetMac
{
public static void main(String arg[])
{
try
{
InetAddress address = InetAddress.getLocalHost();
NetworkInterface nwi = NetworkInterface.getByInetAddress(address);
byte mac[] = nwi.getHardwareAddress();
System.out.println(mac);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
[/sourcecode]

Note : This code will return only the first net address; if you need other detils too, get a list.

Posted from WordPress for Android

Why Java is Platform Independent?

Objectives :

  • Why Java is platform independent?
  • How java program executes?
  • What is execution flow of Java Program?
  • What are the steps to execute a Java Program?
  • What are the steps to run a Java Program?

[gigya src=”http://player.videofy.me/player.swf?videoId=424278″ width=”480″ height=”300″ quality=”high” wmode=”transparent” allowFullScreen=”true” ]

Check your Operating System & its version

Free Source Code

Free Source Code

Objective :

  • How to check your operating system by programming?
  • How to check your operating system by Java programming?
  • Write Java program to check operating system & its version

Hi folks,

Hey guys, if you want to know which operating system you are using & its version, there are 2 ways to do it as follows;

  • Using Command Prompt
  • Using Programming

1. Using Command Prompt

  • Go to Start Menu
  • Go to Run
  • Type cmd & press Enter/return. Command Prompt will open.
  • Type ver & press Enter/return, you will get the Name of your OS & its Version that you are using
Here I have used, ver command one of the DOS commands which returns Name of Operating System and its version.

2. Using Programming

Here we are using a Java Program to find the operating system you are using & its version :
[sourcecode language=”java”]
package com.si.java.utility.os;

/**
*
* Language : Java
* File : MyOS.java
* Date : Tuesday, October 5, 2010
* @author Atul Palandurkar
* Email : atul.palandurkar@gmail.com
* Website : www.shardainfotech.com
* Blog : http://atulpalandurkar.wordpress.com
*
*/

public class MyOS
{
public static void main(String[] arg)
{
//To find the name of operating system.
String myOS = System.getProperty("os.name");
System.out.println("Operating System : " + myOS);

//To find the version of operating system.
String myOSVersion = System.getProperty("os.version");
System.out.println("Version : " + myOSVersion);
}
}
[/sourcecode]

So, what are you waiting for?
Use it to create various system utilities & have fun.

Find your IP Address

Free Source Code

Free Source Code

Objective :

  • How to find IP address of your computer?
  • How to find IP address by programming?
  • How to find IP address by Java programming?
  • Write a Java program to find IP Address.

Hello guys.

Do you want to find your IP Address?

There are following ways to check / find your IP Address

  1. Using Command prompt.
  2. Using Programming.
1. Using Command Prompt :
  • Open Command Prompt.
  • Type “ipconfig” without quotes & Press Enter. IP Address will be displayed.
2. Using Programming :
Here we are using a Java Program to find the IP Address. The Java Program to find the IP Address is as follows;

[sourcecode language=”java”]

package com.si.java.utility.ip;

import java.net.InetAddress;

/**
*
* Language : Java
* File : IPAddressFinder.java
* Date : Saturday, October 2, 2010
* @author Atul Palandurkar
* Email : atul.palandurkar@gmail.com
* Website : www.shardainfotech.com
*
*/

public class IPAddressFinder
{

public static void main(String[] args)
{
try
{
InetAddress ia = InetAddress.getLocalHost();
String ip = ia.getHostAddress();
System.out.println("Your IP Address :- "+ip);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
[/sourcecode]

The above code can be very useful to find the IP address of your computer, as well as this can be used to find the IP address of the user in internet based applications with a little change in it.
Use it & have fun.
..