[go: up one dir, main page]

0% found this document useful (0 votes)
41 views41 pages

Java Full QB Solution

Uploaded by

patilkrushna280
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views41 pages

Java Full QB Solution

Uploaded by

patilkrushna280
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

1.What are the properties of the Object Oriented Programming?

Why java is platform


independent?

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

Useful for developing (Mobile) Android apps

Programming for hardware devices and gadgets

Helps to build Enterprise Software

Useful for Big Data analytics

Applicable in mobile applications

It is also useful for many server-side technologies.

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.

2.Explain in detail the steps to write and execute Java

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.

3.Explain loop control Statements (while,do-while,for,nested for)

Ans- 1. For loop in Java


Java for loop consists of 3 primary factors which define the loop itself.
These are the initialization statement, a testing condition, an increment or
decrement part for incrementing/decrementing the control variable.

The basic syntax of java for loop goes like this:


for(initializing statement;testing condition;increment/decrement)
{
//code to be iterated
}

2. While loop in Java


While loops are very important as we cannot know the extent of a loop
everytime we define one. For example if we are asked to take a dynamic
collection and asked to iterate through every element, for loops would be
impossible to use because we do not know the size of the collection. Then
we would have to use an enhanced for loop or a while loop.

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.

Nested Loops in Java


As the name suggests, nested loops are basically one loop functioning inside
another one.

Basic syntax for a for loop inside a for loop:


for(initializer;condition;increment/decrement)
{
for(initializer;condition;increment/decrement)
{
//code to be nested
}
}

4.Differentiate between while and do-while

while do-while

Condition is checked first then Statement(s) is executed atleast


statement(s) is executed. once, thereafter condition is checked.

It might occur statement(s) is


executed zero times, If condition is At least once the statement(s) is
false. executed.

No semicolon at the end of while. Semicolon at the end of while.


while(condition) while(condition);

If there is a single statement,


brackets are not required. Brackets are always required.
while do-while

Variable in condition is initialized variable may be initialized before or


before the execution of loop. within the loop.

while loop is entry controlled loop. do-while loop is exit controlled loop.

while(condition) do { statement(s); }
{ statement(s); } while(condition);

1. 5. Explain operators In java and give an example of each.

1. Java Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on variables


and data. For example,

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after division)

class Main {

public static void main(String[] args) {

// declare variables

int a = 12, b = 5;
// addition operator

System.out.println("a + b = " + (a + b));

// subtraction operator

System.out.println("a - b = " + (a - b));

// multiplication operator

System.out.println("a * b = " + (a * b));

// division operator

System.out.println("a / b = " + (a / b));

// modulo operator

System.out.println("a % b = " + (a % b));

2. Java Assignment Operators

Assignment operators are used in Java to assign values to variables.

class Main {

public static void main(String[] args) {

// create variables
int a = 4;

int var;

// assign value using =

var = a;

System.out.println("var using =: " + var);

// assign value using =+

var += a;

System.out.println("var using +=: " + var);

// assign value using =*

var *= a;

System.out.println("var using *=: " + var);

3. Java Relational Operators

Relational operators are used to check the relationship between two


operands.

class Main {

public static void main(String[] args) {

// create variables
int a = 7, b = 11;

// value of a and b

System.out.println("a is " + a + " and b is " + b);

// == operator

System.out.println(a == b); // false

// != operator

System.out.println(a != b); // true

// > operator

System.out.println(a > b); // false

// < operator

System.out.println(a < b); // true

// >= operator

System.out.println(a >= b); // false

// <= operator

System.out.println(a <= b); // true

} class Main {
public static void main(String[] args) {

// create variables

int a = 7, b = 11;

// value of a and b

System.out.println("a is " + a + " and b is " + b);

// == operator

System.out.println(a == b); // false

// != operator

System.out.println(a != b); // true

// > operator

System.out.println(a > b); // false

// < operator

System.out.println(a < b); // true

// >= operator

System.out.println(a >= b); // false

// <= operator
System.out.println(a <= b); // true

4. Java Logical Operators

Logical operators are used to check whether an expression is true or false .

They are used in decision making.

class Main {

public static void main(String[] args) {

// && operator

System.out.println((5 > 3) && (8 > 5)); // true

System.out.println((5 > 3) && (8 < 5)); // false

// || operator

System.out.println((5 < 3) || (8 > 5)); // true

System.out.println((5 > 3) || (8 < 5)); // true

System.out.println((5 < 3) || (8 < 5)); // false

// ! operator

System.out.println(!(5 == 3)); // true

System.out.println(!(5 > 3)); // false

}
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)
{

int num1 = 50, num2 = 20;


if (num1 == num2)
System.out.println ("both are equal");
else if (num1 > num2)
System.out.println (num1 + " is greater");

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;

public class EvenOdd {

public static void main(String[] args) {

Scanner reader = new Scanner(System.in);

System.out.print("Enter a number: ");


int num = reader.nextInt();

if(num % 2 == 0)
System.out.println(num + " is even");
else
System.out.println(num + " is odd");
}
}

1. 8. What is array? Explain 1D and 2D Array (Definition, Syntax, Example)


Ans- 1D array or single dimensional array stores a list of variables of the same
data type. It is possible to access each variable using the index.
. The syntax for 1D array is, data-type[] name = new data-type[size];

2D array or multi-dimensional array stores data in a format consisting of rows and


columns.

the syntax for 2D array is, data-type[][] name = new data-type[rows][columns];

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.

Ans- public class FindLargestSmallestNumber {

public static void main(String[] args) {

//numbers array
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};

//assign first element of an array to largest and smallest


int smallest = numbers[0];
int largetst = numbers[0];

for (int i = 1; i < numbers.length; i++) {


if (numbers[i] > largetst)
largetst = numbers[i];
else if (numbers[i] < smallest)
smallest = numbers[i];
}

System.out.println("Largest Number is : " + largetst);


System.out.println("Smallest Number is : " + smallest);
}
}

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

a new keyword, it invokes a constructor of that class.

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.

A Constructor can be used to initialize A Method consists of Java code to


an object. be executed.
Constructors Methods

A Constructor is invoked implicitly by A Method is invoked by the


the system. programmer.

A Constructor is invoked when a


object is created using the A Method is invoked through method
keyword new. calls.

A Constructor doesn’t have a return


type. A Method must have a return type.

A Constructor initializes a object that A Method does operations on an


doesn’t exist. already created object.

A Constructor’s name must be same


as the name of the class. A Method’s name can be anything.

A class can have many Constructors


but must not have the same A class can have many methods but
parameters. must not have the same parameters.

Example of constructor and method mix

public class JavaTester {


int num;
JavaTester(){
num = 3;
System.out.println("Constructor invoked. num: " + num);
}
public void init(){
num = 5;
System.out.println("Method invoked. num: " + num);
}
public static void main(String args[]) {
JavaTester tester = new JavaTester();
tester.init();
}
}
Q.57 What is Inheritance in Java? Why do we need to use inheritance?
Ans : Inheritance is an important pillar of OOP(Object-Oriented Programming).
It is the mechanism in java by which one class is allowed to inherit the
features(fields and methods) of another class. In Java, inheritance means
creating new classes based on existing ones. A class that inherits from another
class can reuse the methods and fields of that class. In addition, you can add
new fields and methods to your current class as well.
Why do we need to use inheritance?
• Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.
Q.58 What is super class and subclass?

Ans: In Java, it is possible to inherit attributes and methods


from one class to another. We group the "inheritance concept"
into two categories:

• subclass (child) - the class that inherits from another


class
• superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

In the example below, the Car class (subclass) inherits the


attributes and methods from the Vehicle class (superclass):

class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}

class Car extends Vehicle {


private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {

// Create a myCar object


Car myCar = new Car();

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

Q.58 What are the types of inheritance in Java?


Ans : Java supports the following four types of inheritance:
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
1.Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes it is also known as simple
inheritance.

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

Q.65 Compare Method Overriding and Method Overloading?


Method Overloading Method Overriding

Method overloading is a compile-time Method overriding is a run-time


polymorphism. polymorphism.

It is used to grant the specific


implementation of the method which is
It helps to increase the readability of the already provided by its parent class or
program. superclass.

It is performed in two classes with


It occurs within the class. inheritance relationships.

Method overloading may or may not


require inheritance. Method overriding always needs inheritance.

In method overloading, methods must


have the same name and different In method overriding, methods must have the
signatures. same name and same signature.

In method overloading, the return type


can or can not be the same, but we just In method overriding, the return type must be
have to change the parameter. the same or co-variant.

Static binding is being used for Dynamic binding is being used for
overloaded methods. overriding methods.

It gives better performance. The reason


Poor Performance due to compile time behind this is that the binding of overridden
polymorphism. methods is being done at runtime.

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.

Q.66 How to achieve total abstraction in JAVA


Ans : Abstraction is a feature of OOPs. The feature allows us to hide the
implementation detail from the user and shows only the functionality of the
programming to the user. Because the user is not interested to know the
implementation. It is also safe from the security point of view.

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:

o Using Abstract Class


o Using Interface

Using Abstract Class


Abstract classes are the same as normal Java classes the difference is only that an
abstract class uses abstract keyword while the normal Java class does not use. We use
the abstract keyword before the class name to declare the class as abstract.

Remember that, we cannot instantiate (create an object) an abstract class. An abstract


class contains abstract methods as well as concrete methods. If we want to use an
abstract class, we have to inherit it from the base class.

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:

Abstract method called.

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:

o We can achieve total abstraction.


o We can use multiple interfaces in a class that leads to multiple inheritance.
o It also helps to achieve loose coupling.

To use an interface in a class, Java provides a keyword called implements. We provide


the necessary implementation of the method that we have declared in the 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 car engine has been started.


The car engine has been stopped.
Q.68 What is an interface? List the rules to create an interface in java with example
Ans: An Interface in Java programming language is defined as an abstract type used to specify the
behavior of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static
constants and abstract methods.

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

Abstract class Interface

1) Abstract class can have abstract Interface can have only


and non-abstract methods. abstract methods. Since Java 8, it can
have default and static methods also.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) Abstract class can provide the Interface can't provide the


implementation of interface. implementation of abstract class.

5) The abstract keyword is used to The interface keyword is used to


declare abstract class. declare interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

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.

Types of Packages in Java


It can be categorized into 2 categories.
1. Built-in / predefined packages
2. User-defined packages.
Let’s understand them in a little more detail.

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.

Q. 71 Explain use of keywords in java/ Define significance of visibility control in java


Ans:

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

Ans: In Java, exception is an event that occurs during the execution of a


program and disrupts the normal flow of the program's instructions. Bugs or
errors that we don't want and restrict our program's normal execution of
code are referred to as exceptions. In this section, we will focus on
the types of exceptions in Java and the differences between the two.
Exceptions can be categorized into two ways:

1. Built-in Exceptions
o Checked Exception
o Unchecked Exception

1. These exceptions are checked at These exceptions are just opposite


compile time. These exceptions to the checked exceptions. These
are handled at compile time too. exceptions are not checked and
handled at compile time.

2. These exceptions are direct They are the direct subclasses of


subclasses of exception but not the RuntimeException class.
extended from RuntimeException
class.

3. The code gives a compilation The code compiles without any


error in the case when a method error because the exceptions
throws a checked exception. The escape the notice of the compiler.
compiler is not able to handle the These exceptions are the results of
exception on its own. user-created errors in
programming logic.

4. These exceptions mostly occur These exceptions occur mostly


when the probability of failure is due to programming mistakes.
too high.
Built-in exception :

2. // Java program to demonstrate ArithmeticException


3. class ArithmeticException_Demo
4. {
5. public static void main(String args[])
6. {
7. try {
8. int a = 30, b = 0;
9. int c = a/b; // cannot divide by zero
10. System.out.println ("Result = " + c);
11. }
12. catch(ArithmeticException e) {
13. System.out.println ("Can't divide a number by 0");
14. }
15. }
16. }

Output
Can't divide a number by 0

// Java program to demonstrate NumberFormatException


class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

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

// Java program to demonstrate NumberFormatException


class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}

Output
Number format exception

// Java program to demonstrate ArrayIndexOutOfBoundException


class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}

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

Q.78 Define use of static and finally keywords.


Ans: Final keyword is used in different contexts. First of all, final is a non-
access modifier applicable only to a variable, a method, or a class. Following
are different contexts where final is used. While the static keyword in Java is
mainly used for memory management. The static keyword in Java is used to
share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes.

Final access modifier is a modifier applicable to classes, methods, and variables. If


we declare a parent class method as final then we can’t override that method in the
child class because its implementation is final and if a class is declared as final we
can’t extend the functionality of that class i.e we can’t create a child class for that
class i.e inheritance is not possible for final classes. Every method present inside the
final class is always final y default but every variable present inside the final class
need not be final. The main advantage of the final keyword is we can achieve security
and we can provide a unique implementation. But the main disadvantage of the final
keyword is we are missing key benefits of OOPs like Inheritance(Because of the final
class), Polymorphism(Because of the final method) hence if there are no specific
requirements then it is not recommended to use the final keyword.

Static Access Modifier


Static access modifier is an access modifier that is applicable for methods and variables but
not for classes. We can declare top-level class with a static modifier but we can declare the
inner class as static (such types of inner classes are known as static nested classes). In the
case of instance variable for every object, a separate copy will be created but in the case of
static variable, a single copy will be created at class level and shared by every object of that
class.
Q.80 Explain Thread, Multithreading in java and Write a program to for the
demonstration of use of Thread using Thread class
Ans:

Q.84 Differentiate between array and vector

ArrayList Vector

1) ArrayList is not synchronized. Vector is synchronized.

2) ArrayList increments 50% of current Vector increments 100% means doubles


array size if the number of elements the array size if the total number of
exceeds from its capacity. elements exceeds than its capacity.

3) ArrayList is not a legacy class. It is Vector is a legacy class.


introduced in JDK 1.2.

4) ArrayList is fast because it is non- Vector is slow because it is synchronized,


synchronized. i.e., in a multithreading environment, it
holds the other threads in runnable or non-
runnable state until current thread releases
the lock of the object.

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

must provide method, returning the next byte of input.

A reset() method is invoked which re-positions the stream to the recently marked position.

Example:

Suppose we have a file named input.txt with the following content.

This is a line of text inside the file.

CODE:

import java.io.FileInputStream;

import java.io.InputStream;

class Main {

public static void main(String args[]) {

byte[] array = new byte[100];

try {

InputStream input = new FileInputStream("input.txt");

System.out.println("Available bytes in the file: " + input.available());

input.read(array);

System.out.println("Data read from the file: ");

String data = new String(array);

System.out.println(data);

input.close();

} catch (Exception e) {

e.getStackTrace();

Output:

Available bytes in the file: 39

Data read from the file:

This is a line of text inside the file


Define OutputStream. Write a program to write the content of the file using OutputStream
Class.
Ans:The OutputStream class of the java.io package is an abstract superclass that represents an
output stream of bytes.Since OutputStream is an abstract class, it is not useful by itself.
However,
its subclasses can be used to write data.
Example CODE:
import java.io.FileOutputStream;
import java.io.OutputStream;
public class Main {
public static void main(String args[]) {
String data = "This is a line of text inside the file.";
Abhishek Khatri
try {
OutputStream out = new FileOutputStream("output.txt");
byte[] dataBytes = data.getBytes();
out.write(dataBytes);
System.out.println("Data is written to the file.");
out.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}
Output:
When we run the program, the output.txt file is filled with the following content.
This is a line of text inside the file.

You might also like