Saturday 21 July 2012

TCS aspire communication quiz solutions: TCS aspire communication quiz solutions: Question1...

TCS aspire communication quiz solutions: TCS aspire communication quiz solutions: Question1...: TCS aspire communication quiz solutions: Question1 of 20    10.0 Points What does this Bod... : Question 1 of 20    10.0 Points What does...

Web technology -Quiz1


Web technology -Quiz1
1.What is the correct syntax of the declaration which defines the XML version?
Option: a. < ? xml version="1.0" ? >
b. < xml version="1.0" />
c. < xml version="1.0"? />
d. None of the above
e. < ? xml version="1.0" ? />
Ans: a


2.What is the correct syntax for referring to an external script called "xxx.js"?
option: a. None
b. < script type="text/javascript" name="xxx.js" >
c. < script type="text/javascript" href="xxx.js" >
d. < script type="text/javascript" src="xxx.js" >
ans: d




3. What is the correct HTML for referring to an external style sheet?
option : a. < stylesheet>mystyle.css
b. None of the above
c. < style src="mystyle.css" />
d. < link ="stylesheet" type=text/css/script href="mystyle.css" >
e. < link rel="stylesheet" type="text/css" href="mystyle.css" />
Ans: e


4. What can you use to replace like with hate in I like Eminem?
Option : a. preg_replace("/like/", "/hate/", "I like Eminem")
b. preg_replace("hate", "like", "I like Eminem")
c. preg_replace("/like/", "hate", "I like Eminem")
d. None of the above
e. preg_replace("like", "hate", "I like Eminem")
ans: e


5. What are the genral syntax for inline image?
Option: a. None of the above
b. img=file
c. img src=file
d. src=image
e. image src=file
Ans: c


1. What are the general syntax for inline image? 
Ans: img src=file 
2. What is the correct syntax for referring to an external script called "xxx.js"? 
Ans: <script type="text/javascript" src="xxx.js"> 
3. What is the correct syntax of the declaration which defines the XML version? 
Ans: <? xml version="1.0" ?>
4. What can you use to replace like with hate in i like eminem? 
Ans: preg_replace("like", "hate", "i like eminem") 
5. What is the correct HTML for referring to an external style sheet?
 Ans: <link rel="stylesheet" type=text/css" href="mystyle.css" />






How does JavaScript store date in a date object?


A. The number of seconds since Netscape's public stock offering.


B. None of the options


C. The number of milliseconds since January 1st, 1970


D. The number of days since January 1st, 1900
ans c


What does CSS define in HTML?


A. How to send HTML elements


B. How to save HTML elements


C. How to made HTML elements


D. How to display HTML elements
ANS- D




Among the following options, select the command that you can use to link a page with an HTML page?


A. <a link=\"page.htm\" ></a>


B. <a connect=\"page.htm\" ></a>


C. <a href=\"page.htm\"?phpMyAdmin=70ac9566533a2665b6597346aab7f985&phpMyAdmin=f43d4e0b88acea2d2a393515f6bf38f2 ></a>


D. <a attach=\"page.htm\" ></a>
ans- c


QSTN-__ JavaScript is also called server-side JavaScript. A. Microsoft B. Navigator C. LiveWire D. Native
Ans- c






QSTN-  The <BR> Tag
ANS-Reset margins




QSTN-You used CSS class into your html, but divided your page without break line. Which of following would you have to use?
Ans-The <div> tag






QSTN-How would you set a CSS comment?
ANS- "/*",  "*/", 




QSTN-How would you define CSS padding?'
ANS-p {padding: 2%; border: 1px solid black; } 
h5{padding: 0px; border: 1px solid red;}




QSTN- Which of the following popup boxes would you use to get some information from the user?
ANS-prompt















UNIX ASSIGNMENT 1 Answers


                                   UNIX ASSIGNMENT 1  Answers

Question 1: Write a command to list all the files inside a folder i.e. if there is a folder inside a folder then it should list all files inside the sub-folder which is inside the folder to be listed.
Answer 1: ls –R
Question 2: Search all the files which contains a particular string, say “include” within a folder.
Answer 2: for i in *.*; do grep -l include $i; done
Question 3: Rename all the files within a folder with suffix “Unix_” i.e. suppose a folder has two files a.txt and b.pdf than they both should be renamed from a single command to Unix_a.txt and Unix_b.pdf
Answer 3: for i in *.*; do mv $i Unix_$i; done ;
Question 4: Rename all files within a folder with the first word of their content(remember all the files should be text files. For example if a.txt contains “Unix is an OS” in its first line then a.txt should be renamed to Unix.txt
Answer 4 : for i in *.txt; do j= "$(head -1 $i | cut -f1-d" ").txt"; mv "$i" "$j"; done
Question 5 : Suppose you have a C project in a folder called “project”, it contains .c and .h files, it also contains some other .txt files and .pdf files. Write a Linux command that will count the number of lines of your text files. That means total line count of every file. (remember you have to count the lines in .txt files only)
Answer 5 : wc -l *.txt
Question 6 : Rename all files which contain the sub-string 'foo', replacing it with 'bar' within a given folder.
Answer 6 :for i in ./*foo*; do mv "$i" "${i//foo/bar}";done
Question 7 : Show the most commonly used commands from “history”. [hint: remember the history command, use cut, and sort it.
Answer 7 : history |cut -f6- -d" " | sort

UNIX QUIZ ANSWERS


UNIX QUIZ ANSWERS

“ls” command in UNIX
A. Lists the files in a directory
B. Compare the size of two files
C. Gives the currently logged session details
D. Compares two numerals and prints the lower value

Answer Key: A
[ Tips: “ls” command in UNIX lists all the contents in a directory. Ls can be used with many options to display additional details ]
# Question 2 of 10 10.0 Points
Which among the following is not a part of UNIX operating system
A. Programs
B. Libraries
C. Kernel
D. Shell

Answer Key: B
[ Tips: Libraries. The UNIX operating system is made up of three parts; the kernel, the shell and the programs. ]
# Question 3 of 10 10.0 Points
In UNIX, the shell act as an interface between user and
A. Kernel
B. Operating System
C. Hardware
D. Programs

Answer Key: A
[ Tips: The shell acts as an interface between the user and the kernel. When a user logs in, the login program checks the username and password, and then starts another program called the shell. The shell is a command line interpreter (CLI). It interprets the commands the user types in and arranges for them to be carried out. ] 
# Question 4 of 10 10.0 Points
Everything in UNIX is
A. None
B. a Process
C. a file or a process
D. a File

Answer Key: C
[ Tips: Everything in UNIX is either a file or a process. A process is an executing program identified by a unique PID (process identifier). A file is a collection of data. They are created by users using text editors, running compilers etc. ]
# Question 5 of 10 10.0 Points
Which command is used for changing directory in UNIX?
A. mkdir
B. cd
C. chgdir
D. cddir

Answer Key: B
[ Tips: The command cd directory means change the current working directory to ‘directory’. The current working directory may be thought of as the directory you are in, i.e. your current position in the file-system tree. ] 
# Question 6 of 10 10.0 Points
In UNIX, file permissions are not set for
A. User
B. Other users
C. Devices
D. User Groups

Answer Key: C
[ Tips: Every directory and file on the system has an owner, and also an associated group. It also has a set of permission flags which specify separate read, write and execute permissions for the ‘user’ (owner), ‘group’, and ‘other’ (everyone else with an account on the computer) ]
# Question 7 of 10 10.0 Points
In Unix, how can you read the manual – help pages – about a command
A. Type ‘help’ and the command
B. Type ‘options’ and the command
C. Type ‘details’ and the command
D. Type ‘man’ and the command


Answer Key: D
[ Tips: To see what all a Linux command can do, type “man ”. This will show you the manual of the specified command.] 
# Question 8 of 10 10.0 Points
Which is the most common text editor in UNIX ?
A. Visual editor
B. notepad
C. Word
D. Open office


Answer Key: A
[ Tips: The default editor that comes with the UNIX operating system is called vi (visual editor). Alternate editors for UNIX environments include pico and emacs, a product of GNU.]
# Question 9 of 10 10.0 Points
You have created a shell script and wants to run the script. What should you do before trying to run the script ?
A. No action required
B. Compile the script to create the executable
C. Update the execute permission of the script
D. Give ownership of the file to system admin


Answer Key: C
[ Tips: You have to update the execute permission of the script using the command ‘chmod’]
# Question 10 of 10 10.0 Points
Which is valid mode of operation in vi editor ?
A. Typing mode“ls” command in UNIX


B. Command Mode
C. Append mode
D. Open mode

Answer Key: B

Unix Assignment-2 - Answers


Unix Assignment-2 - Answers

  1. Create a tree structure named ‘training’ in which there are 3 subdirectories – ‘level 1’,’ level2’ and ‘cep’. Each one is again further divided into 3. The ‘level 1’ is divided into ‘sdp’, ‘re’ and ‘se’. From the subdirectory ‘se’ how can one reach the home directory in one step and also how to navigate to the subdirectory ‘sdp’ in one step? Give the commands, which do the above actions?

Ans :  To navigate from ‘se’ to home , the command is cd
To navigate to sdp from se – cd /home/training/level1/sdp


  1. How will you copy a directory structure dir1 to dir2 ? (with all the subdirectories)

Ans : cp –R dir1 dir2


  1. How can you find out if you have the permission to send a message?

Ans : ls -l


  1. Find the space occupied ( in Bytes) by the /home directory including all its subdirectories.

Ans : du -sb


  1. What is the command for printing the current time in 24-hour format?

Ans : date ‘+%R’ or date ‘+%H:%M:%S’


  1. What is the command for printing the year, month, and date with a horizontal tab between the fields?

Ans : date ‘+%Y%t%m%t%d’


  1. Create the following files: chapa, chapb, chapc, chapd, chape, chapA, chapB, chapC, chapD, chapE, chap01, chap02, chap03, chap04, chap05, chap11, chap12, chap13, chap14, and chap15.
    
     Ans: cat > chapa
type Contents of file
Ctrl+D
cat > chapb
type Contents of file
Ctrl+D
cat > chapc
type Contents of file
. . .
cat> chap14
type Contents of file
Ctrl+D
cat> chap15
Contents of file
Ctrl+D



  1. With reference to question 7, What is the command for listing all files ending in small letters?

Ans : find . –name “*[a-z]”


  1. With reference to question 7, What is the command for listing all files ending in capitals?

Ans : find . –name “*[A-Z]”


  1. With reference to question 7, What is the command for listing all files whose last but one character is 0?

Ans: find . -name “*0?”


  1. With reference to question 7, What is the command for listing all files which end in small letters but not ‘a’ and ‘c’?

Ans :  find . -name “*[^ac]” or  find . –name “*[b d-z].*” or


  1. In an organisation one wants to know how many programmers are there. The employee data is stored in a file called ‘personnel’ with one record per employee. Every record has field for designation. How can grep be used for this purpose?

Ans : grep -c programmer personnel


  1. In the organisation mentioned in question 12 how can sed be used to print only the records of all employees who are programmers.

Ans: sed -n “/programmer/p” personnel


  1. In the organisation mentioned in question 12 how can sed be used to change the designation ‘programmer’ to ‘software professional’ every where in the ‘personnel’ file

Ans :  sed -e “s/programmer/software professional/g” personnel


  1. Find out about the sleep command and start five jobs in the background, each one sleeping for 10 minutes.

Ans:  sleep 600 & sleep 600 & sleep 600 & sleep 600 & sleep 600 &


  1. How do you get the status of all the processes running on the system? i.e. using what option?

Ans : ps

software engineering quiz answers


software engineering quiz





Question 1 of 10    10.0 Points
Requirements can be classified in to two types, namely, functional requirements and non-functional requirements


   True


 False


Answer Key True




Question 2 of 10    10.0 Points
Some examples of non-functional requirements are.


1.Number of significant digits to which accuracy should be maintained in all numerical calculations is 10
2.The response time of the system should always be less than 5 seconds
3.The software should be developed using C language on a UNIX based system
4.The matrix diagonalisation routine should zero out all off-diagonal elements, which are equal to or less than 10-3
5.Experienced officers should be able to use all the system functions after a total training of two hours. After this training, the average number of errors made by experienced officers should not exceed two per day.






     True


 False
Answer Key True






Question 3 of 10    10.0 Points
Every software system has the following essential characteristics


        A. It has processes which collaborate with each other to generate the outputs.   
    


    B. All the above   
    


    C. It has a boundary. The boundary separates what is with in system scope and what is outside.   
    


    D. The system may also use data stores to store data which has a life beyond the system.   
    


    E. These processes operate on data by creating, modifying, destroying, and querying it.   
    


    F. It takes inputs from external agents and generates outputs.   
Answer Key B






Question 4 of 10    10.0 Points
ERD complements DFD. While DFD focuses on data and the relationships between them, ERD focuses on processes and data flow between them
     True


 False


Answer Key False






Question 5 of 10    10.0 Points
Polymorphism - It is the means by which an operation behaves differently in different contexts.
     True


 False


Answer Key True




Question 6 of 10    10.0 Points
Encapsulation This helps in controlling the visibility of internal details of the objects. It improves security and integrity of data
      True


 False
Answer Key True




Question 7 of 10    10.0 Points
There are 4 types of Abstraction, namely Entity, Action, Virtual machine & Coincidental.
 True


 False


Answer Key True




Question 8 of 10    10.0 Points
There can be more than one hash fields on a file.


 True


 False


Answer Key False






Question 9 of 10    10.0 Points
Concurrency refers to multiple transactions accessing the same database at the same time. In a system which allows concurrency, some kind of control mechanism has to be in place to ensure that concurrent transactions do not interfere with each other.


 True


 False


Answer Key True






Question 10 of 10    10.0 Points
Software genetic development process contains three genetic phrases namely
    A. Software engineering, Definition, Coding   
    


    B. Definition, development, maintenance   
    


    C. Coding, design, Software engineering   
    


    D. Design, Coding, Development   
    


    E. Development, Definition, Testing   


Answer Key B
1.Which of the following Construct in formal model in software engineering execute each statement in succession.
Choose one answer.
a. Iteration Construct. 
b. Statement Construct. 
c. Selection Construct. 
d. Business Construct. 
e. Sequence Construct.


Ans  e


2.What is software engineering
Choose one answer.
a. Software engineering implement a single independent function 
b. Set of computer programs, procedures and possibly associated document concerned with the operation of data processing. 
c. None of the above 
d. Software engineering is the establishment and use of sound engineering practice in order to produce economical and reliable software that will perform efficiently on real machine 
e. Software engineering is Design, Coding, Development 




ans  d




3.What is a software


Choose one answer.
a. A mathematical formulae 
b. A set of compiler instructions. 
c. None of the above 
d. Set of computer programs, procedures and possibly associated document concerned with the operation of data processing. 
e. All of the above


ans  d




4.Which of the following translators convert high-level language on statement-by-statement basis
Choose one answer.
a. Interpreter. 
b. Assembler 
c. Machine level language converter 
d. Compiler


ans  a




5.Which of the following is not an example of Prototype in engineering paradigm
Choose one answer.
a. Paper prototype. 
b. Software prototype. 
c. Existing prototype. 
d. Engineering prototype. 
e. Working prototype.


ans  a


 Question 1 of 10 10.0 Points
Requirements can be classified in to two types, namely, functional requirements and non-functional requirements
- True
- False
Answer Key True 


# Question 2 of 10 10.0 Points
Some examples of non-functional requirements are.
1.Number of significant digits to which accuracy should be maintained in all numerical calculations is 10 2.The response time of the system should always be less than 5 seconds
3.The software should be developed using C language on a UNIX based system
4.The matrix diagonalisation routine should zero out all off-diagonal elements, which are equal to or less than 10-3
5.Experienced officers should be able to use all the system functions after a total training of two hours. After this training, the average number of errors made by experienced officers should not exceed two per day. 
- True
- False


Answer Key True 


# Question 3 of 10 10.0 Points
Every software system has the following essential characteristics 
A. It has processes which collaborate with each other to generate the outputs.
B. All the above
C. It has a boundary. The boundary separates what is with in system scope and what is outside.
D. The system may also use data stores to store data which has a life beyond the system.
E. These processes operate on data by creating, modifying, destroying, and querying it.
F. It takes inputs from external agents and generates outputs.


Answer Key B 


# Question 4 of 10 10.0 Points
ERD complements DFD. While DFD focuses on data and the relationships between them, ERD focuses on processes and data flow between them 
- True
- False


Answer Key False 


# Question 5 of 10 10.0 Points
Polymorphism – It is the means by which an operation behaves differently in different contexts. 
- True
- False


Answer Key True 


# Question 6 of 10 10.0 Points
Encapsulation This helps in controlling the visibility of internal details of the objects. It improves security and integrity of data 
- True
- False


Answer Key True 


# Question 7 of 10 10.0 Points
There are 4 types of Abstraction, namely Entity, Action, Virtual machine & Coincidental. 
- True
- False


Answer Key True 


# Question 8 of 10 10.0 Points
There can be more than one hash fields on a file.
- True
- False


Answer Key False 


# Question 9 of 10 10.0 Points
Concurrency refers to multiple transactions accessing the same database at the same time. In a system which allows concurrency, some kind of control mechanism has to be in place to ensure that concurrent transactions do not interfere with each other. 
- True
- False




Answer Key True 


# Question 10 of 10 10.0 Points
Software genetic development process contains three genetic phrases namely
A. Software engineering, Definition, Coding
B. Definition, development, maintenance
C. Coding, design, Software engineering
D. Design, Coding, Development
E. Development, Definition, Testing




Answer Key B 

Introduction to Java basics-Assignment 2


Introduction to Java basics-Assignment 2

1.Create a washing machine class with methods as switchOn, acceptClothes, acceptDetergent,switchOff. acceptClothes accepts the noofClothes as argument & returns the no of Clothes.
/*washing machine*/
 import java.util.*;
class  WashingMachine
{
Scanner input=new Scanner(System.in);
public void switchOn ()
{
System.out.println ("The lid is open.");
}
public void start ()
{
System.out.println ("Start washing ...");
}
public void acceptDetergent ()
{
System.out.println("Adding Detergent.. ");
start();
}
public int acceptClothes()
{
System.out.println("Enter no of clothes: ");
int no=input.nextInt();
return no;
}
public void switchOff ()
{
System.out.println ("The lid is closed.");
}
public static void main(String[] args)
{
WashingMachine wm=new WashingMachine();
wm.switchOn();
int numOFClothes=wm.acceptClothes();
wm.acceptDetergent();
wm.switchOff();
System.out.println(numOFClothes+" clothes get washed");
}
}





2.Create a calculator class which will have methods add, multiply, divide & subtract
/*calculator*/
 import java.util.*;
class Calculation
{
public int add(int a,int b)
{
return a+b;
}
public int subtract(int a,int b)
{
if(a>b)
{
return a-b;
}
else
{
return b-a;
}
}
public int multiply(int a,int b)
{
return a*b;
}
public int divide(int a,int b)
{
if(a>b)
{
return a/b;
}
else
{
return b/a;
}
}
}
public class Calculator
{
public static void main(String []args)
{
Calculation cal=new Calculation();
int add=cal.add(5,10);
int sub=cal.subtract(5,10);
int mul=cal.multiply(5,10);
int div=cal.divide(5,10);
System.out.println(add);
System.out.println(sub);
System.out.println(mul);
System.out.println(div);
}
}



3. Create a class called Student which has the following methods:
i.    Average: which would accept marks of 3 examinations & return whether the student has passed or failed depending  on whether he has scored an average above 50 or not.
ii.    Input name: which would accept the name of the student & returns the name?




/*Student results*/
import java.util.*;
public class Student
{
 Scanner input=new Scanner(System.in);
public String average()
{
System.out.print("Enter Marks1: ");
double m1=input.nextDouble();
System.out.print("Enter Marks2: ");
double m2=input.nextDouble();
System.out.print("Enter Marks3: ");
double m3=input.nextDouble();
double tm=m1+m2+m3;
double avg=tm/3;
if(avg<50)
{
return "Failed";
}
if(avg>50)
{
return "Passed";
}
return " ";
}
public String getName()
{
System.out.println("Enter Name:");
String  name=input.nextLine();
String result=average();
return name+" get "+result;
}
public static void main(String[]args)
{
Student data=new Student();
String nameAndResut=data.getName();
System.out.println(nameAndResut);
}
}



4.Create a Bank class with methods deposit & withdraw. The deposit method would acceptattributes amount & balance & returns the new balance which is the sum of amount &balance. Similarly, the withdraw method would accept the attributes amount & balance &returns the new balance ?balance ? amount? if balance > = amount or return 0 otherwise.

/*bank calculations*/
import javax.swing.*;
class  Customer
{
int bal;
Customer(int bal)
     {
this.bal = bal;
}
int deposit(int amt)
{
if (amt < 0)
{
System.out.println("Invalid Amount");
return 1;
}
bal = bal + amt;
return 0;
}
     int withdraw(int amt)
{
if (bal < amt)
{
System.out.println("Not sufficient balance.");
return 1;
}
if (amt < 0)
{
System.out.println("Invalid Amount");
return 1;
}
bal = bal - amt;
return 0;
}
void check()
{
JOptionPane.showMessageDialog(null,"Balance:" + Integer.toString(bal));
}
}
public class Bank
{
public static void main(String[]args)
{
Customer Cust=new Customer(1500);
String st1=JOptionPane.showInputDialog(null,"Enter the amount to deposit:");
int dep=Integer.parseInt(st1)
int bal1=Cust.deposit(dep);
Cust.check();
String st2=JOptionPane.showInputDialog(null,"Enter the amount to withdraw:");
int with=Integer.parseInt(st2);
int bal2=Cust.withdraw(with);
Cust.check();
}
}
5. Create an Employee class which has methods netSalary which would accept salary & tax asarguments & returns the netSalary which is tax deducted from the salary. Also it has a methodgrade which would accept the grade of the employee & return grade.
/*employee sal & tax*/
import java.util.*;
class  Employee
{
static Scanner input=new Scanner(System.in);
public double netSalary(double salary, double taxrate)
{
double tax=salary*taxrate;
double netpay=salary=tax;
return netpay;
}
public static String grade( )
{
System.out.print("Enter Grade: ");
String grade=input.next();
return grade;
}
public static void main(String[] args)
{
Employee emp=new Employee();
System.out.print("Enter Salary: ");
double sal=input.nextDouble();
System.out.print("Enter Tax in %: ");
double taxrate=input.nextDouble()/100;
String g=emp.grade();
double net=emp.netSalary(sal,taxrate);
System.out.println("Net Salary is: "+net);
System.out.println("Grade is: "+g);
}
}



6.Create Product having following attributes: Product ID, Name, Category ID and UnitPrice. CreateElectricalProduct having the following additional attributes: VoltageRange and Wattage. Add a behavior to change the Wattage and price of the electrical product. Display the updatedElectricalProduct details.

/*electrical product*/
import java.util.*;
class Product
{
int productID;
String name;
int categoryID;
double price;
Product(int productID,String name,int categoryID,double price)
{
this.productID=productID;
this.name=name;
this.categoryID=categoryID;
this.price=price;
}
}
public class ElectricalProduct extends Product
{
int voltageRange;
int wattage;
ElectricalProduct(int productID,String name,int categoryID,double price,int voltageRange, intwattage)
{
super(productID,name,categoryID,price);
this.voltageRange=voltageRange;
this.wattage=wattage;
}
public void display()
{
System.out.println("Product ID: "+productID);
System.out.println("Name: "+name);
System.out.println("Category ID: "+categoryID);
System.out.println("Price: "+price);
System.out.println("Voltage Range: "+voltageRange);
System.out.println("Wattage: "+wattage);
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Enter Product ID: ");
int pid=input.nextInt();
System.out.println("Enter Name: ");
String name=input.next();
System.out.println("Enter Catagory ID: ");
int cid=input.nextInt();
System.out.println("Enter Price: ");
double price=input.nextDouble();
System.out.println("Enter Voltage Range: ");
int vrange=input.nextInt();
System.out.println("Enter Wattage: ");
int wattage=input.nextInt();
System.out.println("****Details of Electrical Product****");
System.out.println();
ElectricalProduct p=new ElectricalProduct(pid,name,cid,price,vrange,wattage);
p.display();
}
}


7. Create Book having following attributes: Book ID, Title, Author and Price. Create Periodical whichhas the following additional attributes: Period (weekly, monthly etc...) .Add a behavior to modify the Price and the Period of the periodical. Display the updated periodical details.

/*Book details*/
import java.util.*;
class Book
{
int id;
String title;
String author;
double price;
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setTitle(String title)
{
this.title=title;
}
public String getTitle()
{
return title;
}
 public void setAuthor(String author)
{
this.author=author;
}
public String getAuthor()
{
return author;
}
public void setPrice(double price)
{
this.price=price;
}
public double getPrice()
{
return price;
}
}
class Periodical
{
String timeperiod;
public void setTimeperiod(String timeperiod)
{
this.timeperiod=timeperiod;
}
public String getTimeperiod()
{
          return timeperiod;
}
}
public class BookInformation
{
public static void main(String[]args)
{
Book b=new Book();
Periodical p=new Periodical();
Scanner input=new Scanner(System.in);
System.out.print("Book ID: ");
int id=input.nextInt();
b.setId(id);
System.out.print("Title: ");
String  title=input.next();
b.setTitle(title);
System.out.print("Author: ");
String  author=input.next();
b.setAuthor(author);
System.out.print("Price: ");
double  price=input.nextDouble();
b.setPrice(price);
System.out.print("Period: ");
String  pp=input.next();
p.setTimeperiod(pp);
System.out.println();
System.out.println("----Book Information----");
System.out.println();
System.out.println("Book ID: "+b.getId());
System.out.println("Title: "+b.getTitle());
System.out.println("Author: "+b.getAuthor());
System.out.println("Price: "+b.getPrice());
System.out.println("Period: "+p.getTimeperiod());
}
}




8.Create Vehicle having following attributes: Vehicle No., Model, Manufacturer and Color. Createtruck which has the following additional attributes: loading capacity (100 tons).Add a behavior tochange the color and loading capacity. Display the updated truck details.
/*vehicle*/
import java.util.*;
class  Vehicle
{
int no;
String model;
String manufacturer;
String color;
Vehicle(int no,String model,String manufacturer,String color)
{
this.no=no;
this.model=model;
this.manufacturer=manufacturer;
this.color=color;
}
}
public class Truck extends Vehicle
{
int capacity;
Truck(int no,String model,String manufacturer,String color,int capacity)
{
super( no, model, manufacturer, color);
this.capacity=capacity;
}
void show()
{
System.out.println("No = " + no);
System.out.println("Model = " + model);
System.out.println("manufacturer = " + manufacturer);
System.out.println("Color = " + color);
System.out.println("Capacity = " + capacity);
}
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("Truck No: ");
int no=input.nextInt();
System.out.println("Model: ");
String model=input.next();
System.out.println("Manufacturer: ");
String manufacturer=input.next();
 System.out.println("Color: ");
String color=input.next();
System.out.println("Loading Capacity: ");
int cap=input.nextInt();
Truck t=new Truck(no,model,manufacturer,color,cap);
System.out.println("****Truck Details****");
System.out.println();t.show();
}
}



9.Write a program which performs to raise a number to a power and returns the value. Provide a behavior to the program so as to accept any type of numeric values and returns the results.
/*power of given number*/
import java.util.*;
import java.text.*;
class  NumberProgram
{
public static void main(String[] args)
{
DecimalFormat df=new DecimalFormat("##.##");
Scanner input=new Scanner(System.in);
System.out.print("Enter Number: ");
double num=input.nextDouble();
System.out.print("Raise Number's power: ");
double pow=input.nextDouble();
double value=Math.pow(num,pow);
System.out.println("Result is: "+df.format(value));
}
}



10. Write a function Model-of-Category for a Tata motor dealers, which accepts category of carcustomer is looking for and returns the car Model available in that category. the function shouldaccept the following categories "SUV", "SEDAN", "ECONOMY", and "MINI" which in turn returns"TATA SAFARI" , "TATA INDIGO" , "TATA INDICA" and "TATA NANO" respectively.

/*car problem*/
import java.util.*;
 class  TataMotors
{
String category;
String model;
TataMotors(String category,String model)
{
this.category=category;
this.model=model;
}
public String getCategory()
{
return category;
}
public String getModel()
{
return model;
}
public static void ModelOfCategory(ArrayList<TataMotors> list)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter Category: ");
String category=input.nextLine();
System.out.println();
System.out.print("Model is: ");
for (TataMotors tm : list)
{
if(tm.getCategory().equals(category))
{
System.out.print(tm.getModel());
}
}
}
public static void main(String[] args)
{
ArrayList<TataMotors> list=new ArrayList<TataMotors>();
list.add(new TataMotors("SUV","TATA SAFARI"));
list.add(new TataMotors("SEDAN","TATA INDIGO"));
list.add(new TataMotors("ECONOMY","TATA INDICA"));
list.add(new TataMotors("MINI","TATA NANO"));
 ModelOfCategory(list);
}

}


Introduction to Java basics-Assignment 1


Introduction to Java basics-Assignment 1

1. Write a program to find the difference between sum of the squaresand the square of the sums of n numbers?
Solution:
import java.io.*;
importjava.util.Scanner;
class Difference
{
publicstaticvoid main(String args[]) throwsIOException
{
Scanner s=newScanner(System.in);
System.out.println("Enter the value of n: ");
int n=s.nextInt();
int a[]=newint[n];
int i, sqr, diff, sum=0, add=0;
System.out.print("The "+n);
System.out.println(" numbers are : ");
for(i=0;i<n;i++)
{
a[i]=s.nextInt();
sum+=(a[i]*a[i]);
add+=a[i];
}
sqr=add*add;
diff=sqr-sum;
System.out.println("");
System.out.print("Sum of Squares of given "+n);
System.out.println(" numbers is : "+sum);
System.out.print("Squares of Sum of given "+n);
System.out.println(" numbers is : "+sqr);
System.out.println("");
System.out.println("Difference between sum of the squares and the square of the sum of given "+n);
System.out.print(" numbers is : "+diff);
System.out.println("");
}
}
Output:
Enter the value of n: 4
The 4 numbers are :
2
3
4
5
Sum of Squares of given 4 numbers is : 54
Squares of Sum of given 4 numbers is : 196
Difference between sum of the squares and the square of the sum of given 4
numbers is : 142



2. Develop a program that accepts the area of a square and willcalculate its perimeter.
Solution:
importjava.util.Scanner;
publicclassCalculateSquarePeri
{
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s=newScanner(System.in);
System.out.println("Area of Square : ");
double a=s.nextDouble();
double p=4*Math.sqrt(a);
System.out.println("");
System.out.print("Perimeter of the Square : "+p);
System.out.println("");
}
}
Output:        
Enter the area:
23
Perimeter of the square is: 19.183326093250876



3. Develop the program calculate Cylinder Volume., which accepts radius of a cylinder's base disk and its height and computes the volume of the cylinder.
Solution:
import java.io.*;
importjava.util.Scanner;
classcalculateCylinderVolume
{
publicstaticvoid main(String args[]) throwsIOException
{
Scanner s=newScanner(System.in);
System.out.println("Enter the radius : ");
double rad=s.nextDouble();
System.out.println("Enter the height : ");
doubleht=s.nextDouble();
doublevol=Math.PI*rad*rad*ht;
System.out.println("");
System.out.println("Volume of the cylinder is : " + vol);
}
}

Output:
Enter the radius :
12
Enter the height :
13
Volume of the cylinder is : 5881.061447520093


4. Utopias tax accountants always use programs that compute income taxes even though the tax rate is a solid, never-changing 15%. Define the program calculateTax which determines the tax on the gross pay. Define calculateNetPay that determines the net pay of an employee from the number of hours worked. Assume an hourly rate of $12.
Solution:
importjava.util.Scanner;
publicclasscalculateTax {
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s=newScanner(System.in);
System.out.println("Enter the no. of working days in the year : ");
int d=s.nextInt();
System.out.println("Enter the no. of working hours in a day : ");
int h=s.nextInt();
System.out.println("Enter the no. of hours worked in over time : ");
intot=s.nextInt();
System.out.println("Enter the no. of hours took leave : ");
int l=s.nextInt();
double gross=((d*h)+ot-l)*12;
double tax= gross*0.15;
double net=gross-tax;
System.out.println("");
System.out.println("Gross Pay (in $) : "+gross);
System.out.println("Tax (in $) : "+tax);
System.out.println("Net Pay (in $) : "+net);
}
}

Output:
Days worked by employer in a year :
300
Enter the no. of working hours in a day :
6
Enter the no. of hours worked in over time :
1
Enter the no. of hours took leave :
1560
Gross Pay (in $) : 2892.0
Tax (in $) : 433.8
Net Pay (in $) : 2458.2



5. An old-style movie theater has a simple profit program. Each customer pays $5 per ticket. Every performance costs the theater $20, plus $.50 per attendee. Develop the program calculateTotalProfit that consumes the number of attendees (of a show) and calculates how much income the show earns.
Solution:
importjava.util.Scanner;
publicclasscalculateTotalProfit
{
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s = newScanner(System.in);
System.out.println("Enter the no. of attendees of a show : ");
int n=s.nextInt();
double profit = (n*5)-(20+(n*0.5));
System.out.println("");
System.out.println("Total Profit of the theater per show (in $) is : " + profit);
}
}
Output:
Enter the no. of attendees per show :
50
Total Profit of the theater per show (in $) is : 205.0







6. Develop the program calculateCylinderArea, which accepts radius of the cylinder's base disk and
its height and computes surface area of the cylinder.


Program:

importjava.util.Scanner;


publicclasscalculateCylinderArea
{

/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s=newScanner(System.in);
System.out.println("Enter the base radius : ");
double rad=s.nextDouble();
System.out.println("Enter the height : ");
doubleht=s.nextDouble();
double area=2*Math.PI*rad*(rad+ht);
System.out.println("");
System.out.println("Surface Area of the cylinder is : " + area);
}

}



Output:

Enter the base radius :
12
Enter the height :
13
Surface Area of the cylinder is : 1884.9555921538758





7. Develop the program calculatePipeArea. It computes the surface area of a pipe, which is an open cylinder. The program accpets three values: the pipes inner radius, its length, and the thickness of its wall.
Solution:
importjava.util.Scanner;
publicclasscalculatePipeArea
{
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s=newScanner(System.in);
System.out.println("Enter the inner radius : ");
double rad=s.nextDouble();
System.out.println("Enter the length : ");
doublelen=s.nextDouble();
System.out.println("Enter the thickness : ");
double thick=s.nextDouble();
double area=2*Math.PI*(rad+thick)*len;
System.out.println("");
System.out.println("Surface Area of the pipe is : " + area);
}
}
Output:
Enter the inner radius :
13
Enter the length :
20
Enter the thickness :
5
Surface Area of the pipe is : 2261.946710584651




8. Develop the program calculateHeight, which computes the height that a rocket reaches in a given amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g • t in t time units and a height of 1/2 * v * t where v is the speed at t.
Solution:
importjava.util.Scanner;
publicclasscalculateHeight
 {
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
 {
Scanner s=newScanner(System.in);
System.out.println("Enter the time (in seconds) : ");
double t=s.nextDouble();
double v=9.8*t;
double height=0.5*v*t;
System.out.println("");
System.out.println("Height reached (in meters) is : " + height);
}
}
Output:
Enter the time (in seconds) :
300
Height reached (in meters) is : 441000.0




9. Develop a program that computes the distance a boat travels across a river, given the width of the river, the boat's speed perpendicular to the river, and the river's speed. Speed is distance/time, and the Pythagorean Theorem is c2 = a2 + b2.
Solution:
importjava.util.Scanner;
publicclassBoatDistance
{
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s= newScanner(System.in);
System.out.println("Enter the width of the river (in meters) : ");
doublerw=s.nextDouble();
System.out.println("Enter the river's speed (in meter/sec) : ");
doublers=s.nextDouble();
System.out.println("Enter the boat's speed (in meter/sec) : ");
doublebs=s.nextDouble();
double time=rw/bs; //time takes to travel from shore to shore straight by the boat
double w2=time*rs; //distance due to down stream
doublebd=Math.sqrt((rw*rw)+(w2*w2));
System.out.println("");
System.out.println("The distance travelled by boat (in meters) is : "+bd);
}
}
Output:
Enter the width of the river (in meters) :
15
Enter the river's speed (in meter/sec) :
200
Enter the boat's speed (in meter/sec) :
250
The distance travelled by boat (in meters) is : 19.209372712298546



10. Develop a program that accepts an initial amount of money (called the principal), a simple annual interest rate, and a number of months will compute the balance at the end of that time. Assume thatno additional deposits or withdrawals are made and that a month is 1/12 of a year. Total interest is the product of the principal, the annual interest rateexpressed as a decimal, and the number of years.
Solution:
importjava.util.Scanner;
publicclasscalculateBalance {
/**
* @paramargs
*/
publicstaticvoid main(String[] args)
{
Scanner s=newScanner(System.in);
System.out.println("Enter the principal amount : ");
double p=s.nextDouble();
System.out.println("Enter the annual interest rate : ");
double r=s.nextDouble();
System.out.println("Enter the no. of months : ");
double m=s.nextDouble();
doublesi=(p*(m/12)*r)/100;
doublebal=p+si;
System.out.println("");
System.out.print("Balance after " +(int)m);
System.out.println(" month(s) is : "+bal);
}
}
Output:
Enter the principal amount :
15000
Enter the annual interest rate :
12
Enter the no. of months :
24
Balance after 24 month(s) is : 18600.0

 


Introduction to Java basics- Quiz1





You want subclasses in any package to have access to members of a superclass. Which is the most restrictive access that accomplishes this objective?


A. public B. private
C. protected D. transient
Answer & Explanation
Answer: Option C


Qstn-public class Outer 

    public void someOuterMethod() 
    {
        //Line 5 
    } 
    public class Inner { } 
    
    public static void main(String[] argv) 
    {
        Outer ot = new Outer(); 
        //Line 10
    } 

Which of the following code fragments inserted, will allow to compile?


A. new Inner(); //At line 5
B. new Inner(); //At line 10
C. new ot.Inner(); //At line 10
D. new Outer.Inner(); //At line 10
Answer: Option A


Qstn- interface Base 
{
    boolean m1 ();
    byte m2(short s);
}
which two code fragments will compile?
interface Base2 implements Base {}
abstract class Class2 extends Base 
{ public boolean m1(){ return true; }}
abstract class Class2 implements Base {}
abstract class Class2 implements Base 
{ public boolean m1(){ return (7 > 4); }}
abstract class Class2 implements Base 
{ protected boolean m1(){ return (5 > 7) }}
A. 1 and 2 B. 2 and 3
C. 3 and 4 D. 1 and 5
Answer & Explanation
Answer: Option C






QSTN- Which three form part of correct array declarations?


public int a [ ]
static int [ ] a
public [ ] int a
private int a [3]
private int [3] a [ ]
public final int [ ] a
A. 1, 3, 4 B. 2, 4, 5
C. 1, 2, 6 D. 2, 5, 6
Answer & Explanation
Answer: Option C


Explanation:




qstn- public class Test { }
What is the prototype of the default constructor?
A. Test( ) B. Test(void)
C. public Test( ) D. public Test(void)
Answer & Explanation
Answer: Option C




QStN-What is the most restrictive access modifier that will allow members of one class to have access to members of another class in the same package?


A. public B. abstract
C. protected D. synchronized
E. default access
Answer & Explanation
Answer: Option E








QSTN- Which of the following is/are legal method declarations?


protected abstract void m1();
static final void m1(){}
synchronized public final void m1() {}
private native void m1();
A. 1 and 3
B. 2 and 4
C. 1 only
D. All of them are legal declarations.
Answer & Explanation
Answer: Option D






QSTN-Which cause a compiler error?


A. int[ ] scores = {3, 5, 7};
B. int [ ][ ] scores = {2,7,6}, {9,3,45};
C. String cats[ ] = {"Fluffy", "Spot", "Zeus"};
D. boolean results[ ] = new boolean [] {true, false, true};
E. Integer results[ ] = {new Integer(3), new Integer(5), new Integer(8)};
Answer & Explanation
Answer: Option B


QSTN-You want a class to have access to members of another class in the same package. Which is the most restrictive access that accomplishes this objective?


A. public B. private
C. protected D. default access
Answer & Explanation
Answer: Option D






QSTN- Which three are valid method signatures in an interface?


private int getArea();
public float getVol(float x);
public void main(String [] args);
public static void main(String [] args);
boolean setFlag(Boolean [] test);
A. 1 and 2 B. 2, 3 and 5
C. 3, 4, and 5 D. 2 and 4
Answer & Explanation
Answer: Option B






QSTN- What is the narrowest valid returnType for methodA in line 3?


public class ReturnIt 

    returnType methodA(byte x, double y) /* Line 3 */
    { 
        return (long)x / y * 2; 
    } 
}
A. int B. byte
C. long D. double
Answer & Explanation
Answer: Option D






QSTN- class A 
{  
    protected int method1(int a, int b) 
    {
        return 0; 
    } 
}
Which is valid in a class that extends class A?
A. public int method1(int a, int b) {return 0; }
B. private int method1(int a, int b) { return 0; }
C. public short method1(int a, int b) { return 0; }
D. static protected int method1(int a, int b) { return 0; }
Answer & Explanation
Answer: Option A






QSTN- Which one creates an instance of an array?


A. int[ ] ia = new int[15];
B. float fa = new float[20];
C. char[ ] ca = "Some String";
D. int ia[ ] [ ] = { 4, 5, 6 }, { 1,2,3 };
Answer & Explanation
Answer: Option A




QSTN- Which two of the following are legal declarations for nonnested classes and interfaces?


final abstract class Test {}
public static interface Test {}
final public class Test {}
protected abstract class Test {}
protected interface Test {}
abstract public class Test {}
A. 1 and 4 B. 2 and 5
C. 3 and 6 D. 4 and 6
Answer & Explanation
Answer: Option C






QSTN- Which of the following class level (nonlocal) variable declarations will not compile?


A. protected int a;
B. transient int b = 3;
C. private synchronized int e;
D. volatile int d;
Answer & Explanation
Answer: Option C






QSTN-
Which two cause a compiler error?


float[ ] f = new float(3);
float f2[ ] = new float[ ];
float[ ]f1 = new float[3];
float f3[ ] = new float[3];
float f5[ ] = {1.0f, 2.0f, 2.0f};
A. 2, 4 B. 3, 5
C. 4, 5 D. 1, 2
Answer & Explanation
Answer: Option D




QSTN- Given a method in a protected class, what access modifier do you use to restrict access to that method to only the other members of the same class?


A. final B. static
C. private D. protected
E. volatile
Answer & Explanation
Answer: Option C






QSTN-  Which is a valid declaration within an interface?


A. public static short stop = 23;
B. protected short stop = 23;
C. transient short stop = 23;
D. final void madness(short stop);
Answer & Explanation
Answer: Option A