NPTEL Programming In Java Assignment 2022

nptel programming in java

NPTEL Programming In Java With the growth of Information and Communication Technology, there is a need to develop large and complex software. To meet this requirement object-oriented paradigm has been developed and based on this paradigm the Java programming language emerges as the best programming environment.

NPTEL Programming in Java is a MOOC-based course that is 12 weeks in duration and can fulfill the criteria of 4 credits in a year. You can visit the NPTEL SWAYAM platform and register yourself for the course. This course is brought to you by Prof. Dr. Debasis Samanta who holds a Ph.D. in Computer Science and Engineering from the Indian Institute of Technology Kharagpur.

  1. INTENDED AUDIENCE: All Undergraduates
  2. Requirements/Prerequisites: NIL
  3. INDUSTRY SUPPORT: All compaines or industry

CRITERIA TO GET A CERTIFICATE

Students have to score Average assignment score = 25% of the average of the best 6 assignments out of the total 8 assignments given in the course.
Exam score = 75% of the proctored certification exam score out of 100 Final scores = Average assignment score + Exam score

Programming In Java Assignment 7 Answers 2022

Students will be eligible for CERTIFICATE ONLY IF AVERAGE ASSIGNMENT SCORE >=10/25 AND EXAM SCORE >= 30/75. If any of the 2 criteria are not met, the student will not get the certificate even if the Final score >= 40/100.

NPTEL Programming In Java ASSIGNMENT WEEK 12 ANSWERS:-

Q1. Complete the code to develop an extended version of the ADVANCED CALCULATOR with added special functions that emulates all the functions of the GUI Calculator as shown in the image.

Code:-

For Online programming test help and final exam preparation material Click Me

		outerloop:
		for(int i=0; i<seq.length; i++){
			if(seq[i]=='C'){				//Clear
				operand1=0.0;
				operand2=0.0;
				output=0.0;
				outflag=0;
				break outerloop;
			}else if(seq[i]=='R'){			//Square Root
				for(int j=0; j<i; j++){
					o1+=Character.toString(seq[j]);
				}
				operand1=Double.parseDouble(o1);
				output=Math.sqrt(operand1);
				outflag=1;
				break outerloop;
			}
			else if(seq[i]=='S'){			//Square
				for(int j=0; j<i; j++){
					o1+=Character.toString(seq[j]);
				}
				operand1=Double.parseDouble(o1);
				output=Math.pow(operand1,2);
				outflag=1;
				break outerloop;
			}else if(seq[i]=='F'){			//Inverse
				for(int j=0; j<i; j++){
					o1+=Character.toString(seq[j]);
				}
				operand1=Double.parseDouble(o1);
				output=Math.pow(operand1,-1);
				outflag=1;
				break outerloop;
			}else{
				int r=0;
	                     if(seq[i]=='+'||seq[i]=='\0'||seq[i]=='/'||seq[i]=='*'||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]=='*'){
								            
                      output=operand1*operand2;
				 }
				break outerloop;
				}else{
			o2+=Character.toString(seq[k]);
						}
					}
				}
			}
		}

Q2. A partial code fragment is given. The URL class object is created in try block.You should write appropriate method( )  to print the protocol name and host name from the given url string.

Code:-

try{  
     URL url=new URL("http://www.Nptel.com/java-tutorial");    
    //use appropriate method() to print the protocol name and host name from url 
    //Write the method() by replacing the blank space.
    System.out.println("Protocol: "+url.getProtocol());  
     System.out.println("Host Name: "+url.getHost());  
   
 
      }
   catch(Exception e){System.out.println(e);}  
   }  
}

Q3. Write a program to create a record by taking inputs using Scanner class as first name as string ,last name as string ,roll number as integer ,subject1 mark as float,subject2 mark as float. Your program should print in the format  “name  rollnumber avgmark”.

Code:-

//Read your first name
    String f = s1.next();
    //Read your last name
    String l = s1.next();
    //Read rollnumber
    int n = s1.nextInt();
    //Read 1st subject mark
       double db = s1.nextDouble();
	//Read 2nd subject mark
	double db1 = s1.nextDouble();
	double avg=(db+db1)/2;
	System.out.println(f + l +" "+ n +" "+avg );

    

Q4. A program code is given to call the parent class static method and instance method in derive class without creating object of parent class. You should write the appropriate code so that the program print the contents of static method() and instance method () of parent class.

Code:-

public static void main(String[] args) {
     // Call the instance method in the Parent class 
    Child c= new Child();
    c.testInstanceMethod();
		
     // Call the static method in the Parent class
    Parent.testClassMethod();
  }
}

Q5. Write a recursive function to print the sum of  first n odd integer numbers. The recursive function should have the prototype
 ” int sum_odd_n(int n) “.

Code:-

For Online programming test help and final exam preparation material Click Me

return 2*n-1 + sum_odd_n(n-1);

NPTEL Programming In Java ASSIGNMENT WEEK 11 ANSWERS:-

Q1. Complete the code segment to insert the following data using prepared statement in the existing table ‘PLAYERS.

Code:-

// Execute the statement containing SQL command

String query = " insert into PLAYERS (UID, first_name, last_name, age)"  + " values (?, ?, ?, ?)";

			PreparedStatement preparedStmt = conn.prepareStatement(query);
			preparedStmt.setInt (1, 1);
			preparedStmt.setString (2, "Ram");
			preparedStmt.setString (3, "Gopal");
			preparedStmt.setInt(4, 26);

			preparedStmt.execute();
	  
			preparedStmt.setInt (1, 2);
			preparedStmt.setString (2, "John");
			preparedStmt.setString (3, "Mayer");
			preparedStmt.setInt(4, 22);

			preparedStmt.execute();
			

For Online programming test help and final exam preparation material Click Me

Q2. Write the required code in order to update the following data in the table ‘PLAYERS.

Code:-

String sql = "UPDATE PLAYERS " + "SET Age = 24 WHERE UID == 1";
stmt.executeUpdate(sql); 
String sql1 = "UPDATE PLAYERS " + "SET Last_Name = 'Gopala' WHERE UID == 1";
stmt.executeUpdate(sql1);
String sql2 = "UPDATE PLAYERS " + "SET First_Name = 'Rama' WHERE UID == 1";
stmt.executeUpdate(sql2);
quizxp telegram

Q3. Write the appropriate code in order to delete the following data in the table ‘PLAYERS.

Code:-

// Execute the command in order to delete a row from the table
String sql = "DELETE FROM PLAYERS " +"WHERE UID = 1";
	stmt.executeUpdate(sql);

Q4. Complete the following program to calculate the average age of the players in the table ‘PLAYERS.

Structure of Table ‘PLAYERS’ is given below:

Code:-

For Online programming test help and final exam preparation material Click Me

		
			
			preparedStmt.setInt (1, 1);
			preparedStmt.setString (2, "Rama");
			preparedStmt.setString (3, "Gopala");
			preparedStmt.setInt(4, 24);
			preparedStmt.execute();
			preparedStmt.setInt (1, 2);
			preparedStmt.setString (2, "John");
			preparedStmt.setString   (3, "Mayer");
			preparedStmt.setInt(4, 22);
			preparedStmt.execute();
			preparedStmt.setInt (1, 3);
			preparedStmt.setString (2, "Leo");
			preparedStmt.setString   (3, "Martin");
			preparedStmt.setInt(4, 27);
			preparedStmt.execute();

               ResultSet rs = stmt.executeQuery("SELECT * FROM players;");
			int count=0,total=0;
			while(rs.next()){
				count++;
				total = total + Integer.parseInt(rs.getString(4));
			}
			
			//Output
			System.out.println("Average age of players is " +(total/count));
  conn.close();

Q5. Complete the code segment to drop the table named ‘PLAYERS.

Code:-

 // Write the SQL command to drop a table
    query = "DROP TABLE players;";

// Execute the SQL command to drop a table
stmt.executeUpdate(query);
                       

NPTEL Programming In Java ASSIGNMENT WEEK 10 ANSWERS:-

Q1. The following code needs some package to work properly. Write appropriate code to import the required package(s) in order to make the program compile and execute successfully.

Code:-

If you want help with the 16 oct Online Programming test and help in the final exam take our membership for a better score in the exam read more here:- Final Exam Membership

import java.sql.*;
import java.lang.*;

Q2. Write the JDBC codes needed to create a Connection interface using the DriverManager class and the variable DB_URL.  Check whether the connection is successful using ‘isAlive(timeout)’ method to generate the output, which is either ‘true’ or ‘false’.

Code:-

conn= DriverManager.getConnection(DB_URL);

if(conn.isClosed())
   System.out.print("false");
else
   System.out.print("true");

Q3. Due to some mistakes in the below code, the code is not compiled/executable. Modify and debug the JDBC code to make it execute successfully.

Code:-

import java.sql.*;  // All sql classes are imported
import java.lang.*; // Semicolon is added
import java.util.Scanner;
public class Question103 {
    public static void main(String args[]) {
        try {
              Connection conn = null;
              Statement stmt = null;
              String DB_URL = "jdbc:sqlite:/tempfs/db";
              System.setProperty("org.sqlite.tmpdir", "/tempfs");
              // Connection object is created
              conn = DriverManager.getConnection(DB_URL);
              conn.close();
              System.out.print(conn.isClosed());
       }
       catch(Exception e){ System.out.println(e);}  
    }
}

Q4. Complete the code segment to create a new table named ‘PLAYERS’ in SQL database using the following information.

Code:-

// The statement containing SQL command to create table "players"
String CREATE_TABLE_SQL="CREATE TABLE players (UID INT, First_Name VARCHAR(45), Last_Name VARCHAR(45), Age INT);";
// Execute the statement containing SQL command
stmt.executeUpdate(CREATE_TABLE_SQL);
         

Q5. Complete the code segment to rename an already created table named ‘PLAYERS’ into ‘SPORTS’.

Code:-

If you want help with the 16 oct Online Programming test and help in the final exam take our membership for a better score in the exam read more here:- Final Exam Membership

// Write the SQL command to rename a table
String alter="ALTER TABLE players RENAME TO sports;";

// Execute the SQL command
stmt.executeUpdate(alter);

NPTEL Programming In Java ASSIGNMENT WEEK 9 ANSWERS:-

Q1. Complete the code to develop a BASIC CALCULATOR that can perform operations like AdditionSubtractionMultiplication, and Division.

Code:-

If you want help with the 16 oct Online Programming test and help in the final exam take our membership for a better score in the exam read more here:- Final Exam Membership

int i=0; int j=0;
double k=0;
// Split the input string into character array
char s[] = input.toCharArray();
/*
Write your method to separate two operands
and operators and then perform the required operation.
*/
for(int a=0; a<s.length; a++){
  if(s[a]=='+')
  {
    i=Integer.parseInt(input.substring(0,a));

    j=Integer.parseInt(input.substring(a+1,s.length));

	k=(double)i+j;
  }

  else if(s[a]=='-')
  {
	i=Integer.parseInt(input.substring(0,a));
    j=Integer.parseInt(input.substring(a+1,s.length));
	k=(double)i-j;
  }
  else if(s[a]=='*')
  {
	i=Integer.parseInt(input.substring(0,a));

    j=Integer.parseInt(input.substring(a+1,s.length));

	k=(double)i*j;
  }
  else if(s[a]=='/')
  {
	i=Integer.parseInt(input.substring(0,a));

    j=Integer.parseInt(input.substring(a+1,s.length));

	k=(double)i/j;
  }
}
// Print the output as stated in the question
System.out.print(input+" = "+Math.round(k));

Q2. Complete the code to develop an ADVANCED CALCULATOR that emulates all the functions of the GUI Calculator as shown in the image.

Code:-

String num1="",num2="";

char op='a';

int equal=0,flag=0,check=0,j=0,ch=0;

char[] charArray = input.toCharArray();

char[] numarray = new char[input.length()];

for(int i=0; i<input.length(); i++)

{
  if(charArray[i]<'a' || charArray[i]>'p')
  {
    check=1;
    break;

  }

  if(charArray[i]=='c')
    ch=1;
  char out=gui_map(charArray[i]);
  numarray[i]=out;
  if(out=='+' || out=='-'|| out=='X'|| out=='/')
  {
    flag=1;
    op=out;
  }
  if(flag==0)
    num1=num1 + String.valueOf(out);
  else
  {
    if(j==0)
    {
      j++;

      continue;

    }

    if(out== '=')

    {

      equal=1;

      break;

    }

    num2=num2 + String.valueOf(out);

  }

}

if(ch==1 && check==0)

{

  double a=Double.parseDouble(num1);

  double b=Double.parseDouble(num2);

  if(op=='+') System.out.print(a+b);

  else if(op=='-') System.out.print(a-b);

  else if(op=='X') System.out.print(a*b);

  else if(op=='/') System.out.print(a/b);
    }

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:

Code:-

String arr[]=new String[5];
for(int i=0;i<5;i++)
  arr[i]=sc.nextLine();
char matrix[][]=new char[5][5];
for(int i=0;i<5;i++){
  char[] chararray=arr[i].toCharArray();
  for(int j=0;j<5;j++){
    matrix[i][j]=chararray[j];
  }
}
char newmatrix[][]=new char [5][5];
for(int i=0;i<5;i++)
{
  for(int j=0;j<5;j++)
  {
    if(i==0 && j<3)
      newmatrix[i][j+2]=matrix[i][j];
    else if (i==0 && j==3)
      newmatrix[i+1][j+1]=matrix[i][j];
      else if(i<3 && j==4)
      newmatrix[i+2][j]=matrix[i][j];
      else if (i==3 && j==4)
      newmatrix[i+1][j-1]=matrix[i][j];
      else if(i==4 && j>1)
      newmatrix[i][j-2]=matrix[i][j];
      else if (i==4 && j==1)
      newmatrix[i-1][j-1]=matrix[i][j];
      else if(i>1 && j==0)
      newmatrix[i-2][j]=matrix[i][j];
      else if (i==1 && j==0)
      newmatrix[i-1][j+1]=matrix[i][j];
      else if(i==1 && j>0 && j<4){
      if(j==3)
        newmatrix[i+1][j]=matrix[i][j];
      else
        newmatrix[i][j+1]=matrix[i][j];
    }
    else if(i==2 && j>0 && j<4){
      if(j==2)
        newmatrix[i][j]=matrix[i][j];
      else if (j==3)
        newmatrix[i+1][j]=matrix[i][j];
        else
        newmatrix[i-1][j]=matrix[i][j];
    }
    else{
      if(j==1)
        newmatrix[i-1][j]=matrix[i][j];
      else
        newmatrix[i][j-1]=matrix[i][j];
    }
  }
}
for(int i=0;i<5;i++){
  for(int j=4;j>=0;j--)
    System.out.print(newmatrix[i][j]);
  System.out.println();
}

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:

Code:-

String a[] = new String[5];

char r[][] = new char[5][5];

int i,j,k=0;
// Input 5x5 2D Array using Scanner Class
for(j=0; j<5; j++)
 a[j] = sc.nextLine();
// Perform the reflection operation

for( i=0; i<5; i++)

  for( j=4,k=0; j>=0; j--,k++)

  r[i][k] = a[i].charAt(j);
// Output 5x5 2D Reflection Array
  for(i=0; i<5; i++)
{
  for(k=0; k<5; k++)

    System.out.print(r[i][k]);

  System.out.println();

}

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:

Code:-

If you want help with the 16 oct Online Programming test and help in the final exam take our membership for a better score in the exam read more here:- Final Exam Membership

// Declare the 5X5 2D array to store the input


String a[] = new String[5];

int i,j;

char matrix[][] = new char[5][5];



// Input 2D Array using Scanner Class and check data validity

for(i=0; i<5; i++)

  a[i] = sc.nextLine();



// Perform the Flip-Flop Operation

for(i=0; i<5; i++)

{

  char[] chararray = a[i].toCharArray();

  for(j=0; j<5; j++)

    matrix[i][j] = chararray[j];

}



// Output the 2D Flip-Flop Array



for(i=0; i<5; i++)

{

  for(j=0; j<5; j++)

  {

    if(matrix[i][j]=='0')

      System.out.print('1');

    else

      System.out.print('0');

  }

    System.out.println();

}
// Input 2D Array using Scanner Class and check data validity

// Perform the Flip-Flop Operation

// Output the 2D Flip-Flop Array

NPTEL Programming In Java ASSIGNMENT WEEK 8 ANSWERS:-

Q1. Write a program which will print a pyramid of “*” ‘s of height “n” and print the number of “*” ‘s in the pyramid.

Code:-

If you want help with the 16 oct Online Programming test and help in the final exam take our membership for a better score in the exam read more here:- Final Exam Membership

int k=0, s=0;

      for(int i=1;i<=n;++i,k=0){

        for(int j =1;j<=n-i;++j){

          System.out.print("  ");

        }

        while(k !=2 *i-1){

          System.out.print("* ");

          s=s+1;

          ++k;

                           

         }

          System.out.println();

         }

       System.out.println(s);

       }

 }

Q2. Write a program which will print a pascal  pyramid of  “*” ‘s of height “l” .

Code:-

import java.util.*;
public class Pattern2 
{
    public static void main(String[] args) 
    {
        Scanner inr = new Scanner(System.in);
		int l = inr.nextInt();
        // Add the necessary code in the below space
      
        int i,j,k;
         for(i=l;i>=1;i--)
         {   
             for(k=i-1;k>0;k--)
                System.out.print(" ");
             for(j=i;j<=l;j++)
             { 
                System.out.print('*');
                System.out.print(" ");
             } 
           if(i!=1)
            System.out.print("\n");
           else 
             break;
         }
    }
}

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.

Code:-

 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.println(sum); 
    }
}   

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”.

Code:-

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
	  	
	// Check whether line number is odd
	   if (l%2!=0){
	   ul=(l/2)+1;			
	   ll=l-ul;
	//Code for upper half
	for(int i=1;i<=ul; i++){	
	//Space management
	for(int s=1;s<=(ul-i); s++){
	    System.out.print(" ");
	}
	// Star management
	for(int j=1;j<=i; j++){
	     System.out.print("* ");
	}
	System.out.println();
	}
			
	//Code for lower half
	int llc=ll;
	for(int i=1;i<=ll; i++){
	//Space management
	for(int s=llc;s<ll; s++){
	   System.out.print(" ");
	}
	// Star management
	for(int j=1;j-1<=ll-i; j++){
	   System.out.print(" *");
	 }
	 llc--;
	System.out.println();
        }
	}
        else{
	   System.out.print("Invalid line number");
	}

    }
}

Q5. Write a program to display any digit(n) from 0-9 represented as a “7 segment  display”

Code:-

If you want help in online programming test and help in final exam take our membership for better score in exam read more here:- Final Exam Membership

import java.util.*;

public class Pattern5 {
   public static void main(String[] args) throws Exception {
           Scanner inr = new Scanner(System.in);
	   int n = inr.nextInt();
           // Add the necessary code in the below space    
   
if(n==2 || n==3 || n==5 || n==6 || n==7 || n==8 || n==9 || n==0 )
  System.out.println(" _ ");
else     
  System.out.println("   ");          
if(n==1 || n==7 )
  System.out.println("  |");     
else if(n==2 || n==3 )
  System.out.println(" _|");     
else if(n==4 || n==8 || n==9 )
  System.out.println("|_|");     
else if(n==5 || n==6 )
  System.out.println("|_ ");             
else
  System.out.println("| |");  
if(n==1 || n==4 || n==7 )
  System.out.print("  |");     
else if(n==3 || n==5 || n==9 )
  System.out.print(" _|");
else if(n==6 || n==8 || n==0 )
  System.out.print("|_|");
else
  System.out.print("|_");
   }
}

NPTEL Programming In Java ASSIGNMENT WEEK 7 ANSWERS:-

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.

Code:-

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;
         	}
           

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”.

Code:-

 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");
    }

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.

Code:-

 String s2 = new String(barr,n,1);  
        System.out.println(barr[n]);
	System.out.println(s2); 
	}

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”.

Code:-

        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;
             }    
         }  

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.

Code:-

byte[] barr=s1.getBytes();   
	      
                byte b1 = (byte) c;
            	barr[n]=b1;
		System.out.println(new String(barr)); 
	   }

NPTEL Programming In Java ASSIGNMENT WEEK 6 ANSWERS:-

Q1. Complete the code segment to print the following using the concept of extending the Thread class in Java:

Code:-

 public class Question61 extends Thread{
	public void run(){
		System.out.print("Thread is Running.");
	}

Q2. 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.

Code:-

// Create main() method and appropriate statements in it
public static void main(String []g)
{
System.out.println("Welcome to Java Week 6 New Question.");
Question62 t = new Question62();
 Thread x = new Thread (t);
 x.setName("Main Thread");
 x.start();
}

Q3. 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.

Code:-

 // 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");
	}
}

Q4. 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:  

Code:-

// Returns the sum of a and b. (reader)
// Should always return an even number.
synchronized public int sum() { // line 1 :- answer
return(a+b);
}
// Increments both a and b. (writer)
synchronized public void inc() { //line 2 :- answer
a++;
b++;
}
}

Q5. Given a snippet of code, add necessary codes to print the following:

Code:-

t1.setName("Week 6 Assignment Q5"); 
t2.setName("Week 6 Assignment Q5 New");

NPTEL Programming In Java ASSIGNMENT WEEK 5 ANSWERS:-

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.

Code:-

//Create a class A which implements the interface Number.
class A implements Number
{
  public int findSqr(int i)
  {
    return i*i;
  }
}

Q2. This program isto 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).

Code:-

//Create a class B, which implements the interface GCD.
class B implements GCD
{
  public int findGCD(int a, int b)
  {
    if(b==0)
      return a;
    else
      return findGCD(b,a%b);
  }
}

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.

Code:-

//Read any two values for a and b.
 //Get the result of a/b;
a=input.nextInt();
b=input.nextInt();
{
  try
  {
    if(b!=0)
    {
      System.out.print(a/b);
      System.exit(0);
    }
  }
  finally
  {
    System.out.print("Exception caught: Division by zero.");
  }
}

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.

Code:-

try
{
  for(int i=0; i<length; i++)
  {
    name[i]=sc.nextInt();
    sum=sum+name[i];
  }
  System.out.print(sum);
  System.exit(0);
}
finally
{
  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.

Code:-

         try {
	         switch (i) {
		    case 0 : 
			int zero = 0; 
			j = 92/ zero; 		
			break;
		    case 1 : 
			int b[ ] = null; 
			j = b[0] ; 	
			break;
	           default:
		       System.out.println("No exception");
		    } 		
	      }
            // catch block			
		catch (Exception e) {		
		   System.out.println(e) ;
		}

NPTEL Programming In Java ASSIGNMENT WEEK 4 ANSWERS:-

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.

Code:-

// Import the required package(s) and/or class(es)// Import the required package(s) and/or class(es)
import java.io.*;
import java.util.*;
import static java.lang.System.*;
quizxp telegram

Q2. Complete the code segment to print the current year. Your code should compile successfully.

Code:-

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

Q3. The program in this assignment is attempted to print the following output: 

Code:-

interface ExtraLarge{
 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.println(extra);
  }
}

Q4. Complete the code segment to call the default method in the interface First and Second.

Code:-

// Call show() of First interface.
First.super.show();
// Call show() of Second interface.
Second.super.show();

Q5. Modify the code segment to print the following output.

Code:-

// 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);
 }
 // Override method in ShapeY interface
  public void display2(){
  System.out.println("Circle: " + ShapeY.base);}
}

NPTEL Programming In Java ASSIGNMENT WEEK 3 ANSWERS:-

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.

Code:-

 if (n==1)      //Terminate condition    
   return 0;       
else if(n==2)         
  return 1; 
  return fib(n - 1) + fib(n - 2); //Recursive call of function
quizxp telegram

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.

Code:-

class Point{
      double x,y;
      
      public double distance(Point p1, Point p2)
                {
                  
                  double root=(p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y);
                  root=Math.sqrt(root);
                  System.out.print(root);
                  return root;
                }
}

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.

Code:-

Note:- WE NEVER PROMOTE COPYING AND We do not claim 100% surety of answers, these answers are based on our sole knowledge, and by posting these answers we are just trying to help students to reference, so we urge do your assignment on your own.

//Create a derived class constructor which can call the one parametrized constructor of the base class
double height;
Test1(double l, double h){
  super(l);
  this.length=l;
  this.height=h;
}

//Create a derived class constructor which can call the two parametrized constructor of the base class
Test1(double l, double b, double h){
  super(l,b);
  this.length=l;
  this.breadth=b;
  this.height=h;
}
  
  

//Override the method calculate() in the derived class to find the volume of a shape instead of finding the area of a shape

double calculate(){
  
  return length*breadth*height;}

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.  

Code:-

QuestionScope a= new QuestionScope();
 System.out.println(a.sum(n1,n2));
 System.out.print(QuestionScope.multiply(n1,n2));

Q5. Complete the code segment to swap two numbers using call-by-object reference.

Code:

static void swap(Question obj)
        {
          int temp;
          temp=obj.e1;
          obj.e1=obj.e2;
          obj.e2=temp;
        }

Also check :- Internship oppurtinites

Note:- We do not claim 100% surety of answers, these answers are based on our sole knowledge and by posting these answers we are just trying to help students, so we urge do you assignment own your own.