0% found this document useful (0 votes)
52 views48 pages

Java Programming (Bcse 2333) Lab File: Submitted by

The document contains the details of various Java programming experiments conducted by a student. It includes 15 experiments on topics like basic Java programs, operators, classes, methods, arrays, strings, inheritance, exceptions, file handling, threads and collections. Each experiment lists the aim, code and output for the programming problem solved.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views48 pages

Java Programming (Bcse 2333) Lab File: Submitted by

The document contains the details of various Java programming experiments conducted by a student. It includes 15 experiments on topics like basic Java programs, operators, classes, methods, arrays, strings, inheritance, exceptions, file handling, threads and collections. Each experiment lists the aim, code and output for the programming problem solved.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 48

JAVA PROGRAMMING (BCSE 2333)Lab File

Submitted by-
Himanshu kumar
21SCSE1010370
B.Tech
C.S.E
|||
SCHOOL OF COMPUTING SCIENCE AND ENGINEERING

2021

INDEX
Exp No TOPIC Lab Experiments
1 Basic program a)Write a JAVA program to print “Hello World.”
b)WAP in java to print the values of various primitive
data types.
2 Operators WAP in java to demonstrate operator precendence.
3 Simple java class WAP in java to create a class Addition and a method add() to
add two numbers.
4 Command line argument Write a program that uses length property for displaying
any number of command line arguments.
5 Console Input(Scanner WAP in javato find the average of N numbers.
class)
6 Control Statement I WAP in java to find out the first N even numbers.
7 Control Statement II WAP in java to find out factorial of a number
8 Control Statement III WAP in java to find out the Fibonacci series
9 Arrays I WAP in java to sort elements in 1D array in ascending order.

10 Arrays II WAP in java to perform matrix addition using two 2D


arrays.
11 Strings I WAP in java to find out the number of characters in a
string.
12 Strings II WAP in java (i)find a character at a specific index in string.
(ii)to concatenate two strings (iii) to compare two strings
ignoring the cases.

13 Class,methods and objects Create a class Book with the following information.
Member variables : name (String), author (of the class
Author you have just created), price (double), and
qtyInStock (int)
[Assumption: Each book will be written by exactly one
Author]
Parameterized Constructor: To initialize the variables Getters
and Setters for all the member variables

In the main method, create a book object and print all details
of the book (including the author details)
14
15 Methods and OOPS I WAP in java that implements method overloading. 17. WAP
that shows passing object as parameter. 1
16 Methods and OOPS II WAP in java to show that the value of non static
variable is not visible to all the instances, and therefore
cannot be used to count the number of instances.
17 Constructor overloading Create a class Shape and override area() method to
calucate area of rectangle, square and circle
18 Static Keyword Create a class Student with non-static variable name and
static variable Course. Create 3 objects of class
,store and display information.
19 Access modifiers WAP in java to demonstrate the properties of public private
and protected variables and methods(with package).

20
21 Wrapper Class I WAP in javato show autoboxing and unboxing
22
23 Inheritence I a)Create a class named ‘Animal’ which includes methods
like eat() and sleep().

Create a child class of Animal named ‘Bird’ and override


the parent class methods. Add a new method named fly().

Create an instance of Animal class and invoke the eat and


sleep methods using this object.

Create an instance of Bird class and invoke the eat, sleep


and fly methods using this object.
Inheritance
24 Method overidding WAP that illustrates method overriding
25 Inheritence II a)WAP in java for abstract class to find areas of
different shapes .
b)Write an interface called Playable, with a method
void play();
Let this interface be placed in a package called music.
Write a class called Veena which implements Playable
interface
26 Exception Handling I a) WAP in java demonstrating arithmetic exception and
ArrayOutOf Bounds Exception using try catch block b)WAP
in java to demonstrate the use of nested try
block and nested catch block.
27 Exception Handling II WAP in java to demonstrate the use of throw and throws

28 IO Stream I Write a program to count the number of times a character


appears in a File.
[Note : The character check is case insensitive... i.e, 'a' and 'A'
are considered to be the same]
29 IO Stream II Write a program to copy contents from one file to
another and check the output.
30 Multi Threading I WAP in java in two different ways that creates a thread by
(i)extending thread class(ii) implementing runnable interface
which displays 1st 10 natural numbers.
31 Multi Threading II WAP in java which demonstrate the lifecycle methods
of thread.
32 Collections I Create TreeSet, HashSet, LinkedHashSet. Add same integer
values in all three. Display all three set and note down the
difference.
33 Collections II WAP in java WAP in java and run applications that use
"List" Collection objects
34 Collections III Create a HashMap<Rollno, Name>. Display Map, take
rollno from user and display name.
35 JDBC I WAP to do CRUD operation in java
EXPERIMENT NO.1(a)

AIM: Write a JAVA program to print “Hello World.”

CODE:

public class Main

public static void main(String[] args) {


System.out.println("Hello World");
}

}
EXPERIMENT NO.1(b)

AIM: WAP in java to print the values of various primitive


data types.

CODE:

class PrimitiveConcept
{
public static void main(String args[])
{
byte b;
int i;
boolean bool;
float f;
double d;
short s;
char c;
String str;
b=12;
i=2555;
bool=true;
f=11.23f;
d=122.32d;
s=3;
c='S';
str="TejSumeru";

System.out.println("Value Of Byte Variable - "+b);


System.out.println("Value Of Integer Variable - "+i);
System.out.println("Value Of Boolean Variable - "+bool);
System.out.println("Value Of Float Variable - "+f);
System.out.println("Value Of Double Variable - "+d);
System.out.println("Value Of Short Variable - "+s);
System.out.println("Value Of Character Variable - "+c);
System.out.println(str);
}
}
EXPERIMENT NO.3
AIM: WAP in java to create a class Addition and a method add() to add two numbers

CODE:

import java.util.Scanner;  
public class IntegerSumExample2 
{  
public static void main(String[] args) 
{  
System.out.println("Enter the Two numbers for addtion: ");  
      Scanner readInput = new Scanner(System.in);  
      int a = readInput.nextInt();  
        int b = readInput.nextInt();  
        readInput.close();  
        System.out.println("The sum of a and b is = " + Integer.sum(a, b));  
    }  
}  
EXPERIMENT NO.4
AIM: Write a program that uses length property for displaying any number of command line
arguments.

CODE:

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

for(int i=0;i<args.length;i++)
System.out.println(args[i]);

}
}

 
EXPERIMENT NO.5
AIM: WAP in java to find the average of N numbers.

CODE:
import static java.lang.Float.sum;  
import java.util.Scanner;  
public class Average {  
 public static void main(String[] args)  
   {  
 int n, count = 1;   
  float  xF, averageF, sumF = 0;   
 Scanner sc = new Scanner(System.in);     
System.out.println("Enter the value of n");  
n = sc.nextInt();  
while (count <= n)   
 {   
System.out.println("Enter the "+count+" number?");  
xF = sc.nextInt();  
 sumF += xF;   
++count;   
 }   
averageF = sumF/n;   
System.out.println("The Average is"+averageF);  
 }    
}  
EXPERIMENT NO.6
AIM: WAP in java to find out the first N even numbers.
CODE:

public class DisplayEvenNumbersExample1  
{  
public static void main(String args[])   
{  
int number=100;  
System.out.print("List of even numbers from 1 to "+number+": ");  
for (int i=1; i<=number; i++)   
{  
if (i%2==0)   
{  
System.out.print(i + " ");  
}  }  }  }  
EXPERIMENT NO.7
AIM: WAP in java to find out factorial of a number
CODE:
class FactorialExample{  

public static void main(String args[]){  
 int i,fact=1;  
int number=5;//It is the number to calculate factorial    
for(i=1;i<=number;i++){    
fact=fact*i;    
  }    
 System.out.println("Factorial of "+number+" is: "+fact);    
 }  
}  
EXPERIMENT NO.8
AIM: WAP in java to find out the Fibonacci series
CODE:

class FibonacciExample2
{  
static int n1=0,n2=1,n3=0;    
static void printFibonacci(int count)
{    
 if(count>0)
{    
n3 = n1 + n2;    
n1 = n2;    
 n2 = n3;    
System.out.print(" "+n3);   
printFibonacci(count-1);    
 }    
 }    
 public static void main(String args[]){    
int count=10;    
System.out.print(n1+" "+n2);  
 printFibonacci(count-2);
 }  
}  
EXPERIMENT NO.9
AIM: WAP in java to sort elements in 1D array in ascending order
CODE:

public class SortAsc
 {    
    public static void main(String[] args)
{        
int [] arr = new int [] {5, 2, 8, 7, 1};     
int temp = 0;    
 System.out.println("Elements of original array: ");    
for (int i = 0; i < arr.length; i++) {     
System.out.print(arr[i] + " ");    
       }    
for (int i = 0; i < arr.length; i++) {     
for (int j = i+1; j < arr.length; j++) {     
 if(arr[i] > arr[j]) {    
 temp = arr[i];    
 arr[i] = arr[j];    
arr[j] = temp;    
 }     
}     
}    
System.out.println();    
System.out.println("Elements of array sorted in ascending order: ");    
for (int i = 0; i < arr.length; i++) 
{     
 System.out.print(arr[i] + " ");    
 }    
}    
}    
EXPERIMENT NO.10
AIM: WAP in java to perform matrix addition using two 2D arrays

CODE:
public class MatrixAdditionExample
{  
public static void main(String args[])
{  
int a[][]={{1,3,4},{2,4,3},{3,4,5}};    
int b[][]={{1,3,4},{2,4,3},{1,2,4}};    
int c[][]=new int[3][3];  
    
for(int i=0;i<3;i++)
{    
for(int j=0;j<3;j++)
{    
c[i][j]=a[i][j]+b[i][j];    
System.out.print(c[i][j]+" ");    
}    
System.out.println();//new line    
}    
}

}  
EXPERIMENT NO.11
AIM: WAP in java to find out the number of characters in a string
CODE:

public class CountCharacter    
{    
  public static void main(String[] args) 
{    
 String string = "The best of both worlds";    
int count = 0;    
for(int i = 0; i < string.length(); i++)
{    
if(string.charAt(i) != ' ')    
    count++;    
        }    
System.out.println("Total number of characters in a string: " + count);    
    }    
}     
EXPERIMENT NO.12
AIM: WAP in java (i)find a character at a specific index in string. (ii)to concatenate two strings (iii)
to compare two strings ignoring the cases.

CODE:

class Main
{
static boolean equalIgnoreCase(String str1, String str2)
{
int i = 0;
int len1 = str1.length();
int len2 = str2.length();
if (len1 != len2)
return false;
while (i < len1)
{
if (str1.charAt(i) == str2.charAt(i))
{
i++;
}

else if (!((str1.charAt(i) >= 'a' && str1.charAt(i) <= 'z')


|| (str1.charAt(i) >= 'A' && str1.charAt(i) <= 'Z')))
{
return false;
}

else if (!((str2.charAt(i) >= 'a' && str2.charAt(i) <= 'z')


|| (str2.charAt(i) >= 'A' && str2.charAt(i) <= 'Z')))
{
return false;
}

else
{
if (str1.charAt(i) >= 'a' && str1.charAt(i) <= 'z')
{
if (str1.charAt(i) - 32 != str2.charAt(i))
return false;
}

else if (str1.charAt(i) >= 'A' && str1.charAt(i) <= 'Z')


{
if (str1.charAt(i) + 32 != str2.charAt(i))
return false;
}
i++;

}
return true;

static void equalIgnoreCaseUtil(String str1, String str2)


{
boolean res = equalIgnoreCase(str1, str2);

if (res == true)
System.out.println( "Same" );

else
System.out.println( "Not Same" );
}

public static void main(String args[])


{
String str1, str2;

str1 = "Geeks";
str2 = "geeks";
equalIgnoreCaseUtil(str1, str2);

str1 = "Geek";
str2 = "geeksforgeeks";
equalIgnoreCaseUtil(str1, str2);
}

Output: 
EXPERIMENT NO.13
AIM: Create a class Book with the following information. Member variables : name (String),
author (of the class Author you have just created), price (double), and qtyInStock (int)
[Assumption: Each book will be written by exactly one Author]
Parameterized Constructor: To initialize the variables Getters and Setters for all the member
variables

In the main method, create a book object and print all details of the book (including the author details)
CODE:
package database;
public class Book
{
public String title;
public String author;
public int year;
public String publisher;
public double cost;
public Book(String title,String author,int year,String publisher,double cost)
{
this.title=title;
this.author=author;
this.year=year;
this.publisher=publisher;
this.cost=cost;
}
public String getTitle()
{
return title;
}
public String getAuthor()
{
return author;
}
public int getYear()
{
return year;
}
public String getPublisher()
{
return publisher;
}
public double getCost()
{
return cost;
}
public void setTitle(String title)
{
this.title=title;
}

public void setAuthor(String author)


{
this.author=author;
}
public void setYear(int year)
{
this.year=year;
}
public void setPublisher(String publisher)
{
this.publisher=publisher;
}
public void setCost(double cost)
{
this.cost=cost;
}
public String toString()
{
return "The details of the book are: " + title + ", " + author + ", " + year + ", " + publisher + ", " +
cost;
}
}
EXPERIMENT NO.15
AIM: WAP in java that implements method overloading. 17. WAP that shows passing object as
parameter. 1
CODE:
public class Box
{
int length,breadth,height;
Box()
{
length=breadth=height=2;
System.out.println("Intialized with default constructor");
}
Box(int l, int b)
{
length=l; breadth=b; height=2;
System.out.println("Initialized with parameterized constructor having 2 params");
}
Box(int l, int b, int h)
{
length=l; breadth=b; height=h;
System.out.println("Initialized with parameterized constructor having 3 params");
}
public int getVolume()
{
return length*breadth*height;
}
public static void main(String args[])
{
Box box1 = new Box();
System.out.println("The volume of Box 1 is :"+ box1.getVolume());
Box box2 = new Box(10,20);
System.out.println("Volume of Box 2 is :" + box2.getVolume());
Box box3 = new Box(10,20,30);
System.out.println("Volume of Box 3 is :" + box3.getVolume());}}
EXPERIMENT NO.16

AIM: WAP in java to show that the value of non static variable is not visible to all the instances, and
therefore cannot be used to count the number of instances.

CODE:

class variable {  
int number;  
public static void increment()  
 {  
  number++;  
  }  
}  
class StaticExample {  
 public static void main(String args[])  
{  
 variable var1 = new variable();  
variable var2 = new variable();  
variable var3 = new variable();  
 var1.number = 12;  
var2.number = 13;  
var3.number = 14;  
 variable.increment();  
System.out.println(var1.number);  
System.out.println(var2.number);  
System.out.println(var3.number);  
 }  
}  
EXPERIMENT NO.17

AIM: Create a class Shape and override area() method to calucate area of rectangle, square and
circle

CODE:

class OverloadDemo
{
void area(float x)
{
System.out.println("the area of the square is "+Math.pow(x, 2)+" sq units");
}
void area(float x, float y)
{
System.out.println("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
System.out.println("the area of the circle is "+z+" sq units");
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
ob.area(5);
ob.area(11,12);
ob.area(2.5);
}
}
EXPERIMENT NO.18

AIM: Create a class Student with non-static variable name and static variable Course. Create 3
objects of class ,store and display information.

CODE:

class Student{
int rollno;//instance variable
String name;
static String college ="Galgotias University";//static variable
Student(int r, String n){
rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}


}
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Himanshu");
Student s2 = new Student(222,"Mukul");
s1.display();
s2.display();
}
}
EXPERIMENT NO.19

AIM: WAP in java to demonstrate the properties of public private and protected variables and
methods(with package).

CODE:

Private access modifier

The scope of private modifier is limited to the class only.

1. Private Data members and methods are only accessible within the class
2. Class and Interface cannot be declared as private
3. If a class has private constructor then you cannot create the object of that class from
outside of the class.

Let’s see an example to understand this:

Private access modifier example in java

This example throws compilation error because we are trying to access the private data member and
method of class ABC in the class Example. The private data member and method are only accessible
within the class.

class ABC{
private double num = 100;
private int square(int a){
return a*a;
}
}
public class Example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
Output:

Protected Access Modifier

Protected data member and method are only accessible by the classes of the same package and the
subclasses present in any package. You can also say that the protected access modifier is similar to
default access modifier with one exception that it has visibility in sub classes.
Classes cannot be declared protected. This access modifier is generally used in a parent child
relationship.

Protected access modifier example in Java

In this example the class Test which is present in another package is able to call
the addTwoNumbers() method, which is declared protected. This is because the Test class extends
class Addition and the protected modifier allows the access of protected members in subclasses (in
any packages).
Addition.java

package abcpackage;
public class Addition {

protected int addTwoNumbers(int a, int b){


return a+b;
}
}
Test.java

package xyzpackage;
import abcpackage.*;
class Test extends Addition{
public static void main(String args[]){
Test obj = new Test();
System.out.println(obj.addTwoNumbers(11, 22));
}
}
EXPERIMENT NO.21

AIM: WAP in javato show autoboxing and unboxing

CODE:

class BoxingExample1
{  
 public static void main(String args[])
{  
 int a=50;  
Integer a2=new Integer(a); 
 Integer a3=5
 System.out.println(a2+" "+a3);  
 }   
}  
      
EXPERIMENT NO.23

AIM: a)Create a class named ‘Animal’ which includes methods like eat() and sleep().

Create a child class of Animal named ‘Bird’ and override the parent class methods. Add a new
method named fly().

Create an instance of Animal class and invoke the eat and sleep methods using this object.

Create an instance of Bird class and invoke the eat, sleep and fly methods using this object.
Inheritance

CODE:

class Animal {
public void eat(){
System.out.println("eat method");

}
public void sleep(){
System.out.println("sleep method");
}
}
class Bird extends Animal{
public void eat(){
super.eat();
System.out.println("overide eat");
}
public void sleep()
{
super.sleep();
System.out.println("override sleep");
}

public void fly() {


System.out.println("in fly method");

}
}
class Animals
{
public static void main(String[] args)
{
Animal a =new Animal();
Bird b = new Bird();
a.eat();
a.sleep();
b.eat();
b.sleep();
b.fly();
}
}

EXPERIMENT NO.24

AIM: WAP that illustrates method overriding

CODE:

class Vehicle
{  
void run(){System.out.println("Vehicle is running");}  
}  
  
class Bike2 extends Vehicle{  
void run(){System.out.println("Bike is running safely");}  
public static void main(String args[]){  
Bike2 obj = new Bike2();  
  obj.run();
  }  
}  
EXPERIMENT NO.25(a)

AIM: WAP in java for abstract class to find areas of different shapes .

CODE:

import java.util.*;
abstract class Diagram
{
        private int d1,d2;
        abstract public void areaCalculation();
        public void readData()
        {
                Scanner sin=new Scanner(System.in);
                System.out.println("Enter two dimensions:");
                d1=sin.nextInt();
                d2=sin.nextInt();
        }
        public void displayData()
        {
                System.out.println("D1:"+d1+"\nD2:"+d2);
        }
        public int getD1()
        {
                return d1;
        }
        public int getD2()
        {
               return d2;
        }
}
class Rectangle extends Diagram
{
        private int area;
        public void areaCalculation()
        {
                int x=super.getD1();
                int y=super.getD2();
                area=x*y;
        }
        public void displayData()
        {
                super.displayData();
                System.out.println("Area:"+area);
        }}
class Triangle extends Diagram{
        private int area;
        public void areaCalculation()
        {
           int x=super.getD1();
                int y=super.getD2();
                area=(1/2)*x*y;
        }
        public void displayData()
        {
                super.displayData();
                System.out.println("Area:"+area);
        }}
class Ellipse extends Diagram{
        private int area;
        public void areaCalculation()
        {
                int x=super.getD1();
                int y=super.getD2();
                area=(1/2)*x*y;
        }
        public void displayData()
        {
      super.displayData();
                System.out.println("Area:"+area);
        }}
public class Draw{
        public static void main(String args[])
        {
                Scanner sin=new Scanner(System.in);
                Diagram d1;
                int ch;
                do
                {
                        System.out.println("1.RECTANGLE(default)");
                        System.out.println("2.TRIANGLE");
                        System.out.println("3.ELLIPSE");
                        System.out.print("Enter ur choice:");
                        ch=sin.nextInt();
                        switch(ch)  {
                                case 1:
                                        d1=new Rectangle();
            break;
                                case 2:
                                        d1=new Triangle();
                                        break;
                                case 3:
                                        d1=new Ellipse();
                                        break;
                                default :
                                        d1=new Rectangle();
                                        System.out.println("Enter correct Choice");
                                        break;
                        }
                        d1.readData();
                        d1.areaCalcultion();
                        d2.displayData();
                        System.out.print("Do u want to continue(y-1)(n-0):");
                        ch=sin.nextInt();
                }while(ch==1);
        }}

EXPERIMENT NO.25(b)

AIM: Write an interface called Playable, with a method void play();

CODE:

package live;

import music.Playable;

import music.string.Veena;

import music.wind.Saxophone;

public class Test {

public static void main (String[]args) {

Veena v = new Veena();

v.play();

Playable pv = new Veena();

pv.play();

Saxophone s = new Saxophone();

s.play();

Playable ps= new Saxophone();

ps.play();

}
}

package music;

public interface Playable {

void play();

package music.string;

import music.Playable;

public class Veena implements Playable {

public void play() {

System.out.println("Veena Plays");

package music.wind;

import music.Playable;

public class Saxophone implements Playable{

public void play() {

System.out.println("SaxophonePlays");

}
EXPERIMENT NO.26(a)

AIM: WAP in java demonstrating arithmetic exception and ArrayOutOf Bounds Exception using try
catch block

CODE:

class Example1
{
public static void main(String args[])
{
int num1, num2;
try
{

num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e)
{

System.out.println("You should not divide a number by zero");


}
catch (Exception e) {

System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:
EXPERIMENT NO.26(b)

AIM: WAP in java to demonstrate the use of nested try block and nested catch block.

CODE:

public class NestedTryBlock2 {  

    public static void main(String args[])  
  {  
    try {  
    try {  
    try {  
               int arr[] = { 1, 2, 3, 4 };  
System.out.println(arr[10]);  
      }  
catch (ArithmeticException e) {  
System.out.println("Arithmetic exception");  
System.out.println(" inner try block 2");  
  }  
 }  
            catch (ArithmeticException e) {  
System.out.println("Arithmetic exception");  
System.out.println("inner try block 1");  
       }   }  
        catch (ArrayIndexOutOfBoundsException e4) {  
 System.out.print(e4);  
System.out.println(" outer (main) try block");  
        }  
        catch (Exception e5) {  
          System.out.print("Exception");  
System.out.println(" handled in main try-block");  
        }  
    }  
}  

Output:

EXPERIMENT NO.27

AIM: WAP in java to demonstrate the use of throw and throws

CODE:

class Main

public static void divideByZero()

throw new ArithmeticException("Trying to divide by 0");

public static void main(String[] args)

divideByZero();

}
EXPERIMENT NO.28

AIM: Write a program to count the number of times a character appears in a File.

CODE:

// Java program to count the


// number of lines, words, sentences,
// characters, and whitespaces in a file
import java.io.*;

public class Test {


public static void main(String[] args)
throws IOException
{
File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt");
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String line;
int wordCount = 0;
int characterCount = 0;
int paraCount = 0;
int whiteSpaceCount = 0;
int sentenceCount = 0;

while ((line = bufferedReader.readLine()) != null) {


if (line.equals("")) {
paraCount += 1;
}
else {
characterCount += line.length();
String words[] = line.split("\\s+");
wordCount += words.length;
whiteSpaceCount += wordCount - 1;
String sentence[] = line.split("[!?.:]+");
sentenceCount += sentence.length;
}
}
if (sentenceCount >= 1) {
paraCount++;
}
System.out.println("Total word count = "+ wordCount);
System.out.println("Total number of sentences = "+ sentenceCount);
System.out.println("Total number of characters = "+ characterCount);
System.out.println("Number of paragraphs = "+ paraCount);
System.out.println("Total number of whitespaces = "+ whiteSpaceCount);
}
}

EXPERIMENT NO.29

AIM: Write a program to copy contents from one file to another and check the output.

CODE:
import java.io.*;
import java.util.*;
public class CopyFromFileaToFileb
{
public static void copyContent(File a, File b)
throws Exception
{
FileInputStream in = new FileInputStream(a);
FileOutputStream out = new FileOutputStream(b);
Try
{
int n;
while ((n = in.read()) != -1) {
out.write(n);
} }
Finally
{
if (in != null)
{
in.close();
}
if (out != null) {
out.close();
} }
System.out.println("File Copied");
}
public static void main(String[] args) throws Exception
{
Scanner sc = new Scanner(System.in);
System.out.println( "Enter the source filename from where you have to read/copy :");
String a = sc.nextLine();
File x = new File(a);
System.out.println( "Enter the destination filename where you have to write/paste :");
String b = sc.nextLine();
File y = new File(b);
copyContent(x, y);
}
}

EXPERIMENT NO.30

AIM: WAP in java in two different ways that creates a thread by (i)extending thread class(ii)
implementing runnable interface which displays 1st 10 natural numbers.

CODE:

class MyThread implements Runnable


{
String name;
Thread t;
MyThread (String thread)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start();
}

public void run() {


try {
for(int i = 5; i > 0; i--)
{
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}

class MultiThread
{
public static void main(String args[])
{
new MyThread("One");
new MyThread("Two");
new NewThread("Three");
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
EXPERIMENT NO.31

AIM: WAP in java which demonstrate the lifecycle methods of thread.

CODE:

class ABC implements Runnable


{
public void run()
{
try
{
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t1 while it invoked the method join() on thread t2 -"+
ThreadState.t1.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}

public class ThreadState implements Runnable


{
public static Thread t1;
public static ThreadState obj;
public static void main(String argvs[])
{
obj = new ThreadState();
t1 = new Thread(obj);
System.out.println("The state of thread t1 after spawning it - " + t1.getState());
t1.start();
System.out.println("The state of thread t1 after invoking the method start() on it - " + t1.getState());
}
public void run()
{
ABC myObj = new ABC();
Thread t2 = new Thread(myObj);

System.out.println("The state of thread t2 after spawning it - "+ t2.getState());


t2.start();
System.out.println("the state of thread t2 after calling the method start() on it - " + t2.getState());
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 after invoking the method sleep() on it - "+
t2.getState() );
try
{
t2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it's execution - " + t2.getState());
} }
EXPERIMENT NO.32

AIM: Create TreeSet, HashSet, LinkedHashSet. Add same integer values in all three. Display all
three set and note down the difference.

CODE:

package my.app;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
public class DeduplicationWithSetsBenchmark {
static Item[] inputData = makeInputData();
public int deduplicateWithHashSet() {
return deduplicate(new HashSet<>());
}
public int deduplicateWithLinkedHashSet() {
return deduplicate(new LinkedHashSet<>());
}
public int deduplicateWithTreeSet() {
return deduplicate(new TreeSet<>(Item.comparator()));
}

private int deduplicate(Set<Item> set)


{
for (Item i : inputData)
{
set.add(i);
}
return set.size();
}

public static void main(String[] args) throws RunnerException


{
DeduplicationWithSetsBenchmark x = new DeduplicationWithSetsBenchmark();
int count = x.deduplicateWithHashSet();
assert(count < inputData.length);
assert(count == x.deduplicateWithLinkedHashSet());
assert(count == x.deduplicateWithTreeSet());

Options opt = new OptionsBuilder()


.include(DeduplicationWithSetsBenchmark.class.getSimpleName())
.forks(1)
.build();

new Runner(opt).run();
}

private static Item[] makeInputData() {


int count = 1000000;
Item[] acc = new Item[count];
Random rnd = new Random();

for (int i=0; i<count; i++) {


Item item = new Item();
// We are looking to include a few collisions, so restrict the space of the values
item.name = "the item name " + rnd.nextInt(100);
item.id = rnd.nextInt(100);
acc[i] = item;
}
return acc;
}

private static class Item {


public String name;
public int id;

public String getName() {


return name;
}

public int getId() {


return id;
}
public boolean equals(Object obj) {
Item other = (Item) obj;

return name.equals(other.name) && id == other.id;


}
public int hashCode()
{
return name.hashCode() * 13 + id;
}

static Comparator<Item> comparator()


{
return Comparator.comparing(Item::getName, Comparator.naturalOrder())
.thenComparing(Item::getId, Comparator.naturalOrder());
}
}
}

EXPERIMENT NO.33

AIM: WAP in java WAP in java and run applications that use "List" Collection objects

CODE:

import java.util.*;

public class ArrayListExample1

public static void main(String args[])

ArrayList<String> list=new ArrayList<String>();

list.add("Mango");

list.add("Apple");

list.add("Banana");

list.add("Grapes");

System.out.println(list);

}
}

EXPERIMENT NO.34

AIM: Create a HashMap<Rollno, Name>. Display Map, take rollno from user and display name.

CODE:
import java.util.*;
import java.io.*;
public class Main
{
public static class Student
{
private int rollno;
private String name;
public Student(int rollno, String name)
{
this.rollno = rollno;
this.name = name;
}

public String getname()


{
return this.name;
}

public int getmarks()


{
return this.rollno;
}

public void setname(String name)


{
this.name = name;
}

public void setmarks(int rollno)


{
this.rollno = rollno;
}
public int hashCode()
{
final int temp = 14;
int ans = 1;
ans = temp * ans + rollno;
return ans;
}

public boolean equals(Object o)


{
if (this == o) {
return true;
}
if (o == null) {
return false;
}
if (this.getClass() != o.getClass()) {
return false;
}
Student other = (Student)o;
if (this.rollno != other.rollno) {
return false;
}
return true;
}
}
public static void main(String[] args) throws NumberFormatException, IOException
{
HashMap<Student, String> map = new HashMap<>();

Student one = new Student(1, "Himanshu"); // key1

Student two = new Student(2, "Mukul"); // key2


map.put(one, one.getname());
map.put(two, two.getname());
one.setname("Not Geeks1");
two.setname("Not Geeks2");
System.out.println(map.get(one));
System.out.println(map.get(two));
Student three = new Student(1, "Geeks3");
System.out.println(map.get(three));}}
EXPERIMENT NO.35

AIM: WAP to do CRUD operation in java

CODE:

import java.util.*;
import java.sql.*;
public class EmpDao
{
public static Connection getConnection()
{
Connection con=null;
Try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
}
catch(Exception e){System.out.println(e);}
return con;
}
public static int save(Emp e)
{
int status=0;
try
{
Connection con=EmpDao.getConnection();
PreparedStatement ps=con.prepareStatement( "insert into
user905(name,password,email,country) values
(?,?,?,?)");
ps.setString(1,e.getName());
ps.setString(2,e.getPassword());
ps.setString(3,e.getEmail());
ps.setString(4,e.getCountry());
status=ps.executeUpdate();
con.close();
}
catch(Exception ex){ex.printStackTrace();
}

return status;
}
public static int update(Emp e)
{
int status=0;
try
{
Connection con=EmpDao.getConnection();
PreparedStatement ps=con.prepareStatement( "update user905 set
name=?,password=?,email=?,country=?
where id=?");
ps.setString(1,e.getName());
ps.setString(2,e.getPassword());
ps.setString(3,e.getEmail());
ps.setString(4,e.getCountry());
ps.setInt(5,e.getId());

status=ps.executeUpdate();
con.close();
}
catch(Exception ex){ex.printStackTrace();}
return status;
}
public static int delete(int id){
int status=0;
try
{
Connection con=EmpDao.getConnection();
PreparedStatement ps=con.prepareStatement("delete from user905 where id=?");
ps.setInt(1,id);
status=ps.executeUpdate();

con.close();
}
catch(Exception e){e.printStackTrace();
}

return status;
}
public static Emp getEmployeeById(int id)
{
Emp e=new Emp();

try{
Connection con=EmpDao.getConnection();
PreparedStatement ps=con.prepareStatement("select * from user905 where id=?");
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
if(rs.next()){
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setPassword(rs.getString(3));
e.setEmail(rs.getString(4));
e.setCountry(rs.getString(5));
}
con.close();
}catch(Exception ex){ex.printStackTrace();}

return e;
}
public static List<Emp> getAllEmployees(){
List<Emp> list=new ArrayList<Emp>();

try{
Connection con=EmpDao.getConnection();
PreparedStatement ps=con.prepareStatement("select * from user905");
ResultSet rs=ps.executeQuery();
while(rs.next()){
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setPassword(rs.getString(3));
e.setEmail(rs.getString(4));
e.setCountry(rs.getString(5));
list.add(e);
}
con.close();
}
catch(Exception e){e.printStackTrace();
}
return list;
}
}

You might also like