Likes

Java Lab_10_Ans_1

Write a program to accept two numbers and perform division, the program should provide the functionality such that if a usertries to divide the number by 0, the program should terminate with a customized message.

SOLUTION





import java . util . Scanner;

public class Divison {

 public static void main (String args []) {
   
  int num1, num2, result;
  Scanner input = new Scanner (System . in);
  System.out.println ("Enter the 1st number");
  num1 = input . nextInt ();

 System.out.println ("Enter the 2nd number");

 num2 = input . nextInt ();

 try {

   result = num1 / num2;
   System.out.println ("The result is " + result);

 } catch (ArithmeticException e) {

 System,out.println ("Divison by zero not Possible! ");
  }

 }

}

java Lab09_Solution2.

David has been assigned a task of creating an application to store the employee details. For this, David decided to display the following menu when the application starts:

1.  Entry Data
2.  Display Data
3.  Exit

Thereafter, he decides to implement the following functionalities:

-When a user selects the option to entry data, the employee details. such as employee ID, employee name, department, designation, date of joining, date of birth, marital status, and date of marrige, should be captured. In addition, a functionality to add more records should be implemented.

-When a user selects the option to display the data, the stored data muust be displayed.

-When a user selects the option to exit, the application must be terminated. Further, David needs to implement user- defined exceptions for the following cases:

- If the menu input entered by the user is other than1,2,or3, an appropriate message should be displayed to the user and the application must restart.

- If the employee ID does not start with the aplhabet, e or E, an appropriate message should be displayed to the user and the application must terminate.

Help David to implement the preceding functionalities.


SOLUTION


1- Create a Java application, Lab09_Solution2.
2- Create a class, SelectionExeption, in the Java application, Lab09_Solution2.
3- Replace the exiting code in the SelectionException.java file with the following code:

class SelectionException extands Exception  {

selectionException ()   {
System.out.println("Invalid input, Please select a valid menu option");

}
}
4- Create a class, PatternException, in the Java application, Lab09_Solution2.
5- Replace the exisiting code in the PatternException.java file with the following code:

public class PatternException extends RuntimeException  {

public PatternException()  {

System.out.println("Invalid pattern for Employee ID...");
}

public PatternException(String msg)   {
super(msg);
}
}
6- Create a class, EmployeeDetails, in the Java application,Lab09_Solution2.
7- Replace the existing code in the EmployeeDetails.java file with the following code:

import java.until.Scanner;

public class EmployeeDetails  {

String employeeDetails[] [] = new String[100] [8];

public void showMenu () throws SelectionException  {
   int option;
Scanner sc = new Scanner (System.in);

System.out.println("----------Menu--------");
System.out.println("1. Entry Data");
System.out.println("2. Display Data");
System.out.println("3. Exit");
System.out.print("\nchoose the option: ");

option = sc.nextInt() ;

Java Lab_8_Ans_5

CREATE A PROGRAM THAT SEARCHES A TEXT FILE BY USING REGULAR EXPRESSIONS.


SOLUTION


Create a simple applications that will loop through a text file(gettys.html) and search for
text by using regular expresions. If the desired text found on a line, print out the line number
and the line text.
9 <h4>Abrahan Lincoln</h4>
10 <h4>Thrusday, November 19, 1863</h4>

Tasks
 The gettys.html file is located in the root of the project folder. To examine the file,
with the project open, click the file tab. Double-click the file to open it and exmaine its
content.
   1. Edit teh FindText.java file.
   2. Create a pattern and a Matcher field.
   3. Generate a Matcher based on the supplied Pattern object.
   4. Search each line for the pattern supplied.
   5. Print the line numver and the line that has matching text.
   6. Run the FindText.java file and search for these patterns.
              All lines that contain <h4>
              All the ines that contain the word "to" (For example, line 17 should
              not be selected.)
              All the lines that start with 4 spaces'
              Lines that bedin with "<p" or "<d"
              Lines that only contain HTML closing tags( for example, "</div>")
                 
Open the StringPractice02 project and make the followng changes. Please note that the
code to read a file has been supplied for you.
    1. Edit the FindText.java file.
    2. Create fields for a Pattern and a Matcher object
       private Pattern pattern;
       private Matcher m;
    3. Outside the search loop, create and initialize your pattern object.
       pattern = pattern.compile("<h4>");
    4. Inside the search loop, generate a Matcher based on the supplied Pattern
       object.
      m = pattern.matcher(line);
    5. Inside the search loop, search each line for the pattern supplied. print the line
       number and the line that has matching text.
       if (m.find() )  {
           System.out.println(" " + " "+ line);
       }
   6. Run the FindText.java file and search for these patterns.
              All the lines that contain <h4>
              pattern = Pattern.compile("<h4>");
             
             All the lines that contain the word "to" (For example, line 17 should
             not be selected.)
     
             pattern = Pattern.compile("\\bto\\b"0;
       
             All the lines that start with 4 spaces
             
            pattern = Pattern.compile("^\\s{4}");

            Lines that begin with "<p" or "<d"
 
            pattern = Pattern.compile("^<[p|d]");

            Lines that only contain HTML closin tags(For example, "</div>")
 
            pattern = Pattern.compile("^</.*?>$");

Java Lab_8_Ans_4

Paras comma-delimited text and convert the data into Shirt objects.

SOLUTION



you have been given some comma-delimated shirt data . parse the data . store it in shirt
objects and print the results. the output from the program should like the following.

=== Shirt List ===

Shirt ID: S001

Description: Black Polo Shirt

Color: Black

Size: XL

Shirt ID: S002

Description: Black Polo Shirt


Color: Black

Size: L

Shirt ID: S003

Description: Blue Polo Shirt

Color: Blue

Size: XL

Shirt ID: S004

Description: Blue Polo Shirt

Color: Blue

Size: M

Shirt ID: S005

Description: Tan Polo Shirt

Color: Tan

Size: XL

Shirt ID: S006

Description: Black T-Shirt

Color: Black

Size: XL

Shirt ID: S007

Description: White T-Shirt

Color: White

Size: L

Shirt ID: S008

Description: White T-Shirt

Color: White

Size:L

Open the StringPractice01 project and make the following changes.

1 Edit the main method of the StringSplitTest . java file.

2 Parse each line of the shirts array. Create a shirt object for each
  line and add the shirts to a List. A for loop tp perform
  these steps could be as follows.

   for (Stirng curLine:shirts){
     String[] e = curLine . split(",");
     shirtList . add(new Shirt(e[0], e[1], e[2], e[3] ) );
  }

3 Print out the list of shirts. A loop to do this could be like the
  following.

  System.out.println("=== Shirt List ===");
  for (Shirt shirt:shirtsList){
    System.out.println(shirt . toString() );
  }

4 Run the StringSplitList . java file and verify that your output is similar

Java Lab_8_Ans_3

Write a program to accept the date from the user and validateit according to the format, DD/MMYYYY or D/M/YYYY. In addition, the year should be from 1900 to 2099.


SOLUTION



import java . util . Scanner;
import java . util . regex . Matcher;
import java . util . regex . Pattern;

 public class DateValidator {

 private Pattern pattern;
 private Matcher matcher;
 private static final String DATE_PATTERN = " (0 ? [1-9] | [12] [0-9] | 3 [01] ) / (0 ? [1-9] | [012] ) /
             ( ( 19 | 20) \\ d\\d)";
     public DateValidator () {
       pattern = Pattern . compile (DATE _ PATTERN);
  }
   
     public boolen validate (final String date) {
 
     matcher = pattern . matcher(date);

     if (matcher . matches () ) {
   
        matcher . reset ();

     if (matcher . find () ) {

          String day = matches . group (1);
          String month = matcher . group (2);
          int year = Integer . parseInt (matcher . group
     (3) );
            if (day . equals ("31")
                   && (month . equals ("4") ||
   month . equals ("6") || month . equals ("9")
         
       || month . equals ("11") || month . equals ("04") || month . equals ("11") .
       
        || month . equals ("09") ) ) {
       return false; // only 1,3,5,7,8,10,12 has 31 days
        } else if (month . equals ("2") ||
   month . equals (:02") ) {
                              // leap year
                            if (year % 4 == 0) {
                            if (day . equals ("30") ||
           ("31") ) {
                          return false;
                      } else {
                                return true;
                      } else {
                             if (day . equals ("29") || day . equals
               ("30") || day . equals ("31") ) {
                                               return false;
                                             } else {
                                                   return true;
                                             } else {
                                          }
                                       }
                                 } else {
                                       return true;
                                    }
                               } else {
                            }
                                 return false;
                        }
                              } else {
                                  return false;
                           }
                       }
                             
                       public static void main (String [] args) {
                        DateValidator dv = new ateValidator ();
                         boolen status;
                          do {
                               Scanner sc = new Scanner (System. in);
                               String dt;

                               System.out.println ("Enter the date: ");
                               dt = sc . next ();
                       
                               status = dv . validate (dt);
                                if (status) {
                                      System.out.println ("Date is in correct format");
                                          } else {
                                              System.out.println ("Date is not in correct format");
                                            }
                                         } while (status == false);
                                    }
                                }      







                          

Java Lab_8_Ans_2

Write a program to accept a three letter word as an input from the message, Expression Matched, if the world starts with ,"a","b","c", and ends with, "at".Solution


import java . util . Scanner;
import java . util . regex . Matcher;
imort java  . util . regex . Pattern;

 public class TestRegx {

 public static void main (String [] args) {
 Scanner sc = new Scanner (System . in);
 String input;

 System.out..print ("Enter the string: ");
 input = sc . next ();
 Pattern myPattern = Pattern . compile (" [abc] at");
 Matcher myMatcher = myPattern . matcher (input);
 boolen  myBoolen  = myMatcher . matches ();
 if (myBoolen) {
      System.out.println ("Expression is Matched");
    } else {
      System.out.println ("Expression Not Matched");
    }
  }

}




Java Lab_8_Ans_1

Write a program that the URL of the Web portal from the user, such as http://www.xyx.com,or ftp://xyz.com,and validate the format of the URL with the following fields:
- Protocol, such as https or http
-Domin, such as google or yahoo
-Top level domain, such as.co or .com

SOLUTION



import java . util . Scanner;
import java . util . regex . Matcher;
import java . util . regex . Pattern;

class UrlChecker {

 public static void main (String [] args) {
   pattern Mypattern = Pattern . compile ("^ ( (https ? |
 ftp) : // | (www | ftp) \\ .) [ a-zO-9-] + [a-z] + ) + ( [/ ?] . *) ?$" );
      Scanner input = new Scanner (System . in);
      System.out.println ("Enter the Url  to be checked:
  ");
      String name = input . nextLine ();
      Matcher Mymatcher = Mypattern . matcher (name);
      Boolen Myboolen = Mymatcher . matches ();
      if (Myboolen == true) {
          System.out.println ("Url is correct");
       } else {
          System.out.println ("Url is incorrect");
     }
  }

}

Java Lab_7_Ans_4

Write a program to store the student details, such as name and marks. In addition, you need to 

implement the functionality that helps in sorting the details according to name and marks, 

separately. For this, you need to implement  two different logics. One will sort the details 

according to the name in assending  order, and other will sort the details according to the 

marks in ascending order.



Solution


Public class Student implements Comparable  {


private String name;
private int marks;

public Student (String nm, int mk)  {
this.name = nm;
this.marks = mk;
}

public int getMarks()   {
return marks;
}

public void getName()  {
return name;
}

public void setName(String name)  {
this.name = name;
}

public int compareTo (Object obj)  {
Student s = (Student) obj;

if (this.marks > s.getMarks())  {
    return 1;
} else if (this.marks < s.getMarks())  {
    return -1;
} Else {
    return 0;
}
}
public String toString()  {
StringBuffer buffer = new StringBuffer();
buffer.append("Name: " + name + "\n");
buffer.append("Marks: " + marks + "\n");
return buffer.toString();
}
}


import Java.until.Comparator;
public class NameCompare implements Conparator{
public int compare(Object a, Object b)
{
Student x = (Student) a;
Student yx = (Student) b;
return x.getName() .compareTo(y.getName());
}
}


import java.until.ArrayList;
import java.until.Collections;
import java.until.ListIterator;

public class Sorting  {

public static void main (String[]  args)  {
Student s1 = new Student("Joe",88);
Student s2 = new Student("Bob",90);
Student s1 = new Student("Alex",78);

ArrayList<Student> obj = new ArrayList<>();
obj.add(s1);
obj.add(s2);
obj.add(s3);

System.out.println("Student details are:");

ListIterator li = obj.listIterator();
while (li.hasNext())   {
  System.out.println(li.next());
}

collection.sort(obj);

System,out.println("Mark wise sort:");

ListIterator li2 = obj.listIterator();
while (li2.hasNext())
  System.out.println(li2.next());
}
Collection.sort(obj, new NameCompare());

System.out.println("Name wise sort:");

ListIterator li3 = obj.listIterator();
while (li3.hasNext())  {
  System.out.println(li3.next());
}
}
}

Java Lab_7_Ans_3

Kiwi Inc. is a leading software development company in the US. The top managment of the organization has found that the Help Desk division does not handle queries or issues of the employees on a priority basis. For this, the top managment has decided to automate the tasks of the help Desk division. Therefore the managment has assigned this task to the development team to create an application that has the following functionalities:

- Application must enable employees to log their requests or issues.
-Application must enable the team of the Help Desk division to handle queries on the first come first served basis.

The development team has assigned the task to john, the Senior Software Developer. However, in the initial phase of development, John needs to create the user interface and creat the application only for a single user. Help John to achieve the preceding requirement.


Solution


import java.until.ArrayDequr;

public class Request  {

ArrayDeque<String> pool;

public Request()   {
    pool = new ArrayDeque<String>();
}

public void initRequest(String i, String p)   {
String ID = i;
String prb = p;

String rqt = "Empliyee ID: " + ID +"\nProblem: " + prb;
pool.add(rqt);

}

public void dispRequest()   {
System.out.println
("================================================================");
System.out.println("-----------------------REQUEST POOL-------\n");

if (pool.isEmpty () == true) {
           System.out.println ("Currently, there is no request in the pool.");
        }
           else
        {
             for (String s : pool) {
             System.out.println (s);
             System.out.println
      ("--------------------------------------------");
    }
 }

}
      public void attdRequest () {
       String status;
   
     if (pool . isEmpty () == true) {
         System.out.println
   ("=====================================================");
     System.out.println ("Currently, there is no request in the pool.");
      } else {
           System.out.println
   ("=====================================================");
      System.out.println ("You need to resolve yhr following problem:");
        System.out.print(pool . getFirst () );
     
        status = "R";
   
      if (status . toUpperCase () . equals ("R") ) {
           System.out.println
    ("======================================================");
       System.out.println ("The problem has been resolved:");
         System.out.println (pool . getFirst () );
          pool . remove ();
     } else if (status . toUpperCase () . equals ("P") ) {
         System.out.println
   ("\n=======================================================");
         System.out.println ("Please resolve the problem ASAP .");
           } else {
              status = "N";
        }
    }
}
   
     public static void main (String [] args) {
        Request rq = new Request ();
        rq . initRequest ("3423", "System is not working");
        rq . initReuest (" 3764", "Internet is not working");
        rq . dispRequest ();
        rq . attdRequest ();
    }
}          

Java Lab06_Ans3

Take an existing application and refactor it to make use of composition.


solution

1 open the petcomposition project as the main project.
 a select file > open project.
 b browse t d:\labs\06-interfaces\practices.
 c select petcomposition and select the "open as main project chek box.
 d click the open project button.

2 expand the project diretories.

3 run the project. you should see output in the output window.

4 centralize all <name> functionality.
  a create a nameable interface (under the com.example package).
  b complete the nameable interface with setname and getname method signatures.
         public interface nameable {
         
         public void setname(string name);
     
        public string getname();
   }

c create a nameableimpl class (under the com.example package).

d complete the nameableimpl class. it should
  1 implement the nameable interface.
  2 contain a private string field called name.
  3 only accept names less than 20 characters in length.
  4 print "name too long " if a name is too long.

e modify the pet interface.
  1 extend the nameable interface.
  2 remove the getname and setname method signatures (they are inherited now).

f modify the fish and cat classes to use composition.
  1 delete the name field.
  2 delete exitsing getname and setname methods.
  3 add a new nameable field.

5 centralize all walking functionally.

6 modify the petmain class to test the walk method. the walk method can only be called on spider.

Java Lab06_Ans1

Use the HashMap collection to Count a list of part numbers.

Solution

1 open the genrics-practices project and make the following changes.

for the productcounter class and two private map field.

private map<stirng,long> productcountmap = new hashmap<> ();
private map<string,string> product names = new treemap<> ();

create a one argument constructor thyat accepts a map as a parameter.
  public productcounter (map productnames) {
    this.productname = productnames;
}

3 create a processlist() method to process a list of string part number.
   public void processlist(string[] list) {
      long curval = 0;
   
      for(string itemnumber : list) {
          curval = productcountmap.containskey(itemnumber) ) {
            productountmap.put (itemnumber,new long(1) );
      }
         else
    {
        productcountmap.put(itemnumber,new long (curval) ) ;
 }

}

}
  

IMPORTANT NOTES OF SQL

Q.1 what are NULL values? Why should we avoid permitting null values in database?

Ans. A NULL value in a column implies that the data value for the column is not available. It states that the corresponding value is either unknown or undefined.  It is different from zero or "". They should be avoided to avoid the complexity in select & update queries and also because columns which have constraints like primary or foreign key constraints cannot contain a NULL value.

Q.2 Explain the use of the PIVOT and UNPIVOT clauses in SQL server
PIVOT

The pivot  clause is used to transform a set of columns into values. PIVOT rotates a table-valued expression by turning the unique values from one column in the expression into multiple columns in the output. In addition, it performs aggregations on the remaining column values if required in the output. The syntax of the PIVOT operator is:
SELECT* from table_name
PIVOT(aggeration_function (value_column) FOR pivot_column IN (column_list)) table_alias
UNPIVOT
The UNPIVOT operator allows database user to normalize the data that has earlier been pivoted. This operator transforms the multiple column values of a record into multiples records with the same values in a single column.

Q.3 To summarize or group data in database, what kind of various clauses or operators can be used? Explain with definition.

SQL Server provides aggregate functions to generate summarized data.
The syntax of aggregate function is:
SELECT aggregate_function([ALL|DISTINCT] expression) FROM table_name
Following aggregate function are :
Avg(): returns the average of values in a numeric expression, all or distinct
Count(): returns the number of values in an expression.
Min(): returns the lowest value in the expression.
Max(): returns the highest value un the expression.
Sum(): returns the sum total of values in a numeric expression.
To view the summarized data in different in different groups based on specific criteria, you can group the data by using the GROUP BY clauses of the SELECT statement.
The GROUP BY clauses summarizes the result set into groups by using the aggregate functions. The HAVING clauses further restricts the result set to produce data based on a condition.The syntax  of the GROUP BY clauses is:
SELECT column_list FROM table_name WHERE condition [GROUP BY [ALL] expression [, expression] [HAVING search_
condition]

Q.4 What are range operators in SQL server?

Range operators retrieve data based on a range. The syntax for using range operators in the SELECT statement is:
SELECT column_list FROM table_name WHERE expression1 range_operator expression2 AND expression3
Range operators are of the following types:
Between: specifies an inclusive range to search. The following SQL query retrieves records from the employee table where the number of hours that the employees can avail to go on a vacation is between 20 and 50:
SELECT EmployeeID, Vacationhours FROM Humanresources.Employee WHERE Vacationhours BETWEEN 20 AND 50
NOTBETWEEN: excludes the specified range from the result set. The following SQLquery retrieves records from the employee where the numbers of hours that the employees canavail to go on a vacation is not between 40 and 50:
SELECT Employee, Vacationhours FROM Humanresources.employee WHERE Vacationhours NOT BETWEEN 40 AND 50

    Q.5 What is the need of DBCC commands in SQL Server?

The database console commands (DBCC) are a series of statements in transact-SQL programming language to check the physical and logical consistency of a Microsoft SQL Server. These commands are also used to fix existing issues. They are also used for administration and file management.
DBCC have a number of advantages.  Their uses is  extremely essential in some instances
Occasionally, there have been bad allocations of database pages.
Indexes could be destroyed and corrupted easily.
There could misunderstandings on the part of the SQL server engine.
There could be problems when a large number of updates need to be carried out.
Individual pages may lose their optimal storage footprint.

Q.6 what is the difference between truncate, drop, and delete commands?

Ans. TRUNCATE
TRUNCATE removes all rows from a table. The operation cannot be rolled back and no triggers will be fired. As such, TRUNCATE is faster and doesn't use as much undo space as a DELETE.
DROP
The DROP command removes a table from the database. All the tables' rows, indexes and privileges will also be removed. No DML triggers will be fired. The operation cannot be rolled back.
DELETE
The DELETE command is used to remove rows from a table. A WHERE clause can be used to only remove some rows. If no WHERE condition is specified, all rows will be removed. After performing a DELETE operation you need to COMMIT or ROLLBACK the transaction to make the change permanent or to undo it. Note that this operation will cause all DELETE triggers on the table to fire.

Q.7  what are the advantages of using a DBMS?

Ans. The main advantages of using DBMS are:
It designed to maintain large volumes of data.
It provides an efficient and easy way to store, update, and retrieve data from a database.
It manages information about the users who interacts with DBMS and the tasks that users can perform on the data.
It provides data security against unauthorized access.


Q.8  explain the various guidelines that need to be followed while creating views.

Ans while creating views, you should consider the following guidelines:
The name of a view must follow the rules for identifiers and must not be the same as that of the table on which it is based.
A view can be created only if there is a SELECT permission on its base table.
A view cannot derive its data from temporary tables.
In a view, ORDER BY cannot be used in SELECT statement.


Q.9 what are synonyms of SQL. Explain with syntax

Ans  SQL server provides the concept of synonym that is a single-part alias name for a database object with a name, which has multiple parts.
Synonyms provides a layer of abstraction that protects SQL statements from changes made to the database object. you can create a synonym for a database object by using the CREATE SYNONYM statement.
The syntax of the CREATE SYNONYM statement is:
CREATE SYNONYM [schema_name_1.]
Synonym_name FOR <object>
<object>::=
{
[server_name[database_name].[schema_name_2].|database_name. [schema_name_2.] object_name
}

Q. 10 what are DDL and DML statement?

Ans Data Definition Language (DDL): it is used to define the database, data types, structures and constraints on the data.
Some of the DDL  statements are:
CREATE: used to create a new database object, such as a table.
ALTER: used to modify the database objects.
DROP: used to delete the objects.
Data Manipulation Language (DML): it is used to manipulate the data in database objects.
Some of the DML statements are:
INSERT: used to insert a new data record in a table.
UPDATE: used to modify an existing record in a table.
DELETE: used to delete a record from a table.
10 marks

Q.1 what are statistics? How it can be created and updated? Explain with syntax.

Ans  statistics in SQL Server refers to information that the server collects about the distribution of data in columns and indexes. This data , in turn, is used by the query optimizer to determine the execution plan for returning results when you run a query. Statistics is created automatically when you create indexes. In addition, SQL Server creates statistics for columns that do not have indexes defined on them.
SQL Server can automatically create and update statistics. This feature is set to ON by default.
If you need to use statistics on columns that are not indexed in order to create more optimal execution plans, you can manually create and update statistics.
Creating statistics
Statistics can be created on specific columns of a table or view by using CREATE STATISTICS statement.
The syntax of the CREATE STATISTICS is:
CREATE STATISTICS statistics_name ON {table|view} (column [,…n]) [with[[FULLSCAN|SAMPLE NUMBER{PERCENT|ROWS}] [NORECOMPUTE]]]
Update statistics
Statistics can be updated by using the UPDATE STATISTICS statement. You can update the information about the distribution of keys values for one or more statistics groups in the specified table or indexed view.
The syntax of the UPDATE STATISTICS statement is:
UPDATE STATISTICS table|view
[{{index|statistics_name}|({index|statistics_name}[,…n])}]
[WITH[[FULLSCAN]|SAMPLE number {PERCENT|ROWS}]|RESAMPLE]
[[[,]] [ALL|COLOUMNS|INDEX][[,]NORECOMPUTE]]


Q.2 Define Data Manipulation Language (DML). Explain DML statements in SQL Server with syntax.

Ans DML is used to manipulate the data in database objects
Some DML statements are:
INSERT
The smallest unit of data that you can add in a table is a row. You can add a row by using the INSERT statement. The syntax of the INSERT statement is:
INSERT [INTO]{table_name}[(column_list)]
VALUES {DEFAULT|values_list|select_statement}
UPDATE
You need to modify the data in the database when the specification of a customer, a client, a transaction or any other data maintained by the organization undergo a change. You can use the UPDATE DML  statement to make  the changes. The syntax of the UPDATE statement is:
UPDATE table_name
SET column_name = value [, column_name=value]
[FROM table_name]
[WHERE condition]
DELETE
You need to delete data from a database when it is no longer required. Th smallest unit that can be deleted from a database from database is a row.
You can delete a row from a table by using the DELETE DML statement. The syntax of the DELETE statement is :
DELETE[FROM] table_name [WHERE condition]


Q. 3 what are user defined functions? What kind of user defined functions can be created in SQL Server?

Ans similar to stored procedures, you can also create functions to store a set of T-SQL statements permanently. These functions are also referred to as User-Defined Functions (UDFs). A UDF is a database object that contain a asset of T-SQL statements, accept parameters, performs an action, and returns the result of that action as a value. The return value can be either single scalar value or a result set
UDFs are of different types, scalar functions and table-valued functions.
Scalar functions
Scalar functions accept a single parameter and return a single data value of thw type specified in the RETURNS clause. A scalar function can return any data type except text, ntext, image, cursor and timestamp.
A function contains a series of T-SQL statements defined in a BEGIN…END block of the function body that returns a single value.
Table-valued fuctions

Java Lab05_Ans1 Nested class (Example)



public class OuterClass {

public int x = 42;

   
public void method1() {


        class LocalClass {


            public void localPrint() {

                System.out.println("In local class");

                System.out.println(x);

            }

       }

        LocalClass lc = new LocalClass();

        lc.localPrint();
    }


    public void method2() {

        Runnable r = new Runnable() {


            @Override
            public void run() {


                System.out.println("In an anonymous local class method");

                System.out.println(x);

            }

        };

        r.run();
    }
    public Runnable r = new Runnable() {


        @Override

        public void run() {

            System.out.println("In an anonymous class method");

            System.out.println(x);

        }

    };

    Object o = new Object() {


        @Override
        public String toString() {

            return "In an anonymous class method";

        }

    };


    public class InnerClass {


       


        public static final int y = 44;


        public void innerPrint() {

            System.out.println("In a inner class method");

            System.out.println(x);

        }

    }


   



public class NestedClassesMain {

   
    public static void main(String[] args) {

       
        OuterClass co = new OuterClass();

        co.method1();

        co.method2();

       
        co.r.run();

       
        OuterClass.InnerClass i = co.new InnerClass();

        i.innerPrint();

       
        OuterClass.StaticNestedClass sn = new OuterClass.StaticNestedClass();

        sn.staticNestedPrint();

       
        OuterClass.A.B nested = co.new A().new B();

    }

}

Java Lab05_Ans5

FURNITURE AND FITTINGS COMPANY(FFC) MANUFACTURES SEVERAL FURNITURE ITEMS, SUCH AS CHAIR AND BOOKSHELVES. tHE FURNITURE ITEM IN THE COMPANY HACE SOME COMMON CHARACTERISTICS, SUCH AS PRICE, WIDTH, AND HEIGHT. HOWEVER, SOME FURNITURE ITEMS HAVE SOME SPECIFIC DETAILS. FOR EXAMPLE, A BOOKSHELF HAS A NUMBER OF SHELVES. NOW,WRITE A JAVA PROGRAM THAT USES THE CONCEPT OF ADSTRACT CLASS TO STORE AND DISPLAY THE DETAILS OF FURNITURE ITEMS.


ANSWER

public adstract class Furniture {

protected String color;
protected int width;
protected int height;
public adstract void accept();
public adstract void display();
}
   class chair extends Furniture {
private int numOf_legs;

public void accept() {

colour = "Brown"
width = 36;
height = 48;
numOf_legs = 4;
}
  public void display()    {
System.out.println("DISPLAYING VALUE FOR CHAIR");
system.out.println
("==================================");
System.out.println("Color is" + color);
System.out.println("Width is" + width);
System.out.println("Height is" + height);
System.out.println("Number of legs is" + numOf_legs);
System.out.println(" ");
}
}

class Bookshelf extends Furniture {

private int numOf_shelves;

public void accept()  {

colour ="Black";
width = 72;
height = 84;
numOf_shelves = 4;
}
public void display ()  {
System.out.println("DISPLAYING VALUES FOR BOOKSHELF")
System.out.println
("===================================");

System.out.println("Color is" + color);
System.out.println("Width is" + width);
System.out.println("Height is" + height);
System.out.println("Number of shelves is" + numOf_shelves);
System.out.println(" ");
}
}

class FurnitureDemo  {
public static void main(String[] args)   {
bookShelf b1 = new BookShelf();
b1.accept();
b1.display();


Chair c1 = new Chair ();
c1.accept();
c1.display();

}
}

Java Lab05_Ans4

WRITE A PROGRAM TO CALCULATE THE AREA OF TRIANGLE,CIRCLE,SQUARE,AND RECTANGLE. HOWEVER,YOU NEED TO ENSURE THAT THE PRECEDING SET OF FUNCTIONALITIES MUST BE ARCHIEVED BY IMPLEMENTING ABSTRACTION.

ANSWER

abstract class Area  {
double dim1, dim2, result;

abstract void calArea();

double disArea()    {

return result;
}
}
   class Circle extends Area   {
double pie = 3.14;

public Circle(double rad)   {
dim1 = rad;

}

void calArea()  {
result= pie*dim1*dim1;
}
}

  class Rectangle extends Area   {
public Rectangle(double ln, double br)   {
dim1 = ln;
dim2 = br;
}

void calArea()   {
result = dim1 * dim2;
}
}

 claSS Square extand Area   {
public Square(double side)   {
dim1 = side;
}

void calArea()   {
result =dim1* dim1;
}
}

 class Triangle extends Area  {
public Triangle (double bas, double high)   {
dim1 = bas;
dim2 = high;
}

void calArea() {
result = (dim1 * dim2 ) /2;

  }
}
  public class Area calculator   {
public static void main (String[] args)  {
Square sobj = new Square (44.5);
sobj.calArea();
System.out.println("The area of square is " + sobj.disArea());

Rectangle robj = new Rectangle (23.4, 12);
robj.calArea();
System.out.println("The area of rectangle is " + robj.disArea());


Circle cobj = new Circle (5.7);
cobj.calArea();
System.out.println("The area of circle is " + cobj.disArea());


Triangle tobj = new Triangle (20, 20);
tobj.calArea();
System.out.println("The area of triangle is " + tobj.disArea());
}
}

Java Lab05_Ans3

Mark has been assigned a task of developing a bame console. In this game console,he needs to ensure that the following functionalities are implemented:
- Each game in the game console must offer functionalities, such as play game compute score, and display score.
- The display score functionality will remain the same for all the games. However the play game and computer score functionalities will be different for each game.
In the inital phase, you do not need to implement the logic of the functionalities. However, display appropriate message, such as the play game functionality will display the message, Starting the game. Now, help Mark to achive the preceding reguirments.

ANSWER

abstract class GameConsole  {

int score;
  void displayScore ()   {
System.out.println("The displayScore method.");
}

abstract void computeScore();
abstract void playGame();
}

class Badminton extends GameConsole   {

void playGame()   {
System.out.println("Starting the Badmintion Game...");
}

void computeScore()  {
System.out.println("Calculating Score for the Badmintion Game...");
}
}
class TableTennis extends GameConsole  {

void playGame()   {
System.out.println("Starting the TableTennis Game...);
}
void computeScore()  {
System.out.println("Calculating Score for the TableTennis Game...");
}
}

public class GameDemo   {

public static void main(String args[])   {
Badminton obj1 = new Badminton ();
obj1.playGame();
obj1.computeScore();
obj1.displayScore();

TableTennis obj2 = new TableTennis();
obj2.playGame();
obj2.computeScore();
obj2.displayScore();
}
}

Java Lab05_Ans2

WRITE A PROGRAM TO CREAT THAT CONTAINS A METHOD THAT ACCEPTS COMPASS DIRECTIONS AND DISPLAYS THE SAME.IN ADDITION,YOU NEED TO ENSURE THAT THE METHOD MUST ACCEPT ANY ONE OF THE DIRECTIONS: NORTH,SOUTH,EAST,WEST,NORTHEAST,SOUTHEAST,SOUTHWEST,OR NORTHWEST

ANSWER

enum CompassDirections
{
  NORTH, SOUTH, EAST, WEST, NORTHEAST, SOUTHEAST, SOUTHWEST, NORTHWEST;
}
     class TestCompassDirections
{


public void displayDirection(CompassDirections cd)
{
System.out.println(cd);
}
  public static void main(String[] args)
   {
TestCompassDirections tcd = new TestCompassDirections();
tcd.displayDirection(CompassDirections.EAST);
}
}

Java Lab04_Ans7

WRITE A PROGRAM TO DEMONSTRATE THE POLYMORPHISM CONCEPT BY OVERLOADING THE ADD METHOD THAT ALLOWS ADDITION OF THE FOLLOWING NUMBERS:
-TWO INTEGER NUMBER
-TWO FRACTIONAL NUMBERS
-THREE INTEGER NUMBERS


ANSWER




public class addition {
 
  public int add(int num1 , int num2) {
    return num1 + num2;
 }
    public double add (double num1, double num2 ) {
     return (double) num1 + num2;
}
    public int add(int num1 , int num2 , int num3) {
      return num1 + num2 + num3;
}
     public static void main (string[] args) {
        int a = 10, b = 15, c = 7;
        double x = 4.5, y = 3.2;
        addition obj = new addition ();
 
       system.out.println (" the addition of two integer numbers is " + obj.add(a , b) );
       system.out.println (" the addition of two fractional numbers is " + obj . add(x , y) ) ;
       system.out.println (" the addition of three integer numbers is " + obj . add (a,b,c) ) ;
 }

}

Java Lab04_Ans5

WRITE A PROGRAM THAT STORES THE DETAILS OF THE SOFTWARE AND HARDWARE BOOKS. THE SOFTWARE BOOKS INCLUDES THE SOFTWARE VERSION AND SOFTWARE NAME. THE HARDWARE BOOK INCLUDES THE HARDWARE CATEGORY AND PUBLISHER. HOWEVER, BOTH THE BOOKS INCLUDE SOME COMMON DETAILS, SUCH AS AUTHOR NAME,TITLE,PRICE,AND NUMBER OF PAGES. THEREFORE, YOU NEED TO STORE AND DISPLAY THE BOOK DETAILS BY IMPLEMENTING THE CODE REUSABILITY IN THE PROGRAM.



ANSWER



class book {
   
   string author;
   string title;
   int price;
   int pages;
   int stock;

    public void getdetails(string at, string tt, int pr, int pg, int st) {
       author = at;
       title = tt;
       price = pr;
       pages = pg;
       stock = st;
   }
      public void showdetails () {
       system.out.println (" ");
       system.out.println ("books information");
       system.out.println ("============================");
       system.out.println (" book author: " + author);
       system.out.println (" book title: " + title);
       system.out.println (" book price: " + price);
       system.out.println (" number of pages: " + pages);
       system.out.println (" book of stock: " + stock);
  }
   
}
    class hardwarebook extends book {
 
     string hardwarecatagoery;
     string publisher;
 
     public void getdetails () {
       super . getdetails ("mark franklin" , "all about pc", 120, 150, 80);
           hardwarecategory = "machine";
           publisher = "denmark";
    }
         public void showdetails() {
           system.out.println (" ");
           system.showdetails ();
           system.out.println ("hardware category: " + hardwarecategory);
           system.out.println ("publisher name: " + publisher);
           system.out.println (" ");
      }
 }
          public class bookdemo {
     
          public static void main(string args []) {
   
          softwarebook softdetails = new softwarebook ();
          softdetails. getdetails ();
          softdetails . showdetails ();
     
          hardwarebook harddetails = new hardwarebook ();
          harddetails . getdetails ();
          harddetails . showdetails ();
   }

}
    

Java Lab04_Ans4

WRITE A PROGRAM THAT STORES THE DETAILS OF STUDENT AND EMPLOYEES .THE STUDENT DETAILS INCLUDE FIRST NAME,LAST NAME,AGE,COURSE ENROLLED, AND STUDENT ID. THE EMPLOYEE DETAILS INCLUDE FIRST NAME,LAST NAME,AGE,SALARY,DEPARTMENT NAME,DESIGNATION,AND EMPLOYEEID. YOU NEED TO IMPLEMENT THE PRECEDING FUNCTIONALITIES BY ENSURING THE REUSABILITY OF CODE.

ANSWER


public class persondetails {
 
  String firstname;
  String lastname;
  int age;

   public void showdetails() {
   system.out.println("\nThe student details are: \n");
   system.out.println("first name: " + super.firstname);
   system.out.println("last name: " + super.lastname);
   system.out.println("age: " + super.age);
   system.out.println("course enrolled: + + stream);
   system.out.println("student id: " + studentid);
 
  }
}

   public class employeedetails extends persondetails {
   
    double salary;
    string desg;
    string dept;
   
    public void getdetail(string name1, int age, double sal, string des, string dep) {
     super . getdetail (name1,name2,age);
      salary = sal;
      desg = des;
      dept = dep;
      showdetail ();
  }

     public void showdetail () {
      system.out.println("\nthe employee details are : \n");
      system.out.println(" first name: " + super. firstname);
      system.out.println("age: " + super.age);
      system.out.println("{departmment: " + dept);
      system.out.println("designation: " + desg);
     system.out.println("salary: " + salary);
   }
 }
     public class main details {
 
      public static void main (string [] args) {
       studentdetails sobj = new studentdetails ();
       sobj.getdetail("peter", "parker", 23 , "science", 125);
       employeedetails eobj = new employeedetails ();
       eobj.getdetail("david", "henson",  34, 2000, "manager", "admin");
    }
}

Java Lab04_Ans3

Write a program to create a class that will store the length and breadth of the rectangle.In addition, you need to check whether two objects of the class contain the same values or not.

ANSWER



public class rectangle {
 
   double length;
   double breadth;

  public rectangle ( double len , double brd) {
     length = len;
     breadth = brd;
 
   public boolen equals (object obj) {
    rectangle rec  = (rectangle) obj;
  if (this. length == rec.length && this.breadth == rec.breadth) {
   
     return true;
     }
       else {
      return false;
    }
  }
      public static void main(String [] arg) {
       rectangle obj1 = new rectangle (10.5 , 23.6);
       rectangle obj2 = new rectangle (10.5 , 33.6);
     
       if (obj1.equals(obj2) ) {
        system.out.println("obj1 and obj2 are equal");
       }
         else {
            system.out.println ("obj1 aand obj2 are not equal");
        }
  }

}
 
   

Java Lab04_Ans2

Write a program to store the employee details, such as employee ID, name,designation.
In addition, the employee details should be display when the object of the class is printed.


Answer


public class Employee {
public int empID;
Public String empName;
Public String empDesg;
Public String empDept;

public Employee()  {

empID = 2132;
empName = "Kamal Sharma";
empDesg = "Manager";
empDept = "Admin";
}

public String toString() {
StringBuffer = new StringBuffer();
buffer.append("The Employee Details are: \n");
buffer.append("The Employee ID: "+ empID+ "\n");
buffer.append("The Employee Name: "+ empName+"\n");
buffer.append("The Employee Designation: "+ empDesg+"\n");
buffer.append("The Employee Department: "+ empDept+"\n");
return buffer.toString();
    }
public static void main(String[] args) {
Employee oobj = new Employee();
System.out.println(eobj);
    }
}

Java Lab02_Ans4

Write a program that will store the employee records, such as employee ID, employee name, department, designation,
date of joining, date of birth, and marital status, in an array. In addition, the stored record needs to be displayed.

ANSWER


public class employeerecord

  string employeeDetails [] [] = new String [1] [7];
    public void storeData() {
 
   employeeDeatils [0] [0] = "A101";
   employeeDeatils [0] [1] = "john mathew";
   employeeDetails [0] [2] = "admin";
   employeeDetails [0] [3] = "manager";
   employeeDetails [0] [4] = "05/04/1998";
   employeeDetails [0] [5] = "11/09/1997";
   employeeDetails [0] [6] = "married";
 }
    public void displayData() {
     system.out.println ("Employee Details:");
    for ( int i = 0; i < employeeDetails,length;
    for ( int j = 0; j < employeeDetails[i].length; j++ {

      system.out.println(employeeDetails[i] [j] );
    }
 }


}

     public static void main (String [] args) {
      EmployeeRecord obj = new EmployeeRecord();
      obj.storeData();
     obj.displayData();
  }

}

JAVA Lab03_Ans3

Write a Program to print the table of five.


Answer


public class table {

  public static void main(String [] args)
  int result;
 
   for (int i = 1; i <=10; i++) {
    result = i * 5;
 
  system.out.println("5 * " + i " = " + result);
 
   }
 }

 } 

JAVA Lab03_Ans2

Write a program to check if the first number is divisible by the second number or not.
In addition, display approprate message accordingtothe result...


ANSWER

public class DivisibleChecker {

public static void main(string [] args) {

int num1, num2;
num1 = 32;

num2 = 12;

if (num1 % num2 == 0) {
    System.out.println("The first number is divisible by the second number");
} else {
System.out.println("The first number is not divisible by the second number");
}
}
}

NIIT HTML Lab@ Home

Java Lab02_Ans2

Write a program to creat a class named EmployeeDetails and display a menue similar to the following menu:
--------------Menu--------
1. Enter Data 
2. Display Data 
3. Exit

Chosse the option
Thereafter, invoke the respective method according to the given menu input. The methods will contain appropriate message, such as the displayData() 
method will contain the message, displayData method is invoked.



ANSWER

1. Create a Java application, Lab02_Ans2.
2. Create a class, EmployeeDetails, in the Java application, Lab02_Ans2.
3. Replace the exisiting code in the EmployeeDetails.java file with following code:

   public class EmployeeDetails {

     public void showMenue ()  {
         int option;
         System.out.println("------------Menu--------");
         System.out.println("1. Enter Data");
         System.out.println("2. Display Data");
         System.out.println("3. Exit");
         System.out.println("\nChoose the option:  ");


         Option = 2;
switch (option)  {
case 1:
enterData();
break;
case2:
DisplayData();
break;
case3:
exitMenue();
break;
defalt:
System.out.println("Incorrect menu option");
showMenu();
break;
 }
}
public void enterData() {
System.out.println("enterData method is invoked");
}

public void enterData() {
System.out.println("displayData method is invoked");
}


public void enterData() {
System.out.println("exitMenu method is invoked");
System.exit(0);
}

public static void main(String[] args)  {
EmployeeDetails obj = new EmployeeDetails();
obj.showMenu();
  }
}