Chapter 4 Unit 3: Compiling and Executing Programs

PrevNextBack

Chapter 4 Unit 3: Compiling and Executing Programs

Contents

Write whether the following statements are True or False

Question 1

Java is a case sensitive language.
True

Question 2

A single line comment is represented by the symbol // (forward slash) in programming.
True

Question 3

BlueJ is a DOS based platform to operate Java program.
False

Question 4

In a decision making program, if checks the true part and else the false.
True

Question 5

You may or may not include java.io.* package in a Stream Reader Class program.
False

Predict the output of the given snippet, when executed

Question 1

int x = 1,y = 1;
if(n>0)    
{           
x=x+1;    
y=y+1;     
}           

What will be the value of x and y, if n assumes a value (i) 1 (ii) 0?

Output

When n is 1:
x is 2 and y is 2

When n is 0:
x is 1 and y is 1

Explanation

When n is 1, if (n>0) is true. So the statements x=x+1; and y=y+1; are executed making the values of x and y as 2.

When n is 0, if (n>0) is false. Statements x=x+1; and y=y+1; are not executed so values of x and y remain 1.

Question 2

int b=3,k,r;
float a=15.15,c=0;    
if(k==1)              
{                     
r=(int)a/b;           
System.out.println(r);
}                     
else                  
{                     
c=a/b;                
System.out.println(c);
Output

Syntax Error

Explanation

There are 2 syntax errors in this program:

  1. Variable k is not initialized with any value before using it in the if check.
  2. The closing curly brace is missing for the compound statement block of else part.

Question 3

int a=1,b=1,m=10,n=5;
if((a==1)&&(b==0))
{
System.out.println((m+n)); 
System.out.println((m-n));
}
if((a==1)&&(b==1))
{
System.out.println((m*n)); 
System.out.println((m%n));
} 
Output

50
0

Explanation

The condition of the statement if((a==1)&&(b==0)) evaluates to false as b is not equal to 0. Statements inside its block are not executed. Condition of next if statement if((a==1)&&(b==1)) is true as both a and b are 1. So statements in its block are executed, printing the result of m*n (10 * 5 = 50) and m%n (10 % 5 = 0) as the output.

Correct the errors of the given programs

Question 1

class public
{                                     
public static void main(String args{})
{                                     
int a=45,b=70,c=65.45;                
sum=a+b;                              
diff=c-b;                             
System.out.println(sum,diff);         
}                                     
}                                     

Answer

Errors in the snippet
  1. Name of the class can't be public as public is a keyword.
  2. Argument of main function should be an array of Strings.
  3. We cannot assign 65.45 to c as c is an int variable and 65.45 is a floating-point literal.
  4. Variable sum is not defined.
  5. Variable diff is not defined.
  6. println method takes a single argument.
Corrected Program
class A     //1st correction                                 
{                                     
public static void main(String args[])  //2nd correction
{                                     
int a=45,b=70;
double c=65.45;     //3rd correction              
int sum=a+b;        //4th correction
double diff=c-b;    //5th correction
System.out.println(sum + " " + diff);   //6th correction
}                                     
}   

Question 2

class Square
{
public static void main(String args[])
{
int n=289,r;
r=sqrt(n);
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}

Answer

Errors in the snippet
  1. Math.sqrt(n) is the correct way to call sqrt method of Math class.
  2. As Math.sqrt(n) returns double value, so the return value should be explicitly casted to int.
Corrected Program
class Square
{
public static void main(String args[])
{
int n=289,r;
r=(int)Math.sqrt(n);    //1st & 2nd Corrections
if(n==r)
System.out.println("Perfect Square");
else
System.out.println("Not a Perfect Square");
}
}

Question 3

class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10,b=5,c=1,d=2;
c=a2+b2;
d=(a+b)2;
p=c/d;
System.out.println(c + " "+ " "+d+ " " +p);
}
}

Answer

Errors in the snippet
  1. Multiple variable assignment statements cannot be separated by a comma. Semicolon should be used instead.
  2. Variables a2 and b2 are not defined. They should be a and b.
  3. The line d=(a+b)2 needs an operator between (a+b) and 2.
  4. Variable p is not defined.
Corrected Program
class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10;b=5;c=1;d=2;       //1st correction
c=a+b;                  //2nd correction
d=(a+b) / 2;            //3rd correction
int p=c/d;              //4th correction
System.out.println(c + " "+ " "+d+ " " +p);
}
}

Question 4

class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12; 
if(n=25)
{
k=pow(p,2)
System.out.println("The value of"+p+ "= "+k);
}
else
{
r=Math.square root(n); 
System.out.println("The value of"+n+ "= "+r);
} 
} 
}

Answer

Errors in the snippet
  1. if(n=25) should be if(n==25)
  2. Correct way to call method pow is Math.pow(p,2);
  3. Return type of Math.pow is double. Variable k is of float type so return value should be explicitly casted to float.
  4. Math.square root(n) should be Math.sqrt(n)
  5. Return type of Math.sqrt is double. Variable r is of float type so return value should be explicitly casted to float.
Corrected Program
class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12; 
if(n==25)       //1st correction
{
k=(float)Math.pow(p,2); //2nd & 3rd corrections
System.out.println("The value of"+p+ "= "+k);
}
else
{
r=(float)Math.sqrt(n);  //4th & 5th corrections
System.out.println("The value of"+n+ "= "+r);
} 
} 
}

Answer the following questions

Question 1

What are the three ways to input the values in a Java Programming?

Answer

Three ways to input the values in Java Programming are:

  1. Using InputStreamReader class.
  2. Using Scanner class.
  3. Using Command Line Arguments.

Question 2

Write down the syntax with reference to Java Programming:

(a) to accept an integral value from the user from console

Answer

InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int p = Integer.parseInt(in.readLine());

(b) to accept a fractional number from the user from console

Answer

InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
double n = Double.parseDouble(in.readLine());

(c) if - else statement

Answer

if (condition 1) {
    Statement a;
    Statement b;
    ..
}
else {
    Statement c;
    Statement d;
    ..
}

Question 3

Distinguish between Syntax error and Logical error.

Answer

Syntax ErrorsLogical Errors
Syntax Errors occur when we violate the rules of writing the statements of the programming language.Logical Errors occur due to our mistakes in programming logic.
Program fails to compile and execute.Program compiles and executes but doesn't give the desired output.
Syntax Errors are caught by the compiler.Logic errors need to be found and corrected by the people working on the program.

Question 4

What are the different types of errors that take place during the execution of a program?

Answer

Logical errors and Run-Time errors occur during the execution of the program.

Question 5

What is a compound statement? Give an example.

Answer

Two or more statements can be grouped together by enclosing them between opening and closing curly braces. Such a group of statements is called a compound statement.

if (a < b) {
            
    /*
    * All statements within this set of braces 
    * form the compound statement
    */

    System.out.println("a is less than b");
    a = 10;
    b = 20;
    System.out.println("The value of a is " + a);
    System.out.println("The value of b is " + b);
            
}

Question 6

Explain with an example the if-else-if construct.

Answer

if-else-if ladder construct is used to test multiple conditions and then take a decision. It provides multiple branching of control. Below is an example of if-else-if:

if (marks < 35)
    System.out.println("Fail");
else if (marks < 60)
    System.out.println("C grade");
else if (marks < 80)
    System.out.println("B grade");
else if (marks < 95)
    System.out.println("A grade");
else
    System.out.println("A+ grade");

Question 7

What is the use of the keyword 'import' in Java programming?

Answer

import keyword is used to import built-in and user-defined packages into our Java program.

Question 8

Write different ways of using comments in Java.

Answer

There are 3 ways to give comments in Java:

  1. Single line comment (//)
  2. Multi line comment
    /* Line 1
         Line 2 */
  3. Documentation comment
    /**Line 1
         Line 2*/

Question 9

Mention five features of BlueJ.

Answer

Five features of BlueJ are:

  1. Simple beginner friendly graphical user interface.
  2. It allows creating objects of the class dynamically, invoking their methods and also supplying data to the method arguments if present.
  3. It supports syntax highlighting. (Syntax highlighting means showing the different tokens of the program like keywords, variables, separators, etc. in different colours so that they show up more clearly.)
  4. It facilitates easier debugging as lines causing compilation errors are marked clearly and the error is displayed at the bottom of the window.
  5. It provides a code editor, compiler and debugger integrated into a single tool.

Question 10

What are the points to be taken care while naming a class in a Java program?

Answer

A class name should be a valid Java identifier i.e. it should follow the below three rules:

  1. Name of the class should be a sequence of alphabets, digits, underscore and dollar sign characters only.
  2. It should not start with a digit.
  3. It should not be a keyword or a boolean or null literal.

Solutions to unsolved programs

Question 1

Write a program as per the given details:

class name : Myself
My name:
Father's name:
Postal address:
Contact Number:

The program displays all the details on the output screen.

import java.io.*;

public class Myself
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter your name: ");
        String name = in.readLine();
        
        System.out.print("Enter your Father's name: ");
        String father = in.readLine();
        
        System.out.print("Enter your address: ");
        String address = in.readLine();
        
        System.out.print("Enter your contact number: ");
        long number = Long.parseLong(in.readLine());
        
        System.out.println("My name: " + name);
        System.out.println("Father's name: " + father);
        System.out.println("Postal address: " + address);
        System.out.println("Contact Number: " + number);
    }
}
Output
BlueJ output of Myself.java

Question 2

Write a program to calculate the gross salary of an employee when
Basic Salary = Rs.8600
DA = 20% of Salary
HRA = 10% of Salary
CTA = 12% of the Salary.
Gross Salary = (Salary + DA + HRA + CTA)

public class KboatSalary
{
    public static void main(String args[]) {
        int sal = 8600;
        double da = 20 / 100.0 * sal;
        double hra = 10 / 100.0 * sal;
        double cta = 12 / 100.0 * sal;
        double gross = sal + da + hra + cta;
        System.out.println("Gross Salary = " + gross);
    }
}
Output
BlueJ output of KboatSalary.java

Question 3

Write a program to input the temperature in Celsius and convert it into Fahrenheit. If the temperature is more than 98.6 °F then display "Fever" otherwise "Normal".

import java.io.*;

public class KboatTemperature
{
    public static void main(String args[]) throws IOException {
        
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter temperature in Celsius: ");
        double cel = Double.parseDouble(in.readLine());
        
        double far = 1.8 * cel + 32;
        
        if (far > 98.6)
            System.out.println("Fever");
        else
            System.out.println("Normal");
    }
}
Output
BlueJ output of KboatTemperature.java
BlueJ output of KboatTemperature.java

Question 4

Write a program to accept marks of a student obtained in 5 different subjects (English, Phy., Chem., Biology, Maths.) and find the average. If the average is 80% or more then he/she is eligible to get "Computer Science" otherwise "Biology".

import java.io.*;

public class KboatMarks
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter marks in English: ");
        int eng = Integer.parseInt(in.readLine());
        
        System.out.print("Enter marks in Physics: ");
        int phy = Integer.parseInt(in.readLine());
        
        System.out.print("Enter marks in Chemistry: ");
        int chem = Integer.parseInt(in.readLine());
        
        System.out.print("Enter marks in Biology: ");
        int bio = Integer.parseInt(in.readLine());
        
        System.out.print("Enter marks in Maths: ");
        int math = Integer.parseInt(in.readLine());
        
        double avg = (eng + phy + chem + bio + math) / 5.0;
        
        if (avg >= 80) {
            System.out.println("Eligible for Computer Science");
        }
        else {
            System.out.println("Eligible for Biology");
        }
    }
}
Output
BlueJ output of KboatMarks.java

Question 5

Write a program to accept three angles of a triangle and check whether the triangle is possible or not and display the message accordingly.

import java.io.*;

public class KboatTriangle
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter first angle: ");
        int a = Integer.parseInt(in.readLine());
        
        System.out.print("Enter second angle: ");
        int b = Integer.parseInt(in.readLine());
        
        System.out.print("Enter third angle: ");
        int c = Integer.parseInt(in.readLine());
        
        int sum = a + b + c;
        
        if(a != 0 && b != 0 && c != 0 && sum == 180) {
            if((a + b) >= c || (b + c) >= a || (a + c) >= b) {
                System.out.println("Triangle is possible");
            }
            else {
                System.out.println("Triangle is not possible");
            }
        }
        else {
            System.out.println("Triangle is not possible");
        }
    }
}
Output
BlueJ output of KboatTriangle.java
BlueJ output of KboatTriangle.java

Question 6

Write a program to accept a number and check whether the number is a perfect square or not.
Sample Input: 49
Sample Output: A perfect square

import java.io.*;

public class KboatPerfectSquare
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter the number: ");
        int a = Integer.parseInt(in.readLine());
        
        double srt = Math.sqrt(a);
        double diff = srt - Math.floor(srt);
        
        if (diff == 0) {
            System.out.println(a + " is a perfect square");
        }
        else {
            System.out.println(a + " is not a perfect square");
        }
    }
}
Output
BlueJ output of KboatPerfectSquare.java
BlueJ output of KboatPerfectSquare.java

Question 7

A shopkeeper announces two successive discounts 20% and 10% on purchasing of goods on the marked price. Write a program to input marked price and calculate the selling price of an article.

import java.io.*;

public class KboatSuccessiveDiscount
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter marked price: ");
        double mp = Double.parseDouble(in.readLine());
        
        double d1 = mp * 20 / 100.0;
        double amt1 = mp - d1;
        
        double d2 = amt1 * 10 / 100.0;
        double amt2 = amt1 - d2;
        
        System.out.print("Selling Price = " + amt2);
    }
}
Output
BlueJ output of KboatSuccessiveDiscount.java

Question 8

Write a program to input two unequal numbers. Display the numbers after swapping their values in the variables without using a third variable.
Sample Input: a=23, b= 56
Sample Output: a=56, b=23

import java.io.*;

public class KboatNumberSwap
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter first number: ");
        int a = Integer.parseInt(in.readLine());
        
        System.out.print("Enter second number: ");
        int b = Integer.parseInt(in.readLine());
        
        a = a + b;
        b = a - b;
        a = a - b;
        
        System.out.println("Numbers after Swap:");
        System.out.println("a = " + a + "\t" + "b = " + b);
    }
}
Output
BlueJ output of KboatNumberSwap.java

Question 9

Write a program to accept Principal, Rate and Time. Calculate and display the interest accumulated for the first year, second year and the third year compound annually.

Sample Input:
Principal = ₹5,000, Rate = 10% per annum, Time = 3 years

Sample Output:
Interest for the first year: ₹500
Interest for the second year: ₹550
Interest for the third year: ₹605

import java.io.*;

public class KboatInterest
{
    public static void main(String args[]) throws IOException {
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter Principal: ");
        double p = Double.parseDouble(in.readLine());
        
        System.out.print("Enter Rate: ");
        double r = Double.parseDouble(in.readLine());
        
        System.out.print("Enter Time: ");
        int t = Integer.parseInt(in.readLine());
        
        double i1 = p * r * 1 / 100.0;
        double amt = p + i1;
        System.out.println("Interest for the first year: " + i1);
        
        double i2 = amt * r * 1 / 100.0;
        amt = amt + i2;
        System.out.println("Interest for the second year: " + i2);
        
        double i3 = amt * r * 1 / 100.0;
        amt = amt + i3;
        System.out.println("Interest for the third year: " + i3);
    }
}
Output
BlueJ output of KboatInterest.java

Question 10

'Mega Market' has announced festival discounts on the purchase of items, based on the total cost of the items purchased:

Total costDiscount
Up to ₹2,0005%
₹2,001 to ₹5,00010%
₹5,001 to ₹10,00015%
Above ₹10,00020%

Write a program to input the total cost. Display name of the customer, discount and the amount to be paid after discount.

import java.io.*;

public class KboatDiscount
{
    public static void main(String args[]) throws IOException {
        
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        
        System.out.print("Enter customer name: ");
        String name = in.readLine();
        
        System.out.print("Enter total cost: ");
        double c = Double.parseDouble(in.readLine());
        
        int d = 0;
        
        if (c <= 2000)
            d = 5;
        else if (c <= 5000)
            d = 10;
        else if (c <= 10000)
            d = 15;
        else
            d = 20;
            
        double disc = c * d / 100.0;
        double amt = c - disc;
        
        System.out.println("Customer Name: " + name);
        System.out.println("Discount: " + disc);
        System.out.println("Amount to be paid: " + amt);
    }
}
Output
BlueJ output of KboatDiscount.java