0% found this document useful (0 votes)
43 views39 pages

Java Programming Concepts and Examples

Uploaded by

JETHALAL ROCKS
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)
43 views39 pages

Java Programming Concepts and Examples

Uploaded by

JETHALAL ROCKS
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

Java End-Sem Question Bank

1)What Is Java?

Ans:
Java is a widely used high-level, class-based, object-oriented programming language. It was
originally developed by Sun Microsystems (now a subsidiary of Oracle Corporation) in the
mid-1990s and has since become one of the most popular programming languages in use today.
Java is used for developing a wide range of applications, from mobile and web applications to
enterprise software solutions. Its popularity is due in part to its platform independence, which
means that Java applications can run on any computer or mobile device that has the Java Virtual
Machine (JVM) installed. Additionally, Java is known for its robustness, reliability, and security
features, making it a popular choice for developing mission-critical applications.

2)Demonstrate the features of Java With OOPS Concepts?

Ans:
Features Of Java:

1)Simple

2)Secure

3)Follow the OOPS Concepts

4)Robust Language

5)High Performance

6)Multi Threading'

7)Platform Independent

OOPS Concepts:

Java is a popular programming language that is widely used for developing various types of
applications, including desktop, web, and mobile applications. One of the key features of Java is
its support for Object-Oriented Programming (OOP) concepts, which allows developers to
design and implement complex applications easily.

1. Classes and Objects:


In Java, a class is a blueprint for creating objects, and an object is an instance of a class. The
class defines the characteristics and behavior of the object, while the object represents a
real-world entity or concept. An object contains both data and code.

2. Inheritance:

Inheritance is a mechanism that allows a new class to be based on an existing class. The new
class contains all the attributes and methods of the existing class and can also add its own
attributes and methods. This helps to reduce code duplication and makes code more
manageable.

3. Polymorphism:

Polymorphism is the ability of an object to take on multiple forms. In Java, polymorphism can be
achieved through method overloading and method overriding. Method overloading allows a
class to have multiple methods with the same name but with different arguments, while
method overriding allows a subclass to provide its own implementation of a method that is
already defined in its superclass.

4. Abstraction:

Abstraction is the process of hiding implementation details and showing only the necessary
information to the user. Abstraction can be achieved in Java through abstract classes and
interfaces. An abstract class contains one or more abstract methods that are not implemented
and can only be implemented by subclasses. An interface is a collection of abstract methods
that is used to define the behavior of an object.

5. Encapsulation:

Encapsulation is the process of wrapping data and methods into a single unit called a class. This
helps to protect the data from unauthorized access and modification. In Java, encapsulation can
be achieved through the use of access modifiers such as public, private, and protected.

3)Classify The Objects And Class Of Java?

Ans:
The objects and classes in Java can vary widely depending on the specific context, but in
general, a class in Java is a blueprint or template for creating objects that represent real-world
entities or abstract concepts. An object in Java is an instance of a class that has attributes (data)
and methods (functions) associated with it.

For example, in a simple program that creates and manipulates shapes, we might have a class
called `Shape` and subclasses like `Circle`, `Rectangle`, and `Triangle`, each with their own
methods for calculating area and perimeter. We could then create objects of each of these
classes to represent specific shapes in our program.

In a more complex program, you might have classes and objects that represent users, products,
orders, or anything else that the program needs to interact with.

So, to classify the objects and classes in Java, you would need to consider the specific context
and identify the classes that represent entities or concepts in that context, and the objects that
represent specific instances of those entities or concepts.

4)What Is the Uses Of Polymorphism And Abstraction?

Ans:
Polymorphism and abstraction are fundamental concepts in object-oriented programming,
including Java.

Polymorphism means the ability of an object to take on multiple forms. In Java, this is typically
achieved through inheritance and method overriding. For example, you can define a method in
a parent class, and override it with a different implementation in one or more of its child
classes. Then, you can call the method on either the parent or the child class object and get
different results. This can make your code more flexible and reusable.

Abstraction means the process of hiding complex details and showing only the essential
features to the user. In Java, this is typically achieved through abstract classes and interfaces. An
abstract class cannot be instantiated, but it can provide a partial implementation of a class so
that its child classes can inherit and customize its behavior. An interface, on the other hand,
defines a set of methods that a class must implement, but it does not provide any
implementation. This can make your code more modular and maintainable.

Overall, polymorphism and abstraction are powerful tools that can help you write efficient and
effective Java code. They can make your code more flexible, modular, and extensible.

5)State the diagram and Structure of Java Program?

Ans:
The structure of a Java program typically consists of several parts:

1. Documentation Section: This section contains comments about the program and its purpose.

2. Package Statement: This statement declares the package the program belongs to. It is an
optional statement and can be omitted if the program does not belong to a package.

3. Import Statements: These statements import other classes that the program will use.

4. Interface Section: This section defines the interfaces that the program implements. It is
optional and can be omitted if the program does not use interfaces.

5. Class Definition: This section defines the class or classes that form the core of the program.

6. Main Method: This method is the entry point of the program and is called when the program
is executed.

As for the diagram, it depends on what specifically is being referred to. There are several types
of diagrams used in Java programming, including class diagrams, sequence diagrams, and state
diagrams. Each diagram serves a different purpose in modeling and designing software.

6)What Is Array?Explain two Dimensional Array And


Multi-Dimensional Array With Example?

Ans:
An Array Is a Collection Of Similar Type Of Data.

Ex:- String[]array=new String[100];

Here,the above array cannot store more than 100 names.The number of Values in Java
array is always fixed.

Ex:- Age (0) (1) (2) (3) (4)

12 4 5 2 5

Array includes always Start From 0 that is the first element of an array is at index 0.

If the size of an array is n, then the last element of the array will be at index n-1.

Multidimensional Array:-

A multidimesional Array is an array of arrays.Each element of of multidimensional array


is an array it-self.
Ex:-

String[][]data=newString[3][4][2];

Two-Dimensional Array:-

Ex:-

class multidimensional array()

publicstaticvoidmain(string[]args){
int[]a={

{1,2,3}

{4,5,6}

{7}

s.o.p(length of row 1:"ta[0].length);

s.o.p(length of row 2:"ta[1].length);

s.o.p(length of row 3:"ta[2].length);

7)What Is Control Statement? Write Down Nested if,if-else-if, and


Switch Case With Example?
Ans:
A control statement is a statement in programming that determines the order in which code is
executed based on certain conditions. In Java, there are several types of control statements,
including:

1. if statement: The if statement executes a block of code if a given condition is true. Here is an
example:

```

int x = 10;

if(x > 5) {

System.out.println("x is greater than 5");

```

2. if-else statement: The if-else statement executes one block of code if a given condition is true,
and another block of code if the condition is false. Here is an example:

```

int x = 3;

if(x % 2 == 0) {

System.out.println("x is even");

} else {

System.out.println("x is odd");
}

```

3. nested if statement: A nested if is an if statement that is the target of another if statement.


Here is an example:

```

int x = 10, y = 5;

if(x > 5) {

if(y > 2) {

System.out.println("x is greater than 5 and y is greater than 2");

```

4. else-if statement: The else-if statement allows you to check for multiple conditions. Here is an
example:

```

int x = 10;

if(x > 5) {

System.out.println("x is greater than 5");

} else if(x < 5) {

System.out.println("x is less than 5");

} else {

System.out.println("x is equal to 5");

```

5. switch statement: The switch statement allows you to execute different blocks of code based
on the value of a variable. Here is an example:

```

int x = 2;
switch(x) {

case 1:

System.out.println("x is 1");

break;

case 2:

System.out.println("x is 2");

break;

default:

System.out.println("x is neither 1 nor 2");

```

In this example, because `x` is equal to 2, the second case will be executed and "x is 2" will be
printed to the console.

8)What Is Loop Statement? Write Down For Loop And While Loop
With Example?
Ans:
A loop statement is used in programming languages to repeatedly execute a block of code until
a specific condition is met. In Java, there are mainly two types of loop statements: the for loop
and the while loop.

The for loop has the following syntax:

```

for (initialization; condition; update) {

// code block to be executed

```

Here, the `initialization` statement is executed only once, at the beginning of the loop. The
`condition` statement is evaluated at the beginning of each iteration of the loop, and if it is true,
the code block inside the loop is executed. The `update` statement is executed at the end of
each iteration of the loop. The loop continues until the condition evaluates to false.

Here is an example of a for loop that prints the numbers from 1 to 5:


```

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

System.out.println(i);

```

The while loop has the following syntax:

```

while (condition) {

// code block to be executed

```

Here, the `condition` statement is evaluated at the beginning of each iteration of the loop, and
if it is true, the code block inside the loop is executed. The loop continues until the condition
evaluates to false.

Here is an example of a while loop that prints the numbers from 1 to 5:

```

int i = 1;

while (i <= 5) {

System.out.println(i);

i++;

```

In both these examples, the output would be:

```

3
4

```

9)Write Down Arrays,Fill(),Sort(),Equal(),Binary Search() Arrays With


Example?
Ans:
In Java, an array is a container object that holds a fixed number of values of a single data type.
Arrays can be created with a specified size and filled with initial values using the `fill()` method.
Here's an example of how to create an array and fill it with a single value:

```

int[] myArray = new int[5];

Arrays.fill(myArray, 1);

```

This creates an array of integers with a size of 5 and fills all elements with the value of 1.

To sort the elements of an array in ascending order, you can use the `sort()` method provided by
the `Arrays` class. Here's an example of how to sort an array of integers:

```

int[] myArray = {5, 3, 1, 4, 2};

Arrays.sort(myArray);

```

This would sort the elements of the `myArray` array in ascending order, resulting in the array
`{1, 2, 3, 4, 5}`.

To check if two arrays are equal, you can use the `equal()` method provided by the `Arrays`
class. Here's an example of how to check if two arrays of integers are equal:

```

int[] firstArray = {1, 2, 3};

int[] secondArray = {1, 2, 3};

boolean isEqual = Arrays.equals(firstArray, secondArray);

```
In this example, `isEqual` would be set to `true` because the `firstArray` and `secondArray` have
the same values in the same order.

To perform a binary search on a sorted array, you can use the `binarySearch()` method provided
by the `Arrays` class. Here's an example of how to perform a binary search on an array of
integers:

```

int[] myArray = {1, 2, 3, 4, 5};

int index = Arrays.binarySearch(myArray, 3);

```

In this example, `index` would be set to `2` because the value `3` is located at index `2` in the
`myArray` array. If the value is not found in the array, the method returns a negative number to
indicate that.

10)What Is String? Write Down Compare String,Combine


String,Reverse String,Uppercase String Example.
Ans:
In Java, a string is a sequence of characters. The String class in Java provides many methods to
work with strings. Here are some examples for comparing strings, combining strings, reversing
strings, and converting strings to uppercase:

1. Compare Strings: You can use the `equals()` method or the `compareTo()` method to compare
two strings. The `equals()` method checks if two strings have the same value, while
`compareTo()` method returns an integer value that indicates the lexicographical order of two
strings.

Example:

```

String str1 = "Hello";

String str2 = "World";

System.out.println(str1.equals(str2)); // false

System.out.println(str1.compareTo(str2)); // -15

```

2. Combine Strings: You can use the `concat()` method or the `+` operator to concatenate two
strings.
Example:

```

String str1 = "Hello";

String str2 = "World";

String str3 = str1.concat(str2);

String str4 = str1 + str2;

System.out.println(str3); // HelloWorld

System.out.println(str4); // HelloWorld

```

3. Reverse Strings: You can use the `StringBuilder` class or the `StringBuffer` class to reverse a
string.

Example:

```

String str = "Hello";

StringBuilder sb = new StringBuilder(str);

sb.reverse();

String reversedStr = sb.toString();

System.out.println(reversedStr); // olleH

```

4. Uppercase Strings: You can use the `toUpperCase()` method to convert a string to uppercase.

Example:

```

String str = "Hello";

String upperStr = str.toUpperCase();

System.out.println(upperStr); // HELLO

```
11) Draw Compilation and interpretation process of java

Ans:
You have to create your program and compile it before it can be executed.You can use any text editor or
IDE to create and edit a Java source-code file, source file is officially called a compilation unit. This
process is repetitive, as shown in below.

12)What is difference between method overloading and overriding in


Java?
Ans:

13)What is the difference between final method and ordinary method


of a class?
Ans:
Final Method
The final modifier for finalizing the implementations of classes, methods, and variables.

We can declare a method as final, once you declare a method final it cannot be overridden. So, you
cannot modify a final method from a sub class.

The main intention of making a method final would be that the content of the method should not be
changed by any outsider.

Ordinary Method

14)Explain the uses of keyword "super" and "extends" with code.


Ans:
Super Keyword:
The super keyword refers to superclass (parent) objects.

It is used to call superclass methods, and to access the superclass constructor.

The most common use of the super keyword is to eliminate the confusion between superclasses and
subclasses that have methods with the same name.

Example:
class Animal { // Superclass (parent)

public void animalSound() {

System.out.println("The animal makes a sound");

class Dog extends Animal { // Subclass (child)

public void animalSound() {

super.animalSound(); // Call the superclass method

System.out.println("The dog says: bow wow");

}
}

public class Main {

public static void main(String[] args) {

Animal myDog = new Dog(); // Create a Dog object

myDog.animalSound(); // Call the method on the Dog object

Extends Keyword:
The extends keyword extends a class (indicates that a class is inherited from another class).

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

Example:
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);

15)What is meant by interface?Explain with java code.


Ans:
It is used to achieve abstraction.

By interface, we can support the functionality of multiple inheritance.

It can be used to achieve loose coupling.

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default.

Example:
interface printable{

void print();

class A6 implements printable{

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

public static void main(String args[]){

A6 obj = new A6();

obj.print();

16)How method overriding will be achieved in java application?


Ans:
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.]

17)Explain the purpose of "Exception" Class.


Ans;
Exception Handling in Java is one of the effective means to handle the runtime errors so that the regular
flow of the application can be preserved. Java Exception Handling is a mechanism to handle runtime
errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at
run time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and
handled by the program. When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.

18)Explain Static Method in Class.


Ans:
In Java, a static method is a method that belongs to a class rather than an instance of a class. The
method is accessible to every instance of a class, but methods defined in an instance are only able to be
accessed by that object of a class.

A static method is not part of the objects it creates but is part of a class definition. Unlike instance
methods, a static method is referenced by the class name and can be invoked without creating an object
of class.

In simpler terms, they are methods that exist even if no object has been constructed yet and that do not
require an invocation object

19)Explain the uses of keyword "throw" and "finally".


Ans:
Throw:
Throw keyword is used to explicity throw on exception

We can throw either checked or unchecked exception using throw keyword

Throw keyword we can write exception manually by user

Finally:
A finally keyword is use to create a block of code that follows a try or catch block

A finally block of code always executes whether or not exception has occured

A finally block appear at the end of catch block


20)Define String Class With All it's Method.
Ans:
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.

21)What Is The Difference Between "Pass By Value" and "Pass By


Reference" in java?Expain With Proper Example.
Ans:
Pass By Value: The pass by value method copies the value of actual parameters. The called function
creates its own copy of argument values and then uses them. Since the work is done on a copy, the
original parameter does not see the changes.

Pass By Reference: The pass by reference method passes the parameters as a reference(address) of the
original variable. The called function does not create its own copy, rather, it refers to the original values
only. Hence, the changes made in the called function will be reflected in the original parameter as well.

Example:
public class Example {

/*

* The original value of 'a' will be changed as we are trying

* to pass the objects. Objects are passed by reference.

*/

int a = 10;

void call(Example eg) {

eg.a = eg.a+10;

public static void main(String[] args) {

Example eg = new Example();

System.out.println("Before call-by-reference: " + eg.a);


// passing the object as a value using pass-by-reference

eg.call(eg);

System.out.println("After call-by-reference: " + eg.a);

Output:
Before Call By Reference:10

After Call By Reference:20

22)Explain "Array of Refrence Type" Using java code.


Ans:
In Java, an array of reference type is an array of objects, where each element of the array is a
reference(pointer) to an object of a particular class. Here's an example of how to create and use an array
of reference type in Java:

public class MyClass {

public static void main(String[] args) {

// Create an array of String objects

String[] words = new String[3];

// Assign String objects to the array elements

words[0] = "Hello";

words[1] = "World";

words[2] = "!";

// Print the array elements

for (String word : words) {

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

}
In this example, we've created an array of String objects called words, and initialized it with 3 elements.
Each element of the array is a reference to a String object. We then assign String objects to each of the
elements of the array, and finally, print out the array elements using a for-each loop.

Note that when you create an array of reference type in Java, you are only creating an array of
references that point to objects of that type. You still need to create each object separately and assign its
reference to each element of the array.

23)Discuss Final Keyword used with variable,method and class.


Ans:
In Java, the final keyword is a non-access modifier that is used to restrict modification to a class, variable,
or method. Here's how it works with each of these entities:

Variable: When a variable is declared as final, its value cannot be modified after it has been assigned. In
other words, it becomes a constant throughout the program. For example:

final int x = 10;

Method: When a method is declared as final, it cannot be overridden in subclasses. This can be useful
when you want to ensure that a particular implementation of a method is used throughout your
program.

For example:

public final void doSomething() {

// implementation here

Class: When a class is declared as final, it cannot be subclassed. This means that the class cannot be
extended by other classes.

For example:

public final class MyClass {

// class implementation here

It's worth noting that using the final keyword can help make your code more robust and maintainable.
By preventing certain entities from being modified, you can reduce the risk of errors and unexpected
behavior in your program.

24)Describe default and parameterized constructer with example.


Ans:
A default constructor is a constructor that takes no arguments. It is automatically provided by the
compiler if no constructor is explicitly defined in the class. Default constructors initialize the object's
variables to default values. Here is an example of a class with a default constructor.

Ex:-

public class Person {

String name;

int age;

public Person() {

// Default constructor

name = "Unknown";

age = 0;

A parameterized constructor, on the other hand, is a constructor that takes one or more arguments. It is
used to initialize the object's variables with specific values passed as arguments. Here is an example of a
class with a parameterized constructor:

Ex:-

public class Person {

String name;

int age;

public Person(String name, int age) {

// Parameterized constructor

this.name = name;

this.age = age;

In this example, the constructor takes two parameters: name and age. The constructor assigns the
parameter values to the corresponding instance variables using the this keyword.

By using parameterized constructors, we can create objects with specific values for their instance
variables. For example, to create a Person object with the name "Alice" and age 25, we can do:

Person person = new Person("Alice", 25);


This creates a new Person object with the name "Alice" and age 25, initialized using the parameterized
constructor.

25)Discuss Accessibility of access modifiers in different condition.


Ans:
In Java, access modifiers control the accessibility or visibility of classes, interfaces, variables, methods,
constructors, and data members . There are four access modifiers in Java: public, protected, default or
package-private, and private.

The public access modifier makes members and methods accessible from any class in any package. This
means that public members are the most accessible access level.

The protected access modifier makes members and methods accessible from the same class, a subclass
in the same package, or a subclass in a different package. This access modifier means that only
subclasses and classes in the same package can access the members.

The default or package-private access modifier makes members and methods accessible only within the
same package. This access modifier means that a class, interface, or member is only visible and
accessible within the same package, and it is not available to other packages.

Finally, the private access modifier makes members and methods only accessible within the same class
or interface. This access modifier is the most restrictive accessibility level, as it restricts the accessibility
of the member to only the same class or interface.

The choice of access modifier depends on the design goals and objectives of the programmer. Generally,
fields and methods should be restricted to the lowest accessibility level required by their intended use,
to ensure greater encapsulation and maintainability. It is important to use access modifiers correctly to
avoid coupling between classes and to ensure that code is well organized and well-structured.

26)Explain this keyword and it's related concepts with example.


Ans:
In Java, the this keyword refers to the current instance of the class. It can be used to refer to instance
variables or methods of the current object, to avoid confusion with local variables that may have the
same name.

Here is an example of using this to refer to instance variables:

public class Rectangle {

private int length;

private int width;

public Rectangle(int length, int width) {

this.length = length; // using this to refer to instance variable


this.width = width; // using this to refer to instance variable

public int getArea() {

return this.length * this.width; // using this to refer to instance variables in a method

In the above example, this is used to refer to the length and width instance variables, to avoid ambiguity
with the local variables that have the same names.

Here is an example of using this to call a constructor:

public class Person {

private String name;

private int age;

public Person(String name) {

this(name, 0); // using this to call another constructor

public Person(String name, int age) {

this.name = name;

this.age = age;

In the above example, the first constructor calls the second constructor using this, passing a default
value for age.

Overall, this is a useful keyword in Java that allows you to refer to the current instance of a class and to
differentiate between instance variables and local variables that may have the same name.

27)Differential Checked And Unchecked Exceptions.


Ans:
In Java, exceptions can be either checked or unchecked. Checked exceptions are exceptions that must be
checked during compilation time, which means that the developer must handle them or declare them in
the method signature. Unchecked exceptions, on the other hand, are exceptions that do not need to be
handled or declared.

The difference between checked and unchecked exceptions is that checked exceptions are intended to
be used for exceptional conditions that can be reasonably anticipated and handled , whereas unchecked
exceptions are intended to be used for system-level errors that can't be easily handled in code.

For example, FileNotFoundException is a checked exception because it can be anticipated and handled in
code by the developer, while NullPointerException is an unchecked exception because it is usually the
result of a coding error and cannot be easily handled in code.

In Java, all exceptions that inherit from the RuntimeException class are unchecked exceptions, while
those that inherit from Exception but not from RuntimeException are checked exceptions.

It is important to choose the appropriate type of exceptions in your code to ensure that your code is
robust and handles errors appropriately.

28)Why java is platform independent language?How Java achieve this.


Ans:
Java is a platform-independent language because it uses bytecode. When you write Java code, it is first
compiled into a platform-independent bytecode format. This bytecode is then interpreted by the Java
Virtual Machine (JVM) at runtime, which translates it into machine code that can run on the specific
platform it is running on.

In other words, Java achieves platform independence through its bytecode format and the JVM, which is
responsible for executing that bytecode on different platforms. The bytecode does not directly run on
the underlying hardware, but rather on the JVM implementation on each platform.

This approach allows Java programs to be written once and run on any platform that has a JVM installed,
without the need to recompile the code for each platform. This feature has made Java a popular
language for developing applications that need to run on multiple platforms, such as web and mobile
applications.

29)What is Package? State the steps to create and import a package


with required java
Ans:
In Java, a package is a way to group related classes and sub-packages. It helps in organizing the classes
and prevents naming conflicts. Here are the steps to create and import a package in Java:

1. Creating a package:

- Choose the name of the package, which should follow the naming conventions for Java packages (i.e., it
should be in all lowercase letters).

- Create a new directory with the same name as the package in the file system.
- Include the package command as the first line of code in your Java source file, with the name of the
package.

For example, if you want to create a new package called "com.example.mypackage", you would create a
directory structure like this:

```

com

└── example

└── mypackage

└── MyClass.java

```

In the MyClass.java file, you would include the package command at the beginning:

```

package com.example.mypackage;

public class MyClass {

// class code here

```

2. Importing a package:

- Use the import keyword to import the package and its classes into your Java program.

- You can use either a specific class from the package or import the entire package using the * wildcard
character.

For example, if you want to use the MyClass class from the com.example.mypackage package:

```

import com.example.mypackage.MyClass;

public class MyOtherClass {

public static void main(String[] args) {

MyClass obj = new MyClass();

// use MyClass methods and variables here


}

```

If you want to import all classes from the com.example.mypackage package:

```

import com.example.mypackage.*;

public class MyOtherClass {

public static void main(String[] args) {

MyClass obj = new MyClass();

// use MyClass methods and variables here

```

This will import all classes from the com.example.mypackage package.

30)Define Custom exception. Differetiate between checked and


unchecked exception.
Ans:
In Java, custom exceptions can be defined by extending the `Exception` class for checked exceptions, or
the `RuntimeException` class for unchecked exceptions.

Checked exceptions are those that must be declared in the method signature using the `throws` keyword
or caught using a `try-catch` block, and are usually recoverable. Examples of checked exceptions include
`IOException`, `SQLException`, and `InterruptedException`.

On the other hand, unchecked exceptions are not required to be declared in the method signature or
caught using a `try-catch` block, and are usually caused by programming errors such as null pointer
exceptions or index out of bounds exceptions. Examples of unchecked exceptions include
`NullPointerException`, `IndexOutOfBoundsException`, and `IllegalArgumentException`.

The main difference between checked and unchecked exceptions is that checked exceptions are checked
by the compiler at compile-time, while unchecked exceptions are not checked by the compiler.
Additionally, checked exceptions must be declared or caught, while unchecked exceptions do not have
this requirement.

Custom exceptions can be useful in situations where none of the standard exceptions apply or when it is
necessary to provide more specific information about the exception. Custom exceptions can be either
checked or unchecked, depending on whether they extend the `Exception` or `RuntimeException` class.
To define a custom exception, create a new class that extends either `Exception` or `RuntimeException`
and define any necessary constructors and methods. The name of the custom exception class should end
with "Exception", following Java convention.

For example, to create a custom checked exception called `FileProcessingException`:

```

public class FileProcessingException extends Exception {

public FileProcessingException(String message) {

super(message);

```

And for a custom unchecked exception called `InvalidInputException`:

```

public class InvalidInputException extends RuntimeException {

public InvalidInputException(String message) {

super(message);

31)Assume that there are two packeges, student and exam. A student
package contains Student class and exam package contain result
class. Write a java program that generatesca marksheet for students
Ans:
package marksheet;

import student.Student;

import exam.Result;

public class MarksheetGenerator {

public static void main(String[] args) {

Student student = new Student("John Doe", 12345);


Result result = new Result(85, 90, 80);

double average = result.getAverage();

String grade = result.getGrade();

System.out.println("Name: " + student.getName());

System.out.println("Roll Number: " + student.getRollNumber());

System.out.println("Marks Obtained:");

System.out.println("Subject 1: " + result.getSubject1Marks());

System.out.println("Subject 2: " + result.getSubject2Marks());

System.out.println("Subject 3: " + result.getSubject3Marks());

System.out.println("Average: " + average);

System.out.println("Grade: " + grade);

32)Write a java program to implement multiple inheritance.Also


explain the concept implemented.
Ans:
Java does not support multiple inheritance using classes , but it does support multiple inheritance with
interfaces. Here is an example program to implement multiple inheritance using interfaces.

interface A {

void foo();

interface B {

void bar();

class C implements A, B {

public void foo() {


System.out.println("Inside foo method of interface A");

public void bar() {

System.out.println("Inside bar method of interface B");

public class Main {

public static void main(String[] args) {

C obj = new C();

obj.foo();

obj.bar();

Concept implemented:

Java implements several Object-Oriented Programming (OOP) concepts such as abstraction,


encapsulation, inheritance, and polymorphism.

Abstraction is the process of hiding implementation details while showing only the necessary features of
an object. In Java, abstraction can be achieved using abstract classes and interfaces.

Encapsulation is the practice of bundling data and methods that operate on that data within one unit,
such as a class. In Java, encapsulation is achieved using access modifiers to restrict access to the data and
methods of a class.

Inheritance is the process of creating new objects by reusing existing objects. In Java, inheritance is
accomplished by creating a new class that inherits the properties and methods of an existing class.

Polymorphism is the ability of an object to take on many forms. In Java, polymorphism can be achieved
through method overloading and method overriding.

These concepts are fundamental to understanding and developing robust and efficient applications in
Java.

33)Explain custom Exception. Create custom exception named


NoBalanceException and throw NobalanceException with a message
enters debit amount which make balance of account less than 500
Ans:
Custom exceptions are used to customize the exception according to user needs. In Java, we
can create our own exception class by extending the Exception class or any of its subclasses.

class NoBalanceException extends Exception {


public NoBalanceException(String message) {
super(message);
}
}
class Account {
int balance = 1000;
void debit(int amount) throws NoBalanceException {
if(balance - amount < 500) {
throw new NoBalanceException("Debit amount exceeds balance!");
}
balance -= amount;
System.out.println("Debited " + amount + " from account. Remaining balance is " + balance);
}
}
public class Main {
public static void main(String args[]) {
Account acc = new Account();
try {
acc.debit(700);
acc.debit(800);
} catch (NoBalanceException e) {
System.out.println(e.getMessage());
}
}
}

34)Describe abstract class. Create abstract class called Shape which


has three subclasses Triangle, Rectangle, and Circle. Define one
method area () in the abstract class and override this method in these
three subclasses to calculate for specific object and print the result.
Ans:
An abstract class in Java is one that is declared with the abstract keyword.
It may have both abstract and non-abstract methods (methods with bodies).
An abstract class is a java modifier applicable for classes and methods in java but not for Variables.

abstract class Shape {


abstract void area();
}
class Triangle extends Shape {
int base = 10;
int height = 20;
void area() {
double area = 0.5 * base * height;
System.out.println("Area of triangle is " + area);
}
}
class Rectangle extends Shape {
int length = 10;
int width = 20;
void area() {
int area = length * width;
System.out.println("Area of rectangle is " + area);
}
}
class Circle extends Shape {
int radius = 10;
void area() {
double area = Math.PI * radius * radius;
System.out.println("Area of circle is " + area);
}
}
public class Main {
public static void main(String args[]) {
Shape s;
s = new Triangle();
s.area();
s = new Rectangle();
s.area();
s = new Circle();
s.area();
}
}

35)Write a java program to create a class “Matrix” that would contain


integer values having varied Numbers of columns for each row. Print
row-wise sum of the integer values for each row

Ans:
import java.util.Scanner;

public class Matrix {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of rows:");
int rows = sc.nextInt();
int[][] arr = new int[rows][];
for (int i = 0; i < rows; i++) {
System.out.println("Enter number of columns for row " + (i + 1) + ":");
int cols = sc.nextInt();
arr[i] = new int[cols];
System.out.println("Enter elements for row " + (i + 1) + ":");
for (int j = 0; j < cols; j++) {
arr[i][j] = sc.nextInt();
}
}
System.out.println("Row-wise sum:");
for (int i = 0; i < rows; i++) {
int sum = 0;
for (int j = 0; j < arr[i].length; j++) {
sum += arr[i][j];
}
System.out.println(sum);
}
}
}
36)Create a class “Vehicle” with instance variable vehicle_type. Inherit
the class in a class called “Car” with instance model_type, company
name etc. display the information of the vehicle by defining the
display() in both super and sub class.

Ans:

class Vehicle {
String vehicle_type;
public void display() {
System.out.println("Vehicle Type is = " + vehicle_type);
}
}

class Car extends Vehicle {


String model_type;
String company_name;
public void display() {
super.display();
System.out.println("Model Type is = " + model_type);
System.out.println("Company Name is = " + company_name);
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car();
car.vehicle_type = "Four Wheeler";
car.model_type = "Sedan";
car.company_name = "Toyota";
car.display();
}
}
37)Write a program to create two threads, one thread will print odd
numbers and second thread will print even numbers between 1 to 100
numbers.

Ans:

class OddThread extends Thread {


public void run() {
for (int i = 1; i <= 100; i += 2) {
System.out.println("Odd Thread: " + i);
}
}
}

class EvenThread extends Thread {


public void run() {
for (int i = 2; i <= 100; i += 2) {
System.out.println("Even Thread: " + i);
}
}
}

public class Main {


public static void main(String[] args) {
OddThread oddThread = new OddThread();
EvenThread evenThread = new EvenThread();
oddThread.start();
evenThread.start();
}
}

38)What is multithreading? Why it is required? Explain thread Life


Cycle.

Ans:

 Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU.
 Each part of such program is called a thread. So, threads are light-weight processes within a
process.
 Threads can be created by using two mechanisms:
 Extending the Thread class
 Implementing the Runnable Interface
 If we extend the Thread class, our class cannot extend any other class because Java doesn’t
support multiple inheritance.
 But, if we implement the Runnable interface, our class can still extend other base classes.
 Multithreading is required because it allows us to write more efficient programs that can take
advantage of multiple CPUs or cores.

 It also allows us to write programs that can perform multiple tasks simultaneously.

 The life cycle of a thread in Java consists of five different states:

New
Runnable
Running
Blocked/Waiting
Terminated

 When a new thread is created, it is in the New state3. When the thread starts running, it moves
to the Runnable state.
 In this state, the thread is ready to run but it may not get CPU time immediately.
 When the thread gets CPU time, it moves to the Running state.
 In this state, the thread is actually executing its task.
 If a running thread is blocked or waiting for some resource, it moves to the Blocked/Waiting
state.
Finally, when a thread completes its task or is terminated by some other means, it moves to the
terminated state.

39)Draw and explain life cycle of Thread. Also list and explain
various methods of thread

Ans:

 The life cycle of a thread in Java consists of five different states:


New
Runnable
Running
Blocked/Waiting
Terminated
 When an instance of a thread is created and is executed by calling start() method of Thread class,
the thread goes into runnable state.
 In this state, the thread is ready to run but it may not get CPU time immediately.
 When the thread gets CPU time, it moves to the Running state.
 In this state, the thread is actually executing its task.
 If a running thread is blocked or waiting for some resource, it moves to the Blocked/Waiting
state.
 Finally, when a thread completes its task or is terminated by some other means, it moves to the
Terminated state.
 Here’s a diagram that shows the different states involved in the life cycle of a thread in Java :
New -> Runnable -> Running -> Blocked/Waiting -> Terminated
 There are several methods that can be used with threads in Java:
start(): starts the execution of a thread by calling its run() method.
run(): contains the code that will be executed when a thread starts running.
sleep(): causes the currently executing thread to sleep for a specified number of milliseconds.
join(): waits for a thread to die.
yield(): causes the currently executing thread to yield execution to another thread that has equal
priority.

40)Explain Abstract Class and Interface with example. Compare


Both.

Ans:

 An abstract class in Java is a class that is declared with the abstract keyword.
 It can have both abstract and non-abstract methods.
 An abstract method is a method that has no implementation.
 Abstract classes cannot be instantiated.
 Instead, they are meant to be extended by other classes that provide an implementation for
their abstract methods.

 An interface in Java is a collection of abstract methods.

 It can also contain constants, default methods, and static methods.

 An interface cannot be instantiated.

 Instead, it is meant to be implemented by classes that provide an implementation for its


methods.

Here’s an example of an abstract class in Java

abstract class Animal {


public void eat() {
System.out.println("I can eat.");
}
public abstract void makeSound();
}

Here’s an example of an interface in Java:

interface Animal {
public void eat();
public void makeSound();
}

The main difference between an abstract class and an interface is that an abstract class can have
both abstract and non-abstract methods while an interface can only have abstract methods. Another
difference is that a class can extend only one abstract class while it can implement multiple interface.
41)What Is An Applet?
Ans:
In Java, an applet is a type of Java program that can be embedded in a web page. It runs
inside a web browser and can perform various interactive operations with the user. Applets
are designed to be small and portable, and they can be used to provide dynamic and
interactive content on a web page. Compared to other types of Java applications, applets
have some restrictions in terms of what they can do, such as not being able to access the
local file system directly, but they can easily communicate with a server-side application to
overcome these restrictions. Applets are typically written in Java but other programming
languages that can compile to Java bytecode can also be used.

42)Explain The Life-Cycle Of an Applet?


Ans:
The life cycle of an applet in Java refers to the different stages involved in the creation,
initialization, execution, and destruction of an applet. The applet life cycle is handled by the
Applet Container, which is responsible for executing and managing the applet's behavior.
The different stages of an applet's life cycle are as follows:

1. Initialization: In this stage, the applet is created and initialized by the JVM. The init()
method is called only once during the applet's life cycle.

2. Starting: In this stage, the applet enters the running state and the start() method is called.
Once the start() method is called, the applet is visible on the user's screen and begins to
execute.

3. Painting: In this stage, the applet is redrawn on the screen if necessary using the paint()
method. The paint() method is called whenever the applet needs to be redrawn on the
screen, such as when a GUI component changes or the user interacts with the applet.

4. Stopping: In this stage, the applet enters the stopped state and the stop() method is
called. This happens when the user navigates away from the applet or the browser window
is minimized.

5. Destroying: In this stage, the applet is destroyed and the destroy() method is called. This
happens when the user closes the browser window or navigates away from the page
containing the applet.

Understanding the life cycle of an applet is important because it helps developers know
exactly when each method is called and what it does, which allows them to create more
efficient and robust applets.

43)What Happens When Applet Is Loaded?


Ans:
When an applet is loaded in Java, it goes through several stages before it can be fully
functional. First, the browser sends a request to the server for the applet's code and
resources. Once downloaded, the browser creates a new JVM process to run the applet. The
JVM then loads and executes the applet's code, creating and initializing its objects and
executing its methods. During this process, the applet may display GUI components and
interact with the user. Once the applet is fully loaded and initialized, it is ready to be used by
the user.

It is important to note that applets are being phased out of modern web browsers due to
security concerns and compatibility issues. It is recommended to use other technologies,
such as HTML5 and JavaScript, instead of applets.

44)What Is Difference Between An Applet and A Java Application?


Ans:
45)What Are the restriction imposed on Java Applets?
Ans:
The restrictions imposed on Java applets include:

1. An applet cannot load libraries or define native methods.


2. An applet cannot ordinarily read or write files on the execution host.
3. Applets can use only their own Java code and the Java API the applet viewer provides.

These restrictions are put in place for security purposes and to prevent untrusted applets
from accessing sensitive data or performing potentially harmful actions on the user's
system. However, privileged applets do not have some of these restrictions, and can run
outside the security sandbox.

46)What Are Untrusted Applets?


Ans:
Untrusted applets in Java refer to applets that are not signed, meaning they have not been
verified as safe by a recognized certification authority. These applets are subject to several
restrictions, such as being unable to access the local filesystem, connect to third-party
servers, spawn new processes, and define classes in certain packages. Additionally,
untrusted applets cannot access some system properties, use multicast sockets, manipulate
security identities or properties, list, look up, insert, or remove security providers, and much
more. These restrictions are in place to prevent untrusted applets from performing
potentially harmful actions on the user's system.

You might also like