java lab manual (1)
java lab manual (1)
PSO1 To apply software engineering principles and practices for developing quality software for
scientific and business applications.
PSO2 To adapt to emerging Information and Communication Technologies (ICT) to innovate ideas
and solutions to existing/novel problems.
OBJECTIVES:
• To understand Object Oriented Programming concepts and basics of Java programming
language
TOTAL: 45 HOURS
OUTCOMES:
Upon Completion of the course, the students will be able to:
CO1:Apply the concepts of classes and objects to solve simple problems
CO2: Develop programs using inheritance and interfaces
CO3:Make use of exception handling mechanisms and packages to solve real
world problems
CO4:Build Java applications with string classes, Collections and generics concepts
CO5:Develop java program using I/O packages,
LIST OF EQUIPMENT FOR A BATCH OF 30
STUDENTS:
SOFTWARE: Eclipse,JDK .
HARDWARE: Standalone desktops – 30 Nos. (or) Server supporting 30 terminals or
more.
INDEX
Procedure:
In this program, we have an int variable num. We are using Scanner class to get the
Once the entered number is stored in the variable num, we are using if..else statement to
executing if block (if condition true) or else block (if condition is false).
Program:
import java.util.Scanner;
public class JavaExample
{
public static void main(String args[])
{
int num;
System.out.print("Enter an Integer number: ");
Procedure:
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
mathematically:
To determine whether a year is a leap year, follow these steps:
1. If the year is evenly divisible by 4, go to step 2. Otherwise, go to step 5.
2. If the year is evenly divisible by 100, go to step 3. Otherwise, go to step 4.
3. If the year is evenly divisible by 400, go to step 4. Otherwise, go to step 5.
4. The year is a leap year (it has 366 days).
5. The year is not a leap year (it has 365 days). Source of these steps.
Program:
import java.util.Scanner;
public class Demo {
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else {
isLeap = false;
}
if(isLeap==true)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
Output:
Procedure:
The alphabets A, E, I, O and U (smallcase and uppercase) are known as Vowels and rest of
the alphabets are known as consonants. Here we will write a java program that checks
whether the input character is vowel or Consonant using Switch Case in Java.
import java.util.Scanner;
class JavaExample
{
public static void main(String[ ] arg)
{
boolean isVowel=false;;
Scanner scanner=new Scanner(System.in);
System.out.println("Enter a character : ");
char ch=scanner.next().charAt(0);
scanner.close();
switch(ch)
{
case 'a' :
case 'e' :
case 'i' :
case 'o' :
case 'u' :
case 'A' :
case 'E' :
case 'I' :
case 'O' :
case 'U' : isVowel = true;
}
if(isVowel == true) {
System.out.println(ch+" is a Vowel");
}
else {
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
System.out.println(ch+" is a Consonant");
else
System.out.println("Input is not an alphabet");
}
}
}
Output 1:
Enter a character :
A
A is a Vowel
Output 2:
Enter a character :
P
P is a Consonant
Output 3:
Enter a character :
9
Input is not an alphabet
d) Java Program to Calculate Compound Interest
Procedure:
P (1 + R/n) (nt) - P
Here P is principal amount.
R is the annual interest rate.
t is the time the money is invested or borrowed for.
n is the number of times that interest is compounded per unit t, for example if interest is
compounded monthly and t is in years then the value of n would be 12. If interest is compounded
quarterly and t is in years then the value of n would be 4.
Procedure:
This program reverses every word of a string and display the reversed string as an output. For
example, if we input a string as “Reverse the word of this string” then the output of the program
would be: “esrever eht drow fo siht gnirts”.
To understand this program you should have the knowledge of following Java
Programming topics:
Welcome to BeginnersBook
emocleW ot kooBsrennigeB
This is an easy Java Program
sihT si na ysae avaJ margorP
b) Java program to find the occurrence of a character in a string
procedure:
In this program we are finding the occurrence of each character in a String. To do this we are
first creating an array of size 256 (ASCII upper range), the idea here is to store the occurrence
count against the ASCII value of that character. For example, the occurrence of ‘A’ would be
stored in counter[65] because ASCII value of A is 65, similarly occurrences of other chars are
stored in against their ASCII index values.
We are then creating an another array array to hold the characters of the given String, then we are
comparing them with the characters in the String and when a match is found the count of that
particular char is displayed using counter array.
Program:
class JavaExample {
//String length
int len = str.length();
if (flag == 1)
System.out.println("Occurrence of char " +
str.charAt(i)
+ " in the String is:" + counter[str.charAt(i)]);
}
}
public static void main(String[] args)
{
String str = "beginnersbook";
countEachChar(str);
}
}
Output:
Procedure:
In this example, we have two arrays. We are finding the count of the elements in both the arrays.
The steps to count the number of elements is same in any type of array, you can simply
use .length property of the array to quickly find the size of the array.
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count, temp;
Program1:
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name="Sonoo";
s2.id=102;
s2.name="Amit";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
}
2) Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and
initializing the value to these objects by invoking the insertRecord method.
Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
c) Object and Class Example: Initialization through a constructor
We will learn about constructors in Java later.
a)Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
b) Polymorphism
Method overloading:
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Method overriding:
class Bank{
int getRateOfInterest(){return 0;}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
Exception Handling:
Program1:
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Program2:
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Program3:
// main method
public static void main(String args[])
{
try
{
// calling the method
validate(13);
}
catch (InvalidAgeException ex)
{
System.out.println("Caught the exception");
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Expriment7: Program to discover application of collectios.
Program1:
import java.util.*;
public class ArrayListExample4{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
al.add("Mango");
al.add("Apple");
al.add("Banana");
al.add("Grapes");
//accessing the element
System.out.println("Returning element: "+al.get(1));//it will return the 2n
d element, because index starts from 0
//changing the element
al.set(1,"Dates");
//Traversing list
for(String fruit:al)
System.out.println(fruit);
}
}
Program2:
import java.util.*;
class ArrayList7{
public static void main(String args[]){
ArrayList<String> al=new ArrayList<String>();
System.out.println("Initial list of elements: "+al);
//Adding elements to the end of the list
al.add("Ravi");
al.add("Vijay");
al.add("Ajay");
System.out.println("After invoking add(E e) method: "+al);
//Adding an element at the specific position
al.add(1, "Gaurav");
System.out.println("After invoking add(int index, E element) metho
d: "+al);
ArrayList<String> al2=new ArrayList<String>();
al2.add("Sonoo");
al2.add("Hanumat");
//Adding second list elements to the first list
al.addAll(al2);
System.out.println("After invoking addAll(Collection<? extends E>
c) method: "+al);
ArrayList<String> al3=new ArrayList<String>();
al3.add("John");
al3.add("Rahul");
//Adding second list elements to the first list at specific position
al.addAll(1, al3);
System.out.println("After invoking addAll(int index, Collection<? ex
tends E> c) method: "+al);
}
}