Java Program To Calculate Average of Numbers Using Array
Java Program To Calculate Average of Numbers Using Array
1
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
num = input.nextInt(); {
if ( num%j == 0 )
/* If number is divisible by 2 then it's an {
even number status = 0;
* else odd number*/ break;
if ( num % 2 == 0 ) }
System.out.println("Entered number is }
even"); if ( status != 0 )
else {
System.out.println("Entered number is System.out.println(num);
odd"); i++;
} }
} status = 1;
num++;
}
3. Java Program to display }
first 100 prime numbers }
import java.util.Scanner;
class PrimeNumberDemo
{
public static void main(String args[]) 4. Java Program to display
{ prime numbers between 1
int n; and 100 or 1 and n
int status = 1;
int num = 3; It will display the prime numbers between 1
//For capturing the value of n and 100.
Scanner scanner = new
Scanner(System.in); class PrimeNumbers
System.out.println("Enter the value of {
n:"); public static void main (String[] args)
//The entered value is stored in the var n {
n = scanner.nextInt(); int i =0;
if (n >= 1) int num =0;
{ //Empty String
System.out.println("First "+n+" prime String primeNumbers = "";
numbers are:");
//2 is a known prime number for (i = 1; i <= 100; i++)
System.out.println(2); {
} int counter=0;
for(num =i; num>=1; num--)
for ( int i = 2 ; i <=n ; ) {
{ if(i%num==0)
for ( int j = 2 ; j <= Math.sqrt(num) ; {
j++ ) counter = counter + 1;
2
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
} if (counter ==2)
} {
if (counter ==2) //Appended the Prime number to
{ the String
//Appended the Prime number primeNumbers = primeNumbers
to the String + i + " ";
primeNumbers = }
primeNumbers + i + " "; }
} System.out.println("Prime numbers from
} 1 to n are :");
System.out.println("Prime numbers System.out.println(primeNumbers);
from 1 to 100 are :"); }
System.out.println(primeNumbers); }
}
}
5. Java Program to check
It will display all the prime numbers Prime Number
between 1 and n (n is the number, entered by import java.util.Scanner;
user). class PrimeCheck
{
import java.util.Scanner; public static void main(String args[])
class PrimeNumbers2 {
{ int temp;
public static void main (String[] args) boolean isPrime=true;
{ Scanner scan= new
Scanner scanner = new Scanner(System.in);
Scanner(System.in); System.out.println("Enter any
int i =0; number:");
int num =0; //capture the input in an integer
//Empty String int num=scan.nextInt();
String primeNumbers = ""; scan.close();
System.out.println("Enter the value of for(int i=2;i<=num/2;i++)
n:"); {
int n = scanner.nextInt(); temp=num%i;
scanner.close(); if(temp==0)
for (i = 1; i <= n; i++) {
{ isPrime=false;
int counter=0; break;
for(num =i; num>=1; num--) }
{ }
if(i%num==0) //If isPrime is true then the number
{ is prime else not
counter = counter + 1; if(isPrime)
} System.out.println(num + " is a
} Prime Number");
3
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
else return str;
System.out.println(num + " is not //Calling Function Recursively
a Prime Number"); return reverseString(str.substring(1)) +
} str.charAt(0);
} }
}
6. Java Program to Reverse a Example 2: Program to reverse a string
String using Recursion entered by user
import java.util.Scanner;
Java Program to Reverse a String using public class JavaExample {
Recursion
public static void main(String[] args) {
By Chaitanya Singh | Filed Under: Java String str;
Examples System.out.println("Enter your
username: ");
We will see two programs to reverse a Scanner scanner = new
string. First program reverses the given Scanner(System.in);
string using recursion and the second str = scanner.nextLine();
program reads the string entered by user and scanner.close();
then reverses it. String reversed = reverseString(str);
System.out.println("The reversed string
To understand these programs you should is: " + reversed);
have the knowledge of following core java }
concepts:
1) substring() in java public static String reverseString(String
2) charAt() method str)
{
Example 1: Program to reverse a string if (str.isEmpty())
return str;
public class JavaExample { //Calling Function Recursively
return reverseString(str.substring(1)) +
public static void main(String[] args) { str.charAt(0);
String str = "Welcome to }
Beginnersbook"; }
String reversed = reverseString(str);
System.out.println("The reversed string
is: " + reversed);
7. Java Program to Reverse a
} number using for, while loop
and recursion
public static String reverseString(String
str) There are three ways to reverse a number in
{ Java.
if (str.isEmpty())
4
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
1) Using while loop import java.util.Scanner;
2) Using for loop class ForLoopReverseDemo
3) Using recursion {
4) Reverse the number without user public static void main(String args[])
interaction {
int num=0;
Program 1: Reverse a number using while int reversenum =0;
Loop System.out.println("Input your number
and press enter: ");
The program will prompt user to input the //This statement will capture the user
number and then it will reverse the same input
number using while loop. Scanner in = new Scanner(System.in);
//Captured input would be stored in
import java.util.Scanner; number num
class ReverseNumberWhile num = in.nextInt();
{ /* for loop: No initialization part as num
public static void main(String args[]) is already
{ * initialized and no
int num=0; increment/decrement part as logic
int reversenum =0; * num = num/10 already decrements the
System.out.println("Input your number value of num
and press enter: "); */
//This statement will capture the user for( ;num != 0; )
input {
Scanner in = new Scanner(System.in); reversenum = reversenum * 10;
//Captured input would be stored in reversenum = reversenum + num%10;
number num num = num/10;
num = in.nextInt(); }
//While Loop: Logic to find out the
reverse number System.out.println("Reverse of specified
while( num != 0 ) number is: "+reversenum);
{ }
reversenum = reversenum * 10; }
reversenum = reversenum + num%10; Program 3: Reverse a number using
num = num/10;
recursion
}
import java.util.Scanner;
System.out.println("Reverse of input class RecursionReverseDemo
number is: "+reversenum); {
} //A method for reverse
} public static void reverseMethod(int
number) {
Program 2: Reverse a number using for if (number < 10) {
Loop System.out.println(number);
return;
5
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
} }
else {
System.out.print(number % 10);
//Method is calling itself: recursion
reverseMethod(number/10);
8. Java Program to Find Sum
} of Natural Numbers
}
public static void main(String args[]) The positive integers 1, 2, 3, 4 etc. are
{ known as natural numbers. Here we will see
int num=0; three programs to calculate and display the
System.out.println("Input your sum of natural numbers.
number and press enter: ");
Scanner in = new First Program calculates the sum
Scanner(System.in); using while loop
num = in.nextInt(); Second Program calculates the sum
System.out.print("Reverse of the using for loop
input number is:"); Third Program takes the value of
reverseMethod(num); n(entered by user) and calculates the
System.out.println(); sum of n natural numbers
}
} To understand these programs you should be
familiar with the following concepts of Core
Example: Reverse an already initialized Java Tutorial: Java For loop and Java While
number.In all the above programs we are loop
prompting user for the input number,
however if do not want the user interaction Example 1: Program to find the sum of
part and want to reverse an initialized natural numbers using while loop
number then this is how you can do it.
6
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
System.out.println("Sum of first
Example 2: Program to calculate the sum of "+num+" natural numbers is: "+total);
natural numbers using for loop }
}
public class Demo {
7
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
positive number"); else
} {
else if(number < 0) System.out.println(number+" is
{ neither positive nor negative");
System.out.println(number+" is a }
negative number"); }
} }
else
{
10. Java Program to check
System.out.println(number+" is Leap Year
neither positive nor negative");
} Here we will write a java program to check
} whether the input year is a leap year or not.
} Before we see the program, lets see how to
determine whether a year is a leap year
Example 2: Check whether the input mathematically:
number(entered by user) is positive or To determine whether a year is a leap year,
negative follow these steps:
1. If the year is evenly divisible by 4, go to
Here we are using Scanner to read the step 2. Otherwise, go to step 5.
number entered by user and then the 2. If the year is evenly divisible by 100, go
program checks and displays the result. to step 3. Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go
import java.util.Scanner; to step 4. Otherwise, go to step 5.
public class Demo 4. The year is a leap year (it has 366 days).
{ 5. The year is not a leap year (it has 365
public static void main(String[] args) days). Source of these steps.
{
int number; Example: Program to check whether the
Scanner scan = new input year is leap or not
Scanner(System.in);
System.out.print("Enter the number Here we are using Scanner class to get the
you want to check:"); input from user and then we are using if-else
number = scan.nextInt(); statements to write the logic to check leap
scan.close(); year. To understand this program, you
if(number > 0) should have the knowledge of following
{ concepts of Core Java Tutorial:
System.out.println(number+" is → If-else statement
positive number"); → Read input number in Java program
}
else if(number < 0) import java.util.Scanner;
{ public class Demo {
System.out.println(number+" is
negative number"); public static void main(String[] args) {
}
8
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
int year; By type casting character value as int
Scanner scan = new
Scanner(System.in); Lets write a program to understand how it
System.out.println("Enter any works:
Year:");
year = scan.nextInt(); Example: Program to find ASCII code of a
scan.close(); character
boolean isLeap = false;
public class Demo {
if(year % 4 == 0)
{ public static void main(String[] args) {
if( year % 100 == 0)
{ char ch = 'P';
if ( year % 400 == 0) int asciiCode = ch;
isLeap = true; // type casting char as int
else int asciiValue = (int)ch;
isLeap = false;
} System.out.println("ASCII value of
else "+ch+" is: " + asciiCode);
isLeap = true; System.out.println("ASCII value of
} "+ch+" is: " + asciiValue);
else { }
isLeap = false; }
}
12. Java Program to Multiply
if(isLeap==true) two Numbers
System.out.println(year + " is a Leap
Year."); When you start learning java programming,
else you get these type of problems in your
System.out.println(year + " is not a assignment. Here we will see two Java
Leap Year."); programs, first program takes two integer
} numbers (entered by user) and displays the
} product of these numbers. The second
11.Java Program to find ASCII program takes any two numbers (can be
integer or floating point) and displays the
value of a character result.
ASCII is a code for representing English Example 1: Program to read two integer and
characters as numbers, each letter of english print product of them.This program asks
alphabets is assigned a number ranging from user to enter two integer numbers and
0 to 127. For example, the ASCII code for displays the product. To understand how to
uppercase P is 80. use scanner to take user input, checkout this
In Java programming, we have two ways to program: Program to read integer from
find ASCII value of a character 1) By system input.
assigning a character to the int variable 2)
9
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
import java.util.Scanner; well as floating point numbers.
/* This reads the input provided by user public static void main(String[] args) {
* using keyboard
*/ /* This reads the input provided by user
Scanner scan = new * using keyboard
Scanner(System.in); */
System.out.print("Enter first number: Scanner scan = new
"); Scanner(System.in);
System.out.print("Enter first number:
// This method reads the number ");
provided using keyboard
int num1 = scan.nextInt(); // This method reads the number
provided using keyboard
System.out.print("Enter second double num1 = scan.nextDouble();
number: ");
int num2 = scan.nextInt(); System.out.print("Enter second
number: ");
// Closing Scanner after the use double num2 = scan.nextDouble();
scan.close();
// Closing Scanner after the use
// Calculating product of two numbers scan.close();
int product = num1*num2;
// Calculating product of two numbers
// Displaying the multiplication result double product = num1*num2;
System.out.println("Output:
"+product); // Displaying the multiplication result
} System.out.println("Output:
} "+product);
}
Example 2: Read two integer or floating }
point numbers and display the multiplication
10
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
like int, double etc. and strings. 14. Java Program to Add two
Example: Program to read the number Numbers
entered by user
ere we will see two programs to add two
We have imported the package numbers, In the first program we specify the
java.util.Scanner to use the Scanner. In order value of both the numbers in the program
to read the input provided by user, we first itself. The second programs takes both the
create the object of Scanner by passing numbers (entered by user) and prints the
System.in as parameter. Then we are using sum.
nextInt() method of Scanner class to read the
integer. If you are new to Java and not First Example: Sum of two numbers
familiar with the basics of java program then
read the following topics of Core Java: public class AddTwoNumbers {
→ Writing your First Java Program
→ How JVM works public static void main(String[] args) {
System.out.println("Enter Second
11
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
Number: "); class DecimalToHexExample
num2 = sc.nextInt(); {
public static void main(String args[])
sc.close(); {
sum = num1 + num2; Scanner input = new Scanner( System.in
System.out.println("Sum of these );
numbers: "+sum); System.out.print("Enter a decimal
} number : ");
} int num =input.nextInt();
12
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
Method 1: Using toBinaryString() method obj.convertBinary(45);
class DecimalBinaryExample{ System.out.println("\nBinary
representation of 999: ");
public static void main(String a[]){ obj.convertBinary(999);
System.out.println("Binary }
representation of 124: "); }
13
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
}
There are two following ways to convert
binary number to decimal number: public static void main(String args[]){
Details obj = new Details();
1) Using Integer.parseInt() method of System.out.println("110 -->
Integer class. "+obj.BinaryToDecimal(110));
2) Do conversion by writing your own logic System.out.println("1101 -->
without using any predefined methods. "+obj.BinaryToDecimal(1101));
System.out.println("100 -->
Method 1: Binary to Decimal conversion "+obj.BinaryToDecimal(100));
using Integer.parseInt() method System.out.println("110111 -->
import java.util.Scanner; "+obj.BinaryToDecimal(110111));
class BinaryToDecimal { }
public static void main(String args[]){ }
Scanner input = new Scanner(
System.in );
System.out.print("Enter a binary 18. Java Program to Convert
number: ");
String binaryString =input.nextLine();
Decimal to Octal
System.out.println("Output:
this tutorial we will learn following two
"+Integer.parseInt(binaryString,2));
ways to convert a decimal number to
}
equivalent octal number.
}
Method 2: Conversion without using 1) Using predefined method
parseInt Integer.toOctalString(int num)
2) Writing our own logic for conversion
public class Details {
import java.util.Scanner;
public int BinaryToDecimal(int
class DecimalToOctalExample
binaryNumber){
{
public static void main(String args[])
int decimal = 0;
{
int p = 0;
Scanner input = new Scanner( System.in
while(true){
);
if(binaryNumber == 0){
System.out.print("Enter a decimal number
break;
: ");
} else {
int num =input.nextInt();
int temp = binaryNumber%10;
decimal += temp*Math.pow(2, p);
/* Method 1:
binaryNumber = binaryNumber/10;
* Using predefined method
p++;
toOctalString(int)
}
* Pass the decimal number to this method
}
and
return decimal;
* it would return the equivalent octal
14
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
number getHostAddress() method.
*/
String octalString = import java.net.InetAddress;
Integer.toOctalString(num);
System.out.println("Method 1: Decimal to class GetMyIPAddress
octal: " + octalString); {
public static void main(String args[])
/* Method 2: throws Exception
* Writing your own logic: Here we will {
write
* our own logic for decimal to octal InetAddress
conversion myIP=InetAddress.getLocalHost();
*/
/* public String getHostAddress():
// For storing remainder Returns the IP
int rem; * address string in textual presentation.
*/
// For storing result System.out.println("My IP Address is:");
String str="";
System.out.println(myIP.getHostAddress());
// Digits in Octal number system }
char dig[]={'0','1','2','3','4','5','6','7'}; }
while(num>0)
{ 20. Java Program to get
rem=num%8; Input From User
str=dig[rem]+str;
num=num/8; In this tutorial we are gonna see how to
} accept input from user. We are using
System.out.println("Method 2: Decimal to Scanner class to get the input. In the below
octal: "+str); example we are getting input String, integer
} and a float number. For this we are using
} following methods:
1) public String nextLine(): For getting input
19. Java Program to Get IP String
2) public int nextInt(): For integer input
Address 3) public float nextFloat(): For float input
In this example we are gonna see how to get Example:
IP address of a System. The steps are as
import java.util.Scanner;
follows:
class GetInputData
1) Get the local host address by calling
{
getLocalHost() method of InetAddress class.
public static void main(String args[])
2) Get the IP address by calling
15
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
{ //Create a HashMap
int num; Map<Character, Integer> map = new
float fnum; HashMap<Character, Integer>();
String str;
//Convert the String to char array
Scanner in = new Scanner(System.in); char[] chars = str.toCharArray();
16
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
/* Program: It Prints Floyd's triangle based
System.out.println("\nString: on user inputs
ChaitanyaSingh"); * Written by: Chaitanya from
System.out.println("------------------------- beginnersbook.com
"); * Input: Number of rows
obj.countDupChars("ChaitanyaSingh"); * output: floyd's triangle*/
import java.util.Scanner;
System.out.println("\nString: class FloydTriangleExample
#@$@!#$%!!%@"); {
System.out.println("------------------------- public static void main(String args[])
"); {
obj.countDupChars("#@$@!#$%!!%@"); int rows, number = 1, counter, j;
} //To get the user's input
} Scanner input = new
Scanner(System.in);
22. Java Program to generate Random System.out.println("Enter the number of
Number rows for floyd's triangle:");
//Copying user input into an integer
In the below program, we are using the variable named rows
nextInt() method of Random class to serve rows = input.nextInt();
our purpose. System.out.println("Floyd's triangle");
17
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
{ System.out.println(string + " is not a
//My Method to check palindrome");
public static boolean isPal(String s) }
{ // if length is 0 or 1 then String is }
palindrome
if(s.length() == 0 || s.length() == 1)
return true;
if(s.charAt(0) == s.charAt(s.length()-
1))
25. Java Program to check
/* check for first and last char of String:
* if they are same then do the same Palindrome String using
thing for a substring Stack, Queue, For and
* with first and last char removed. and
carry on this
While loop
* until you string completes or
condition fails In this tutorial we will see programs to
check whether the given String is
* Function calling itself: Recursion
Palindrome or not. Following are the ways
*/
to do it.
return isPal(s.substring(1, s.length()-
1) Using Stack
1));
2) Using Queue
3) Using for/while loop
/* If program control reaches to this
statement it means
* the String is not palindrome hence Program 1: Palindrome check Using Stack
return false.
*/ import java.util.Stack;
return false; import java.util.Scanner;
} class PalindromeTest {
18
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
reverseString = is not a palindrome.");
reverseString+stack.pop();
} }
}
if (inputString.equals(reverseString))
System.out.println("The input String Program 3: Using for loop/While loop and
is a palindrome."); String function charAt
else
System.out.println("The input String import java.util.Scanner;
is not a palindrome."); class PalindromeTest {
public static void main(String args[])
} {
} String reverseString="";
Scanner scanner = new
Program 2: Palindrome check Using Queue Scanner(System.in);
while (!queue.isEmpty()) {
26. Java Program to find
reverseString =
reverseString+queue.remove(); Factorial of a number using
} Recursion
if (inputString.equals(reverseString))
System.out.println("The input String Here we will write programs to find out the
is a palindrome."); factorial of a number using recursion.
else
System.out.println("The input String Program 1:
19
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
Program will prompt user for the input int output;
number. Once user provide the input, the if(n==1){
program will calculate the factorial for the return 1;
provided input number. }
//Recursion: Function calling itself!!
import java.util.Scanner; output = fact(n-1)* n;
class FactorialDemo{ return output;
public static void main(String args[]){ }
//Scanner object for capturing the user }
input
Scanner scanner = new
Scanner(System.in);
27. Java Program to Add the
System.out.println("Enter the number:"); elements of an Array
//Stored the entered value in variable
int num = scanner.nextInt(); In this tutorial we will see how to sum up all
//Called the user defined function fact the elements of an array.
int factorial = fact(num);
System.out.println("Factorial of entered Program 1: No user interaction
number is: "+factorial);
} class SumOfArray{
static int fact(int n) public static void main(String args[]){
{ int[] array = {10, 20, 30, 40, 50, 10};
int output; int sum = 0;
if(n==1){ //Advanced for loop
return 1; for( int num : array) {
} sum = sum+num;
//Recursion: Function calling itself!! }
output = fact(n-1)* n; System.out.println("Sum of array
return output; elements is:"+sum);
} }
} }
20
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
array[i] = scanner.nextInt(); to provide the length and width values. If
} you do not need user interaction and simply
for( int num : array) { want to specify the values in program, refer
sum = sum+num; the below program.
}
System.out.println("Sum of array class AreaOfRectangle2 {
elements is:"+sum); public static void main (String[] args)
} {
} double length = 4.5;
double width = 8.0;
double area = length*width;
28. Java Program to System.out.println("Area of
Calculate Area of Rectangle Rectangle is:"+area);
}
In this tutorial we will see how to calculate }
Area of Rectangle.
21
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
System.out.println("Area of Square is: System.out.println("Enter the height of
"+area); the Triangle:");
} double height = scanner.nextDouble();
}
//Area = (width*height)/2
Program 2: double area = (base* height)/2;
System.out.println("Area of Triangle is:
class SquareAreaDemo2 { " + area);
public static void main (String[] args) }
{ }
//Value specified in the program itself
double side = 4.5; Program 2:
//Area of Square = side*side
double area = side*side; class AreaTriangleDemo2 {
System.out.println("Area of Square is: public static void main(String args[]) {
"+area); double base = 20.0;
} double height = 110.5;
} double area = (base* height)/2;
System.out.println("Area of Triangle is:
" + area);
30. Java Program to }
Calculate the area of }
Triangle
31. Java Program to
Here we will see how to calculate area of
triangle. We will see two following Calculate Area and
programs to do this: Circumference of Circle
1) Program 1: Prompt user for base-width
and height of triangle. In this tutorial we will see how to calculate
2) Program 2: No user interaction: Width area and circumference of circle in Java.
and height are specified in the program There are two ways to do this:
itself.
1) With user interaction: Program will
Program 1: prompt user to enter the radius of the circle
2) Without user interaction: The radius value
import java.util.Scanner; would be specified in the program itself.
class AreaTriangleDemo {
public static void main(String args[]) { Program 1:
Scanner scanner = new
Scanner(System.in); import java.util.Scanner;
class CircleDemo
System.out.println("Enter the width of {
the Triangle:"); static Scanner sc = new
double base = scanner.nextDouble(); Scanner(System.in);
public static void main(String args[])
22
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
{ Order
System.out.print("Enter the radius: ");
/*We are storing the entered radius in import java.util.Scanner;
double
* because a user can enter radius in class BubbleSortExample {
decimals public static void main(String []args) {
*/ int num, i, j, temp;
double radius = sc.nextDouble(); Scanner input = new Scanner(System.in);
//Area = PI*radius*radius
double area = Math.PI * (radius * System.out.println("Enter the number of
radius); integers to sort:");
System.out.println("The area of circle is: num = input.nextInt();
" + area);
//Circumference = 2*PI*radius int array[] = new int[num];
double circumference= Math.PI *
2*radius; System.out.println("Enter " + num + "
System.out.println( "The circumference integers: ");
of the circle is:"+circumference) ;
} for (i = 0; i < num; i++)
} array[i] = input.nextInt();
23
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
array[j+1] to array[j] < array[j+1] in the
above program. Complete code as follows: This program uses linear search algorithm to
find out a number among all other numbers
import java.util.Scanner; entered by user.
24
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
System.out.println(item + " doesn't while( first <= last )
exist in array."); {
} if ( array[middle] < item )
} first = middle + 1;
else if ( array[middle] == item )
{
34. Java Program for Binary System.out.println(item + " found at
Search location " + (middle + 1) + ".");
break;
This program uses binary search algorithm }
to search an element in given list of else
elements. {
last = middle - 1;
import java.util.Scanner; }
class BinarySearchExample middle = (first + last)/2;
{ }
public static void main(String args[]) if ( first > last )
{ System.out.println(item + " is not
int counter, num, item, array[], first, last, found.\n");
middle; }
//To capture user input }
Scanner input = new
Scanner(System.in);
System.out.println("Enter number of 35. Java Program to convert
elements:"); char Array to String
num = input.nextInt();
There are two ways to convert a char array
//Creating array to store the all the (char[]) to String in Java:
numbers 1) Creating String object by passing array
array = new int[num]; name to the constructor
2) Using valueOf() method of String class.
System.out.println("Enter " + num + "
integers"); Example:
//Loop to store each numbers in array This example demonstrates both the above
for (counter = 0; counter < num; mentioned ways of converting a char array
counter++) to String. Here we have a char array ch and
array[counter] = input.nextInt(); we have created two strings str and str1
using the char array.
System.out.println("Enter the search
value:"); class CharArrayToString
item = input.nextInt(); {
first = 0; public static void main(String args[])
last = num - 1; {
middle = (first + last)/2; // Method 1: Using String object
char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r',
25
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
'n', 'i', 'n', 'g'}; }
String str = new String(ch);
System.out.println(str); Output:
26
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
basics. num2 = sumOfPrevTwo;
i++;
Example 1: Program to print fibonacci series }
using for loop }
}
public class JavaExample {
Example 3: Program to display the fibonacci
public static void main(String[] args) { series based on the user input
int count = 7, num1 = 0, num2 = 1; This program display the sequence based on
System.out.print("Fibonacci Series of the number entered by user. For example –
"+count+" numbers:"); if user enters 10 then this program displays
the series of 10 numbers.
for (int i = 1; i <= count; ++i)
{ import java.util.Scanner;
System.out.print(num1+" "); public class JavaExample {
27
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
//We will find the factorial of this
We will write three java programs to find number
factorial of a number. 1) using for loop 2) int number = 5;
using while loop 3) finding factorial of a long fact = 1;
number entered by user. Before going int i = 1;
through the program, lets understand what is while(i<=number)
factorial: Factorial of a number n is denoted {
as n! and the value of n! is: 1 * 2 * 3 * … fact = fact * i;
(n-1) * n i++;
}
The same logic we have implemented in our System.out.println("Factorial of
programs using loops. To understand these "+number+" is: "+fact);
programs you should have a basic }
knowledge of following topics of java }
tutorials:
Example 3: Finding factorial of a number
For loop in Java entered by user
Java – while loop
Program finds the factorial of input number
Example: Finding factorial using for loop using while loop.
28
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
} double output;
switch(operator)
39. Java Program to make a {
calculator using switch case case '+':
output = num1 + num2;
In this Program we are making a simple break;
calculator that performs addition,
subtraction, multiplication and division case '-':
based on the user input. The program takes output = num1 - num2;
the value of both the numbers (entered by break;
user) and then user is asked to enter the
operation (+, -, * and /), based on the input case '*':
program performs the selected operation on output = num1 * num2;
the entered numbers using switch case. break;
If you are new to java, refer this Java tutorial case '/':
to start learning java programming from output = num1 / num2;
basics. break;
29
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
else prints Grade ‘D’ else if(avg>=40 && avg<60)
{
To understand this Program you should have System.out.print("C");
the knowledge of following concepts of }
Java: else
{
Java For Loop System.out.print("D");
Arrays in Java }
if..else-if in Java }
}
Example: Program to display the grade of
student
41. Java Program to check
import java.util.Scanner; whether input character is
vowel or consonant
public class JavaExample
{ The alphabets A, E, I, O and U (smallcase
public static void main(String args[]) and uppercase) are known as Vowels and
{ rest of the alphabets are known as
int marks[] = new int[6]; consonants. Here we will write a java
int i; program that checks whether the input
float total=0, avg; character is vowel or Consonant using
Scanner scanner = new Switch Case in Java.
Scanner(System.in);
If you are new to java, refer this Java
Tutorial to start learning from basics
for(i=0; i<6; i++) {
System.out.print("Enter Marks of Example: Program to check Vowel or
Subject"+(i+1)+":"); Consonant using Switch Case
marks[i] = scanner.nextInt();
total = total + marks[i]; In this program we are not using break
} statement with cases intentionally, so that if
scanner.close(); user enters any vowel, the program
//Calculating average here continues to execute all the subsequent cases
avg = total/6; until Case 'U' is reached and thats where we
System.out.print("The student Grade is: are setting up the value of a boolean variable
"); to true. This way we can identify that the
if(avg>=80) alphabet entered by user is vowel or not.
{
System.out.print("A"); import java.util.Scanner;
} class JavaExample
else if(avg>=60 && avg<80) {
{ public static void main(String[ ] arg)
System.out.print("B"); {
} boolean isVowel=false;;
30
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
Scanner scanner=new find the largest among three numbers. 1)
Scanner(System.in); Using if-else..if 2) Using nested If
System.out.println("Enter a
character : "); To understand these programs you should
char ch=scanner.next().charAt(0); have the knowledge of if..else-if statement
scanner.close(); in Java. If you are new to java start from
switch(ch) Core Java tutorial.
{
case 'a' : Example 1: Finding largest of three numbers
case 'e' : using if-else..if
case 'i' :
case 'o' : public class JavaExample{
case 'u' :
case 'A' : public static void main(String[] args) {
case 'E' :
case 'I' : int num1 = 10, num2 = 20, num3 = 7;
case 'O' :
case 'U' : isVowel = true; if( num1 >= num2 && num1 >= num3)
} System.out.println(num1+" is the
if(isVowel == true) { largest Number");
System.out.println(ch+" is a
Vowel"); else if (num2 >= num1 && num2 >=
} num3)
else { System.out.println(num2+" is the
largest Number");
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')
) else
System.out.println(ch+" System.out.println(num3+" is the
is a Consonant"); largest Number");
else }
System.out.println("Input }
is not an alphabet");
} Example 2: Program to find largest number
} among three numbers using nested if
}
public class JavaExample{
31
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
largest Number"); bitwise operator
else
System.out.println(num3+" is the import java.util.Scanner;
largest Number"); public class JavaExample
} {
else { public static void main(String args[])
{
if(num2 >= num3 int num1, num2;
Scanner scanner = new
System.out.println(num2+" is the Scanner(System.in);
largest Number"); System.out.print("Enter first number:");
else num1 = scanner.nextInt();
System.out.print("Enter second
number:");
System.out.println(num3+" is the num2 = scanner.nextInt();
largest Number");
} //num1 becomes 1111 = 15
} num1 = num1 ^ num2;
} //num2 becomes 1010 = 10
num2 = num1 ^ num2;
//num1 becomes 0101 = 5
43. Java Program to swap num1 = num1 ^ num2;
two numbers using bitwise scanner.close();
operator System.out.println("The First number
after swapping:"+num1);
This java program swaps two numbers using System.out.println("The Second
bitwise XOR operator. Before going though number after swapping:"+num2);
the program, lets see what is a bitwise XOR }
operator: A bitwise XOR compares }
corresponding bits of two operands and
returns 1 if they are equal and 0 if they are 44. Java Program to find
not equal. For example:
smallest of three numbers
num1 = 11; /* equal to 00001011*/ using ternary operator
num2 = 22; /* equal to 00010110 */
This java program finds the smallest of three
num1 ^ num2 compares corresponding bits numbers using ternary operator. Lets see
of num1 and num2 and generates 1 if they what is a ternary operator:
are not equal, else it returns 0. In our This operator evaluates a boolean expression
example it would return 29 which is and assign the value based on the result.
equivalent to 00011101
variable num1 = (expression) ? value if true
Let’s write this in a Java program: : value if false
Example: Swapping two numbers using If the expression results true then the first
32
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
value before the colon (:) is assigned to the System.out.println("Smallest Number
variable num1 else the second value is is:"+result);
assigned to the num1. }}
33
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
public static void main(String[] args) the sum of multiple numbers using Method
{ Overloading. First add() method has two
int num1, num2, num3, result, temp; arguments which means when we pass two
Scanner scanner = new numbers while calling add() method then
Scanner(System.in); this method would be invoked. Similarly
System.out.println("Enter First when we pass three and four arguments, the
Number:"); second and third add method would be
num1 = scanner.nextInt(); invoked respectively.
System.out.println("Enter Second
Number:"); public class JavaExample
num2 = scanner.nextInt(); {
System.out.println("Enter Third int add(int num1, int num2)
Number:"); {
num3 = scanner.nextInt(); return num1+num2;
scanner.close(); }
int add(int num1, int num2, int num3)
{
/* In first step we are comparing only return num1+num2+num3;
num1 and }
* num2 and storing the largest number int add(int num1, int num2, int num3, int
into the num4)
* temp variable and then comparing {
the temp and return num1+num2+num3+num4;
* num3 to get final result. }
*/ public static void main(String[] args)
temp = num1>num2 ? num1:num2; {
result = num3>temp ? num3:temp; JavaExample obj = new
System.out.println("Largest Number JavaExample();
is:"+result); //This will call the first add method
} System.out.println("Sum of two
} numbers: "+obj.add(10, 20));
//This will call second add method
System.out.println("Sum of three
46. Java Program to perform numbers: "+obj.add(10, 20, 30));
Arithmetic Operation using //This will call third add method
Method Overloading System.out.println("Sum of four
numbers: "+obj.add(1, 2, 3, 4));
This program finds the sum of two, three }
and four numbers using method overloading. }
Here we have three methods with the same
name add(), which means we are 47. Java Program to find Area
overloading this method. Based on the
number of arguments we pass while calling of Geometric figures using
add method will determine which method method overloading
will be invoked. Example: Program to find
34
COMPILED BY: ARAYA .M 2010 E.C
AKSUM UNIVERSITY
COLLAGE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
}
This program finds the area of square, }
rectangle and circle using method
overloading. In this program we have three
methods with same name area(), which
means we are overloading area() method. By
having three different implementation of
area method, we are calculating the area of
square, rectangle and circle.
class JavaExample
{
void calculateArea(float x)
{
System.out.println("Area of the square:
"+x*x+" sq units");
}
void calculateArea(float x, float y)
{
System.out.println("Area of the
rectangle: "+x*y+" sq units");
}
void calculateArea(double r)
{
double area = 3.14*r*r;
System.out.println("Area of the circle:
"+area+" sq units");
}
public static void main(String args[]){
JavaExample obj = new
JavaExample();
obj.calculateArea(6.1f);
obj.calculateArea(10,22);
obj.calculateArea(6.1);
35
COMPILED BY: ARAYA .M 2010 E.C