Unit 3 – Fundamentals of Java Programming
XII Information Technology 802 NCERT Book Exercise Solution
Q1. What is Java Bytecode?
Answer: Bytecode is a java compiled code, which translated by java compiler from java source code to java bytecode. Java Bytecode is a highly optimized set of instructions. Bytecode is also known as Java class file.
When the bytecode is to be run on a computer, a Java interpreter, called the Java Virtual Machine (JVM), translates the bytecode into machine code and then executes it.
The advantage of such an approach is that once a programmer has compiled a Java program into bytecode, it can be run on any platform (say Windows, Linux, or Mac) as long as it has a JVM running on it. This makes Java programs platform independent and highly portable.
Q2. Explain the difference between a Class and an Object with an example.
Answer: Class :- A class is a physical or logical entity that has certain attributes, known as Data members and Method members to get, set or update the class data members.
For Example Book is a Class which has title, author, publisher, genre and price as the data members and display_details(), getPrice(), setPrice() etc, are the Member methods.
Objects:- Object is the instance of class i.e. implementation of class physically. Each object has their own data members. To implement the class we need to create instance of class i.e. variable of class type is called object.
A class as a template from which objects are created.
All objects of the same class have the same type of data members.
Method members of a class are invoked on an object to perform the action associated with that method.
Q3. What is a constructor? Why is it used?
Answer: Constructor is a special method member of class, which is used to initialize the data members of the class, when you create the instance of class.
Properties of Constructor:
- The constructor has the same name as the class.
- It has no return type, and
- It may or may not have a parameter list.
- Whenever a new object of a class is created, the constructor of the class is invoked automatically.
- We do not call the constructor explicitly.
Q4. How are exceptions handled in Java?
Answer: Exception is an error situation that is unexpected in the program execution and cause it to terminate unexpectedly. To avoid this condition, you need to handle the exception properly.
To handle the exceptions in Java, you need to use try .. catch block. The basic idea in exception handling is to –
- Denote an exception block – Identify areas in the code where errors can occur
- Catch the exception – Receive the error information
- Handle the exception – Take corrective action to recover from the error
Java provides the following keywords to handle an exception:
- try – A try block surrounds the part of the code that can generate exception(s).
- catch – The catch blocks follow a try block. A catch block contains the exception handler – specific code that is executed when the exception occurs. Multiple catch blocks following a try block can handle different types of exceptions.
- finally – The optional finally block is always executed when the try block exits. This means the finally block is executed whether an exception occurs or not.
- Note:- Programmers use this block to put in clean up code, for example, freeing up resources allocated in the try block.
The structure of a try-catch statement block for exception handling is as below:
try {
// Part of the program where an exception might occur
}
catch (exceptiontype1 argument1) {
// Handle exception of the exceptiontype1
}
catch (exceptiontype2 argument2) {
// Handle exception of the exceptiontype2
}
finally {
//Code to be executed when the try block exits
}
Q5. How can threads be created in Java? Briefly explain with an example.
Answer: A multithreaded program is one that can perform multiple tasks concurrently so that there is optimal utilization of the computer’s resources. A multithreaded program consists of two or more parts called threads each of which can execute a different task independently at the same time.
In Java, threads can be created in two ways
- By extending the Thread class
- By implementing the Runnable interface
Method – 1 :
- The first method to create a thread is to create a class that extends the Thread class from the java.lang package and override the run() method.
- The run() method is the entry point for every new thread that is instantiated from the class.
- To create a thread, instantiate it from the ExtendThread class, and to start its execution, call the start() method of the Thread class.
- Classes that you create by extending the Thread class cannot be extended further.
public class ExtendThread extends Thread {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}
}
public class ExtendMain{
public static void main(String args[]) {
ExtendThread t1 =new ExtendThread();
t1.start();
t2.start();
}
}
Method – 2 :
- The second method to create a thread is to create a class that implements the Runnable interface and override the run() method.
- Implementing the Runnable interface gives the flexibility to extend classes created by this method.
- To create a thread, first instantiate the class that implements the Runnable interface, then pass that object to a Thread instance.
- As before, to start the execution of the thread call the start() method.
public class RunnableDemo implements Runnable {
public void run() {
System.out.println("Created a Thread");
for (int count = 1; count <= 3; count++)
System.out.println("Count="+count);
}
}
public class RunnableMain{
public static void main(String args[]){
RunnableDemo r = new RunnableDemo();
Thread t1 = new Thread(r);
t1.start();
}
}
Lab Exercises:
Q1. Write a program in Java to implement the formula.
area = length * width * height
Answer: Program
public class Area {
public static void main(String args[]){
int length = 25;
int width = 35;
int height = 45;
double area = length * width * height;
System.out.println("Area = "+area);
}
Ouput:
Area = 39375.0
Q2. Write a program in Java to find the result of the following expressions. (Assume a = 20 and b = 30)
i) a%b
ii) a /= b
iii) (a + b * 100) /10
iv) a && b
v) a++
Answer: Program
public class CheckExpression {
public static void main(String args[]){
int a = 20;
int b = 30;
System.out.println("Expression Output ");
System.out.println("a % b = "+ (a /= b));
a = 20;
b = 30;
System.out.println("(a + b * 100)/10 = "+ ( (a + b * 100) / 10 ));
a = 20;
b = 30;
System.out.println("a && b = "+ ((a && b)); // Error && is a logical AND operator require two boolean values
a = 20;
b = 30;
System.out.println("a++ = "+ (a++));
}
Expression Output
a % b = 0
(a + b * 100)/10 = 302
a++ = 20
Q3. Write a program in Java to print the square of every alternate number of an array.
class Square {
public static void main(String[] args) {
int number[] = {5,10,15,20,25,30};
System.out.println("Square of Every Alternate Number of Array\n");
for(int i = 0; i < number.length; i+=2){
System.out.println(number[i] * number[i]);
}
}
}
Output:
Square of Every Alternate Number of Array
25
225
625
Q4. Write a program in Java to create a class Triangle with the data members base, height, area, and color.
- The members base, height, area are of type double and color is of type string.
- Write getter and setter methods for base, height and color, and write method to compute_area ().
- Create two object of class Triangle, compute their area, and compare their area and color. If area and color both are same for the objects then display “Matching Triangles” otherwise display “Non matching Triangles”.
class Triangle {
private double base;
private double height;
private double area;
private String color;
public void setBase(double b){
base = b;
}
public void setHeight(double h){
height = h;
}
public void setColor(String col){
color = col;
}
public double getBase(){
return base;
}
public double getHeight(){
return height;
}
public String getColor(){
return color;
}
public double getArea(){
return area;
}
public void compute_area(){
area = base * height / 2.0;
}
public static void main(String[] args) {
Triangle t1 = new Triangle();
Triangle t2 = new Triangle();
t1.setBase(20.0);
t1.setHeight(30.0);
t1.setColor("Red");
t2.setBase(20.0);
t2.setHeight(30.0);
t2.setColor("Blue");
if(t1.getArea() == t2.getArea() && t1.getColor() == t2.getColor()){
System.out.println("Matching Triangles");
}
else{
System.out.println("Non Matching Triangles");
}
}
}
Output:
Non Matching Triangles
Q5. Write a program in Java to enable users to handle divide by zero exception.
class ExceptionDivideByZero {
static int divide(int dividend, int division){
return (dividend / division);
}
public static void main(String[] args) {
try{
int quotient = divide(10,0);
System.out.println("Quotient = "+quotient);
}
catch (Exception e){
System.out.println("Error => "+e.getMessage());
}
}
}
Output:
Error => / by zero