Java Full QB Solution
Java Full QB Solution
Ans- Java is basically an OOP programming language like C, C++, etc. but with some advanced
features. This was developed and designed by James Gosling and the team in early 1995. Java
programming includes many features like concurrent, dynamic, multithread, secured, etc. that make it
easy to use.
Moreover, another great feature that this coding language involves is that its “Platform independence”.
Java programming is an application development platform with lesser implementation dependencies.
That’s why many users use it for developing dynamic apps for various devices. Like laptops, mobile
phones, data centers, and other useful gadgets.
There are many uses of apps within this programming language. Such as;-
These are some of the features and uses of this language that we are familiar with. But there are some
other advantages also of using this coding platform. Let us move on further in this blog regarding the
platform independence feature of this programming language.
program
Ans- Compiling and running a java program is very easy after JDK installation. Following
are the steps −
Open a command prompt window and go to the directory where you saved the
java program (MyFirstJavaProgram.java). Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption: The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see the result printed on the window.
A while loop iterates through a set of statements till its boolean condition
returns false. As long as the condition given evaluates to true, the loop
iterates. The basic syntax of Java while loop is:
while(boolean condition)
{
//statements;
}
3. do while loop in Java
Java do while loop executes the statement first and then checks for the
condition.Other than that it is similar to the while loop. The difference lies
in the fact that if the condition is true at the starting of the loop the
statements would still be executed, however in case of while loop it would
not be executed at all.
while do-while
while loop is entry controlled loop. do-while loop is exit controlled loop.
while(condition) do { statement(s); }
{ statement(s); } while(condition);
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
class Main {
// declare variables
int a = 12, b = 5;
// addition operator
// subtraction operator
// multiplication operator
// division operator
// modulo operator
class Main {
// create variables
int a = 4;
int var;
var = a;
var += a;
var *= a;
class Main {
// create variables
int a = 7, b = 11;
// value of a and b
// == operator
// != operator
// > operator
// < operator
// >= operator
// <= operator
} class Main {
public static void main(String[] args) {
// create variables
int a = 7, b = 11;
// value of a and b
// == operator
// != operator
// > operator
// < operator
// >= operator
// <= operator
System.out.println(a <= b); // true
class Main {
// && operator
// || operator
// ! operator
}
1. 6. Declare two variables and check which is greater and display appropriate
message. (use if-else)
Ans- // Write a program to find the largest of two numbers in java
public class Main
{
public static void main (String[]args)
{
else
System.out.println (num2 + " is greater");
}
}
7. Declare a variable and check whether the number is even or add and
display appropriate message.
import java.util.Scanner;
if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}
A 1D array is a simple data structure that stores a collection of similar type data in a
contiguous block of memory while the 2D array is a type of array that stores multiple
data elements of the same type in matrix or table like format with a number of rows
and columns. Thus, this is the main difference between 1D and 2D array.
1. 9. Write a program to accept the N numbers from user in array and find the
greatest and smallest element and print it.
//numbers array
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};
10. What is constructor? Give its properties. Write a sample code to overload it.
Ans - A constructor is a special member function of a class with the same name as the
class name but has no return type. Whenever an object of a class is created using
class Sample {
Sample() {
// constructor body
Properties of constructor - They will have the same name as of their class.
They should be declared in the public section.
They are executed automatically when objects are created.
They do not have return types, not even void and thus they can't return
values.
11. How the constructors are different from methods in java? Illustrate with
example.
Ans-
Constructors Methods
A Method is a collection of
A Constructor is a block of code that statements which returns a value
initializes a newly created object. upon its execution.
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the
modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
In the above figure, Employee is a parent class and Executive is a child class. The Executive
class inherits all the properties of the Employee class.
Let's implement the single inheritance mechanism in a Java program.
Executive.java
1. class Employee
2. {
3. float salary=34534*12;
4. }
5. public class extends Employee
6. {
7. float bonus=3000*6;
8. public static void main(String args[])
9. {
10. Executive obj=new Executive();
11. System.out.println("Total salary credited: "+obj.salary);
12. System.out.println("Bonus of six months: "+obj.bonus);
13. }
14. }
Output:
Total salary credited: 414408.0
Bonus of six months: 18000.0
2. Multi-level Inheritance
In multi-level inheritance, a class is derived from a class which is also derived from another
class is called multi-level inheritance. In simple words, we can say that a class that has more
than one parent class is called multi-level inheritance. Note that the classes must be at
different levels. Hence, there exists a single base class and single derived class but multiple
intermediate base classes.
In the above figure, the class Marks inherits the members or methods of the class Students.
The class Sports inherits the members of the class Marks. Therefore, the Student class is the
parent class of the class Marks and the class Marks is the parent of the class Sports. Hence,
the class Sports implicitly inherits the properties of the Student along with the class Marks.
Let's implement the multi-level inheritance mechanism in a Java program.
MultilevelInheritanceExample.java
1. //super class
2. class Student
3. {
4. int reg_no;
5. void getNo(int no)
6. {
7. reg_no=no;
8. }
9. void putNo()
10. {
11. System.out.println("registration number= "+reg_no);
12. }
13. }
14. //intermediate sub class
15. class Marks extends Student
16. {
17. float marks;
18. void getMarks(float m)
19. {
20. marks=m;
21. }
22. void putMarks()
23. {
24. System.out.println("marks= "+marks);
25. }
26. }
27. //derived class
28. class Sports extends Marks
29. {
30. float score;
31. void getScore(float scr)
32. {
33. score=scr;
34. }
35. void putScore()
36. {
37. System.out.println("score= "+score);
38. }
39. }
40. public class MultilevelInheritanceExample
41. {
42. public static void main(String args[])
43. {
44. Sports ob=new Sports();
45. ob.getNo(0987);
46. ob.putNo();
47. ob.getMarks(78);
48. ob.putMarks();
49. ob.getScore(68.7);
50. ob.putScore();
51. }
52. }
Output:
registration number= 0987
marks= 78.0
score= 68.7
3.Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical
inheritance.
In the above figure, the classes Science, Commerce, and Arts inherit a single parent class
named Student.
Let's implement the hierarchical inheritance mechanism in a Java program.
HierarchicalInheritanceExample.java
1. //parent class
2. class Student
3. {
4. public void methodStudent()
5. {
6. System.out.println("The method of the class Student invoked.");
7. }
8. }
9. class Science extends Student
10. {
11. public void methodScience()
12. {
13. System.out.println("The method of the class Science invoked.");
14. }
15. }
16. class Commerce extends Student
17. {
18. public void methodCommerce()
19. {
20. System.out.println("The method of the class Commerce invoked.");
21. }
22. }
23. class Arts extends Student
24. {
25. public void methodArts()
26. {
27. System.out.println("The method of the class Arts invoked.");
28. }
29. }
30. public class HierarchicalInheritanceExample
31. {
32. public static void main(String args[])
33. {
34. Science sci = new Science();
35. Commerce comm = new Commerce();
36. Arts art = new Arts();
37. //all the sub classes can access the method of super class
38. sci.methodStudent();
39. comm.methodStudent();
40. art.methodStudent();
41. }
42. }
Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.
4.Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more
types of inheritance.
In the above figure, GrandFather is a super class. The Father class inherits the properties of
the GrandFather class. Since Father and GrandFather represents single inheritance. Further,
the Father class is inherited by the Son and Daughter class. Thus, the Father becomes the
parent class for Son and Daughter. These classes represent the hierarchical inheritance.
Combinedly, it denotes the hybrid inheritance.
Let's implement the hybrid inheritance mechanism in a Java program.
Daughter.java
1. //parent class
2. class GrandFather
3. {
4. public void show()
5. {
6. System.out.println("I am grandfather.");
7. }
8. }
9. //inherits GrandFather properties
10. class Father extends GrandFather
11. {
12. public void show()
13. {
14. System.out.println("I am father.");
15. }
16. }
17. //inherits Father properties
18. class Son extends Father
19. {
20. public void show()
21. {
22. System.out.println("I am son.");
23. }
24. }
25. //inherits Father properties
26. public class Daughter extends Father
27. {
28. public void show()
29. {
30. System.out.println("I am a daughter.");
31. }
32. public static void main(String args[])
33. {
34. Daughter obj = new Daughter();
35. obj.show();
36. }
37. }
Output:
I am daughter.
https://www.javatpoint.com/types-of-inheritance-in-java
Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.
Private and final methods can be Private and final methods can’t be
overloaded. overridden.
Method Overloading Method Overriding
Argument list should be different while Argument list should be same in method
doing method overloading. overriding.
Let's understand the abstraction with the help of a real-world example. The best
example of abstraction is a car. When we derive a car, we do not know how is the car
moving or how internal components are working? But we know how to derive a
car. It means it is not necessary to know how the car is working, but it is important
how to derive a car. The same is an abstraction.
The same principle (as we have explained in the above example) also applied in Java
programming and any OOPs. In the language of programming, the code
implementation is hidden from the user and only the necessary functionality is shown
or provided to the user. We can achieve abstraction in two ways:
If the class does not have the implementation of all the methods of the interface, we
should declare the class as abstract. It provides complete abstraction. It means that
fields are public static and final by default and methods are empty.
Let's see an example of an abstract class.
MainClass.java
1. //abstract class
2. abstract class Demo
3. {
4. //abstract method
5. abstract void display();
6. }
7. //extends the abstract class
8. public class MainClass extends Demo
9. {
10. //defining the body of the method of the abstract class
11. void display()
12. {
13. System.out.println("Abstract method called.");
14. }
15. public static void main(String[] args)
16. {
17. MainClass obj = new MainClass ();
18. //invoking abstract method
19. obj.display();
20. }
21. }
Output:
Using Interface
In Java, an interface is similar to Java classes. The difference is only that an interface
contains empty methods (methods that do not have method implementation) and
variables. In other words, it is a collection of abstract methods (the method that does
not have a method body) and static constants. The important point about an interface
is that each method is public and abstract and does not contain any constructor.
Along with the abstraction, it also helps to achieve multiple inheritance. The
implementation of these methods provided by the clients when they implement the
interface
Features of Interface:
1. interface CarStart
2. {
3. void start();
4. }
5. interface CarStop
6. {
7. void stop();
8. }
9. public class Car implements CarStart, CarStop
10. {
11. public void start()
12. {
13. System.out.println("The car engine has been started.");
14. }
15. public void stop()
16. {
17. System.out.println("The car engine has been stopped.");
18. }
19. public static void main(String args[])
20. {
21. Car c = new Car();
22. c.start();
23. c.stop();
24. }
25. }
Output:
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction
and multiple inheritance in Java. In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body.
Rules for Declaring Interface
There are some rules that need to be followed by Interface.
• All interface Methods are implicitly public and abstract. Even if you use keyword it
will not create the problem as you can see in the second Method declaration. (Before
Java 8)
• Interfaces can declare only Constant. Instance variables are not allowed. This means
all variables inside the Interface must be public, static, final. Variables inside
Interface are implicitly public static final.
• Interface Methods cannot be static. (Before Java 8)
• Interface Methods cannot be final, strictfp or native.
• The Interface can extend one or more other Interface. Note: The Interface can only
extend another interface.
Q.69 Define abstract class in java with example
Ans: A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
o #Example of Abstract Class
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
Output:
running safely
Q. 70 Difference between abstract class and interface
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Q.71 Define Package. Explain Type of Packages
Ans: PACKAGE in Java is a collection of classes, sub-packages, and interfaces. It helps
organize your classes into a folder structure and make it easy to locate and use them. More
importantly, it helps improve code reusability.
Each package in Java has its unique name and organizes its classes and interfaces into a
separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same package, they
can appear in different packages. This is possible by assigning a separate namespace to each
Java package.
1. Built-in packages
When we install Java into a personal computer or laptop, many packages get installed
automatically. They all are unique on their own and have the capabilities to handle multiple
tasks. Due to this, we don’t have to start building everything from scratch. Some of the
examples of built-in packages are listed below.
• Java.lang
• Java.io
• Java.util
• Java.applet
• Java.awt
• Java.net
Let’s see how you can use an inbuilt package in your Java file.
Importing java.lang
import java.lang.*;
class Main {
public static void main(String args[]) {
String a = "1230";
int b = Integer.parseInt(a);
System.out.println(b);
}
}
Output : 1230
2.User-defined packages
User-defined packages are those that developers create to incorporate different needs of
applications. In simple terms, User-defined packages are those that the users define. Inside a
package, you can have Java files like classes, interfaces, and a package as well (called a sub-
package).
Sub-package
A package defined inside a package is called a sub-package. It’s used to make the
structure of the package more generic. It lets users arrange their Java files into their
corresponding packages. For example, say, you have a package named cars. You’ve defined
supporting Java files inside it.
1) Public Access: – Public Access modifiers Specifies that data Members and Member
Functions those are declared as public will be visible in entire class in which they are
defined. Public Modifier is used when we wants to use the method any where either
in the class or from outside the class. The Variables or methods those are declared as
public are accessed in any where , Means in any Class which is outside from our main
program or in the inherited class or in the class that is outside from our own class
where the method or variables are declared.
2) Protected Access:- The Methods those are declared as Protected Access modifiers
are Accessible to Only in the Sub Classes but not in the Main Program , This is the Most
important Access Modifiers which is used for Making a Data or Member Function as
he may only be Accessible to a Class which derives it but it doesn’t allows a user to
Access the data which is declared as outside from Program Means Methods those are
Declared as Protected are Never be Accessible to Another Class The Protected will be
Accessible to Only Sub Class and but not in your Main Program.
3) Private Access:- The Methods or variables those are declared as private Access
modifiers are not would be not Accessed outside from the class or in inherited Class
or the Subclass will not be able to use the Methods those are declared as Private they
are Visible only in same class where they are declared. By default all the Data Members
and Member Functions is Private, if we never specifies any Access Modifier in front of
the Member and Data Members Functions.
Q.75 What are the types of exception in java. Give an example with program
1. Built-in Exceptions
o Checked Exception
o Unchecked Exception
Output
Can't divide a number by 0
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output
Number format exception
User Defined Exception :
User-Defined Exceptions: In Java, we already have some built-in exception classes
like ArrayIndexOutOfBoundsException,NullPointerException,and ArithmeticExce
ption. These exceptions are restricted to trigger on some predefined conditions. In
Java, we can write our own exception class by extends the Exception class. We can
throw our own exception on a particular condition using the throw keyword. For
creating a user-defined exception, we should have basic knowledge of the try-
catch block and throw keyword.
1. import java.util.*;
2. class UserDefinedException{
3. public static void main(String args[]){
4. try{
5. throw new NewException(5);
6. }
7. catch(NewException ex){
8. System.out.println(ex) ;
9. }
10. }
11. }
12. class NewException extends Exception{
13. int x;
14. NewException(int y) {
15. x=y;
16. }
17. public String toString(){
18. return ("Exception value = "+x) ;
19. }
20. }
Q.76 Write a program to illustrate Numberformat Exception and
ArrayIndexOutofBox Exception
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
Output
Number format exception
Output
Array Index is Out Of Bounds
Q.77 Write a program to illustrate DividebyZero Exception in JAVA.
class example {
public static void main (String args[]) {
int num1 = 15, num2 = 0, result = 0;
try{
result = num1/num2;
System.out.println("The result is" +result);
}
catch (ArithmeticException e) {
System.out.println ("Can't be divided by Zero " + e);
}
}
}
Output:
Can't be divided by Zero java.lang.ArithmeticException: / by zero
ArrayList Vector
5) ArrayList uses the Iterator interface to A Vector can use the Iterator interface
traverse the elements. or Enumeration interface to traverse the
elements.
Q.96 Define InputStream. Write a program to read the content from the file
Ans: InputStream class is the superclass of all the io classes i.e. representing an input stream
of
bytes. It represents input stream of bytes. Applications that are defining subclass of
InputStream
A reset() method is invoked which re-positions the stream to the recently marked position.
Example:
CODE:
import java.io.FileInputStream;
import java.io.InputStream;
class Main {
try {
input.read(array);
System.out.println(data);
input.close();
} catch (Exception e) {
e.getStackTrace();
Output: