Basic Java Examples
[Link] Circle Area using Java Example
/*
Calculate Circle Area using Java Example
This Calculate Circle Area using Java Example shows how to calculate
area of circle using it's radius.
*/
import [Link];
import [Link];
import [Link];
public class CalculateCircleAreaExample {
public static void main(String[] args) {
int radius = 0;
[Link]("Please enter radius of a circle");
try
{
//get the radius from console
BufferedReader br = new BufferedReader(newInputStreamReader([Link]));
radius = [Link]([Link]());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
[Link]("Invalid radius value" + ne);
[Link](0);
}
catch(IOException ioe)
{
[Link]("IO Error :" + ioe);
[Link](0);
}
/*
* Area of a circle is
* pi * r * r
* where r is a radius of a circle.
*/
//NOTE : use [Link] constant to get value of pi
double area = [Link] * radius * radius;
[Link]("Area of a circle is " + area);
}
}
/*
Output of Calculate Circle Area using Java Example would be
Please enter radius of a circle
19
Area of a circle is 1134.1149479459152
*/
2. Calculate Circle Perimeter using Java Example
/*
Calculate Circle Perimeter using Java Example
This Calculate Circle Perimeter using Java Example shows how to calculate
Perimeter of circle using it's radius.
*/
import [Link];
import [Link];
import [Link];
public class CalculateCirclePerimeterExample {
public static void main(String[] args) {
int radius = 0;
[Link]("Please enter radius of a circle");
try
{
//get the radius from console
BufferedReader br = new BufferedReader(newInputStreamReader([Link]));
radius = [Link]([Link]());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
[Link]("Invalid radius value" + ne);
[Link](0);
}
catch(IOException ioe)
{
[Link]("IO Error :" + ioe);
[Link](0);
}
/*
* Perimeter of a circle is
* 2 * pi * r
* where r is a radius of a circle.
*/
//NOTE : use [Link] constant to get value of pi
double perimeter = 2 * [Link] * radius;
[Link]("Perimeter of a circle is " + perimeter);
}
}
/*
Output of Calculate Circle Perimeter using Java Example would be
Please enter radius of a circle
19
Perimeter of a circle is 119.38052083641213
*/
3. Calculate Rectangle Area using Java Example
/*
Calculate Rectangle Area using Java Example
This Calculate Rectangle Area using Java Example shows how to calculate
area of Rectangle using it's length and width.
*/
import [Link];
import [Link];
import [Link];
public class CalculateRectArea {
public static void main(String[] args) {
int width = 0;
int length = 0;
try
{
//read the length from console
BufferedReader br = new BufferedReader(newInputStreamReader([Link]));
[Link]("Please enter length of a rectangle");
length = [Link]([Link]());
//read the width from console
[Link]("Please enter width of a rectangle");
width = [Link]([Link]());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
[Link]("Invalid value" + ne);
[Link](0);
}
catch(IOException ioe)
{
[Link]("IO Error :" + ioe);
[Link](0);
}
/*
* Area of a rectangle is
* length * width
*/
int area = length * width;
[Link]("Area of a rectangle is " + area);
}
/*
Output of Calculate Rectangle Area using Java Example would be
Please enter length of a rectangle
10
Please enter width of a rectangle
15
Area of a rectangle is 150
*/
4. Calculate Rectangle Perimeter using Java Example
/*
Calculate Rectangle Perimeter using Java Example
This Calculate Rectangle Perimeter using Java Example shows how to calculate
perimeter of Rectangle using it's length and width.
*/
import [Link];
import [Link];
import [Link];
public class CalculateRectPerimeter {
public static void main(String[] args) {
int width = 0;
int length = 0;
try
{
//read the length from console
BufferedReader br = new BufferedReader(newInputStreamReader([Link]));
[Link]("Please enter length of a rectangle");
length = [Link]([Link]());
//read the width from console
[Link]("Please enter width of a rectangle");
width = [Link]([Link]());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
[Link]("Invalid value" + ne);
[Link](0);
}
catch(IOException ioe)
{
[Link]("IO Error :" + ioe);
[Link](0);
}
/*
* Perimeter of a rectangle is
* 2 * (length + width)
*/
int perimeter = 2 * (length + width);
[Link]("Perimeter of a rectangle is " + perimeter);
}
/*
Output of Calculate Rectangle Perimeter using Java Example would be
Please enter length of a rectangle
10
Please enter width of a rectangle
15
Perimeter of a rectangle is 50
*/
5. Even Odd Number Example
/*
Even Odd Number Example
This Java Even Odd Number Example shows how to check if the given
number is even or odd.
*/
public class FindEvenOrOddNumber {
public static void main(String[] args) {
//create an array of 10 numbers
int[] numbers = new int[]{1,2,3,4,5,6,7,8,9,10};
for(int i=0; i < [Link]; i++){
/*
* use modulus operator to check if the number is even or odd.
* If we divide any number by 2 and reminder is 0 then the number is
* even, otherwise it is odd.
*/
if(numbers[i]%2 == 0)
[Link](numbers[i] + " is even number.");
else
[Link](numbers[i] + " is odd number.");
}
}
/*
Output of the program would be
1 is odd number.
2 is even number.
3 is odd number.
4 is even number.
5 is odd number.
6 is even number.
7 is odd number.
8 is even number.
9 is odd number.
10 is even number.
*/
6. Find Largest and Smallest Number in an Array Example
/*
Find Largest and Smallest Number in an Array Example
This Java Example shows how to find largest and smallest number in an
array.
*/
public class FindLargestSmallestNumber {
public static void main(String[] args) {
//array of 10 numbers
int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
//assign first element of an array to largest and smallest
int smallest = numbers[0];
int largetst = numbers[0];
for(int i=1; i< [Link]; i++)
{
if(numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}
[Link]("Largest Number is : " + largetst);
[Link]("Smallest Number is : " + smallest);
}
}
/*
Output of this program would be
Largest Number is : 98
Smallest Number is : 23
*/
7. Hello World example
/*
Java Hello World example.
*/
public class HelloWorldExample{
public static void main(String args[]){
/*
Use [Link]() to print on console.
*/
[Link]("Hello World !");
/*
OUTPUT of the above given Java Hello World Example would be :
Hello World !
*/
8. Java Class Example
/*
Java Class example.
This Java class example describes how class is defined and being used
in Java language.
Syntax of defining java class is,
<modifier> class <class-name>{
// members and methods
}
*/
public class JavaClassExample{
/*
Syntax of defining memebers of the java class is,
<modifier> type <name>;
*/
private String name;
/*
Syntax of defining methods of the java class is,
<modifier> <return-type> methodName(<optional-parameter-list>) <exception-list>{
...
}
*/
public void setName(String n){
//set passed parameter as name
name = n;
}
public String getName(){
//return the set name
return name;
}
//main method will be called first when program is executed
public static void main(String args[]){
/*
Syntax of java object creation is,
<class-name> object-name = new <class-constructor>;
*/
JavaClassExample javaClassExample = new JavaClassExample();
//set name member of this object
[Link]("Visitor");
// print the name
[Link]("Hello " + [Link]());
}
}
/*
OUTPUT of the above given Java Class Example would be :
Hello Visitor
*/
9. Java Factorial Example
/*
Java Factorial Example
This Java Factorial Example shows how to calculate factorial of
a given number using Java.
*/
public class NumberFactorial {
public static void main(String[] args) {
int number = 5;
/*
* Factorial of any number is !n.
* For example, factorial of 4 is 4*3*2*1.
*/
int factorial = number;
for(int i =(number - 1); i > 1; i--)
{
factorial = factorial * i;
}
[Link]("Factorial of a number is " + factorial);
}
}
/*
Output of the Factorial program would be
Factorial of a number is 120
*/
10. Reverse Number using Java
/*
Reverse Number using Java
This Java Reverse Number Example shows how to reverse a given number.
*/
public class ReverseNumber {
public static void main(String[] args) {
//original number
int number = 1234;
int reversedNumber = 0;
int temp = 0;
while(number > 0){
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
//output the reversed number
[Link]("Reversed Number is: " + reversedNumber);
}
}
/*
Output of this Number Reverse program would be
Reversed Number is: 4321
*/
11. Swap Numbers Java
/*
Swap Numbers Java Example
This Swap Numbers Java Example shows how to
swap value of two numbers using java.
*/
public class SwapElementsExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
[Link]("Before Swapping");
[Link]("Value of num1 is :" + num1);
[Link]("Value of num2 is :" +num2);
//swap the value
swap(num1, num2);
}
private static void swap(int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
[Link]("After Swapping");
[Link]("Value of num1 is :" + num1);
[Link]("Value of num2 is :" +num2);
}
}
/*
Output of Swap Numbers example would be
Before Swapping
Value of num1 is :10
Value of num2 is :20
After Swapping
Value of num1 is :20
Value of num2 is :10
*/
12. Swap Numbers Without Using Third Variable
/*
Swap Numbers Without Using Third Variable Java Example
This Swap Numbers Java Example shows how to
swap value of two numbers without using third variable using java.
*/
public class SwapElementsWithoutThirdVariableExample {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
[Link]("Before Swapping");
[Link]("Value of num1 is :" + num1);
[Link]("Value of num2 is :" +num2);
//add both the numbers and assign it to first
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
[Link]("Before Swapping");
[Link]("Value of num1 is :" + num1);
[Link]("Value of num2 is :" +num2);
}
/*
Output of Swap Numbers Without Using Third Variable example would be
Before Swapping
Value of num1 is :10
Value of num2 is :20
Before Swapping
Value of num1 is :20
Value of num2 is :10
*/
Java Data Types Examples
13. Java boolean Example
/*
Java boolean Example
This Java Example shows how to declare and use Java primitive boolean variable
inside a java class.
*/
public class JavaBooleanExample {
public static void main(String[] args) {
/*
* boolean is simple Java type which can have only of two values; true or false.
* All rational expressions retrun this type of value.
*
* Declare boolean varibale as below
*
* boolean <variable name> = <default value>;
*
* here assigning default value is optional.
*/
boolean b1 = true;
boolean b2 = false;
boolean b3 = (10 > 2)? true:false;
[Link]("Value of boolean variable b1 is :" + b1);
[Link]("Value of boolean variable b2 is :" + b2);
[Link]("Value of boolean variable b3 is :" + b3);
}
}
/*
Output would be
Value of boolean variable b1 is :true
Value of boolean variable b2 is :false
Value of boolean variable b3 is :true
*/
14. Java byte Example
/*
Java byte Example
This Java Example shows how to declare and use Java primitive byte variable
inside a java class.
*/
public class JavaByteExample {
public static void main(String[] args) {
/*
* byte is smallest Java integer type.
* byte is 8 bit signed type ranges from –128 to 127.
* byte is mostly used when dealing with raw data like reading a
* binary file.
*
* Declare byte varibale as below
*
* byte <variable name> = <default value>;
*
* here assigning default value is optional.
*/
byte b1 = 100;
byte b2 = 20;
[Link]("Value of byte variable b1 is :" + b1);
[Link]("Value of byte variable b1 is :" + b2);
}
}
/*
Output would be
Value of byte variable b1 is :100
Value of byte variable b1 is :20
*/
15. Java char Example
/*
Java char Example
This Java Example shows how to declare and use Java primitive char variable
inside a java class.
*/
public class JavaCharExample {
public static void main(String[] args) {
/*
* char is 16 bit type and used to represent Unicode characters.
* Range of char is 0 to 65,536.
*
* Declare char varibale as below
*
* char <variable name> = <default value>;
*
* here assigning default value is optional.
*/
char ch1 = 'a';
char ch2 = 65; /* ASCII code of 'A'*/
[Link]("Value of char variable ch1 is :" + ch1);
[Link]("Value of char variable ch2 is :" + ch2);
}
}
/*
Output would be
Value of char variable ch1 is :a
Value of char variable ch2 is :A
*/
16. Java double Example
/*
Java double Example
This Java Example shows how to declare and use Java primitive double variable
inside a java class.
*/
public class JavaDoubleExample {
public static void main(String[] args) {
/*
* double is 64 bit double precision type and used when fractional precision
* calculation is required.
*
* Declare double varibale as below
*
* double <variable name> = <default value>;
*
* here assigning default value is optional.
*/
double d = 1232.44;
[Link]("Value of double variable d is :" + d);
}
}
/*
Output would be
Value of double variable f is :1232.44
*/
17. Java float Example
/*
Java float Example
This Java Example shows how to declare and use Java primitive float variable
inside a java class.
*/
import [Link].*;
public class JavaFloatExample {
public static void main(String[] args) {
/*
* float is 32 bit single precision type and used when fractional precision
* calculation is required.
*
* Declare float varibale as below
*
* float <variable name> = <default value>;
*
* here assigning default value is optional.
*/
float f = 10.4f;
[Link]("Value of float variable f is :" + f);
}
}
/*
Output would be
Value of float variable f is :10.4
*/
18. Java int Example
/*
Java int Example
This Java Example shows how to declare and use Java primitive int variable
inside a java class.
*/
public class JavaIntExamples {
public static void main(String[] args) {
/*
* int is 32 bit signed type ranges from –2,147,483,648
* to 2,147,483,647. int is also most commonly used integer
* type in Java.
* Declare int varibale as below
*
* int <variable name> = <default value>;
*
* here assigning default value is optional.
*/
int i = 0;
int j = 100;
[Link]("Value of int variable i is :" + i);
[Link]("Value of int variable j is :" + j);
}
}
/*
Output would be
Value of int variable i is :0
Value of int variable j is :100
*/
19. Java long Example
/*
Java long Example
This Java Example shows how to declare and use Java primitive long variable
inside a java class.
*/
import [Link].*;
public class JavaLongExample {
public static void main(String[] args) {
/*
* long is 64 bit signed type and used when int is not large
* enough to hold the value.
*
* Declare long varibale as below
*
* long <variable name> = <default value>;
*
* here assigning default value is optional.
*/
long timeInMilliseconds = new Date().getTime();
[Link]("Time in milliseconds is : " + timeInMilliseconds);
}
}
/*
Output would be
Time in milliseconds is : 1226836372234
*/
20. Java short Example
/*
Java short Example
This Java Example shows how to declare and use Java primitive short variable
inside a java class.
*/
public class JavaShortExample {
public static void main(String[] args) {
/*
* short is 16 bit signed type ranges from –32,768 to 32,767.
*
* Declare short varibale as below
*
* short <variable name> = <default value>;
*
* here assigning default value is optional.
*/
short s1 = 50;
short s2 = 42;
[Link]("Value of short variable b1 is :" + s1);
[Link]("Value of short variable b1 is :" + s2);
}
}
/*
Output would be
Value of short variable b1 is :50
Value of short variable b1 is :42
*/
21. int to String Example
/*
int to String Example
This int to String java example shows how to convert int to String in Java.
*/
public class StringToIntJavaExample {
public static void main(String args[]){
//int variable
int i = 11;
/*
* To convert int to String, use
* toString(int i)
* method of Integer wrapper class.
*/
String str = [Link](i);
[Link]("int to String : " + i);
}
}
/*
Output of int to String example would be
int to String : 11
*/
For Loop Examples
22. Calculate Average value of Array elements
/*
Calculate Average value of Array elements using Java Example
This Java Example shows how to calculate average value of array
elements.
*/
public class CalculateArrayAverageExample {
public static void main(String[] args) {
//define an array
int[] numbers = new int[]{10,20,15,25,16,60,100};
/*
* Average value of array elements would be
* sum of all elements/total number of elements
*/
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < [Link] ; i++)
sum = sum + numbers[i];
//calculate average value
double average = sum / [Link];
[Link]("Average value of array elements is : " + average);
}
}
/*
Output of Calculate Average value of Array elements using Java Example would be
Average value of array elements is : 35.0
*/
23. Declare multiple variables in for loop Example
/*
Declare multiple variables in for loop Example
This Java Example shows how to declare multiple variables in Java For loop using
declaration block.
*/
public class DeclaringMultipleVariablesInForLoopExample {
public static void main(String[] args) {
/*
* Multiple variables can be declared in declaration block of for loop.
*/
for(int i=0, j=1, k=2 ; i<5 ; i++)
[Link]("I : " + i + ",j : "+ j + ", k : " + k);
/*
* Please note that the variables which are declared, should be of same type
* as in this example int.
*/
//THIS WILL NOT COMPILE
//for(int i=0, float j; i < 5; i++);
}
}
24. Fibonacci Series Java Example
/*
Fibonacci Series Java Example
This Fibonacci Series Java Example shows how to create and print
Fibonacci Series using Java.
*/
public class JavaFibonacciSeriesExample {
public static void main(String[] args) {
//number of elements to generate in a series
int limit = 20;
long[] series = new long[limit];
//create first 2 series elements
series[0] = 0;
series[1] = 1;
//create the Fibonacci series and store it in an array
for(int i=2; i < limit; i++){
series[i] = series[i-1] + series[i-2];
}
//print the Fibonacci series numbers
[Link]("Fibonacci Series upto " + limit);
for(int i=0; i< limit; i++){
[Link](series[i] + " ");
}
}
}
/*
Output of the Fibonacci Series Java Example would be
Fibonacci Series upto 20
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
*/
25. Generate Pyramid For a Given Number
/*
Generate Pyramid For a Given Number Example
This Java example shows how to generate a pyramid of numbers for given
number using for loop example.
*/
import [Link];
import [Link];
public class GeneratePyramidExample {
public static void main (String[] args) throws Exception{
BufferedReader keyboard = new BufferedReader (new InputStreamReader([Link]));
[Link]("Enter Number:");
int as= [Link] ([Link]());
[Link]("Enter X:");
int x= [Link] ([Link]());
int y = 0;
for(int i=0; i<= as ;i++){
for(int j=1; j <= i ; j++){
[Link](y + "\t");
y = y + x;
}
[Link]("");
}
}
}
/*
Output of this example would be
Enter Number:
5
Enter X:
1
0
1 2
3 4 5
6 7 8 9
10 11 12 13 14
----------------------------------------------
Enter Number:
5
Enter X:
2
0
2 4
6 8 10
12 14 16 18
20 22 24 26 28
----------------------------------------------
Enter Number:
5
Enter X:
3
0
3 6
9 12 15
18 21 24 27
30 33 36 39 42
*/
[Link] For loop
/*
Infinite For loop Example
This Java Example shows how to create a for loop that runs infinite times
in Java program. It happens when the loop condition is always evaluated as true.
*/
public class InfiniteForLoop {
public static void main(String[] args) {
/*
* Its perfectely legal to skip any of the 3 parts of the for loop.
* Below given for loop will run infinite times.
*/
for(;;)
[Link]("Hello");
/*
* To terminate this program press ctrl + c in the console.
*/
}
}
/*
Output would be
Hello
Hello
Hello
..
Hello
..
*/
Java Palindrome Number Example
/*
Java Palindrome Number Example
This Java Palindrome Number Example shows how to find if the given
number is palindrome number or not.
*/
public class JavaPalindromeNumberExample {
public static void main(String[] args) {
//array of numbers to be checked
int numbers[] = new int[]{121,13,34,11,22,54};
//iterate through the numbers
for(int i=0; i < [Link]; i++){
int number = numbers[i];
int reversedNumber = 0;
int temp=0;
/*
* If the number is equal to it's reversed number, then
* the given number is a palindrome number.
*
* For example, 121 is a palindrome number while 12 is not.
*/
//reverse the number
while(number > 0){
temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;
}
if(numbers[i] == reversedNumber)
[Link](numbers[i] + " is a palindrome number");
else
[Link](numbers[i] + " is not a palindrome number");
}
}
}
/*
Output of Java Palindrome Number Example would be
121 is a palindrome number
13 is not a palindrome number
34 is not a palindrome number
11 is a palindrome number
22 is a palindrome number
54 is not a palindrome number
*/
28. Java Pyramid 1 Example
/*
Java Pyramid 1 Example
This Java Pyramid example shows how to generate pyramid or triangle like
given below using for loop.
*
**
***
****
*****
*/
public class JavaPyramid1 {
public static void main(String[] args) {
for(int i=1; i<= 5 ;i++){
for(int j=0; j < i; j++){
[Link]("*");
}
//generate a new line
[Link]("");
}
}
}
/*
Output of the above program would be
*
**
***
****
*****
*/
29. Java Pyramid 2 Example
/*
Java Pyramid 2 Example
This Java Pyramid example shows how to generate pyramid or triangle like
given below using for loop.
*****
****
***
**
*
*/
public class JavaPyramid2 {
public static void main(String[] args) {
for(int i=5; i>0 ;i--){
for(int j=0; j < i; j++){
[Link]("*");
}
//generate a new line
[Link]("");
}
}
}
/*
Output of the example would be
*****
****
***
**
*
*/
[Link] Pyramid 3 Example
/*
Java Pyramid 3 Example
This Java Pyramid example shows how to generate pyramid or triangle like
given below using for loop.
*
**
***
****
*****
*****
****
***
**
*
*/
public class JavaPyramid3 {
public static void main(String[] args) {
for(int i=1; i<= 5 ;i++){
for(int j=0; j < i; j++){
[Link]("*");
}
//generate a new line
[Link]("");
}
//create second half of pyramid
for(int i=5; i>0 ;i--){
for(int j=0; j < i; j++){
[Link]("*");
}
//generate a new line
[Link]("");
}
}
}
/*
Output of the example would be
*
**
***
****
*****
*****
****
***
**
*
*/
[Link] Pyramid 4 Example
/*
Java Pyramid 6 Example
This Java Pyramid example shows how to generate pyramid or triangle like
given below using for loop.
*****
****
***
**
*
*
**
***
****
*****
*/
public class JavaPyramid6 {
public static void main(String[] args) {
//generate upper half of the pyramid
for(int i=5; i>0 ;i--){
for(int j=0; j < i; j++){
[Link]("*");
}
//create a new line
[Link]("");
}
//generate bottom half of the pyramid
for(int i=1; i<= 5 ;i++){
for(int j=0; j < i; j++){
[Link]("*");
}
//create a new line
[Link]("");
}
}
}
/*
Output of the example would be
*****
****
***
**
*
*
**
***
****
*****
*/
32. List Even Numbers Java Example
/*
List Even Numbers Java Example
This List Even Numbers Java Example shows how to find and list even
numbers between 1 and any given number.
*/
public class ListEvenNumbers {
public static void main(String[] args) {
//define limit
int limit = 50;
[Link]("Printing Even numbers between 1 and " + limit);
for(int i=1; i <= limit; i++){
// if the number is divisible by 2 then it is even
if( i % 2 == 0){
[Link](i + " ");
}
}
}
}
/*
Output of List Even Numbers Java Example would be
Printing Even numbers between 1 and 50
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50
*/