You are on page 1of 35

AKSUM UNIVERSITY

COLLAGE OF ENGINEERING AND TECHNOLOGY


DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING
(OBJECT-ORIENTED PROGRAMING LAB EXERCISE CLASS OF 2010E.C)
1. Java Program to Calculate public class JavaExample {
average of numbers using public static void main(String[] args) {
Array System.out.println("How many
numbers you want to enter?");
We will see two programs to find the Scanner scanner = new
average of numbers using array. First Scanner(System.in);
Program finds the average of specified array int n = scanner.nextInt();
elements. The second programs takes the double[] arr = new double[n];
value of n (number of elements) and the double total = 0;
numbers provided by user and finds the
average of them using array. To understand for(int i=0; i<arr.length; i++){
these programs you should have the System.out.print("Enter Element
knowledge of following Java Programming No."+(i+1)+": ");
concepts: arr[i] = scanner.nextDouble();
1) Java Arrays 2) For loop }
scanner.close();
Example 1: Program to find the average for(int i=0; i<arr.length; i++){
of numbers using array total = total + arr[i];
}
public class JavaExample {

public static void main(String[] args) {


double[] arr = {19, 12.89, 16.5, 200, double average = total / arr.length;
13.7}; System.out.format("The average is: .3f",
double total = 0; average);
}
for(int i=0; i<arr.length; i++){ }
total = total + arr[i];
}
2. Java Program to Check
Even or Odd Number
double average = total / arr.length;
import java.util.Scanner;
System.out.format("The average is:
%.3f", average); class CheckEvenOdd
} {
} public static void main(String args[])
{
Example 2: Calculate average of numbers int num;
entered by user System.out.println("Enter an Integer
number:");
In this example, we are using Scanner to get
the value of n and all the numbers from user. //The input provided by user is stored in
num
import java.util.Scanner; Scanner input = new Scanner(System.in);

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.

class ReverseNumberDemo public class Demo {


{
public static void main(String args[]) public static void main(String[] args) {
{
int num=123456789; int num = 10, count = 1, total = 0;
int reversenum =0;
while( num != 0 ) while(count <= num)
{ {
reversenum = reversenum * 10; total = total + count;
reversenum = reversenum + num%10; count++;
num = num/10; }
}
System.out.println("Sum of first 10
System.out.println("Reverse of specified natural numbers is: "+total);
number is: "+reversenum); }
} }

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 {

public static void main(String[] args) {


9. Java Program to check if a
number is Positive or
int num = 10, count, total = 0; Negative
for(count = 1; count <= num; count++){ In this post, we will write two java
total = total + count; programs, first java programs checks
} whether the specified number is positive or
negative. The second program takes the
System.out.println("Sum of first 10 input number (entered by user) and checks
natural numbers is: "+total); whether it is positive or negative and
} displays the result.
} → If a number is greater than zero then it is
a positive number
Example 3: Program to find sum of first n → If a number is less than zero then it is a
(entered by user) natural numbers negative number
→ If a number is equal to zero then it is
import java.util.Scanner; neither negative nor positive.
public class Demo {
Lets write this logic in a Java Program.
public static void main(String[] args) {
Example 1: Program to check whether the
int num, count, total = 0; given number is positive or negative

In this program we have specified the value


System.out.println("Enter the value of of number during declaration and the
n:"); program checks whether the specified
//Scanner is used for reading user input number is positive or negative. To
Scanner scan = new understand this program you should have the
Scanner(System.in); basic knowledge of if-else-if statement in
//nextInt() method reads integer entered Core Java Programming.
by user
num = scan.nextInt(); public class Demo
//closing scanner after use {
scan.close(); public static void main(String[] args)
for(count = 1; count <= num; {
count++){ int number=109;
total = total + count; if(number > 0)
} {
System.out.println(number+" is a

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.

public class Demo { import java.util.Scanner;

public static void main(String[] args) { public class Demo {

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

In the above program, we can only integers.


13. Java Program to read
What if we want to calculate the number from Standard
multiplication of two float numbers? This Input
programs allows you to enter float numbers
and calculates the product. In this program we will see how to read an
integer number entered by user. Scanner
Here we are using data type double for class is in java.util package. It is used for
numbers so that you can enter integer as capturing the input of the primitive types

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

import java.util.Scanner; int num1 = 5, num2 = 15, sum;


sum = num1 + num2;
public class Demo {
System.out.println("Sum of these
public static void main(String[] args) { numbers: "+sum);
}
/* This reads the input provided by user }
* using keyboard
*/ Second Example: Sum of two numbers
Scanner scan = new using Scanner
Scanner(System.in);
System.out.print("Enter any number: The scanner allows us to capture the user
"); input so that we can get the values of both
the numbers from user. The program then
// This method reads the number calculates the sum and displays it.
provided using keyboard
int num = scan.nextInt(); import java.util.Scanner;
public class AddTwoNumbers2 {
// Closing Scanner after the use
scan.close(); public static void main(String[] args) {

// Displaying the number int num1, num2, sum;


System.out.println("The number Scanner sc = new Scanner(System.in);
entered by user: "+num); System.out.println("Enter First
} Number: ");
} num1 = sc.nextInt();

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();

// For storing remainder


15. Java Program to convert int rem;
decimal to hexadecimal
// For storing result
There are two following ways to convert String str2="";
Decimal number to hexadecimal number:
// Digits in hexadecimal number system
1) Using toHexString() method of Integer char
class. hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C'
2) Do conversion by writing your own logic ,'D','E','F'};
without using any predefined methods.
while(num>0)
Method 1: Decimal to hexadecimal Using {
toHexString() method rem=num%16;
import java.util.Scanner; str2=hex[rem]+str2;
class DecimalToHexExample num=num/16;
{ }
public static void main(String args[]) System.out.println("Method 2: Decimal
{ to hexadecimal: "+str2);
Scanner input = new Scanner( System.in }
); }
System.out.print("Enter a decimal
number : "); 16. Java Program to Convert
int num =input.nextInt();
Decimal to Binary
// calling method toHexString()
String str = Integer.toHexString(num); here are three following ways to convert
System.out.println("Method 1: Decimal Decimal number to binary number:
to hexadecimal: "+str);
} 1) Using toBinaryString() method of Integer
} class.
2) Do conversion by writing your own logic
Method 2: Decimal to hexadecimal without without using any predefined methods.
using predefined method 3) Using Stack
import java.util.Scanner;

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: "); }

System.out.println(Integer.toBinar Method 3: Decimal to Binary using Stack


yString(124)); import java.util.*;
System.out.println("\nBinary class DecimalBinaryStack
representation of 45: "); {
public static void main(String[] args)
System.out.println(Integer.toBinaryString(4 {
5)); Scanner in = new Scanner(System.in);
System.out.println("\nBinary
representation of 999: "); // Create Stack object
Stack<Integer> stack = new
System.out.println(Integer.toBinaryString(9 Stack<Integer>();
99));
} // User input
} System.out.println("Enter decimal
number: ");
Method 2: Without using predefined method int num = in.nextInt();
class DecimalBinaryExample{
while (num != 0)
public void convertBinary(int num){ {
int binary[] = new int[40]; int d = num % 2;
int index = 0; stack.push(d);
while(num > 0){ num /= 2;
binary[index++] = num%2; }
num = num/2;
} System.out.print("\nBinary representation
for(int i = index-1;i >= 0;i--){ is:");
System.out.print(binary[i]); while (!(stack.isEmpty() ))
} {
} System.out.print(stack.pop());
}
public static void main(String a[]){ System.out.println();
DecimalBinaryExample obj = new }
DecimalBinaryExample(); }
System.out.println("Binary
representation of 124: "); 17. Java Program to convert
obj.convertBinary(124);
System.out.println("\nBinary binary to Decimal
representation of 45: ");

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();

//Get input String /* logic: char are inserted as keys and


System.out.println("Enter a string: "); their count
str = in.nextLine(); * as values. If map contains the char
System.out.println("Input String is: already then
"+str); * increase the value by 1
*/
//Get input Integer for(Character ch:chars){
System.out.println("Enter an integer: "); if(map.containsKey(ch)){
num = in.nextInt(); map.put(ch, map.get(ch)+1);
System.out.println("Input Integer is: } else {
"+num); map.put(ch, 1);
}
//Get input float number }
System.out.println("Enter a float number:
"); //Obtaining set of keys
fnum = in.nextFloat(); Set<Character> keys = map.keySet();
System.out.println("Input Float number
is: "+fnum); /* Display count of chars if it is
} * greater than 1. All duplicate chars
} would be
* having value greater than 1.
*/
21. Java Program to find for(Character ch:keys){
duplicate characters in a if(map.get(ch) > 1){
String System.out.println("Char "+ch+"
"+map.get(ch));
This program would find out the duplicate }
characters in a String and would display the }
count of them. }

import java.util.HashMap; public static void main(String a[]){


import java.util.Map; Details obj = new Details();
import java.util.Set; System.out.println("String:
BeginnersBook.com");
public class Details { System.out.println("-------------------------
");
public void countDupChars(String str){
obj.countDupChars("BeginnersBook.com");

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");

import java.util.*; System.out.println("****************");


class GenerateRandomNumber { for ( counter = 1 ; counter <= rows ;
public static void main(String[] args) { counter++ )
int counter; {
Random rnum = new Random(); for ( j = 1 ; j <= counter ; j++ )
/* Below code would generate 5 random {
numbers System.out.print(number+" ");
* between 0 and 200. //Incrementing the number value
*/ number++;
System.out.println("Random }
Numbers:"); //For new line
System.out.println();
System.out.println("***************"); }
for (counter = 1; counter <= 5; }
counter++) { }
System.out.println(rnum.nextInt(200));
} 24. Java Program to check
}
} Palindrome string using
Recursion
package beginnersbook.com;
23. Java Program to print import java.util.Scanner;
Floyd’s triangle class PalindromeCheck

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 {

public static void main(String[]args) public static void main(String[] args) {


{
//For capturing user input System.out.print("Enter any
Scanner scanner = new string:");
Scanner(System.in); Scanner in=new Scanner(System.in);
System.out.println("Enter the String for String inputString = in.nextLine();
check:"); Stack stack = new Stack();
String string = scanner.nextLine();
/* If function returns true then the for (int i = 0; i < inputString.length();
string is i++) {
* palindrome else not stack.push(inputString.charAt(i));
*/ }
if(isPal(string))
System.out.println(string + " is a String reverseString = "";
palindrome");
else while (!stack.isEmpty()) {

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

import java.util.Queue; System.out.println("Enter a string to


import java.util.Scanner; check if it is a palindrome:");
import java.util.LinkedList; String inputString = scanner.nextLine();
class PalindromeTest {
int length = inputString.length();
public static void main(String[] args) {
for ( int i = length - 1 ; i >= 0 ; i-- )
System.out.print("Enter any reverseString = reverseString +
string:"); inputString.charAt(i);
Scanner in=new Scanner(System.in);
String inputString = in.nextLine(); if (inputString.equals(reverseString))
Queue queue = new LinkedList(); System.out.println("Input string is a
palindrome.");
for (int i = inputString.length()-1; i else
>=0; i--) { System.out.println("Input string is not
queue.add(inputString.charAt(i)); a palindrome.");
}
}
String reverseString = ""; }

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);
} }
} }

Program 2: Program 2: User enters the array’s elements


If you do not want user intervention and
simply want to specify the number in import java.util.Scanner;
program itself then refer this example. class SumDemo{
public static void main(String args[]){
class FactorialDemo2{ Scanner scanner = new
public static void main(String args[]){ Scanner(System.in);
int factorial = fact(4); int[] array = new int[10];
System.out.println("Factorial of 4 is: int sum = 0;
"+factorial); System.out.println("Enter the
} elements:");
static int fact(int n) for (int i=0; i<10; i++)
{ {

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.

Program 1: 29. JavaProgram to Calculate


User would provide the length and width Area of Square
values during execution of the program and
the area would be calculated based on the In this tutorial we will learn how to calculate
provided values. area of Square. Following are the two ways
to do it:
import java.util.Scanner;
class AreaOfRectangle { 1) Program 1: Prompting user for entering
public static void main (String[] args) the side of the square
{ 2) Program 2: Side of the square is specified
Scanner scanner = new in the program’ s source code.
Scanner(System.in);
System.out.println("Enter the Program 1:
length of Rectangle:");
double length = import java.util.Scanner;
scanner.nextDouble(); class SquareAreaDemo {
System.out.println("Enter the public static void main (String[] args)
width of Rectangle:"); {
double width = System.out.println("Enter Side of
scanner.nextDouble(); Square:");
//Area = length*width; //Capture the user's input
double area = length*width; Scanner scanner = new
System.out.println("Area of Scanner(System.in);
Rectangle is:"+area); //Storing the captured value in a
} variable
} double side = scanner.nextDouble();
//Area of Square = side*side
In the above program, user would be asked double area = side*side;

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();

Program 2: for (i = 0; i < ( num - 1 ); i++) {


for (j = 0; j < num - i - 1; j++) {
class CircleDemo2 if (array[j] > array[j+1])
{ {
public static void main(String args[]) temp = array[j];
{ array[j] = array[j+1];
int radius = 3; array[j+1] = temp;
double area = Math.PI * (radius * }
radius); }
System.out.println("The area of circle is: }
" + area);
double circumference= Math.PI * System.out.println("Sorted list of
2*radius; integers:");
System.out.println( "The circumference
of the circle is:"+circumference) ; for (i = 0; i < num; i++)
} System.out.println(array[i]);
} }
}
32. Java Program for bubble Bubble sort program for sorting in
Sort Ascending or descending Order
Descending Order
In order to sort in descending order we just
Bubble sort program for sorting in ascending need to change the logic array[j] >

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.

class BubbleSortExample { import java.util.Scanner;


public static void main(String []args) { class LinearSearchExample
int num, i, j, temp; {
Scanner input = new Scanner(System.in); public static void main(String args[])
{
System.out.println("Enter the number of int counter, num, item, array[];
integers to sort:"); //To capture user input
num = input.nextInt(); Scanner input = new
Scanner(System.in);
int array[] = new int[num]; System.out.println("Enter number of
elements:");
System.out.println("Enter " + num + " num = input.nextInt();
integers: "); //Creating array to store the all the
numbers
for (i = 0; i < num; i++) array = new int[num];
array[i] = input.nextInt(); System.out.println("Enter " + num + "
integers");
for (i = 0; i < ( num - 1 ); i++) { //Loop to store each numbers in array
for (j = 0; j < num - i - 1; j++) { for (counter = 0; counter < num;
if (array[j] < array[j+1]) counter++)
{ array[counter] = input.nextInt();
temp = array[j];
array[j] = array[j+1]; System.out.println("Enter the search
array[j+1] = temp; value:");
} item = input.nextInt();
}
} for (counter = 0; counter < num;
counter++)
System.out.println("Sorted list of {
integers:"); if (array[counter] == item)
{
for (i = 0; i < num; i++) System.out.println(item+" is present
System.out.println(array[i]); at location "+(counter+1));
} /*Item is found so to stop the search
} and to come out of the
* loop use break statement.*/
break;
33. Java Program for Linear }
Search }
if (counter == num)

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:

// Method 2: Using valueOf method String is: a


String str2 = String.valueOf(ch); String is: a
System.out.println(str2);
} Converting String to Char
}
We can convert a String to char using
charAt() method of String class.
36. Java Program to Convert
char to String and String to class StringToCharDemo
Char {
public static void main(String args[])
{
How To Convert Char To String and a // Using charAt() method
String to char in Java String str = "Hello";
for(int i=0; i<str.length();i++){
By Chaitanya Singh | Filed Under: Java char ch = str.charAt(i);
Examples System.out.println("Character at "+i+"
Position: "+ch);
In this tutorial, we will see programs for }
char to String and String to char conversion. }
}
Program to convert char to String
37. Java Program to display
We have following two ways for char to
String conversion. Fibonacci series using loops
Method 1: Using toString() method
Method 2: Usng valueOf() method The Fibonacci sequence is a series of
numbers where a number is the sum of
class CharToStringDemo previous two numbers. Starting with 0 and
{ 1, the sequence goes 0, 1, 1, 2, 3, 5, 8, 13,
public static void main(String args[]) 21, and so on. Here we will write three
{ programs to print fibonacci series 1) using
// Method 1: Using toString() method for loop 2) using while loop 3) based on the
char ch = 'a'; number entered by user
String str = Character.toString(ch);
System.out.println("String is: "+str); To understand these programs, you should
have the knowledge of for loop and while
// Method 2: Using valueOf() method loop.
String str2 = String.valueOf(ch);
System.out.println("String is: "+str2); If you are new to java, refer this java
} programming tutorial to start learning from

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 {

int sumOfPrevTwo = num1 + num2; public static void main(String[] args) {


num1 = num2;
num2 = sumOfPrevTwo; int count, num1 = 0, num2 = 1;
} System.out.println("How may numbers
} you want in the sequence:");
} Scanner scanner = new
Scanner(System.in);
Output: count = scanner.nextInt();
scanner.close();
Fibonacci Series of 7 numbers:0 1 1 2 3 5 8 System.out.print("Fibonacci Series of
"+count+" numbers:");
Example 2: Displaying Fibonacci Sequence
using while loop int i=1;
while(i<=count)
public class JavaExample { {
System.out.print(num1+" ");
public static void main(String[] args) { int sumOfPrevTwo = num1 + num2;
num1 = num2;
int count = 7, num1 = 0, num2 = 1; num2 = sumOfPrevTwo;
System.out.print("Fibonacci Series of i++;
"+count+" numbers:"); }
}
int i=1; }
while(i<=count)
{
System.out.print(num1+" ");
38. Java Program to find
int sumOfPrevTwo = num1 + num2; Factorial using loops
num1 = num2;

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.

public class JavaExample { import java.util.Scanner;


public class JavaExample {
public static void main(String[] args) {
public static void main(String[] args) {
//We will find the factorial of this
number //We will find the factorial of this
int number = 5; number
long fact = 1; int number;
for(int i = 1; i <= number; i++) System.out.println("Enter the number:
{ ");
fact = fact * i; Scanner scanner = new
} Scanner(System.in);
System.out.println("Factorial of number = scanner.nextInt();
"+number+" is: "+fact); scanner.close();
} long fact = 1;
} int i = 1;
while(i<=number)
Example 2: Finding Factorial using while {
loop fact = fact * i;
i++;
public class JavaExample { }
System.out.println("Factorial of
public static void main(String[] args) { "+number+" is: "+fact);
}

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;

Example: Program to make a calculator default:


using switch case in Java System.out.printf("You have
entered wrong operator");
import java.util.Scanner; return;
}
public class JavaExample {
System.out.println(num1+"
public static void main(String[] args) { "+operator+" "+num2+": "+output);
}
double num1, num2; }
Scanner scanner = new
Scanner(System.in);
System.out.print("Enter first number:"); 40. Java Program to
Calculate grades of Student
num1 = scanner.nextDouble();
System.out.print("Enter second This program calculates the grade of a
number:"); student based on the marks entered by user
num2 = scanner.nextDouble(); in each subject. Program prints the grade
based on this logic.
System.out.print("Enter an operator (+, If the average of marks is >= 80 then prints
-, *, /): "); Grade ‘A’
char operator = If the average is <80 and >=60 then prints
scanner.next().charAt(0); Grade ‘B’
If the average is <60 and >=40 then prints
scanner.close(); Grade ‘C’

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{

public static void main(String[] args) {

int num1 = 10, num2 = 20, num3 = 7;


42. Java Program to find if(num1 >= num2) {
Largest of three numbers
if(num1 >= num3)
Here we will write two java programs to System.out.println(num1+" is the

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

Example: Program to find the smallest of


three numbers using ternary operator
45. Java Program to find
largest of three numbers
We have used ternary operator twice to get using ternary operator
the final output because we have done the
comparison in two steps: This program finds the largest of three
First Step: Compared the num1 and num2 numbers using ternary operator. Before
and stored the smallest of these two into a going through the program, lets understand
temporary variable temp. what is a ternary Operator:
Second Step: Compared the num3 and temp Ternary operator evaluates a boolean
to get the smallest of three. expression and assign the value based on the
If you want, you can do that in a single result.
statement like this:
variable num = (expression) ? value if true :
result = num3 < (num1 < num2 ? value if false
num1:num2) ? num3:(num1 < num2 ?
num1:num2); If the expression results true then the first
value before the colon (:) is assigned to the
Here is the complete program: variable num else the second value is
assigned to the num.
import java.util.Scanner;
public class JavaExample Example: Program to find the largest
{ number using ternary operator
public static void main(String[] args)
{ In this Program, we have used the ternary
int num1, num2, num3, result, temp; operator twice to compare the three
Scanner scanner = new numbers, however you can compare all three
Scanner(System.in); numbers in one statement using ternary
System.out.println("Enter First operator like this:
Number:");
num1 = scanner.nextInt(); result = num3 > (num1>num2 ?
System.out.println("Enter Second num1:num2) ? num3:((num1>num2) ?
Number:"); num1:num2);
num2 = scanner.nextInt();
System.out.println("Enter Third However if you are finding it difficult to
Number:"); understand then use it like I have shown in
num3 = scanner.nextInt(); the example below:
scanner.close();
import java.util.Scanner;
temp = num1 < num2 ? num1:num2; public class JavaExample
result = num3 < temp ? num3:temp; {

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.

To understand this program you should have


the knowledge of following Core Java topic:
Method Overloading in Java

Example: Program to find area of Square,


Rectangle and Circle using Method
Overloading

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

You might also like