Complete Practical File
Complete Practical File
Complete Practical File
Place…………………………
Date…………………………
Teacher In-charge
EXAMINERS
INTERNAL EXAMINER
CONTENTS
2 Simple Calculator
4 Reverse Array
5 Palindrome-Strings
6 Exception handling
9 Employee-Access Specifiers
10 Constructor Overloading
11. Factorial
Aim:
To write a simple java program to swap two numbers without using temporary
variables.
Algorithm:
Step 1: Start
Step 2: Define the variables x and y.
Step 3: perform swapping ( t=x; x=y; y=t;)
Step 4: Print x,y after swapping.
Step 5: End
Coding:
import java.util.*;
Public Class Swap
{
public static void main(String a[])
{
int x = 10, y=20,t=0;
System.out.println("before swapping numbers: "+x +" "+ y);
/*Swapping*/
t= x;
x =y;
y = t;
System.out.println("After swapping: "+x +" " + y);
}
}
OUTPUT:
Before swapping numbers: 10 20
After swapping: 20 10
Program No: 2 Simple Calculator Date:
Aim:
To write a program to illustrate simple mathematical operators using switch case.
Algorithm:
Step 1: Start
Step 2: Define two variables a and b.
Step 3: Get the user input through Scanner class.
Step 4: Match the operator using the switch case.
Step 5: Perform the operation.
Step 6: Store the resultant value in the “result” variable.
Step 7: Print the values.
Step 8: Stop.
Coding:
import java.util.*;
import java.io.*;
public class Calculator
{
public static void main(String[] args)
{ double first = 4, second = 5, result=0 ;
System.out.print("Enter an operator (+, -, *, /): ");
Scanner reader = new Scanner(System.in);
char operator = reader.next().charAt(0);
switch(operator)
{
case '+':
result = first + second;
break;
case '-':
result = first - second;
break;
case '*':
result = first * second;
break;
case '/':
result = first / second;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
System.out.printf("Error! operator is not correct");
return;
}
System.out.printf("%.1f %c %.1f = %.1f", first, operator, second, result);
}
}
Output:
4.0 * 5.0 = 20
Program No: 3 Classes and Objects Date:
Aim:
To write a program to illustrate classes and objects in java.
Algorithm:
Step 1: Start
Step 2: Define the class Employee.
Step 3: Declare the variables “name, Designation and salary”.
Step 4: Using the method empDesignation , empSalary , assign the variables.
Step 5.Create an object and invoke these methods.
Step 6: Display all the details of an employee using printEmployee() method.
Step 7: Stop.
Coding:
import java.io.*;
public class Employee
{
String name, designation;
double salary;
public Employee(String name)
{
this.name = name;
}
/* Assign the designation to the variable designation.*/
public void empDesignation(String empDesig)
{
designation = empDesig;
}
/* Assign the salary to the variable salary.*/
public void empSalary(double empSalary)
{
salary = empSalary;
}
/* Print the Employee details */
public void printEmployee()
{
System.out.println("Name:"+ name );
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
public class EmployeeTest
{
public static void main(String args[])
{
/* Create one object using constructor */
Employee empOne = new Employee("James Smith");
// Invoking methods for each object created
empOne.empDesignation("Senior Software Engineer");
empOne.empSalary(1000);
empOne.printEmployee();
}
}
OUTPUT:
Aim:
To write a program in java to reverse the contents of the array without using library
methods.
Algorithm:
Step 1: START
Step 2: Declare arr[]
Step 3: Initialize the array elements through user input
Step 4: print "Original Array:"
Step 5: repeat STEP 6 for(i=0; i<arr.length ; i++)
Step 6: print arr[i]
Step 7: print "Array in reverse order"
Step 8: repeat STEP 9 for(i= arr.length-1; i>=0; i--)
Step 9: print a[i]
Step 10: END
Coding:
import java.io.*;
public class ReverseArray
{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [5] ;
arr[] = { 4,8,1,3,7};
System.out.println("Original array: ");
for (int i = 0; i<arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--)
{
System.out.print(arr[i] + " ");
}
}
}
OUTPUT:
Original array:
4, 8, 1, 3, 7
Array in reverse order:
7, 3, 1, 8, 4
Program No: 5 Palindrome-Strings Date:
Aim:
To write a program in java to check whether the string is palindrome or not.
Algorithm:
Step 1: Start
Step 2: Declare a class “PalindromeTest”.
Step 3: Store that string in “inputString” variable.
Step 4: Find the length of that string using length() method.
Step 5: Using for loop read character by character and store it in “reverseString”
variable.
Step 6: Then match the reverseString and inputString, whether it is same.
Step 7: If it is same, then the String is palindrome.
Step 8: Stop.
Coding:
import java.io.*;
class PalindromeTest
{
public static void main(String args[])
{
String reverseString="";
String inputString = “MALAYALAM”;
int length = inputString.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverseString = reverseString + inputString.charAt(i);
if (inputString.equals(reverseString))
System.out.println("Input string is a palindrome.");
else
System.out.println("Input string is not a palindrome.");
}
}
OUTPUT:
Aim:
To write a program in java to illustrate exception handling.
Algorithm:
Step 1: Start.
Step 2: Declare the class Example1.
Step 3: Write the code that may or may not arise exception in try block.
Step 4: If the exception arises appropriate catch block will be called.
Step 5: Appropriate error message will be displayed.
Step 6: Stop.
Coding:
import java.io.*;
class Example1
{
public static void main(String args[])
{
int num1, num2;
try
{
/* We suspect that this block of statement can throw exception so we handled * it
by placing these statementsinside try and handled the exception in catch block */
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e)
{
/* This block will only execute if any Arithmetic exceptionoccurs in try block */
System.out.println("You should not divide a number by zero");
}
catch (Exception e)
{
/* This is a generic Exception handler which means it can handle all the exceptions.
* This will execute if the exception is nothandled by previous catch blocks.*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
Algorithm:
Step 1: Start.
Step 2: Declare a class ExtendThread.
Step 3: Declare a method run() and print “Thread Created”.
Step 4: Using for loop count the number of times the thread is running.
Step 5: Create an object for the class.
Step 6: invoke obj.start();
Step 7: Stop.
Coding:
Import.java.io.*;
Package extendthread
Public class ExtendThread extendsThread
{
Public void run()
{
System.out.println(“created a thread”);
For (int count=1; count<=3; count++)
{
System.out.println(“Count=”+count);
}
}
Public static void main(String[] args)
{
ExtendThread t1=new ExtendThread();
ExtendThread t2=new ExtendThread();
t1.start();
t2.start();
}
}
OUTPUT:
Created a thread
Created a thread
Count=1
Count=2
Count=3
Count=1
Count=2
Count=3
Program No: 8 Threads - “Runnable Interface” Date:
Aim:
To write a program to illustrate threads in java.
Algorithm:
Step 1: Start.
Step 2: Instantiate the class “RunnableDemo” that implements the runnable interface.
Step 3: Override the run method.
Step 4: Pass the object „r‟ to the thread instance.
Step 5: Run the start method which gives the number of times the thread has been ran.
Step 6: Stop.
Coding:
Package runnabledemo;
Public Class runnableDemo implements Runnable
{
Public void run()
{
System.out.println(“created a Thread”);
For (int count=1; count<=3; count++)
System.out.println(“Count=”+count);
}
Public static void main(String[] args)
{
RunnableDemo r=new RunnaleDemo();
Thread t1= new Thread(r);
T1.start();
}
}
OUTPUT:
Created a Thread
Count=1
Count=2
Count=3
Program No: 9 Employee-Access Specifiers Date:
Aim:
To write a program to illustrate the keywords-public and private in java using the
Class Employee.
Algorithm:
Step 1: Start.
Step 2: Declare the variables id and name as private such that the variables cannot be
accessed outside of the class.
Step 3: Using the getter methods (getID, getName) the employee‟s id and name was
fetched.
Step 4: Using setter methods (id, name) was initialized through the object.
Step 5: Declare the class EmpObj to declare the object of the class Employee.
Step 6: Identify the variables id and name was not visible inside the class EmpObj.
Step 7: Stop.
Coding:
import java.io.*;
class Employee
{
private int id;
private String name;
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
} }
public class EmpObj
{
public static void main(String args[])
{
Employee e=new Employee();
e.setId(101);
e.setName("Parthasarathy");
System.out.println(e.getId()+" "+e.getName);
}
}
Output:
101 Parthasarathy
Program No: 10 Constructor Overloading Date:
Aim:
To write a program to illustrate constructor overloading in java using the Class
Student.
Algorithm:
Step 1: Start.
Step 2: Declare the default constructor Student() which initializes the variable name
and age.
Step 3: Declare the parameterized constructor Student(n,a) such that the values of
name and age are passed while creating objects.
Step 4: Create an obj1 which calls the Default constructor.
Step 5: Create an obj2 such that the values are passed to n and a in the parameterized
constructor.
Step 6: Display the variables.
Step 7: Stop.
Coding:
Import.java.io.*;
Public class Student
{
int age;
String name;
//Default constructor
Student()
{
this.name="Chaitanya";
this.age=30;
}
//Parameterized constructor
Student(String n,int a)
{
this.name=n;
this.age=a;
}
Public static void main(String args[])
{
Student obj1 = new Student();
Student obj2 = new Student("Shilpa", 56);
System.out.println(obj1.name+" "+obj1.age);
System.out.println(obj2.name+" "+obj2.age);
}
}
Output:
Chaitanya 30
Shilpa 56
Program No: 11 Factorial Date:
Aim:
To calculate the factorial of a number using java program.
Algorithm:
Step 1: Start
Step 2: Declare a class Test.
Step 3: Write the main method. Inside it declare a variable num with the value 5.
Step 4: From the main method the factorial method is called. This factorial method
is called as recursive method.
Step 5: This factorial method is declare as static method as it is invoked without the
help of main method.
Step 6: This method will call repeatedly until n==0.
Step 7: Here the calculation is done as follows: 5*4*3*2*1 = 120.
Coding:
Class Test
{
Static int factorial(int n)
{
if(n == 0)
return1;
returnn * factorial(n - 1);
}
Public static void main(String[] args)
{
intnum = 5;
System.out.println("Factorial of "+ num + " is "+ factorial(5));
}
}
Output:
Factorial of 5 is 120
Program No:12 Leap Year Date:
Aim:
To check whether the given year is leap year or not.
Algorithm:
Step 1: Start.
Step 2: Declare a class Test.
Step 3: Write the main method, From that checkyear method is called.
Step 4: The checkYear method is declared as static.
Step 5: This method will divide the given year by 4 and 100 either it is divided
by 400.
Step 6: If the resultant gets 0(zero)then the given year is a leap year.
Coding:
classTest
{
Static Boolean checkYear(int year)
{
return(((year % 4== 0) && (year % 100!= 0)) ||
(year % 400== 0));
}
Public static void main(String[] args)
{
int year = 2000;
System.out.println(checkYear(2000)? "Leap Year" : "Not a Leap Year");
}
}
Output:
Leap Year
Program No:13 Fibonacci Series Date:
Aim:
To generate the Fibonacci series using java program.
Algorithm:
Step 1: Start
Step 2: Declare a class FibonacciExample1.
Step 3: Write the main method.
Step 4: Create the variables named n1=0, n2=1,n3 and count=10.
Step 5: Using for loop test the condition i< count and increment i for each loop.
Step 6: Inside the for loop add the previous two numbers (n1, n2) and store it in n3.
Later n1, n2, n3 is printed. (E.g) 0, 1 (0+1=1).Now the series becomes 0,1,1.
Step 7: Now the n1=1 n2=1. Calculate n3 as the above step.
Step 8: Now the Fibonacci series is ready.
Step 9: End
Coding:
class FibonacciExample1
{
public static void main(String args[])
{
int n1=0,n2=1,n3,i,count=10;
System.out.print(n1+" "+n2); //printing 0 and 1
for(i=2;i<count;++i) //loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
OUTPUT:
0 1 1 2 3 5 8 13 21 34
Program No: 14 Armstrong Number Date:
Aim:
To check whether the given number is an Armstrong number or not.
Algorithm:
Step 1: Start
Step 2: Create the class “Armstrong”.
Step 3: Write the main method. Create the variables named
number, original Number, remainder, result.
Step 4: Now the original no is 371.
Step 5: Reverse the number using while loop.
Step 6: Check whether the given original number and the result is same.
Step 7: If both are same then the given number is an Armstrong number.
Coding:
public class Armstrong
{
public static void main(String[] args)
{
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Output:
Aim:
To write a java program to count a character in string.
Algorithm:
Step 1: Start
Step 2: Write a class- “ CountCharacter”. Within this a main method has written and a
variable named inputString has been initialized with the input “coderolls”.
Step 3: Now I want to count the no. of ocurrance of the character „o‟ in the given
inputString.
Step 4: Using for loop I am checking the character „o‟ at each position in the
inputstring.
Step 5: Once the ch=‟o‟ matches with the position‟s value counter is incremented.
Step 6: Finally counter variable (count) is displayed.
Step 7: End
Coding:
Public class countcharacter
{
public static void main(String[] args)
{
String inputString = "coderolls";
char ch = 'o';
int count = 0;
for (int i = 0; i<inputString.length(); i++)
{
if (inputString.charAt(i) == ch)
{
count++;
}
}
System.out.println ("The character '" + ch + "' found " + count + " times in a string '" +
inputString + "'.");
}
}
OUTPUT: