top of page

JAVA Que. Bank Sem-4 BCA

Updated: May 17, 2023

UNIT : 1


1. Explain below term.

I) Byte Code

II)JVM

Ans.

Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler which is an alias representation of a C++ code. As soon as a java program is compiled, java bytecode is generated. In more apt terms, java bytecode is the machine code in the form of a .class file. With the help of java bytecode we achieve platform independence in java.


Advantage of Java Bytecode :

Platform independence is one of the soul reasons for which James Gosling started the formation of java and it is this implementation of bytecode which helps us to achieve this. Hence bytecode is a very important component of any java program. The set of instructions for the JVM may differ from system to system but all can interpret the bytecode. A point to keep in mind is that bytecodes are non-runnable codes and rely on the availability of an interpreter to execute and thus the JVM comes into play.


JVM :

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).


What is JVM : It is:

1. A specification where working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Oracle and other companies.

2. An implementation Its implementation is known as JRE (Java Runtime Environment).

3. Runtime Instance Whenever you write java command on the command prompt to run the java class, an instance of JVM is created.


  • What it does:

The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

JVM provides definitions for the:

Memory area

Class file format

Register set

Garbage-collected heap

Fatal error reporting etc.


2. Explain features of JAVA.

Ans. The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language. The features of Java are also known as Java buzzwords.


  • Simple:

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun Microsystem, Java language is a simple programming language because:

Java syntax is based on C++ (so easier for programmers to learn it after C++).

Java has removed many complicated and rarely-used features, for example, explicit pointers, operator overloading, etc.

There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in Java.

  • Object-oriented:

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporate both data and behavior.


Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules.

  • Platform Independent:


Java is platform independent because it is different from other languages like C, C++, etc. which are compiled into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-based platform.

  • Secured:

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:

  • No explicit pointer

  • Java Programs run inside a virtual machine sandbox


  • Classloader:

Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources.

Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to objects.

Security Manager: It determines what resources a class can access such as reading and writing to the local disk.

  • Robust:

The English mining of Robust is strong. Java is robust because:

It uses strong memory management.

There is a lack of pointers that avoids security problems.

Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.

There are exception handling and the type checking mechanism in Java. All these points make Java robust.

  • Architecture-neutral :

Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

  • Portable :

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.

  • High-performance:

Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

  • Distributed :

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.

  • Multi-threaded:

A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.

  • Dynamic :

Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.



3. What is JAVA ? Explain Object Oriented Programming Concepts in Java.

Ans. Java is a widely used object-oriented programming language and software platform that runs on billions of devices, including notebook computers, mobile devices, gaming consoles, medical devices and many others. The rules and syntax of Java are based on the C and C++ languages.


One major advantage of developing software with Java is its portability. Once you have written code for a Java program on a notebook computer, it is very easy to move the code to a mobile device. When the language was invented in 1991 by James Gosling of Sun Microsystems (later acquired by Oracle), the primary goal was to be able to "write once, run anywhere."


It's also important to understand that Java is much different from JavaScript. JavaScript does not need to be compiled, while Java code does need to be compiled. Also, JavaScript only runs on web browsers while Java can be run anywhere.


Java OOPs Concepts :

In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data binding, polymorphism, etc.

Simula is considered the first object-oriented programming language. The programming paradigm where everything is represented as an object is known as a truly object-oriented programming language.

Smalltalk is considered the first truly object-oriented programming language.

The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for example, object, classes, abstraction, inheritance, polymorphism, etc.


OOPs (Object-Oriented Programming System):

Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies software development and maintenance by providing some concepts:


  • Object :

Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.

An Object can be defined as an instance of a class. An object contains an address and takes up some space in memory. Objects can communicate without knowing the details of each other's data or code. The only necessary thing is the type of message accepted and the type of response returned by the objects.

  • Class:

Collection of objects is called class. It is a logical entity.

A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.

  • Inheritance:

When one object acquires all the properties and behaviors of a parent object, it is known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.


Polymorphism:

If one task is performed in different ways, it is known as polymorphism. For example: to convince the customer differently, to draw something, for example, shape, triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something; for example, a cat speaks meow, dog barks woof, etc.

  • Abstraction:

Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.

In Java, we use abstract class and interface to achieve abstraction.

  • Encapsulation:

Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

  • Coupling:

Coupling refers to the knowledge or information or dependency of another class. It arises when classes are aware of each other. If a class has the details information of another class, there is strong coupling. In Java, we use private, protected, and public modifiers to display the visibility level of a class, method, and field. You can use interfaces for the weaker coupling because there is no concrete implementation.

  • Cohesion:

Cohesion refers to the level of a component which performs a single well-defined task. A single well-defined task is done by a highly cohesive method. The weakly cohesive method will split the task into separate parts. The java.io package is a highly cohesive package because it has I/O related classes and interface. However, the java.util package is a weakly cohesive package because it has unrelated classes and interfaces.

  • Association:

Association represents the relationship between the objects. Here, one object can be associated with one object or many objects. There can be four types of association between the objects:

  • One to One

  • One to Many

  • Many to One, and

  • Many to Many

Let's understand the relationship with real-time examples. For example, One country can have one prime minister (one to one), and a prime minister can have many ministers (one to many). Also, many MP's can have one prime minister (many to one), and many ministers can have many departments (many to many).

Association can be undirectional or bidirectional.

  • Aggregation:

Aggregation is a way to achieve Association. Aggregation represents the relationship where one object contains other objects as a part of its state. It represents the weak relationship between objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse objects.

  • Composition:

The composition is also a way to achieve Association. The composition represents the relationship where one object contains other objects as a part of its state. There is a strong relationship between the containing object and the dependent object. It is the state where containing objects do not have an independent existence. If you delete the parent object, all the child objects will be deleted automatically.



4. Explain Operators in JAVA.

Ans. Operators in Java :

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

  • Unary Operator,

  • Arithmetic Operator,

  • Shift Operator,

  • Relational Operator,

  • Bitwise Operator,

  • Logical Operator,

  • Ternary Operator and

  • Assignment Operator.


Java Unary Operator:

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

incrementing/decrementing a value by one

negating an expression

inverting the value of a Boolean

  • Java Arithmetic Operators:

Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.

  • Java Left Shift Operator:

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

  • Java Right Shift Operator:

The Java right shift operator >> is used to move the value of the left operand to right by the number of bits specified by the right operand.


Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.


Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false.

  • Java Ternary Operator:

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java programming. It is the only conditional operator which takes three operands.

  • Java Assignment Operator:

Java assignment operator is one of the most common operators. It is used to assign the value on its right to the operand on its left.



5. Explain briefly any 3 data types used in JAVA.

Ans. Data Types in Java :

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

Primitive data types: The primitive data types include Boolean, char, byte, short, int, long, float and double.

Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.


Java Primitive Data Types :

In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in Java language.


There are 8 types of primitive data types:

  • Boolean data type

  • byte data type

  • char data type

  • short data type

  • int data type

  • long data type

  • float data type

  • double data type


  • Boolean Data Type:

The Boolean data type is used to store only two possible values: true and false. This data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

EX. Boolean one = false

  • Byte Data Type:

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

EX. byte a = 10, byte b = -20

  • Short Data Type:

The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times smaller than an integer.

EX. short s = 10000, short r = -5000

  • Int Data Type:

The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem about memory.

EX. int a = 100000, int b = -200000

  • Float Data Type:

The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point numbers. The float data type should never be used for precise values, such as currency. Its default value is 0.0F.

EX. float f1 = 234.5f

  • Double Data Type:

The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The double data type is generally used for decimal values just like float. The double data type also should never be used for precise values, such as currency. Its default value is 0.0d.

EX. double d1 = 12.3



UNIT 2 :

1. Define term - Constant, Literals and Variable in Java.

Ans. Constant: Constant is a value that cannot be changed after assigning it. Java does not directly support the constants. There is an alternative way to define the constants in Java by using the non-access modifiers static and final.


In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-access modifiers. According to the Java naming convention the identifier name must be in capital letters.


Static and Final Modifiers:

The purpose to use the static modifier is to manage the memory.

It also allows the variable to be available without loading any instance of the class in which it is defined.

The final modifier represents that the value of the variable cannot be changed. It also makes the primitive data type immutable or unchangeable.

Why we use constants?

The use of constants in programming makes the program easy and understandable which can be easily understood by others. It also affects the performance because a constant variable is cached by both JVM and the application.


Literals :

In Java, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals of a given type are generally known as tokens. In this section, we will discuss the term literals in Java.


In Java, literals are the constant values that appear directly in the program. It can be assigned directly to a variable. Java has various types of literals. The following figure represents a literal.


Types of Literals in Java:

There are the majorly four types of literals in Java:

  • Integer Literal

  • Character Literal

  • Boolean Literal

  • String Literal

Why use literals?

To avoid defining the constant somewhere and making up a label for it. Instead, to write the value of a constant operand as a part of the instruction.


Variable:

A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.


A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed.

Types of Variables:

There are three types of variables in Java:

  • local variable

  • instance variable

  • static variable

1) Local Variable:

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable:

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable:

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.


2. Define string class with its all methods.

Ans. In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string.

For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

is same as:

String s="javatpoint";


Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.


What is String in Java?

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

There are two ways to create String object:

  • By string literal

  • By new keyword


Java String class methods :

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method ➡️ Description :

  1. char charAt(int index) ➡️ It returns char value for the particular index

  2. int length() ➡️ It returns string length

  3. static String format(String format, Object... args) ➡️ It returns a formatted string.

  4. static String format(Locale l, String format, Object... args) ➡️ It returns formatted string with given locale.

  5. String substring(int beginIndex) ➡️ It returns substring for given begin index.

  6. String substring(int beginIndex, int endIndex) ➡️ It returns substring for given begin index and end index.

  7. boolean contains(CharSequence s) ➡️ It returns true or false after matching the sequence of char value.

  8. static String join(CharSequence delimiter, CharSequence... elements) ➡️ It returns a joined string.

  9. static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) ➡️ It returns a joined string.

  10. boolean equals(Object another) ➡️ It checks the equality of string with the given object.

  11. boolean isEmpty() ➡️ It checks if string is empty.

  12. String concat(String str) ➡️ It concatenates the specified string.

  13. String replace(char old, char new) ➡️ It replaces all occurrences of the specified char value.

  14. String replace(CharSequence old, CharSequence new) ➡️ It replaces all occurrences of the specified CharSequence.

  15. static String equalsIgnoreCase(String another) ➡️ It compares another string. It doesn't check case.

  16. String[] split(String regex) ➡️ It returns a split string matching regex.

  17. String[] split(String regex, int limit) ➡️ It returns a split string matching regex and limit.

  18. String intern() ➡️ It returns an interned string.

  19. int indexOf(int ch) ➡️ It returns the specified char value index.

  20. int indexOf(int ch, int fromIndex) ➡️ It returns the specified char value index starting with given index.

  21. int indexOf(String substring) ➡️ It returns the specified substring index.

  22. int indexOf(String substring, int fromIndex) ➡️ It returns the specified substring index starting with given index.

  23. String toLowerCase() ➡️ It returns a string in lowercase.

  24. String toLowerCase(Locale l) ➡️ It returns a string in lowercase using specified locale.

  25. String toUpperCase() ➡️ It returns a string in uppercase.

  26. String toUpperCase(Locale l) ➡️ It returns a string in uppercase using specified locale.

  27. String trim() ➡️ It removes beginning and ending spaces of this string.

  28. static String valueOf(int value) ➡️ It converts given type into string. It is an overloaded method.


3. What is Array? Explain different types of array with examples.

Ans. Array:- An array is a data structure that contains a group of elements. Typically these elements are all of the same data type, such as an integer or string. Arrays are commonly used in computer programs to organize data so that a related set of values can be easily sorted or searched


Arrays can of following types:

1. One dimensional (1-D) arrays or Linear arrays:

In it each element is represented by a single subscript. The elements are stored in consecutive memory locations. E.g. A [1], A [2], ….., A [N].

2. Multi dimensional arrays:

(a) Two dimensional (2-D) arrays or Matrix arrays:

In it each element is represented by two subscripts. Thus a two dimensional m x n array A has m rows and n columns and contains m*n elements. It is also called matrix array because in it the elements form a matrix. E.g. A [2] [3] has 2 rows and 3 columns and 2*3 = 6 elements.

(b) Three dimensional arrays:

In it each element is represented by three subscripts. Thus a three dimensional m x n x l array A contains m*n*l elements. E.g. A [2] [3] [2] has 2*3*2 = 12 elements.


4. What is Conditional Statement? Explain any two with examples.

Ans. Conditional statements help you to make a decision based on certain conditions. These conditions are specified by a set of conditional statements having Boolean expressions which are evaluated to a Boolean value of true or false.


In our life, we frequently encounter certain situations where we have to make a decision be it your favorite food, movie, hobby, or the color of our shoes. In C programming also, you may encounter similar kinds of situations where you need to make a decision based on the two possibilities that are yes/no or true/false acceptance, we will learn all about the conditional statements in this article.


There are the following types of conditional statements in C.

  • If statement

  • If-Else statement

  • Nested If-else statement

  • If-Else If ladder

  • Switch statement

If statement:

The single if statement in C language is used to execute the code if a condition is true. It is also called a one-way selection statement. When we use the if condition, we pass the argument and if the argument will be satisfied then the respective code will be executed otherwise nothing can happen.


Below is the if statement followed by the conditional expression.

Syntax:

if(expression)

{

//code to be executed

}


if Statement Example:

#include<stdio.h>

#include<conio.h>

void main()

{

int num=0;

printf("enter the number");

scanf("%d",&num);

if(n%2==0)

{

printf("%d number in even",num);

}

getch();

}


If-else statement:

The if-else statement in C language is used to execute the code if the condition is true or false. It is also called a two-way selection statement.


The single if statement may work pretty well, but if you want to work with multiple variables or the extended conditional parameters, then the if-else statement is the optimum choice. By using the if statement, only one block of the code executes after the condition is true but by using the if-else statement, there are two possible blocks of code where the first block is used for handling the success part and the other one for the failure condition.

Syntax:

if(expression)

{

//Statements

}

else

{

//Statements

}


if..else Statement Example:

#include<stdio.h>

#include<conio.h>

void main()

{

int num=0;

printf("enter the number");

scanf("%d",&num);

if(n%2==0)

{

printf("%d number in even", num);

}

else

{

printf("%d number in odd",num);

}

getch();

}


Switch Statement:

switch statement acts as a substitute for a long if-else-if ladder that is used to test a list of cases. A switch statement contains one or more case labels that are tested against the switch expression. When the expression match to a case then the associated statements with that case would be executed.


We have seen the way of using conditional statements such as if, if-else. if-else ladder, but the need for an additional way of dealing with conditional statements may seem unnecessary but based on the certain usage, switch case was defined to check for the single condition, and based on the multiple cases, code can be executed.


Below is the basic syntax that shows how to use and implement a switch statement.

Syntax:

Switch (expression)

{

case value1:

//Statements

break;

case value 2:

//Statements

break;

case value 3:

//Statements

case value n:

//Statements

break;

Default:

//Statements

}


switch statement Example:

#include<stdio.h>

#include<conio.h>

void main( )

{

char grade = 'B';

if (grade == 'A')

{

printf("Excellent!");

}

else if (grade == 'B')

{

printf("Well done");

}

else if (grade == 'D')

{

printf("You passed");

}

else if (grade == 'F')

{

printf("Better try again");

}

else

{

printf("You Failed!");

}

}

getch();

}


5. What is Loop Statement ? Explain any two with example.

Ans. The Java for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop.

There are three types of for loops in Java.



  1. Simple for Loop

  2. For-each or Enhanced for Loop

  3. Labeled for Loop

Java for-each Loop:

The for-each loop is used to traverse array or collection in Java. It is easier to use than simple for loop because we don't need to increment value and use subscript notation.

It works on the basis of elements and not the index. It returns element one by one in the defined variable.

Syntax:

for(data_type variable : array_name){

//code to be executed

}

Example:

ForEachExample.java

//Java For-each loop example which prints the

//elements of the array

public class ForEachExample {

public static void main(String[] args) {

//Declaring an array

int arr[]={12,23,44,56,78};

//Printing array using for-each loop

for(int i:arr){

System.out.println(i);

}

}

}

Output:

12

23

44

56

78


Java Labeled For Loop :

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful while using the nested for loop as we can break/continue specific for loop.

Syntax:

labelname:

for(initialization; condition; increment/decrement){

//code to be executed

}


Example:

LabeledForExample.java

//A Java program to demonstrate the use of labeled for loop

public class LabeledForExample {

public static void main(String[] args) {

//Using Label for outer and for loop

aa:

for(int i=1;i<=3;i++){

bb:

for(int j=1;j<=3;j++){

if(i==2&&j==2){

break aa;

}

System.out.println(i+" "+j);

}

}

}

}

Output:

1 1

1 2

1 3

2 1



6. Explain Array.Sort(),Array.Fill(),Array.BinarySearch() with example.

Ans. Array class is a class containing static methods that are used with arrays in order to search, sort, compare, insert elements, or return a string representation of an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows being present in java.util.Arrays class. Here we will be discussing different plots using the sort() method of the Arrays class.


Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array.

Syntax: sort() Method

Arrays.sort();

Syntax: Overloaded sort() Method

public static void sort(int[] arr, int from_Index, int to_Index) ;


Parameters: It takes three parameters as can be perceived from the syntax which is as follows:

  • The array to be sorted

  • The index of the first element, inclusive, to be sorted (Referred to as from_index)

  • The index of the last element, exclusive, to be sorted (Referred to as last_index)

EX. :

import java.util.Arrays;

class GFG {

public static void main(String args[])

{

int[] arr = { 5, -2, 23, 7, 87, -42, 509 };

System.out.println("The original array is: ");

for (int num : arr) {

System.out.print(num + " ");

}

Arrays.sort(arr);

System.out.println("\nThe sorted array is: ");

for (int num : arr) {

System.out.print(num + " ");

}

}

}

OUTPUT:

The original array is:

5 -2 23 7 87 -42 509

The sorted array is:

-42 -2 5 7 23 87 509


  • Array.Fill() :

By using the Arrays.fill() method, we can either fill a complete array or can fill some part of it. Arrays.fill() method is also capable of filling both the 2D and the 3D Arrays.


Arrays fill() method has the following syntax:

Java.util.Arrays.fill(boolean[] arr, int fromIndex, int toIndex, boolean val )

The arr parameter defines an array to be filled.

The formIndex parameter defines the index of the first element to be filled with the given value.

The toIndex parameter defines the index of the last index to be filled with the given value.

The val parameter defines the value to be stored in all elements of the given array.


EX. :

// import required classes and packages

package javaTpoint.MicrosoftJava;

import java.util.Arrays;

import java.util.Scanner;

// create ArraysFillExample4 to fill 3D array with the given value

public class ArraysFillExample4

{

//main() method start

public static void main(String[] args)

{

int ele;

// create scanner class object

Scanner sc = new Scanner(System.in);

System.out.print("Enter the size of the array: \n");

System.out.print("x : ");

int x = sc.nextInt();

System.out.print("y : ");

int y = sc.nextInt();

System.out.print("z : ");

int z = sc.nextInt();

// create an array of size row*column

int threeDArray[][][] = new int[x][y][z];

System.out.println("Enter the elements in the array: ");

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

for(int j=0; j < threeDArray[i].length; j++){

for(int k=0; k < threeDArray[i][j].length; k++){

System.out.println("Enter element ["+i+"]["+j+"]["+k+"]");

threeDArray[i][j][k] = sc.nextInt();

}

}

}

System.out.print("Enter the element which you want to fill in the array: \n\n");

ele = sc.nextInt();

System.out.println("3D array after inserting elements: \n\n");

System.out.println(Arrays.deepToString(threeDArray));

// fill complete array with ele

for (int[][] newRow : threeDArray) {

for (int[] newRowColumn : newRow) {

Arrays.fill(newRowColumn, ele);

}

}

System.out.println("After filling" +ele+ " in the array:\n\n" + Arrays.deepToString(threeDArray));

sc.close();

}

}

OUTPUT:


  • Array.BinarySearch() :

Binary search is used to search a key element from multiple elements. Binary search is faster than linear search.

In case of binary search, array elements must be in ascending order. If you have unsorted array, you can sort the array using Arrays.sort(arr) method.


Binary Search Example in Java using Arrays.binarySearch() :

import java.util.Arrays;

class BinarySearchExample2{

public static void main(String args[]){

int arr[] = {10,20,30,40,50};

int key = 30;

int result = Arrays.binarySearch(arr,key);

if (result < 0)

System.out.println("Element is not found!");

else

System.out.println("Element is found at index: "+result);

}

}

Output:

Element is found at index: 2


7. Explain pass by value and pass by reference concept with example.

Ans. Pass By Value: In Pass by value, function is called by directly passing the value of the variable as an argument. So any changes made inside the function does not affect the original value.

In Pass by value, parameters passed as an arguments create its own copy. So any changes made inside the function is made to the copied value not to the original value .

Let us take an example to understand better:

function Passbyvalue(a, b) {

let tmp;

tmp = b;

b = a;

a = tmp;

console.log(`Inside Pass by value

function -> a = ${a} b = ${b}`);

}

let a = 1;

let b = 2;

console.log(`Before calling Pass by value

Function -> a = ${a} b = ${b}`);

Passbyvalue(a, b);

console.log(`After calling Pass by value

Function -> a =${a} b = ${b}`);

Output:

Before calling Pass by value Function -> a = 1 b = 2

Inside Pass by value function -> a = 2 b = 1

After calling Pass by value Function -> a =1 b = 2


Pass by Reference: In Pass by Reference, Function is called by directly passing the reference/address of the variable as an argument. So changing the value inside the function also change the original value. In JavaScript array and Object follows pass by reference property.

In Pass by reference, parameters passed as an arguments does not create its own copy, it refers to the original value so changes made inside function affect the original value.


let us take an example to understand better:

function PassbyReference(obj) {

let tmp = obj.a;

obj.a = obj.b;

obj.b = tmp;


console.log(`Inside Pass By Reference

Function -> a = ${obj.a} b = ${obj.b}`);

}

let obj = {

a: 10,

b: 20

}

console.log(`Before calling Pass By Reference

Function -> a = ${obj.a} b = ${obj.b}`);

PassbyReference(obj)

console.log(`After calling Pass By Reference

Function -> a = ${obj.a} b = ${obj.b}`);

Output:

Before calling Pass By Reference Function -> a = 10 b = 20

Inside Pass By Reference Function -> a = 20 b = 10

After calling Pass By Reference Function -> a = 20 b = 10



UNIT 3 :

1. Discuss Accessibility of Access modifiers in different condition.

Ans. There are four types of Java access modifiers:

  • Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

  • Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

  • Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.

  • Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only.


1) Private:

The private access modifier is accessible only within the class.

Simple example of private access modifier:

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error.


class A{

private int data=40;

private void msg(){System.out.println("Hello java");}

}

public class Simple{

public static void main(String args[]){

A obj=new A();

System.out.println(obj.data);//Compile Time Error

obj.msg();//Compile Time Error

}

}

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:


class A{

private A(){}//private constructor

void msg(){System.out.println("Hello java");}

}

public class Simple{

public static void main(String args[]){

A obj=new A();//Compile Time Error

}

}


2) Default :

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier:

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.


//save by A.java

package pack;

class A{

void msg(){System.out.println("Hello");}

}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();//Compile Time Error

obj.msg();//Compile Time Error

}

}

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.


3) Protected :

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifier.


Example of protected access modifier:

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.


//save by A.java

package pack;

public class A{

protected void msg(){System.out.println("Hello");}

}

//save by B.java

package mypack;

import pack.*;

class B extends A{

public static void main(String args[]){

B obj = new B();

obj.msg();

}

}

Output: Hello


4) Public:

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier:

//save by A.java

package pack;

public class A{

public void msg(){System.out.println("Hello");}

}

//save by B.java

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

obj.msg();

}

}

Output: Hello


Java Access Modifiers with Method Overriding:

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.


class A{

protected void msg(){System.out.println("Hello java");}

}

public class Simple extends A{

void msg(){System.out.println("Hello java");}//C.T.Error

public static void main(String args[]){

Simple obj=new Simple();

obj.msg();

}

}

The default modifier is more restrictive than protected. That is why, there is a compile-time error.


2. Discuss final and static method with example.

Ans. Static methods are class level so there are not part of object.

So we can not override static methods but we can call super class static method using subclass name or instance also.

If we are trying to override static methods in sub class from super class then it will be method hiding not method overriding.

Means whenever we call the static method on super class will call super class static method and if we are calling method using sub class it will call sub class method.

So it is clear that static methods are hidden not overridden and they are part of class means class level not object level.

Now the question is can a method be static and final together?

For non static methods if we declare it as final then we are preventing that method from overriding so it can not be overridden in sub class.

When we declare static method as final its prevents from method hiding.

When we declare final static method and override in sub class then compiler shows an error

Compile time error: Cannot override the final method from Super

Lets see an example program to understand this better.


Static methods in java:

Program #1: Java example program to explain about static method in java:

package inheritance Interview Programs;

/*

* @website: www.instanceofjava.com

* @category: Deference between static and final static methods in java

*/

public class Super {

static void method(){

System.out.println("Super class method");

}

}


package inheritance Interview Programs;

// www.instanceofjava.com

public class Sub extends Super {

static void method(){

System.out.println("Sub class method");

}

public static void main (String args[]) {

Super.method();

Sub.method();

}

}

Output:

Super class method

Sub class method


When we override static methods its not overriding it is method hiding and whenever we call method on class name it will call corresponding class method.

If we call methods using objects it will call same methods.


Program #2: Java example program to explain about calling super class static method using sub class in java:

package inheritanceInterviewPrograms;

/*

* @website: www.instanceofjava.com

* @category: Deference between static and final static methods in java

*/

public class Super {

static void method(){

System.out.println("Super class method");

}

}

package inheritanceInterviewPrograms;

// www.instanceofjava.com

public class Sub extends Super {

public static void main (String args[]) {

Super.method();

Sub.method();

}

}

Output:

Super class method

Super class method


We can call super class static methods using sub class object or sub class name also.


Final static methods in java:

Can a method be static and final together in java?

When we declare a method as final we can not override that method in sub class.

In the same way when we declare a static method as final we can not hide it in sub class means we can not create same method in sub class.

If we try to create same static method in sub class compiler will throw an error.

Lets see a java example program on final static methods in inheritance.


Program #3: Java example program to explain about final static method in java :

package inheritance Interview Programs;

/*

* @website: www.instanceofjava.com

* @category: Deference between staic and final static methods in java

*/

public class Super {

final static void method(){

System.out.println("Super class method");

}

}

package inheritanceInterviewPrograms;

// www.instanceofjava.com

public class Sub extends Super {


static void method(){ // compiler time error:

System.out.println("Sub class method");

}

public static void main (String args[]) {

Super.method();

Sub.method();

}

}

Output:



3. Difference between Abstract Class and interface.

Ans. Abstract class and interface both are used to achieve abstraction where we can declare the abstract methods. Abstract class and interface both can't be instantiated.

No.

Abstract class

Interface

1.

Abstract class can have abstract and non-abstract methods.

Interface can have only abstract methods. Since Java 8, it can have default and static methods also.

2.

Abstract class doesn't support multiple inheritance.

Interface supports multiple inheritance.

3.

Abstract class can have final, non-final, static and non-static variables.

Interface has only static and final variables.

4.

Abstract class can provide the implementation of interface.

Interface can't provide the implementation of abstract class.

5.

The abstract keyword is used to declare abstract class.

The interface keyword is used to declare interface.

6.

An abstract class can extend another Java class and implement multiple Java interfaces.

An interface can extend another Java interface only.

7.

An abstract class can be extended using keyword "extends".

An interface can be implemented using keyword "implements".

8.

A Java abstract class can have class members like private, protected, etc.

Members of a Java interface are public by default.

9.

Example:

public abstract class Shape{

public abstract void draw();

}

Example:

public interface Drawable{

void draw();

}



4. What is multithreading? Why it is required? Explain Thread Life Cycle.

ANS. Java is a multi-threaded programming language which means we can develop multi-threaded program using Java. A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources specially when your computer has multiple CPUs.


By definition, multitasking is when multiple processes share common processing resources such as a CPU. Multi-threading extends the idea of multitasking into applications where you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application.


Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program.


Life Cycle of a Thread:

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.



Following are the stages of the life cycle −

  • New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

  • Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

  • Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

  • Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

  • Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.


5. What is difference between method overloading and method overriding.

ANS. There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:

No.

​Method Overloading

Method Overriding

1.

Method overloading is used to increase the readability of the program.

Method overriding is used to provide the specific implementation of the method that is already provided by its super class.

2.

Method overloading is performed within class.

Method overriding occurs in two classes that have IS-A (inheritance) relationship.

3.

In case of method overloading, parameter must be different.

In case of method overriding, parameter must be same.

4.

Method overloading is the example of compile time polymorphism.

Method overriding is the example of run time polymorphism.

5.

In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.

Return type must be same or covariant in method overriding.


Java Method Overloading example:

class OverloadingExample{

static int add(int a,int b){return a+b;}

static int add(int a,int b,int c){return a+b+c;}

}

Java Method Overriding example:

class Animal{

void eat(){System.out.println("eating...");}

}

class Dog extends Animal{

void eat(){System.out.println("eating bread...");}

}


6. Explain Inheritance with example.

ANS. Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.


Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

  • Why use inheritance in java:

For Method Overriding (so runtime polymorphism can be achieved).

For Code Reusability.


Terms used in Inheritance :

Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.

Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.

Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.

Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.


The syntax of Java Inheritance :

class Subclass-name extends Superclass-name

{

//methods and fields

}


The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.


Java Inheritance Example:



As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.


class Employee{

float salary=40000;

}

class Programmer extends Employee{

int bonus=10000;

public static void main(String args[]){

Programmer p=new Programmer();

System.out.println("Programmer salary is:"+p.salary);

System.out.println("Bonus of Programmer is:"+p.bonus);

}

}

OUTPUT:

Programmer salary is:40000.0

Bonus of programmer is:10000


7. What is constructor? Explain types of constructor with example.

ANS. In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

Types of Java constructors :

There are two types of constructors in Java:

Default constructor (no-arg constructor)


Java Default Constructor:

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.

//Java Program to create and call a default constructor

class Bike1{

//creating a default constructor

Bike1(){System.out.println("Bike is created");}

//main method

public static void main(String args[]){

//calling a default constructor

Bike1 b=new Bike1();

}

}

Output:

Bike is created


  • Java Parameterized Constructor :

A constructor which has a specific number of parameters is called a parameterized constructor.

  • Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also.

Example of parameterized constructor :

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.


//Java Program to demonstrate the use of the parameterized constructor.

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

}

//method to display the values

void display(){System.out.println(id+" "+name);}

public static void main(String args[]){

//creating objects and passing values

Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan");

//calling method to display the values of object

s1.display();

s2.display();

}

}

OUTPUT:

111 Karan

222 Aryan


8. What is package? Explain creating and importing package in brief.

ANS. In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains many pre-defined packages such as java.lang, java.io, java.net, etc. When we create any Java program the java.lang package is imported by default. We need not to write the package name at the top of the program. We can also create our own package by providing the name that we want. In this section, we will learn how to create a package in Java.


Creating a Package:

To create a package, follow the steps given below:

Choose a package name according to the naming convention.

Write the package name at the top of every source file (classes, interface, enumeration, and annotations).

Remember that there must be only one package statement in each source file.


Package Naming Convention :

We follow the naming convention rules to name a package. Java has some predefined packages and also allows us to create our own package. So, it is possible that a programmer can create a class with the same name as a package that already contains that type in a predefined package.

Let's take an example of the Rectangle class.

Suppose, a programmer creates a class with the name Rectangle in the package shape. The class with the same name is already present in java.awt package. The compiler allows both classes if they belong to the different packages. The fully qualified name of each class contains the package name that differentiate both Rectangle classes. Therefore, the package name of the user-defined class will be shape.Rectangle and the package name of the predefined class will be java.awt.Rectangle.


Importing a Package:

If we want to use a package in Java program it is necessary to import that package at the top of the program by using the import keyword before the package name.

Syntax:

import packageName;

Let's create a calculator program in Java using the package.

Add.java

package p1;

import java.util.*;

public class Add

{

int s;

public void sum()

{

System.out.print("Enter the first number: ");

Scanner scan=new Scanner(System.in);

int x=scan.nextInt();

System.out.print("Enter the second number: ");

Scanner scan1=new Scanner(System.in);

int y=scan1.nextInt();

s=x+y;

System.out.println("sum="+s);

}

}

Sub.java

package p2;

import java.util.*;

public class Sub

{

int d;

public void diff()

{

System.out.print("Enter the first number: ");

Scanner scan=new Scanner(System.in);

int x=scan.nextInt();

System.out.print("Enter the second number: ");

Scanner scan1=new Scanner(System.in);

int y=scan1.nextInt();

d=x-y;

System.out.println("Difference="+d);

}

}


9. What is Variable? Explain different types of variable.

ANS. A variable is a container which holds the value while the Java program is executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination of "vary + able" which means its value can be changed.


Types of Variables:

There are three types of variables in Java:

  • local variable

  • instance variable

  • static variable

1) Local Variable:

A variable declared inside the body of the method is called local variable. You can use this variable only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable:

A variable declared inside the class but outside the body of the method, is called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable:

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy of the static variable and share it among all the instances of the class. Memory allocation for static variables happens only once when the class is loaded in the memory.

Example to understand the types of variables in java:

public class A

{

static int m=100;//static variable

void method()

{

int n=90;//local variable

}

public static void main(String args[])

{

int data=50;//instance variable

}

}//end of class


10. Write a java program to implement multiple inheritance. Also explain the concept implemented.

ANS. When the child class extends from more than one superclass, it is known as multiple inheritance. However, Java does not support multiple inheritance.

To achieve multiple inheritance in Java, we must use the interface.


Example: Multiple Inheritance in Java :

interface Backend {

// abstract class

public void connectServer();

}

class Frontend {

public void responsive(String str) {

System.out.println(str + " can also be used as frontend.");

}

}

// Language extends Frontend class

// Language implements Backend interface

class Language extends Frontend implements Backend {

String language = "Java";

// implement method of interface

public void connectServer() {

System.out.println(language + " can be used as backend language.");

}

public static void main(String[] args) {

// create object of Language class

Language java = new Language()

java.connectServer()

// call the inherited method of Frontend class

java.responsive(java.language);

}

}

Output:

Java can be used as backend language.

Java can also be used as frontend.

Explanation:

Multiple Inheritance is the process in which a subclass inherits more than one superclass.

In the below image, we can observe that Class C(sub-class) inherits from more than one superclass i.e., Class A, Class B. This is the concept of Multiple Inheritance.

Many real-world examples of Multiple Inheritance also exist. For example, consider a newly born baby, inheriting eyes from mother, nose from father.

Kindly note that Java does not support Multiple Inheritance, but we can use Interfaces to achieve the same purpose.

Now we will be discussing an example to see what happens when we try to implement Multiple Inheritance in Java.

Syntax:

Class sub-class(name) extends super-class(name)

{

}

Parent Class, Base Class are different terminologies for representing Superclass while Child Class, Derived Class are different terminologies for representing Subclass.

In the program given below, we created two classes, i.e., class A and class B, along with the Main class.

Here, class A is the superclass, and class B is the subclass.

The subclass, class B extends Class A (superclass), thereby acquiring its methods also.

Programme:

class A

{

public void perform()

{

System.out.println("Hello.. from Super Class");

}

}

class B extends A { }

public class Main

{

public static void main(String[] args)

{

B obj = new B(); // creating object of class B

obj.perform(); // method gets inherited from class A

}

}

Output:

Hello.. from Super Class



UNIT 4

1. Differentiate Checked and Unlocked Exception.

ANS. What is a Checked Exception?

A checked exception is an exception that should be reported in the method in which it is thrown.

What is an Unchecked Exception?

An exception that occurs at the runtime or at the time of execution is known as an unchecked exception.


Differences between Checked and Unchecked Exceptions in Java

S. No. Checked Exception ➡️ Unchecked Exception

1. Checked exceptions happen at compile time when the source code is transformed into an executable code. ➡️ Unchecked exceptions happen at runtime when the executable program starts running.

2. The checked exception is checked by the compiler. ➡️ These types of exceptions are not checked by the compiler.

3. Checked exceptions can be created manually. ➡️ They can also be created manually.

4. This exception is counted as a sub-class of the class. ➡️ This exception happens in runtime, and hence it is not included in the exception class.

5. Java Virtual Machine requires the exception to to be caught or handled. ➡️ Java Virtual Machine does not need the exception to be caught or handled.


2. What is exception Handling? Explain Try, catch and finally block with example.

Ans. In the tutorial, we will learn about different approaches of exception handling in Java with the help of examples.

In the last tutorial, we learned about Java exceptions. We know that exceptions abnormally terminate the execution of a program.


This is why it is important to handle exceptions. Here's a list of different approaches to handle exceptions in Java.

  • try...catch block

  • finally block

  • throw and throws keyword

1. Java try...catch block :

Syntax:

try {

// code

}

catch(Exception e) {

// code

}

Example: Exception handling using try...catch :

class Main {

public static void main(String[] args) {

try {

// code that generate exception

int divideByZero = 5 / 0;

System.out.println("Rest of code in try block");

}

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

}

}

}

Output:

ArithmeticException => / by zero


2. Java finally block:

Syntax:

try {

//code

}

catch (ExceptionType1 e1) {

// catch block

}

finally {

// finally block always executes

}

Example: Java Exception Handling using finally block :

class Main {

public static void main(String[] args) {

try {

// code that generates exception

int divideByZero = 5 / 0;

}

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

}

finally {

System.out.println("This is the finally block");

}

}

}

Output :

ArithmeticException => / by zero

This is the finally block


3. What is exception? Explain throw and throws block with example.

ANS. Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

  • throw:

The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions.

Syntax:

throw Instance

Example:

throw new ArithmeticException("/ by zero");

The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked and so on. If no matching catch is found then the default exception handler will halt the program.


// Java program that demonstrates the use of throw

class ThrowExcep

{

static void fun()

{

try

{

throw new NullPointerException("demo");

}

catch(NullPointerException e)

{

System.out.println("Caught inside fun().");

throw e; // rethrowing the exception

}

}

public static void main(String args[])

{

try

{

fun();

}

catch(NullPointerException e)

{

System.out.println("Caught in main.");

}

}

}

Output:

Caught inside fun().

Caught in main.

  • throws:

throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.

Syntax:

type method_name(parameters) throws exception_list

exception_list is a comma separated list of all the

exceptions which a method might throw.


In a program, if there is a chance of raising an exception then compiler always warn us about it and compulsorily we should handle that checked exception, Otherwise we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways:

  • By using try catch

  • By using throws keyword

We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception.

// Java program to illustrate error in case

// of unhandled exception

class tst

{

public static void main(String[] args)

{

Thread.sleep(10000);

System.out.println("Hello Geeks");

}

}

Output:

error: unreported exception InterruptedException; must be caught or declared to be thrown

Explanation: In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute main() method which will cause InterruptedException.

// Java program to illustrate throws

class tst

{

public static void main(String[] args)throws InterruptedException

{

Thread.sleep(10000);

System.out.println("Hello Geeks");

}

}

Output:

Hello Geeks

Explanation: In the above program, by using throws keyword we handled the InterruptedException and we will get the output as Hello Geeks


4. Explain types of Errors. Give difference between error and exception.

Ans. The Java.lang.Errors provide varieties of errors that are thrown under the lang package of Java. Some of the errors are:

Error Name ➡️ Description

AbstractMethodError ➡️ When a Java application tries to invoke an abstract method.

Error ➡️ Indicating a serious but uncatchable error is thrown. This type of error is a subclass of Throwable.

AssertionError ➡️ To indicate that an assertion has failed.

ClassCircularityError ➡️ While initializing a class, a circularity is detected.

IllegalAccessError ➡️ A Java application attempts either to access or modify a field or maybe invoking a method to which it does not have access.

ClassFormatError ➡️ When JVM attempts to read a class file and find that the file is malformed or cannot be interpreted as a class file.

InstantiationError ➡️ In case an application is trying to use the Java new construct for instantiating an abstract class or an interface.

ExceptionInInitializerError ➡️ Signals that tell an unexpected exception have occurred in a static initializer.

InternalError ➡️ Indicating the occurrence of an unexpected internal error in the JVM.

IncompatibleClassChangeError ➡️ When an incompatible class change has occurred to some class of definition.

LinkageError ➡️ Its subclass indicates that a class has some dependency on another data.

NoSuchFieldError ➡️ In case an application tries to access or modify a specified field of an object, and after it, that object no longer has this field.

OutOfMemoryError ➡️ In case JVM cannot allocate an object as it is out of memory, such error is thrown that says no more memory could be made available by the GC.

NoClassDefFoundError ➡️ If a class loader instance or JVM, try to load in the class definition and not found any class definition of the class.

ThreadDeath ➡️ Its instance is thrown in the victim thread when in thread class, the stop method with zero arguments is invoked.

NoSuchMethodError ➡️ In case an application tries to call a specified method of a class that can be either static or instance, and that class no longer holds that method definition.

StackOverflowError ➡️ When a stack overflow occurs in an application because it has recursed too deeply.

UnsatisfiedLinkError ➡️ In case JVM is unable to find an appropriate native language for a native method definition.

VirtualMachineError ➡️ Indicate that the JVM is broken or has run out of resources, essential for continuing operating.

UnsupportedClassVersionError ➡️ When the JVM attempts to read a class file and get to know that the major & minor version numbers in the file are unsupportable.

UnknownError ➡️ In case a serious exception that is unknown has occurred in the JVM.

VerifyError ➡️ When it is found that a class file that is well-formed although contains some sort of internal inconsistency or security problem by the verifier.


There are the below points that differentiate between both terms:

Exception Error

Can be handled Cannot be handled.

Can be either checked type or unchecked type Errors are of unchecked type

Thrown at runtime only, but the checked exceptions known by the compiler and the unchecked are not. Occurs at the runtime of the code and is not known to the compiler.

They are defined in Java.lang.Exception package. They are defined in Java.lang.Error package

Program implementation mistakes cause exceptions. Errors are mainly caused because of the environment of the program where it is executing.


5. Explain user defined Exception with example.

ANS. User-defined exceptions are custom exceptions that a programmer can create in their code to handle specific error conditions or situations. These exceptions are derived from the base exception class and provide a way for the programmer to tailor the exception-handling process to their specific needs. User-defined exceptions are used to indicate errors that are specific to the particular application being developed and are often used to provide a higher level of abstraction and readability in the code.


For example, a programmer may create a custom exception for a bank account class that checks if a withdrawal would result in a negative balance. If a withdrawal would cause a negative balance, the custom exception is thrown and can be caught and handled by the code. This allows the programmer to provide more meaningful error messages and handling of specific error conditions in the code, rather than relying on generic exceptions.

Example:

class NegativeBalanceException extends Exception {

public NegativeBalanceException(String message) {

super(message);

}

}

class BankAccount {

private double balance;

public BankAccount(double balance) {

this.balance = balance;

}

public double getBalance(){

return balance;

}

public void withdraw(double amount) throws NegativeBalanceException {

if (balance - amount < 0) {

throw new NegativeBalanceException("Insufficient funds to withdraw " + amount + " dollars.");

} else {

balance -= amount;

}

}

}

class Main {

public static void main(String[] args) {

BankAccount ba = new BankAccount(100);

try {

ba.withdraw(200);

} catch (NegativeBalanceException ex) {

System.out.println(ex.getMessage());

}

System.out.println("Remaining balance: " + ba.getBalance());

} }

Output:

Insufficient funds to withdraw 200.0 dollars.

Remaining balance: 100.0


6. Give Advantages of Exception Handling.

ANS. Importance of Exception Handling:

Below refers to the points why exception handling is important. Let’s see one by one.

Ensures the Continuity of the Program:

One of the key benefits of exception handling is that it ensures the continuity of the program. Without proper exception handling, an unhandled exception would cause the program to terminate abruptly, which can lead to data loss & other issues. With proper exception handling, the program can continue to execute and provide a more stable user experience.

Enhances the Robustness of the Program:

Exception handling allows for the program to anticipate and recover from errors, thus making the program more robust and resistant to unexpected conditions. By catching and handling exceptions, the program can continue to execute and provide a more stable user experience.

Improves the Readability & Maintainability of the Code:

Proper exception handling also improves the readability & maintainability of the code. By catching and handling exceptions, the program can provide clear error messages that accurately describe the error and provide information on how to resolve the issue. This makes it easier for developers to understand and modify the code in the future. Additionally, by providing detailed error messages, proper exception handling allows for more accurate error reporting, which is essential for debugging and troubleshooting purposes.

Allows for more Accurate Error Reporting:

Exception handling allows the program to catch & report errors in a more accurate & detailed manner, providing valuable information to developers for debugging and troubleshooting purposes.

Facilitates Debugging and Troubleshooting:

Exception handling allows the program to catch & report errors in a more accurate and detailed manner, which facilitates debugging and troubleshooting. By providing detailed error messages and stack traces, exception handling allows developers to quickly identify and resolve issues, reducing the amount of time and resources required for debugging.

Improves the Security of the Program:

Exception handling can also improve the security of a program by preventing sensitive information from being exposed in the event of an error. By catching and handling exceptions, the program can prevent sensitive information, such as passwords and personal data, from being displayed to the user or logged-in error messages.

Provides a Better user Experience:

Proper exception handling allows the program to anticipate and recover from errors, providing a more stable user experience. It is particularly important for user-facing applications, as it ensures that the program continues to function even in the event of an error, reducing the likelihood of user frustration and abandonment.

Enables the use of error-recovery Mechanisms:

Exception handling enables the use of error-recovery mechanisms, such as retries or fallbacks, which can improve the reliability and availability of the program. For example, if a program encounters a network error, it can retry the operation or fall back to a different network connection, ensuring that the program continues to function even in the event of an error.

Improves the Scalability and Performance of the Program:

Proper exception handling can also improve the scalability and performance of a program by reducing the amount of unnecessary processing and resource consumption. By catching and handling exceptions, the program can avoid performing unnecessary operations and releasing resources that are no longer needed, reducing the overall load on the system and improving performance.


7. Write a program to handle Divide by Zero Exception using try-catch and finally.

ANS. class DivideByZeroExceptionHandling {

public static void main(String[] args) {

int a=10;

int b=0;

try{

int ans=divide(a,b);

System.out.println("ans: "+ans);

} catch (ArithmeticException e) {

System.out.println("Error: "+ e.getMessage());

} finally {

System.out.println("Finally block executed.");

} }

public static int divide(int a, int b)

return a/b;

} }

28 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating

Connect To Me 

  • YouTube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
  • Pinterest
bottom of page