NPTEL Programming In Java Assignment Answers 2023
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 3 Nptel Programming In Java](https://gecmunger.in/wp-content/uploads/2023/07/Nptel-Programming-In-Java.png)
NPTEL Programming In Java Week 11 Quiz Assignment Answers 2023
Q1. Which of the following statements is true regarding the executeQuery() method of the java.sql.Statement interface in Java Database Connectivity (JDBC?
a. The executeQuery) method is used to execute a DELETE statement.
b. The executeQuery) method is used to execute a SELECT statement.
c. The executeQuery ) method is used to execute an INSERT statement.
d. The executeQuery ) method is used to execute an UPDATE statement.
Answer:- b
Q2. In JDBC, which component is responsible for managing a connection to the database?
a. DriverManager
b. Connection
c. Statement
d. ResultSet
Answer:- a
Q3. What is the primary purpose of a PreparedStatement in JDBC?
a. To execute stored procedures.
b. To execute SQL queries with parameters.
c. To execute batch updates.
d. To retrieve metadata about the database.
[ihc-hide-content ihc_mb_type=”show” ihc_mb_who=”1,2,3″ ihc_mb_template=”1″ ]
Answer:- b
Q4. Which exception is commonly thrown when there is a failure in JDBC database connectivity?
a. FileNotFoundException
b. NullPointerException
c. SQLException
d. ClassNotFoundException
Answer:- c
Q5.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 4 image 30](https://gecmunger.in/wp-content/uploads/2023/10/image-30.png)
Answer:- c
Q6.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 5 image 31](https://gecmunger.in/wp-content/uploads/2023/10/image-31.png)
Answer:- a
Q7.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 6 image 32](https://gecmunger.in/wp-content/uploads/2023/10/image-32.png)
Answer:- a
Q8.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 7 image 33](https://gecmunger.in/wp-content/uploads/2023/10/image-33.png)
Answer:- b
Q9.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 8 image 34](https://gecmunger.in/wp-content/uploads/2023/10/image-34.png)
Answer:- d
Q10.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 9 image 35](https://gecmunger.in/wp-content/uploads/2023/10/image-35.png)
Answer:- c
[/ihc-hide-content]
NPTEL Programming In Java Week 10 Quiz Assignment Answers 2023
Q1. Which of the following statements) is(are) true?
a. TCP is not reliable.
b. UDP is not reliable.
c. TCP is fast and UDP is slow.
d. In HTTPS, all communication between two computers are encrypted.
Answer:- b, d
Q2. Which of the following statements) is/are true?
a. DatagramSocket is a UDP endpoint API.
b. DatagramSocket is a TCP server API.
c. ServerSocket is a TCP server API.
d. ServerSocket is a TCP client API.
Answer:- a, c
Q3. Which of the following is/are interface(s) present in java.net package?
a. InetAddress
b. URLConnection
c. SocketOptions
d. HttpURLConnection
Answer:- c
Q4. Which of the following statements) is/are true?
a. URL is the acronym for Uniform Resource Locator.
b. A URL takes the form of a string that describes how to find a resource on the Internet.
c. URLs have two main components: the protocol needed to access the resource and the location of the resource.
d. The URL class is present in the java.net package.
Answer:- a, b, c, d
Q5. In the following URL, identify the Resource name?
https://nptel.ac.in
a. https
b. nptel.ac.in
c. ac.in
d. https://nptel.ac.in
Answer:- b
Q6. Which of the following is/are application layer protocols)?
а. ТСР
b. UDP
с. HTTP
d. FTP
Answer:- c, d
Q7. In the socket programming, for an IP address, which can be used to find the host name and IPaddress of a client/ server?
a. The ServerSocket class
b. The Socket class
c. The InetAddress class
d The Connection interface
Answer:- c
Q8. Which of the following statement(s) is/are true?
a. Addresses belongs to a Low-Level API.
b. Sockets belong to High-Level API.
c. URIs and URLs are Low-Level API.
d. Interfaces are High-Level API.
Answer:- a
Q9. Which of the following statements) is/are true?
a. DatagramSocket implements Object.
b. DatagramSocket implements Closeable.
c. DatagramSocket extends Object.
d. DatagramSocket extends Closeable.
e. DatagramSocket extends Object implements Closeable
Answer:- e
Q10. Which of the following is/are application layer protocols)?
a. TCP
b. UDP
c. ARP
d. SMTP
Answer:- d
NPTEL Programming In Java Week 9 Quiz Assignment Answers 2023
1. Which of the following Swing components inherently support the WindowListener interface?
a. Swing frames (JFrame)
b. Swing checkboxes (JCheckBox)
c. Swing dialogs (JDialog)
d. Swing combo boxes (JComboBox)
Answer :- a
2. Which class in Swing provides a graphical way to display images, icons, or custom graphics?
a. JImage
b. JLabel
c. JImagelcon
d. JDialog
Answer :- b
3. Which event listener interface is commonly used to handle user actions like button clicks in Swing?
a. ActionListener
b. MouseListener
c. KeyListener
d. WindowListener
[ihc-hide-content ihc_mb_type=”show” ihc_mb_who=”1,2,3″ ihc_mb_template=”1″ ]
Answer :- a
4. What is/are the way(s) to create a Frame in Java Swing?
a. By creating the object of Frame class (association)
b. By extending Frame class (inheritance)
c. By importing a package named Frame
d. By declaring a class with name Frame
Answer :- a, b
5. Which method is used to add a component to a JPanel in Java Swing?
a. add ( )
b. addComponent )
c. addElement)
d. insertComponent)
Answer :- a
6. Which of the following(s) is/are interface(s) of java.awt package?
a. Button
b. Paint
c. Dialog
d. Shape
Answer :- b, d
7. Which AWT layout manager is often used to create a responsive grid of components that automatically adjusts to the container’s size?
a. BorderLayout
b. GridLayout
c. GridBagLayout
d. BoxLayout
Answer :- c
8. Which Swing component is used for allowing users to select files and directories from the file system?
a. JFileChooser
b. JFileSelector
c. JFilePicker
d. JFileDialog
Answer :- a
9. What is the primary disadvantage of using AWT over Swing for GUI development?
a. AWT components are not well-suited for complex layouts.
b. AWT lacks support for event handling.
AWT components are heavyweight and platform-dependent.
d. AWT does not support graphics rendering.
Answer :- c
10. Which of the following is/are valid alignment option(s) for components in a FlowLayout?
a. LEFT
b. TOP
c. BOTTOM
d. LEADING
Answer :- a, d
[/ihc-hide-content]
NPTEL Programming In Java Week 9 Programming Assignment Solutions 2023
Week 9 : Programming Assignment 1
Q1. Complete the code to develop a BASIC CALCULATOR that can perform operations like Addition, Subtraction, Multiplication and Division.
Answer :- import java.util.Scanner; public class Question91{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); String input = sc.nextLine(); // Read as string, e.g., 5+6 int i=0,j=0; double output=0; char seq[] = input.toCharArray(); for(int a=0; a<seq.length; a++){ if(seq[a]=='+'){ i= Integer.parseInt(input.substring(0,a)); j= Integer.parseInt(input.substring(a+1,seq.length)); output = (double)i+j; }else if(seq[a]=='-'){ i= Integer.parseInt(input.substring(0,a)); j= Integer.parseInt(input.substring(a+1,seq.length)); output = (double)i-j; }else if(seq[a]=='/'){ i= Integer.parseInt(input.substring(0,a)); j= Integer.parseInt(input.substring(a+1,seq.length)); output = (double)i/j; }else if(seq[a]=='*'){ i= Integer.parseInt(input.substring(0,a)); j= Integer.parseInt(input.substring(a+1,seq.length)); output = (double)i*j; } } System.out.print(input+" = " + Math.round(output)); } }
Week 9 : Programming Assignment 2
Q2. Complete the code to develop an ADVANCED CALCULATOR that emulates all the functions of the GUI Calculator as shown in the image.
[ihc-hide-content ihc_mb_type=”block” ihc_mb_who=”1,2,3″ ihc_mb_template=”1″ ]
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 10 image 44](https://gecmunger.in/wp-content/uploads/2023/09/image-44.png)
Answer :- import java.util.Scanner; public class Question92{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); String input = sc.nextLine(); char seq[] = input.toCharArray(); int outflag=0; for(int i=0; i<seq.length; i++){ seq[i]=gui_map(seq[i]); } double operand1=0.0; String o1=""; double operand2=0.0; String o2=""; double output=0.0; outerloop: for(int i=0; i<seq.length; i++){ int r=0; if(seq[i]=='+'||seq[i]=='-'||seq[i]=='/'||seq[i]=='X'||seq[i]=='='){ for(int j=0; j<i; j++){ o1+=Character.toString(seq[j]); } operand1=Double.parseDouble(o1); for(int k=i+1; k<seq.length; k++){ if(seq[k]=='='){ outflag=1; operand2=Double.parseDouble(o2); if(seq[i]=='+'){ output=operand1+operand2; }else if(seq[i]=='-'){ output=operand1-operand2; }else if(seq[i]=='/'){ output=operand1/operand2; }else if(seq[i]=='X'){ output=operand1*operand2; } break outerloop; }else{ o2+=Character.toString(seq[k]); } } } } if(outflag==1) System.out.print(output); }// The main() method ends here. // A method that takes a character as input and //returns the corresponding GUI character static char gui_map(char in){ char out = 'N';// N = Null/Empty char gm[][]={{'a','.'} ,{'b','0'} ,{'c','='} ,{'d','+'} ,{'e','1'} ,{'f','2'} ,{'g','3'} ,{'h','-'} ,{'i','4'} ,{'j','5'} ,{'k','6'} ,{'l','X'} ,{'m','7'} ,{'n','8'} ,{'o','9'} ,{'p','/'}}; // Checking for maps for(int i=0; i<gm.length; i++){ if(gm[i][0]==in){ out=gm[i][1]; break; } } return out; } }
Week 9 : Programming Assignment 3
Q3. Complete the code to perform a 45 degree anti clock wise rotation with respect to the center of a 5 × 5 2D Array as shown below:
Answer :- import java.util.Scanner; public class Question93{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); char arr[][]= new char[5][5]; // Input 2D Array using Scanner Class for(int line=0;line<5; line++){ String input = sc.nextLine(); char seq[] = input.toCharArray(); if(seq.length==5){ for(int i=0;i<5;i++){ arr[line][i]=seq[i]; } }else{ System.out.print("Wrong Input!"); System.exit(0); } } // Declaring the array to store Transition char tra[][] = new char[5][5]; String outer[]={"00","10","20","30", "40","41","42","43", "44","34","24","14", "04","03","02","01"}; String inner[]={"11","21","31","32", "33","23","13","12"}; // 45-Degree rotation for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ // Transform outer portion for(int k=0; k<outer.length; k++){ char indices[]=outer[k].toCharArray(); int a = Integer.parseInt(String.valueOf(indices[0])); int b = Integer.parseInt(String.valueOf(indices[1])); if(a==i && b==j){ if(k==15){k=1;} else if(k==14){k=0;} else {k+=2;} indices=outer[k].toCharArray(); a = Integer.parseInt(String.valueOf(indices[0])); b = Integer.parseInt(String.valueOf(indices[1])); tra[a][b] = arr[i][j]; break; } } // Transform inner portion for(int k=0; k<inner.length; k++){ char indices[]=inner[k].toCharArray(); int a = Integer.parseInt(String.valueOf(indices[0])); int b = Integer.parseInt(String.valueOf(indices[1])); if(a==i && b==j){ if(k==7){k=0;} else {k+=1;} indices=inner[k].toCharArray(); a = Integer.parseInt(String.valueOf(indices[0])); b = Integer.parseInt(String.valueOf(indices[1])); tra[a][b] = arr[i][j]; break; } } // Keeping center same tra[2][2] = arr[2][2]; } } // Print the transformed output for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ System.out.print(tra[i][j]); } System.out.println(); } } }
Week 9 : Programming Assignment 4
Q4. A program needs to be developed which can mirror reflect any 5 × 5 2D character array into its side-by-side reflection. Write suitable code to achieve this transformation as shown below:
Answer :- import java.util.Scanner; public class Question94{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); char original[][]= new char[5][5]; // Declaring 5x5 2D char array to store reflection char reflection[][]= new char[5][5]; // Input 2D Array using Scanner Class for(int line=0;line<5; line++){ String input = sc.nextLine(); char seq[] = input.toCharArray(); if(seq.length==5){ for(int i=0;i<5;i++){ original[line][i]=seq[i]; } } } // Performing the reflection operation for(int i=0; i<5;i++){ for(int j=0; j<5;j++){ reflection[i][j]=original[i][4-j]; } } // Output the 2D Reflection Array for(int i=0; i<5;i++){ for(int j=0; j<5;j++){ System.out.print(reflection[i][j]); } System.out.println(); } } }
Week 9 : Programming Assignment 5
Q5. Write suitable code to develop a 2D Flip-Flop Array with dimension 5 × 5, which replaces all input elements with values 0 by 1 and 1 by 0. An example is shown below:
Answer :- import java.util.Scanner; public class Question95{ public static void main(String args[]){ Scanner sc = new Scanner(System.in); char original[][]= new char[5][5]; // Input 2D Array using Scanner Class and check data validity for(int line=0;line<5; line++){ String input = sc.nextLine(); char seq[] = input.toCharArray(); if(seq.length==5){ for(int i=0;i<5;i++){ if(seq[i]=='0' || seq[i]=='1'){ original[line][i]=seq[i]; if(line==4 && i==4) flipflop(original); } else{ System.out.print("Only 0 and 1 supported."); break; } } }else{ System.out.print("Invalid length"); break; } } } static void flipflop(char[][] flip){ // Flip-Flop Operation for(int i=0; i<5;i++){ for(int j=0; j<5;j++){ if(flip[i][j]=='1') flip[i][j]='0'; else flip[i][j]='1'; } } // Output the 2D FlipFlopped Array for(int i=0; i<5;i++){ for(int j=0; j<5;j++){ System.out.print(flip[i][j]); } System.out.println(); } } }
[/ihc-hide-content]
Course Name | Programming In Java |
Category | NPTEL Assignment Answer |
Home | Click Here |
Join Us on Telegram | Click Here |
NPTEL Programming In Java Week 8 Quiz Assignment Answers 2023
1. Which of the following method is/are of class button in java.awt package?
a. getLabelO
b. setLabel(String label)
c. getCurrentO
d. getItem(int index)
Answer :- a, b
2. Which of the following is NOT a class of java.awt package?
a. Button
b. Component
c. Dialog
d. Paint
Answer :- d
3. Which of the following statements) is/are correct?
a. AWT components are platform-independent.
b. AWT follows the MVC (Model View Controller).
c. Swing components are platform-dependent.
d. Swing follows MVC (Model View Controller).
Answer :- d
4. When we invoke repaint () for a java. awt. Component object, the AWT invokes which following method?
a. draw)
b. show
c. update()
d. paint)
Answer :- c
5. Which package provides many event classes and Listener interfaces for event handling?
a. java.awt
b. java.lang
c. java.io
d. java.util
Answer :- a
6.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 11 a8q6](https://storage.googleapis.com/swayam-node1-production.appspot.com/assets/img/noc23_cs74/a8q6.png)
Answer :- d
7. Which of the following is TRUE regarding check box and radio button?
a. Check box is used for single selection item whereas radio button is used for multiple selection.
b. Check box is used for multiple selection items whereas radio button is used for single selection.
c. Both are used for multiple as well as single item selection.
d. Checkbox is always preferred than radio buttons.
Answer :- b
8. Which of the following is TRUE about check bor in Java?
a. A check box can be in either an “on” (true) or “off* (false) state.
b. Clicking on a check box changes its state from “on” to “off,” or from “off” to “on.”
c. A check box can be in an “on” (true) and in “off* (false) state simultaneouslv.
d. Check boxes cannot be grouped together.
Answer :- a, b
9. Which of the following is the latest graphics and media package for Java?
a. Applet
b. AWT
c. Swing
d. JavaFX
Answer :- d
10. If setText(String text) is a method of Label class, then why it is called non editable?
a. Because user-input is unavailable during runtime.
b. A Label is just a TextField with non-editable property turned on.
c. Labels are editable by default.
d. setText(String text) is not a method of Label class.
Answer :- a
NPTEL Programming In Java Week 8 Programming Assignment Solutions 2023
Week 8 : Programming Assignment 1
Q1. Write a program which will print a pyramid of “*” ‘s of height “n” and print the number of “*” ‘s in the pyramid.
For example:
Input : 5
Output:
*
* * *
* * * * *
* * * * * * *
* * * * * * * * *
25
Answer :- import java.util.*; public class Pattern1 { public static void main(String[] args) { Scanner inr = new Scanner(System.in); int n = inr.nextInt(); int k = 0,sum=0; for(int i = 1; i <= n; ++i, k = 0) { for(int space = 1; space <= n - i; ++space) { System.out.print(" "); } while(k != 2 * i - 1) { System.out.print("* "); sum=sum+1; ++k; } System.out.println(); } System.out.print(sum); } }
Week 8 : Programming Assignment 2
Q2. Write a program which will print a pascal pyramid of “*” ‘s of height “l” .
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 12 image 40](https://gecmunger.in/wp-content/uploads/2023/09/image-40.png)
Answer :- import java.util.*; public class Pattern2 { public static void main(String[] args) { Scanner inr = new Scanner(System.in); int l = inr.nextInt(); int i,j; int space=l-1; for(i=0;i< l;i++) { for(j=0;j< space;j++) { System.out.print(" "); } for(j=0;j<=i;j++) { System.out.print("* "); } System.out.print("\n"); space--; } } }
Week 8 : Programming Assignment 3
Q3. Write a program which will print a pyramid of “numbers” ‘s of height “n” and print the sum of all number’s in the pyramid.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 13 image 41](https://gecmunger.in/wp-content/uploads/2023/09/image-41.png)
Answer :- import java.util.*; public class Pattern3 { public static void main(String[] args) { Scanner inr = new Scanner(System.in); int n = inr.nextInt(); int k = 1,sum=0; for(int i = 1; i <= n; ++i, k = 1) { for(int space = 1; space <= n-i; ++space) { System.out.print(" "); } while(k <= 2 * i - 1) { System.out.print(k+" "); sum=sum+k; ++k; } System.out.println(); } System.out.print(sum); } }
Week 8 : Programming Assignment 4
Q4. Write a program to print symmetric Pascal’s triangle of “*” ‘s of height “l” of odd length . If input “l” is even then your program will print “Invalid line number”
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 14 image 42](https://gecmunger.in/wp-content/uploads/2023/09/image-42.png)
Answer :- import java.util.*; public class Pattern4 { public static void main(String[] args) { Scanner inr = new Scanner(System.in); int l = inr.nextInt(); int ul=0; // Upper Line int ll=0; // Lower Line if (l%2!=0) { ul=(l/2)+1; ll=l-ul; for(int i=1;i<=ul; i++) { for(int s=1;s<=(ul-i); s++) { System.out.print(" "); } for(int j=1;j<=i; j++) { System.out.print("* "); } System.out.println(); } int llc=ll; for(int i=1;i<=ll; i++) { for(int s=llc;s<ll; s++) { System.out.print(" "); } for(int j=1;j-1<=ll-i; j++) { System.out.print(" *"); } llc--; System.out.println(); } } else { System.out.print("Invalid line number"); } } }
Week 8 : Programming Assignment 5
Q4. Write a program to display any digit(n) from 0-9 represented as a “7 segment display”.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 15 image 43](https://gecmunger.in/wp-content/uploads/2023/09/image-43.png)
Answer :- import java.util.*; public class Pattern5{ private static final Map<Integer,Integer> encodings=new HashMap<Integer,Integer>(); static{ encodings.put(0, 0x7E); encodings.put(1, 0x30); encodings.put(2, 0x6D); encodings.put(3, 0x79); encodings.put(4, 0x33); encodings.put(5, 0x5B); encodings.put(6, 0x5F); encodings.put(7, 0x70); encodings.put(8, 0x7F); encodings.put(9, 0x7B); } public static void printDigit(int digit) { int code = encodeDigit(digit); char[] bits = String.format("%7s",Integer.toBinaryString(code)) .replace(' ','0').toCharArray(); lightSegmentDisp(bits[0] == '1', " _ \n", " \n"); lightSegmentDisp(bits[5] == '1', "|", " "); lightSegmentDisp(bits[6] == '1', "_", " "); lightSegmentDisp(bits[1] == '1', "|\n", " \n"); lightSegmentDisp(bits[4] == '1', "|", " "); lightSegmentDisp(bits[3] == '1', "_", " "); lightSegmentDisp(bits[2] == '1', "|\n", " \n"); } private static void lightSegmentDisp(boolean On, String onVal, String offVal) { System.out.print(On ? onVal : offVal); try { Thread.sleep(0); } catch (InterruptedException e) { e.printStackTrace(); } } private static int encodeDigit(int d) { return encodings.containsKey(d) ? encodings.get(d) : 0x00; } public static void main(String[] args) throws Exception { Scanner inr = new Scanner(System.in); int n = inr.nextInt(); printDigit(n); } }
Course Name | Programming In Java |
Category | NPTEL Assignment Answer |
Home | Click Here |
Join Us on Telegram | Click Here |
NPTEL Programming In Java Week 7 Quiz Assignment Answers 2023
1.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 16 a7q1](https://storage.googleapis.com/swayam-node1-production.appspot.com/assets/img/noc23_cs74/a7q1.png)
Answer :- d
2. Which method is used to write an array of byte to the current output stream?
a. public void write(int b)throws IOException {{
b. public void flush(byte [ ] b)throws IOException {}
c. public void write (byte [ 1 b)throws IOException {}
d. public int write(int b)throws IOException {}
Answer :- c
3. Which of the following is NOT a Standard Stream?
a. System.in
b. System.out
c. System.eir
d. System.console
Answer :- d
4. Which of the following method(s) not included in OutputStream class?
a. close()
b. write )
c. skip()
d. flush)
Answer :- c
5. Which of the following method of the BufferedReader class is used for reading lines of text from the console, the file or other input streams?
a. read
b. readLine()
c. readByte)
d. read(byte [ ] b)
Answer :- b
6.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 17 a7q6n](https://storage.googleapis.com/swayam-node1-production.appspot.com/assets/img/noc23_cs74/a7q6n.png)
Answer :- a
7. Which of the following is/are interface(s) in java. io package?
a. File Writer
b. FileFilter
c. ObiectOutput
d. DataOutput
Answer :- b, c, d
8. Fill in the blanks.
The class DataInputStream extends ______ and implements the interface _____.
a. FileImputStream , FileInput
b. FilterInputStream, DataImput
c. FilterInputStream, FileImput
d. FileImputStream, Datalmput
Answer :- b
9. Which of the following method(s) not included in ImputStream class?
a. available)
b. reset( )
c. read)
d. flush()
Answer :- d
10. Which of the following package contains a large number of stream classes that provide capabilities for processing all types of data?
a. java.awt.
b. java.io
C. java.net
d. java.util
Answer :- b
NPTEL Programming In Java Week 7 Programming Assignment Solutions 2023
Week 7 : Programming Assignment 1
Q1. Complete the following code fragment to read three integer values from the keyboard and find the sum of the values. Declare a variable “sum” of type int and store the result in it.
Answer :- import java.util.*; public class Question1{ public static void main (String[] args){ int i,n=0,sum=0; Scanner inr = new Scanner(System.in); for (i=0;i<3;i++) { n = inr.nextInt(); sum =sum+n; } System.out.println(sum); } }
Week 7 : Programming Assignment 2
Q2. Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “Please enter valid data” .If there is no such exception, it will print the “square of the number”.
Answer :- import java.io.*; public class Question2{ public static void main(String args[]){ try { InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); String number=br.readLine(); int x = Integer.parseInt(number); System.out.println(x*x); } catch (Exception e){ System.out.println("Please enter valid data"); } } }
Week 7 : Programming Assignment 3
Q3. A byte char array is initialized. You have to enter an index value”n”. According to index your program will print the byte and its corresponding char value.
Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, it will print the required output.
Answer :- import java.util.*; public class Question3 { public static void main(String[] args) { try{ byte barr[]={'N','P','T','E','L','-','J','A','V','A','J','A','N','-','N','O','C','C','S','E'}; Scanner inr = new Scanner(System.in); int n = inr.nextInt(); String s2 = new String(barr,n,1); System.out.println(barr[n]); System.out.println(s2); } catch (Exception e){ System.out.println("exception occur"); } } }
Week 7 : Programming Assignment 4
Q4. The following program reads a string from the keyboard and is stored in the String variable “s1”. You have to complete the program so that it should should print the number of vowels in s1 . If your input data doesn’t have any vowel it will print “0”.
Answer :- import java.io.*; import java.util.*; public class Question4{ public static void main(String[] args) { int c=0; try{ InputStreamReader r=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(r); String s1 = br.readLine(); for(int i=0;i<s1.length();i++){ char s2=s1.charAt(i); if(s2=='e' || s2=='E'|| s2=='a' || s2=='A' || s2=='i' || s2=='I' || s2=='o' || s2=='O' || s2=='u' || s2=='U') { c=c+1; } } System.out.println(c); } catch (Exception e){ System.out.println(e); } } }
Week 7 : Programming Assignment 5
Q5. A string “s1” is already initialized. You have to read the index “n” from the keyboard. Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, your program should replace the char “a” at the index value “n” of the “s1” ,then it will print the modified string.
Answer :- import java.util.*; public class Question5 { public static void main(String[] args) { try{ String s1="NPTELJAVA"; Scanner inr = new Scanner(System.in); int n = inr.nextInt(); char c='a'; byte[] barr=s1.getBytes(); byte b1 = (byte) c; barr[n]=b1; System.out.println(new String(barr)); } catch (Exception e){ System.out.println("exception occur"); } } }
Course Name | Programming In Java |
Category | NPTEL Assignment Answer |
Home | Click Here |
Join Us on Telegram | Click Here |
NPTEL Programming In Java Week 6 Quiz Assignment Answers 2023
Q1. Which of the following is NOT a method of the Thread class in Java?
a. isInterrupted ()
b. interrupt ()
c. joins ()
d. sleep ()
Answer:- c
Q2. Which of the following statements) is/are true?
a. public int getId (): returns the id of the thread.
b. public boolean isAlive (): tests if the thread is alive.
c. public void interrupt (): interrupts the thread.
d. public boolean isInterrupted (): tests if the thread has been interrupted.
Answer:- a, b, c, d
Q3. Which of the following can be used to create an instance of Thread?
a. By implementing the Runnable interface.
b. By extending the Thread class.
c. By creating a new class named Thread and calling method run 0.
d. By importing the Thread class from package.
Answer:- a, b
Q4.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 18 image](https://gecmunger.in/wp-content/uploads/2023/09/image.png)
Answer:- c
Q5. Which one of these keywords must be used to handle the exception thrown by try block in some rational manner?
a. try
b. finally
c. throw
d. catch
Answer:- d
Q6. Assume the following method is properly synchronized and called from a thread A on an object B: wait(2000); After calling this method, when will the thread A become a candidate to get another turn at the CPU?
a) After thread A is notified, or after two seconds.
b) Two seconds after thread A is notified.
c) After the lock on B is released, or after two seconds.
d) Two seconds after lock B is released.
Answer:- a
Q7.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 19 image 1](https://gecmunger.in/wp-content/uploads/2023/09/image-1.png)
Answer:- a
Q8.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 20 image 2](https://gecmunger.in/wp-content/uploads/2023/09/image-2.png)
Answer:- c
Q9. Which of the following is a correct constructor for a thread object?
a. Thread (Runnable a, String str);
b. Thread (Runnable a, int priority);
c. Thread (Runnable a, ThreadGroup t);
d. Thread (int priority);
Answer:- a
Q10. Which of these keyword(s) is used to manually throw an exception?
a. try
b. finally
c. throw
d. catch
Answer:- c
NPTEL Programming In Java Week 6 Programming Assignment Solutions 2023
Q1. Complete the code segment to print the following using the concept of extending the Thread class in Java:
—————–OUTPUT——————-
Thread is Running.
————————————————-
Solution:-
// Write the appropriate code to extend the Thread class to complete the class Question61.
public class Question61 extends Thread{
public void run(){
System.out.print("Thread is Running.");
}
public static void main(String args[]){
// Creating object of thread class
Question61 thread=new Question61();
// Start the thread
thread.start();
}
}
Question : 2 In the following program, a thread class Question62 is created using the Runnable interface Complete the main() to create a thread object of the class Question62 and run the thread. It should print the output as given below.
Output : Welcome to Java Week 6 New Question.
Main Thread has ended.
[ihc-hide-content ihc_mb_type=”show” ihc_mb_who=”1,2,3″ ihc_mb_template=”1″ ]
public class Question62 implements Runnable {
@Override
public void run() {
System.out.print(Thread.currentThread().getName()+" has ended.");
}
// Create main() method and appropriate statements in it
public static void main(String[] args)
{
Question62 ex = new Question62();
Thread t1= new Thread(ex);
t1.setName("Main Thread");
t1.start();
System.out.println("Welcome to Java Week 6 New Question.");
t1.setName("Main Thread");
}
}
Question : 3 A part of the Java program is given, which can be completed in many ways, for example using the concept of thread, etc. Follow the given code and complete the program so that your program prints the message “NPTEL Java week-6 new Assignment Q3“. Your program should utilize the given interface/ class.
// Interface A is defined with an abstract method run()
interface A {
public abstract void run();
}
// Class B is defined which implements A and an empty implementation of run()
class B implements A {
public void run() {}
}
// Class MyThread is defined which extends class B
class MyThread extends B {
// run() is overriden and 'NPTEL Java' is printed.
public void run() {
System.out.print("NPTEL Java week-6 new Assignment Q3");
}
}
// Main class Question is defined
public class Question63 {
public static void main(String[] args) {
// An object of MyThread class is created
MyThread t = new MyThread();
// run() of class MyThread is called
t.run();
}
}
Question : 4 Execution of two or more threads occurs in a random order. The keyword ‘synchronized‘ in Java is used to control the execution of thread in a strict sequence. In the following, the program is expected to print the output as given below. Do the necessary use of ‘synchronized‘ keyword, so that, the program prints the Final sum as given below:
Output : Final sum:6000
class Pair {
private int a, b;
public Pair() {
a = 0;
b = 0;
}
// Returns the sum of a and b. (reader)
// Should always return an even number.
public synchronized int sum() {
return(a+b);
}
// Increments both a and b. (writer)
public synchronized void inc() {
a++;
b++;
}
}
public class PairWorker extends Thread {
public final int COUNT = 1000;
private Pair pair;
// Ctor takes a pointer to the pair we use
public PairWorker(Pair pair) {
this.pair = pair;
}
// Send many inc() messages to our pair
public void run() {
for (int i=0; i<COUNT; i++) {
pair.inc();
}
}
public static void main(String args[]) {
Pair pair = new Pair();
PairWorker w1 = new PairWorker(pair);
PairWorker w2 = new PairWorker(pair);
PairWorker w3 = new PairWorker(pair);
w1.start();
w2.start();
w3.start();
// the 3 workers are running
// all sending messages to the same object
// we block until the workers complete
try {
w1.join();
w2.join();
w3.join();
}
catch (InterruptedException ignored) {}
System.out.println("Final sum:" + pair.sum()); // should be 6000
}
}
Question : 5 Given a snippet of code, add necessary codes to print the following:
—————–OUTPUT——————-
Name of thread ‘t1’:Thread-0
Name of thread ‘t2’:Thread-1
New name of thread ‘t1’:Week 6 Assignment Q5
New name of thread ‘t2’:Week 6 Assignment Q5 New
public class Question65 extends Thread{
public void run(){
}
public static void main(String args[]){
Question65 t1=new Question65();
System.out.println("Name of thread 't1':"+ t1.getName());
Question65 t2=new Question65();
System.out.println("Name of thread 't2':"+ t2.getName());
// start the thread-1
t1.start();
// set the name of thread-1
t1.setName("Week 6 Assignment Q5");
// start the thread-2
t2.start();
// set the name of thread-2
t2.setName("Week 6 Assignment Q5 New");
System.out.println("New name of thread 't1':"+ t1.getName());
System.out.println("New name of thread 't2':"+ t2.getName());
}
}
NPTEL Programming In Java Week 5 Quiz Assignment Answers 2023
Q1.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 21 image 39](https://gecmunger.in/wp-content/uploads/2023/08/image-39.png)
Answer:- b
Q2. Which of the following statements) is/are false?
- A class can extend more than one class.
- An interface can extend many interfaces.
- An interface can implement many interfaces.
- A class can extend one class and implement mamy interfaces.
a. 1
b. 2
c. 3
d. 4
Answer:- a, c
Q3.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 22 image 40](https://gecmunger.in/wp-content/uploads/2023/08/image-40.png)
Answer:- c
Q4. Which of the following statements) is/are false?
a. Interface can provide the implementation of an abstract class.
b. The variables defined inside an interface are static and final by default.
c. An interface is used to achieve full abstraction.
d. Inside an interface, a constructor can be called using the super keyword with hierarchy.
Answer:- a, d
Q5.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 23 image 41](https://gecmunger.in/wp-content/uploads/2023/08/image-41.png)
Answer:- d
Q6. Which of the following keywords is/are a part of exception handling?
a. finally
b. throws
c. throw
d. thrown
Answer:- a, b, c
Q7.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 24 image 42](https://gecmunger.in/wp-content/uploads/2023/08/image-42.png)
Answer:- a
Q8. Exception class exist in which of the following package?
a. java.void
b. java.io
c. java.lang
d. java.awt
Answer:- c
Q9.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 25 image 43](https://gecmunger.in/wp-content/uploads/2023/08/image-43.png)
Answer:- c, d
Q10.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 26 image 44](https://gecmunger.in/wp-content/uploads/2023/08/image-44.png)
Answer:- c
NPTEL Programming In Java Week 5 Programming Assignment Solutions 2023
Q1. An interface Number is defined in the following program. You have to declare a class A, which will implement the interface Number. Note that the method findSqr(n) will return the square of the number n.
Solution:
import java.util.Scanner; interface Number { int findSqr(int i); // Returns the square of n } //Create a class A which implements the interface Number. class A implements Number { //Define a method to find the square of a number int i, square; public int findSqr(int i) { square=i*i; return square; } } public class Question5_1{ public static void main (String[] args){ A a = new A(); //Create an object of class A // Read a number from the keyboard Scanner sc = new Scanner(System.in); int i = sc.nextInt(); System.out.print(a.findSqr(i)); } }
Q2. This program is to find the GCD (greatest common divisor) of two integers writing a recursive function findGCD(n1,n2). Your function should return -1, if the argument(s) is(are) other than positive number(s).
Solution:-
import java.util.Scanner; interface GCD { public int findGCD(int n1,int n2); } //Create a class B, which implements the interface GCD. class B implements GCD { int n1,n2; //Create a method to calculate GCD public int findGCD(int n1, int n2){ if(n1==0&& n2==0) { return -1; } else if(n2 == 0){ return n1; } else { return findGCD(n2, n1%n2); } } } public class Question5_2{ public static void main (String[] args){ B a = new B(); //Create an object of class B // Read two numbers from the keyboard Scanner sc = new Scanner(System.in); int p1 = sc.nextInt(); int p2 = sc.nextInt(); System.out.print(a.findGCD(p1,p2)); } }
Q3. Complete the code segment to catch the ArithmeticException in the following, if any. On the occurrence of such an exception, your program should print “Exception caught: Division by zero.” If there is no such exception, it will print the result of division operation on two integer values.
Solution:
//Prefixed Fixed Code: import java.util.*; public class Question5_4{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int length = sc.nextInt(); // create an array to save user input int[] name = new int[length]; int sum=0;//save the total sum of the array. //Define try-catch block to save user input in the array "name", if there is an exception then catch the exception otherwise print the total sum of the array. try { for(int i=0;i<length;i++) { int userInput=sc.nextInt(); name[i] = userInput; sum=sum+name[i]; } System.out.print(sum); } catch(InputMismatchException e) { System.out.print("You entered bad data."); } } }
Q4. In the following program, an array of integer data to be initialized. During the initialization, if a user enters a value other than integer value, then it will throw InputMismatchException exception. On the occurrence of such an exception, your program should print “You entered bad data.” If there is no such exception it will print the total sum of the array.
Solution:
import java.util.*; public class Question5_4{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); int length = sc.nextInt(); // create an array to save user input int[] name = new int[length]; int sum=0;//save the total sum of the array. //Define try-catch block to save user input in the array "name", if there is an exception then catch the exception otherwise print the total sum of the array. try { for(int i=0;i<length;i++) { int userInput=sc.nextInt(); name[i] = userInput; sum=sum+name[i]; } System.out.print(sum); } catch(InputMismatchException e) { System.out.print("You entered bad data."); } } }
Q5. In the following program, there may be multiple exceptions. You have to complete the code using only one try-catch block to handle all the possible exceptions.
For example, if user’s input is 1, then it will throw and catch “java.lang.NullPointerException“.
Solution:
import java.util.Scanner; public class Question5_5{ public static void main (String args[ ] ) { Scanner scan = new Scanner(System.in); int i = scan.nextInt(); int j; // Put the following code under try-catch block to handle exceptions try{ switch (i) { case 0 : int zero = 0; j = 92/ zero; break; case 1 : int b[ ] = null; j = b[0] ; break; default: System.out.print("No exception"); } } // catch block catch (Exception e) { System.out.print(e) ; } } }
NPTEL Programming In Java Week 4 Quiz Assignment Answers 2023
Q1. Which of the following is the correct statement for creating a package?
a. package;
b. package «package name>;
c. package:
d. «package name>;
Answer:- b
2. How Java Runtime Environment (JRE) knows where to look for a package that you create?
a. It searches in the current directory.
b. It searches in the location set in the CLASSPATH environment variable.
c. A user can set the path during runtime using the -classpath option.
d. Using the -path option, a user can set the path.
Answer:- a, b, c
3. Which of the following statements) is/are false?
a. Java packages are hierarchical.
b. system.out.println () is a predefined java function.
c. Java can have a nested class structure.
d. The Java static kevword is a non-access modifier.
Answer:- a
4. Which of the following is/are NOT correct regarding packages in Java?
a. Java supports both pre-defined and user-defined packages.
b. Packages are used to organize a set of related classes and interfaces.
c. Pre-defined packages help to develop programs easily by providing thousands of classes.
d. Packages are used to organize only a set of related classes and not interfaces.
Answer:- d
5. Consider the program given below.
public class Main {
public static void main (String args []) {
System.out.println (cos (2*PI));
}
}
What will be the output if the above program is executed?
a. It will give compile-time error
b. It will give run-time ertor
c. 1.0
d. 3.14
Answer:- a
6. Which of the following is the minimum requirement for executing a Java program?
a. JDK
b. RE
c. JDK without JRE
d. JRE without JDK
Answer:- b, d
7. Which of the following is required for developing a Java program?
a. DK
b. IRE
c. JDK without JRE
d. JRE without JDK
Answer:- a
8. Which of the following is/are valid declaration(s) of an interface?
a. public interface Question (
void method (int value) {
System.out.println ("Nptel");
]
b.public interface Question (
void method (int value);
)
c. public interface Question (
)
d. public interface Question (
default void method (int value) |
System.out.println ("Nptel");
Answer:- b, c, d
9. Which of the following statements) is/are NOT true?
a. The default package in the Java language is java lang.
b. String is a final class and it is present in java.lang package.
c. Runnable is a class present in java.lang package.
d. Thread is a class present in java.lang package.
Answer:- c
10. Which of the following statements) is/are true?
a. With the import statement, generally import only a single package member or an entire
package.
b. To import all the types contained in a particular package, use the import statement with
the asterisk () wildcard character. import package.;
C. import package.A: it used to match a subset of the classes in a package starts with “A”
d. import package.A: it generates compilation error.
Answer:- a, b, d
NPTEL Programming In Java Week 4 Programming Assignment Solutions 2023
Q1. Complete the code segment to execute the following program successfully. You should import the correct package(s) and/or class(s) to complete the code.
Solution:-
// Import the required package(s) and/or class(es) import java.util.Scanner; import static java.lang.System.*; // main class Question is created public class Question41{ public static void main(String[] args) { // Scanner object is created Scanner scanner = new Scanner(System.in); // Read String input using scanner class String courseName = scanner.nextLine(); // Print the scanned String out.println("Course: " + courseName); } }
Q2. Complete the code segment to print the current year. Your code should compile successfully.
Note: In this program, you are not allowed to use any import statement. Use should use predefined class Calendar defined in java.util package.
Solution:-
// The following is the declaration of the main class named Question42 public class Question42 { public static void main(String args[]){ int year; // integer type variable to store year // Create an object of Calendar class. java.util.Calendar current; // Use getInstance() method to initialize the Calendar object. current = java.util.Calendar.getInstance(); // Initialize the int variable year with the current year year = current.get(current.YEAR); // Print the current Year System.out.println("Current Year: "+year); //~~~THERE IS SOME INVISIBLE CODE HERE~~~ } }
Q3. The program in this assignment is attempted to print the following output:
—————–OUTPUT——————-
This is large
This is medium
This is small
This is extra-large
———————————————–
However, the code is intentionally injected with some bugs. Debug the code to execute the program successfully.
Solution:-
interface ExtraLarge{ static String extra = "This is extra-large"; void display(); } class Large { public void Print() { System.out.println("This is large"); } } class Medium extends Large { public void Print() { super.Print(); System.out.println("This is medium"); } } class Small extends Medium { public void Print() { super.Print(); System.out.println("This is small"); } } class Question43 implements ExtraLarge{ public static void main(String[] args) { Small s = new Small(); s.Print(); Question43 q = new Question43(); q.display(); } public void display(){ System.out.print(extra); } }
Q4. Complete the code segment to call the default method in the interface First and Second.
Solution:-
interface First{ // default method default void show(){ System.out.println("Default method implementation of First interface."); } } interface Second{ // Default method default void show(){ System.out.println("Default method implementation of Second interface."); } } // Implementation class code class Question44 implements First, Second{ // Overriding default show method public void show(){ // Call show() of Second interface. Second.super.show(); // Call show() of First interface. First.super.show(); } public static void main(String args[]){ Question44 q = new Question44(); q.show(); } }
Q5. Modify the code segment to print the following output.
—————–OUTPUT——————-
Circle: This is Shape1
Circle: This is Shape2
————————————————-
Solution:-
// Interface ShapeX is created interface ShapeX { public String base = "This is Shape1"; public void display1(); } // Interface ShapeY is created which extends ShapeX interface ShapeY extends ShapeX { public String base = "This is Shape2"; public void display2(); } // Class ShapeG is created which implements ShapeY class ShapeG implements ShapeY { public String base = "This is Shape3"; //Overriding method in ShapeX interface public void display1() { System.out.println("Circle: " + ShapeX.base); } // Overriding method in ShapeY interface public void display2() { System.out.print("Circle: " + ShapeY.base); } } // Main class Question public class Question45{ public static void main(String[] args) { //Object of class shapeG is created and display methods are called. ShapeG circle = new ShapeG(); circle.display1(); circle.display2(); } }
NPTEL Programming In Java Week 3 Quiz Assignment Answers 2023
1. In which of the following scenario(s), the static block is used in Java?
a. To create static variables.
b. To initialize instance variables.
c. To initialize static variables.
d. To create new objects.
Answer :- c
2. Consider the following piece of code.
public static void main(String[] args) {
incrementCount();
System.out.println("Count: " + count);
}
___________ incrementCount() {
count++;
}
}
Fill in the blank with the appropriate keyword(s) from the list given below so that the program compiles successfully.
a. public void
b. private void
c. public static void
d. private static void
Answer :- c, d
3. Consider the following piece of code.
class A {
public void display() {
System.out.println("A's display method");
}
}
class B extends A {
public void display() {
System.out.println("B's display method");
}
}
public class Main {
public static void main(String[] args) {
A a = new B();
a.display();
((B) a).display();
}
}
What is the output of the above code?
a. A’s display method
B’s display method
b. A’s display method
A’s display method
c. B’s display method
B’s display method
d. B’s display method
A’s display method
Answer :- c
4. Which of the following statements) is/are false?
a. You can write a new instance method in the subclass with the same signature as the one in the superclass, thus overriding it.
b. You can write a new static method in the subclass with the same signature as the one in the superclass, thus hiding it.
c. A subclass inherits all of its parent’s public and protected members, no matter what package the subclass is in.
d. You cannot declare new methods in the subclass that are not in the superclass.
Answer :- d
5. Which of the following statement(s) is/are true?
a. You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass.
b. You can prevent a class from being subclassed by using the final keyword in the class’s declaration.
c. An abstract class can be instantiated.
d. Common behaviour can be defined in a superclass and inherited into a subclass using the extends keyword.
Answer :- a, b, d
6. Consider the following program.
public class Question {
public static void main(String[] args) {
String str = " programming in java ";
System.out.println(str.substring(1, 3)+str.substring(4, 5) +
str.substring(6, 8));
}
}
What is the output of the above program?
a. prgam
b. program
c. gramm
d. ing in
Answer :- a
7. Consider the following piece of code.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 27 a3q7](https://storage.googleapis.com/swayam-node1-production.appspot.com/assets/img/noc23_cs74/a3q7.png)
Which of the following is the output of the above program?
a. 10
100
b. 10
20
c. 100
10
d. 10
10
Answer :- a
8. Consider the following program.
class Question {
int a = 400;
int b = 200;
}
class Child extends Question {
int a = 1000;
int b = 2000;
void add(int a, int b) {
System.out.println(a + this.b - super.a);
}
}
public class Main {
public static void main(String[] args) {
Child c = new Child();
c.add(100, 300);
}
}
If the program is executed, then what will be the output from the execution?
a. 1700
b. 1300
c. 0
d. 2600
Answer :- a
9. Which of the following statement(s) is/are true?
a. Hiding internal data from the outside world and accessing it only through publicly exposed methods is known as data encapsulation.
b. Static methods in interfaces are never inherited.
c. The term “class variable” is another name for a non-static field.
d. A local variable stores a temporary state; it is declared inside a method.
Answer :- a, b, d
10. All classes in java are inherited from which class?
a. java.lang.class
b. java.class.inherited
c. java.class.object
d. java.lang.Object
Answer :- d
NPTEL Programming In Java Week 3 Programming Assignment Solutions 2023
Q1. This program is related to the generation of Fibonacci numbers.
For example: 0,1, 1,2, 3,5, 8, 13,… is a Fibonacci sequence where 13 is the 8th Fibonacci number.
A partial code is given and you have to complete the code as per the instruction given .
Solution:-
import java.util.Scanner; //This package for reading input public class Fibonacci { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); //Read an integer System.out.println(fib(n)); //Generate and print the n-th Fibonacci //number } static int fib(int n) { if (n==1) //Terminal condition return 0; else if(n==2) return 1; return fib(n - 1) + fib(n - 2); //Recursive call of function } }
Q2. Define a class Point with two fields x and y each of type double. Also, define a method distance(Point p1, Point p2) to calculate the distance between points p1 and p2 and return the value in double.
Complete the code segment given below. Use Math.sqrt( ) to calculate the square root.
Solution:-
import java.util.Scanner; public class Circle extends Point{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); Point p1=new Point(); p1.x=sc.nextDouble(); p1.y=sc.nextDouble(); Point p2=new Point(); p2.x=sc.nextDouble(); p2.y=sc.nextDouble(); Circle c1=new Circle(); c1.distance(p1,p2); } } class Point{ double x; double y; public static void distance(Point p1,Point p2) { double d; d=Math.sqrt((p2.x-p1.x)*(p2.x-p1.x) + (p2.y-p1.y)*(p2.y-p1.y)); System.out.print(d); } }
Q3. A class Shape is defined with two overloading constructors in it. Another class Test1 is partially defined which inherits the class Shape. The class Test1 should include two overloading constructors as appropriate for some object instantiation shown in main() method. You should define the constructors using the super class constructors. Also, override the method calculate( ) in Test1 to calculate the volume of a Shape.
Solution:-
import java.util.Scanner; class Shape{ double length, breadth; Shape(double l, double b){ //Constructor to initialize a Shape object length = l; breadth= b; } Shape(double len){ //Constructor to initialize another Shape object length = breadth = len; } double calculate(){// To calculate the area of a shape object return length * breadth ; } } public class Test1 extends Shape{ //Template code: double height; Test1(double length,double h) { //base class constructor with one parameter is called super(length); height=h; } Test1(double length,double breadth,double h) { //base class constructor having two argument is called super(length,breadth); height=h; } double calculate() { return length*breadth*height; } public static void main(String args[]){ Scanner sc = new Scanner(System.in);//Create an object to read //input double l=sc.nextDouble(); //Read length double b=sc.nextDouble(); //Read breadth double h=sc.nextDouble(); //Read height Test1 myshape1 = new Test1(l,h); Test1 myshape2 = new Test1(l,b,h); double volume1; double volume2; volume1 = myshape1.calculate(); volume2=myshape2.calculate(); System.out.println(volume1); System.out.println(volume2); } }
Q4. This program to exercise the call of static and non-static methods. A partial code is given defining two methods, namely sum( ) and multiply ( ). You have to call these methods to find the sum and product of two numbers. Complete the code segment as instructed.
Solution:-
import java.util.Scanner; class QuestionScope { int sum(int a, int b){ //non-static method return a + b; } static int multiply(int a, int b){ //static method return a * b; } } public class Exercise3_4{ public static void main( String[] args ) { Scanner sc = new Scanner(System.in); int n1=sc.nextInt(); int n2=sc.nextInt(); //Called the method sum() to find the sum of two numbers. //Called the method multiply() to find the product of two numbers. QuestionScope st = new QuestionScope(); // Create an object to call non-static method int result1=st.sum(n1,n2); // Call the method int result2=QuestionScope.multiply(n1,n2); // Create an object to call static method System.out.println(result1); System.out.print(result2); } }
Q5. Complete the code segment to swap two numbers using call by object reference.
Solution:-
import java.util.Scanner; class Question { //Define a class Question with two elements e1 and e2. Scanner sc = new Scanner(System.in); int e1 = sc.nextInt(); //Read e1 int e2 = sc.nextInt(); //Read e2 } public class Question3 { // Define static method swap()to swap the values of e1 and e2 of class Question. public static void swap(Question t) { int temp = t.e1; t.e1 = t.e2; t.e2 = temp; } public static void main(String[] args) { //Create an object of class Question Question t = new Question (); //Call the method swap() swap(t); System.out.println(t.e1+" "+t.e2); } }
Course Name | Programming In Java |
Category | NPTEL Assignment Answer |
Home | Click Here |
Join Us on Telegram | Click Here |
NPTEL Programming In Java Week 2 Assignment Answers 2023
1. Consider the following code segment:
1 class Question{
2 public static void main(String args){
3. System.out.print(“Welcome to NPTEL”);
4. }
5. }
Identify the numbers where there is/are error(s) in the above code.
a. 1
b. 2
c. 3
d. 4 and 5
Answer :- b
2. Consider the following code segment:
1 class Question{
2 public static void main(String[] param 0{
3 System.out.print(“Welcome to NPTEL”);))
4 }
5 }
Identify the numbers where there is/are error(s) in the above code.
a. 1
b. 2
c. 3
d. 4 and 5
Answer :- d
3. Consider the following code segment:
1 class Question{
2 public static void main(String args[]) {
3. for(int n=1; n<=10; n++){
4. system.out.print(n+” “);
5. }
6. }
7. }
Select the correct output description for the above code.
a. Prints first n natural numbers in a single line.
b. Prints first n natural numbers, one number in a single line.
c. Prints first 10 natural numbers in a single line.
d. Prints first 10 natural numbers in a single line with no spaces.
Answer :- c
4. Consider the following code segment:
1 class Question{
2 public static void main(String args[]) {
3. for(int n=1; n<=10; n++){
4. system.out.print(n+” “);
5. }
6. }
7. }
Modify the above code such that it prints all the even numbers till 100.
a. Replace line 3 with for (int n=2; n<=100; n++){
b. Replace line 3 with for (int n=2; n<=100; n+=2){
c. Replace line 4 with system.out.print(++n + ” “);
d. Both option a and c.
Answer :- c
5. Following is a program given for this question.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 28 image 5](https://gecmunger.in/wp-content/uploads/2023/08/image-5.png)
What will be the output of the above program?
a. 22221018
b. 22222018
c. 22101018
d. 22221218
Answer :- b
6. Consider the following incorrect program.
1 public class Question
2 public static void main (String[] args) {
3. short x = 10;
4. x = x * 5;
5. System.out.print (x);
6. }
7. }
How to correct the above code segment?
a. Change line 4 as x = (short) (x * 5);
b. Change line 4 as x = (short) x * 5;
c. Change line 4 as x = (short) x * (short) 5;
d. Change line 4 as (short) x = x * 5;
Answer :- a
7. What will be the output of the above program?
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 29 image 6](https://gecmunger.in/wp-content/uploads/2023/08/image-6.png)
a. 210
b. 120
c. 012
d. 000
Answer :- d
8. Consider the following piece of code.
public class Question!
public static void main (String[] args) {
String str = “anpotdelqjpava”;
System.out.printin(str.substring (1, 3) +str.substring (4, 5) +
str.substring (6, 8));
Which of the following option is the output of the above program?
a. java
b. nptel java
c. nptel java
d. nptel
Answer :- d
9. What is the output of the following program?
public class Main{
public void static main (string args []) {
char a = ‘a
int b = 20;
System.out.printin (a+b);
}
}
a. 60
b. 117
c. 33
d. Compilation error
Answer :- d
10. Consider the following program.
public class Question
public static void main (String[] args) {
int x = 5;
x *= (2 + 8) ;
System.out.printin (x) ;
}
}
What will be the output of the program if it is executed?
a. 50
b. 10
c. Compiler error
d. 5
Answer :- a
NPTEL Programming In Java Week 2 Programming Assignment Answers
1. Complete the code segment to call the method print() of class Student first and then call print() method of class School.
Solution:-
class School { // This is a method in class School public void print() { System.out.println("Hi! I class SCHOOL."); } } // This is the class named Student class Student { // This is a method in class Student public void print() { System.out.println("Hi! I am class STUDENT"); } } public class Question21{ public static void main(String args[]){ // Create an object of class Student Student student = new Student(); // Call 'print()' method of class Student student.print(); // Create an object of class School School school = new School(); // Call 'print()' method of class School school.print(); } }
2. Complete the code segment to call the method print() of class given class Printer to print the following.
——————————–
Hi! I am class STUDENT
Hi! I class SCHOOL.
——————————–
// This is the class named Printer class Printer { // This are the methods in class Printer public void print() { System.out.println("Hi! I class SCHOOL."); } public void print(String s) { System.out.println(s); } } public class Question22{ public static void main(String[] args) { // Create an object of class Printer Printer p = new Printer(); // Call 'print()' methods for desired output p.print("Hi! I am class STUDENT"); p.print(); } }
3. Complete the code segment tocall print() method of class Question by creating a method named ‘studentMethod()’.
// This is the main class Question public class Question23{ public static void main(String[] args) { // Object of the main class is created Question23 q = new Question23(); // Print method on object of Question class is called q.studentMethod(); } // 'print()' method is defined in class Question void print(Question23 object){ System.out.print("Well Done!"); } // Define a method named 'studentMethod()' in class Question void studentMethod(){ // Call the method named 'print()' in class Question print(this); } }
4. Complete the code segment to call default constructor first and then any other constructor in the class.
// This is the main class Question public class Question214{ public static void main(String[] args){ Answer a = new Answer(10,"MCQ"); } } class Answer{ // This is the default constructor of the class Answer Answer(){ System.out.println("You got nothing."); } // This is a parameterized constructor of the class Answer Answer(int marks, String type){ //The 'this()' referene variable is able to call the default constructor of the class. this(); //Print marks and type of the question System.out.print("You got "+marks+" for an "+ type); } }
5. Complete the code segment to debug / complete the program which is intended to print ‘NPTEL JAVA’.
public class Question215{ public static void main(String[] args) { //Declare variable with name 'nptel', 'space' and 'java' and proper datatype. String nptel,space,java; //Initialize the variables with proper input nptel="NPTEL"; space=" "; java="JAVA"; System.out.print(nptel+space+java); } }
NPTEL Programming In Java Week 1 Assignment Answers 2023
1. Which of the following is NOT a primitive data type in Java??
a. int
b. boolean
c. String
d. char
Answer :- c
2. Consider the following program.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 30 image 1](https://gecmunger.in/wp-content/uploads/2023/07/image-1.png)
What is the output of the above code?
a. 127
b. -127
c. 129
d. 2
Answer :- b
3.Which of the following concept that Java doesn’t support?
a. inheritance
b. encapsulation
c. pointer
d. arrey
Answer :- c
4. Which of the following is not a keyword in java?
a. import
b. super
c. method
d. class
Answer :- c
5. Consider the following program.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 31 image 2](https://gecmunger.in/wp-content/uploads/2023/07/image-2.png)
What will be the output of the program if it is executed?
a. 12 20 13
b. 12 20 15
c. 12 20 015
d. 12 20 F
Answer :- a
6. Match the following java terms with their descriptions?
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 32 image 3](https://gecmunger.in/wp-content/uploads/2023/07/image-3.png)
a. A-1. B-2, C-3
b. A-2, B-3. C-1
c. A-3, B-2,C-1
d. A-3, B-1.C-2
Answer :- a
7. Consider the following program.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 33 image 4](https://gecmunger.in/wp-content/uploads/2023/07/image-4.png)
What will be the output of the program if it is executed ?
a. 20
b. 2
C. Compiler error
d. 40
Answer :- c
8. What is the output of the following code?
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 34 image 5](https://gecmunger.in/wp-content/uploads/2023/07/image-5.png)
a. null
b. true
c. false
d. 1
Answer :- c
9. Which program is used to compile Java source code into bytecode?
a. javap
b. javac
C. java
d. javad
Answer :- b
10. Consider the following program.
![[Week 11] NPTEL Programming In Java Assignment Answers 2023 35 image 7](https://gecmunger.in/wp-content/uploads/2023/07/image-7.png)
What will be the output of the program if it is executed?
a. 50
b. 10
c. Compiler error
d. 5
Answer :- a
NPTEL Programming In Java Week 1 Programming Assignment Answers
Complete the code segment to find the perimeter and area of a circle given a value of radius.
1.You should use Math.PI constant in your program. If radius is zero or less than zero then print ” please enter non zero positive number “.
if (radius <= 0) { System.out.println("Please enter a non-zero positive number."); } else { perimeter = 2 * Math.PI * radius; area = Math.PI * radius * radius; System.out.println(perimeter); System.out.println(area); }
2. Complete the code segment to find the largest among three numbers x,y, and z. You should use if-then-else construct in Java.
if (x >= y && x >= z) { result = x; } else if (y >= z) { result = y; } else { result = z; } System.out.println(result);
3. Consider First n even numbers starting from zero(0).Complete the code segment to calculate sum of all the numbers divisible by 3 from 0 to n. Print the sum.
Example:
Input: n = 5
——-
0 2 4 6 8
Even number divisible by 3:0 6
sum:6
int result = 0; int i = 0; while (result < n) { if (i % 2 == 0) { if (i % 3 == 0) { sum = sum + i; } result = result + 1; } i = i + 2; } System.out.print(sum);
4. Complete the code segment to check whether the number is an Armstrong number or not.
Armstrong Number:
A positive number is called an Armstrong number if it is equal to the sum of cubes of its digits for example 153 = 13+53+33, 370, 371, 407, etc.
int originalNumber = n; int sum = 0; // Rename 'result' to 'sum' // Calculate the sum of cubes of digits while (n > 0) { int digit = n % 10; sum += digit * digit * digit; n /= 10; } // Check if the sum is equal to the original number if (sum == originalNumber) { System.out.println("1"); // Armstrong number } else { System.out.println("0"); // Not an Armstrong number }
5. Complete the code segment to help Ragav , find the highest mark and average mark secured by him in “s” number of subjects.
int highestMark = arr[0]; for (i = 1; i < arr.length; i++) { if (arr[i] > highestMark) { highestMark = arr[i]; } } // Calculate the average mark int sum = 0; for (i = 0; i < arr.length; i++) { sum += arr[i]; } mark_avg = (double) sum / arr.length; System.out.println(highestMark); System.out.println(mark_avg);
Course Name | Programming In Java |
Category | NPTEL Assignment Answer |
Home | Click Here |
Join Us on Telegram | Click Here |