Likes

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

}
}