Java Source Code

Java Program to Convert Binary to Decimal

Objectives :

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

Java Program :

[sourcecode lang=”java”]

import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter binary number: ");
String binary = scanner.nextLine();
int decimal = binaryToDecimal(binary);
System.out.println("Decimal equivalent of "+ binary +" is "+ decimal);
}

private static int binaryToDecimal(String binary) {
final int base = 2;
int decimal = 0;
for (int i = 0; i < binary.length(); i++) {
if (binary.charAt(i) == ‘0’) {
decimal += 0 * Math.pow(base, binary.length() – i – 1);
} else if (binary.charAt(i) == ‘1’) {
decimal += 1 * Math.pow(base, binary.length() – i – 1);
} else {
System.out.println("Invalid Binary Number");
System.out.println("Binary Number Contains only 0’s or 1’s");
System.exit(0);
}
}
return decimal;
}
}

[/sourcecode]

Output :
Enter binary number: 1110
Decimal equivalent of 1110 is 14

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.

Simple Interest Example in Java

Starting a series of some Java programs as many students were asking to share the programs. Here is the first program of the series.

Objectives:

  • Write a Program that calculates and prints the simple interest using the formula : Simple Interest = PTR/100
  • How to calculate Simple Interest in Java?
  • Write a program to calculate Simple Interest in Java.
  • Write a Java program that calculates and prints the simple interest using the formula : “SimpleInterest = PTR/100” and input values P, T, R should be accepted as command line.
  • How to use Command Line Arguments in Java?
  • How to pass values from command line in Java?
  • How to take input in Java from console?

 

This particular program can be written in various ways, we will try to write the solution program in different ways here and one can try to understand the difference between them.

Method 1 :

[sourcecode lang=”java”]
import java.util.Scanner;

public class SimpleInterestExample {

public static void main(String[] args) {

int p,t,r, result;

Scanner sc = new Scanner(System.in);

System.out.println(&quot;Enter the Value of P : &quot;);
p = sc.nextInt();

System.out.println(&quot;Enter the Value of T : &quot;);
t = sc.nextInt();

System.out.println(&quot;Enter the Value of R : &quot;);
r = sc.nextInt();

result = (p*t*r)/100;
System.out.println(&quot;Interest is : &quot; + result);
}
}
[/sourcecode]

This one is the simplest way to write the program to find simple interest in Java. Here we have simply created the object of Scanner class for taking input. Scanner class was introduced in Java 6. To use Scanner class we will have to import the class from java.util package.

Method 2:

Now we will write a Java program that calculates and prints the simple interest using the Scanner class again but with object oriented programming approach.

[sourcecode lang=”java”]
import java.util.Scanner;

public class SimpleInterestExample
{
double principalAmount = 0;
double interestRate = 0;
double term = 0;
double simpleInterest = 0;

public void calculateSimpleInterest()
{
Scanner input = new Scanner(System.in);

System.out.print(&quot;Enter the Principal amount : &quot;);
principalAmount = input.nextDouble();

System.out.print(&quot;Enter the Rate As a decimal : &quot;);
interestRate = input.nextDouble();

System.out.print(&quot;Enter the amount of time in years : &quot;);
term = input.nextDouble();

simpleInterest = (principalAmount * interestRate * term) / 100;
}

public void displaySimpleInterest()
{
System.out.println(&quot;The Simple Interest is : &quot; + simpleInterest);
}
}
[/sourcecode]

Mock Test Program for above code so that we can test the code. keep both the classes in same package and run the Mock Test Program or MockTestProgram.java

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

public static void main(String[]args);
{
SimpleInterestExample simpleInt = new SimpleInterestExample();
simpleInt.calculateSimpleInterest();
simpleInt.displaySimpleInterest();
}
}
[/sourcecode]

Method 3:

Now we will write a Java program that calculates and prints the simple interest using the formula : “SimpleInterest = PTR/100” and input values P, T, R should be accepted as command line.

[sourcecode lang=”java”]
import java.util.Scanner;

public class SimpleInterestExample {

public static void main(String[] args) {
double p,t,r, result;

p = Double.parseDouble(args[0]);
t = Double.parseDouble(args[1]);
r = Double.parseDouble(args[2]);

Scanner sc = new Scanner(System.in);

System.out.println(&quot;Enter the Value of P : &quot;);
p = sc.nextDouble();

System.out.println(&quot;Enter the Value of T : &quot;);
t = sc.nextDouble();

System.out.println(&quot;Enter the Value of R : &quot;);
r = sc.nextDouble();

result = (p*t*r)/100;
System.out.println(&quot;Interest is : &quot; + result);
}
}
[/sourcecode]

 

I will be sharing more programs soon as many students were asking for programs which were carried out during Java training and were asked in assignments after Java training. By the time enjoy coding in Java and use NetBeans, it will ease your life.

Book : NetBeans IDE How-to Instant

NetBeans IDE How-to : Atul Palandurkar : Packt Publishing, UK

NetBeans IDE How-to : Atul Palandurkar : Packt Publishing, UK

I was asked to write a book for Java Application Development using NetBeans IDE by PACKT Publishing, UK which is one of the leading technology books publishers in world. It will be a great experience to work with the great publishing house and their team. Thanks a lot Packt & Team.

I know, Java and NetBeans community will definitely accept the book with a grand welcome. The book is intended for Java Developers who are not aware of NetBeans IDE or those who have experience of Java development but have not used NetBeans for development of Java applications. This book can be referred by novice also to learn Java and Java application development using NetBeans IDE very easily.

My outline (contents) was selected out of few other authors and then after we signed the contract, now the book is complete and very soon the book will hit the market in different formats by the publisher in March 2013.

I just love it, I have tried my best in writing this book and to make it easier for novice to experts. It was a great pleasure working with Packt Team.

You will learn many things from this book such as :

  • Use NetBeans IDE for Java technologies
  • Develop a HelloWorld application with NetBeans IDE
  • Explore the layout of NetBeans IDE
  • Develop different Java applications in NetBeans
  • Use the Visual Designer
  • Design Java projects
  • Develop web applications using NetBeans IDE
  • Add and handle images in your application
  • Write interfaces in NetBeans IDE
  • Handle exceptions in NetBeans IDE
  • Deploy UI applications

You can order the book to avail huge discount. Instead of Packt Publishing the NetBeans IDE How-to book is also available on Amazon, Amazon UK, Barnes & Noble, Safari Books Online too.

You can buy and download the book in different formats such as e-book (pdf), e-pub, kindle book, etc.

Buy NetBeans IDE How-to Book

I hope you will like the book. After reading, please mail me your reviews.

You can book your copy from following links :

Get your copy now and start developing professional applications within few minutes.

Hello World in different languages

Free Source Code

Free Source Code

Objectives :
* How to write Hello World in Java?
* How to write Hello World in C?
* How to write Hello World in PHP?
* How to write Hello World in C++?
* How to write Hello World in JavaScript?
* How to write Hello World in HTML?
* How to write Hello World in CSS?
* How to write Hello World in COBOL?

Java

[sourcecode language=”java”]
class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello World!”);
}
}
[/sourcecode]

C

[sourcecode language=”c”]
#include
#include
void main()
{
clrscr();
printf(“Hello World!”);
getch();
}
[/sourcecode]

C++

[sourcecode language=”cpp”]
#include
#include
void main()
{
clrscr();
cout<getch();
}
[/sourcecode]

CSS

[sourcecode language=”css”]
body:before
{
content: “Hello World”;
}
[/sourcecode]

COBOL

[sourcecode language=”text”]
****************************
IDENTIFICATION DIVISION.
PROGRAM-ID. HELLO ENVIRONMENT DIVISION.
DATA DIVISION.
PROCEDURE DIVISION.
MAIN SECTION.
DISPLAY “Hello World!”
STOP RUN
****************************
[/sourcecode]

HTML

[sourcecode language=”html”]
<html>
<head>
<title>Hello World Example</title>
</head>
<body>
Hello World!
</body>
</html>
[/sourcecode]

JavaScript

[sourcecode language=”javascript”]
document.write("Hello World");
[/sourcecode]

PHP

[sourcecode language=”php”]
<!–?php echo ‘Hello World!’ ?–>
[/sourcecode]

Linux Shell Script

[sourcecode language=”text”]
echo "Hello World !"
[/sourcecode]

Enjoy coding!

Posted from WordPress for Android

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

Writing Comments in Java

Objective :

  • How to write comments in Java?
  • How to write single line comment in Java?
  • How to write multi line comment in Java?
  • How to write documentation comment in Java?
  • What are the types of comments in Java?

Writing Comments in Java :

  • Comments are the statements which are never executed (i.e. non-executable statements).
  • Comments are often used to add notes between source code so that it becomes easy to understand & explain the function or operation of the corresponding part of source code.
  • Java Compiler doesn’t read comments; comments are simply ignored during compilation.
  • There are 3 types of comments available in Java as follows;
  1. Single Line Comment
  2. Multi Line Comment
  3. Documentation Comment

Single Line Comment :

This comment is used whenever we need to write anything in single line.

Syntax : 

//<write comment here>

Example :

[sourcecode language=”java”]
//This is Single Line Comment.
[/sourcecode]

Multi Line Comment :

This type of comments are used whenever we want to write detailed notes (i.e. more than one line or in multiple lines)related to source code.

Syntax :

/*

<write comment here>

*/

Example :  

[sourcecode language=”java”]
/*
This
Is
The
Multi
Line
Comment
*/
[/sourcecode]

Documentation Comment :

  • The documentation comment is used commonly to produce the javadoc for the respective program.
  • The javadoc is generally HTML, if used in project it is a set of multiple HTML files describing each java program in the corresponding project.
  • In the documentation comment we can add different notations such as author of the project or program, version, parameters required, information on results in return if any, etc.
  • To add these notations, we have ‘@’ operator.  We just need to write the required notation along with the ‘@’ operator.
  • Some javadoc tags are;
    1. @author – To describe the author of the project.
    2. @version – To describe the version of the project.
    3. @param – To explain the parameters required to perform respective operation.
    4. @return – To explain the return type of the project.

Syntax :

/**

*<write comment/description here>

*@author <write author name>

*@version <write version here>

*@param <write parameter here>

*@return <write return type here>

*/

Example :  

[sourcecode language=”java”]
/**
* This is Documentation Comment.
* @author Atul Palandurkar
* @version 1.0.0
*/
[/sourcecode]

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