KEMBAR78
Java Notes | PDF | Inheritance (Object Oriented Programming) | Class (Computer Programming)
0% found this document useful (0 votes)
23 views29 pages

Java Notes

Uploaded by

tabar21955
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)
23 views29 pages

Java Notes

Uploaded by

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

Department of Computer Applications

OOP through JAVA, IIBCom (CA)

SHORT QUESTIONS: 4 MARKS

1. Write about Displaying Output using System.Out.Println ()?


Java System.out.println() is used to print an argument that is passed to it.
Parts of System.out.println()
The statement can be broken into 3 parts which can be understood separately:
1. System: It is a final class defined in the java.lang package.
2. out: This is an instance of PrintStream type, which is a public and static member
field of the System class.
3. println(): As all instances of the PrintStream class have a public method
println(), we can invoke the same on out as well. This is an upgraded version of
print(). It prints any argument passed to it and adds a new line to the output. We
can assume that System.out represents the Standard Output Stream.

2. Write about Features of Object Oriented Program?


1) Classes
In Object-Oriented Programming, classes are fundamental building blocks, acting as
blueprints for creating Objects. A class defines the structure and behaviour that
Objects of that class will exhibit. It encapsulates data attributes and methods,
providing a modular and organised approach to software design.

2) Objects
Objects mirror tangible or conceptual entities, allowing developers to model and
manipulate complex systems easily.
3) Inheritance
Inheritance is a fundamental concept in OOPs where a new class (subclass or
derived class) inherits properties and behaviours from an existing class (superclass
or base class). This mechanism fosters code reusability, allowing the derived class to
leverage the attributes and methods of the base class.
4) Abstraction
Abstraction in OOPs involves simplifying complex systems by modelling classes
based on real-world entities. It focuses on essential features while concealing
unnecessary details, creating a clear and concise design.
.
5) Encapsulation
Encapsulation in OOP is a fundamental feature that involves bundling data
(attributes) and methods (functions) that operate on that data into a single unit—an
Object
6) Polymorphism
Polymorphism, a key feature of OOPs, allows Objects of different classes to be
treated as Objects of a standard base class.
6) Polymorphism
Polymorphism, a key feature of OOPs, allows Objects of different classes to be
treated as Objects of a standard base class.
8) Method overloading
Method overloading in OOPs allows a class to have multiple methods with the same
name but different parameters.
9) Constructors and destructors
Constructors and Destructors are integral features of OOPs that manage Object
lifecycle.

3. Explain the Naming Conventions in Java.

Identifiers Naming Rules Examples


Type

Class It should start with the public class Employee


uppercase letter. {
It should be a noun such as //code snippet
Color, Button, System, }
Thread, etc.
Use appropriate words,
instead of acronyms.

Interface It should start with the interface Printable


uppercase letter. {
It should be an adjective //code snippet
such as Runnable, Remote, }
ActionListener.
Use appropriate words,
instead of acronyms.

Method It should start with class Employee


lowercase letter. {
It should be a verb such as // method
main(), print(), println(). void draw()
If the name contains {
multiple words, start it with //code snippet
a lowercase letter followed }
by an uppercase letter such }
as actionPerformed().

Variable It should start with a class Employee


lowercase letter such as id, {
name. // variable
It should not start with the int id;
special characters like & //code snippet
(ampersand), $ (dollar), _ }
(underscore).
If the name contains
multiple words, start it with
the lowercase letter
followed by an uppercase
letter such as firstName,
lastName.
Avoid using one-character
variables such as x, y, z.

Package It should be a lowercase //package


letter such as java, lang. package com.javatpoint;
If the name contains class Employee
multiple words, it should be {
separated by dots (.) such as //code snippet
java.util, java.lang. }
Constant It should be in uppercase class Employee
letters such as RED, {
YELLOW. //constant
If the name contains static final
multiple words, it should be int MIN_AGE = 18;
separated by an //code snippet
underscore(_) such as }
MAX_PRIORITY.
It may contain digits but not
as the first letter.

4. Explain about Break Statement & Continue Statement.


Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was
used to "jump out" of a switch statement.The break statement can also be used to jump out of
a loop.This example jumps out of the for loop when i is equal to 4:

for (int i = 0; i< 10; i++) {


if (i == 4) {
break;
}
System.out.println(i);
}

Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.

This example skips the value of 4:


for (int i = 0; i< 10; i++) {
if (i == 4) {
continue;
}
System.out.println(i);
}
5. Write about String Class Methods?
String Methods in Java
1. int length()
Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i)
Returns the character at ith index.
"GeeksforGeeks".charAt(3); // returns ‘k’
3. String substring (int i)
Return the substring from the ith index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j)
Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
5. String concat( String str)
Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”
6. int indexOf (String s)
Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.
1. String s = ”Learn Share Learn”;
int output = s.indexOf(“Share”); // returns 6
2. String s = "Learn Share Learn"
int output = s.indexOf(“Play”); // return -1

6. Write about String Comparison?


Java String.compareTo() Method
The Java compareTo() method compares the given string with the current
string lexicographically. It returns a positive number, a negative number, or 0. It compares
strings based on the Unicode value of each character in the strings.

Variants of CompareTo() Method


There are three variants of the compareTo() method which are as follows:
1. using int compareTo(Object obj)
2. using int compareTo(String AnotherString)
3. using int compareToIgnoreCase(String str)
1. int compareTo(Object obj)
This method compares this String to another Object.
Syntax:
int compareTo(Object obj)
2. int compareTo(String anotherString)
This method compares two strings lexicographically.
Syntax:
int compareTo(String anotherString)

Parameters:
anotherString: the String to be compared.
3. int compareToIgnoreCase(String str)
This method compares two strings lexicographically, ignoring case differences.
Syntax:
int compareToIgnoreCase(String str)

Parameters:
str: the String to be compared.
7. Write about Object Creation Initializing the Instance Variables.
An object is a variable of the type class, it is a basic component of an object-
oriented programming system. A class has the methods and data members
(attributes), these methods and data members are accessed through an object. Thus,
an object is an instance of a class.
There are three steps when creating an object from a class −
• Declaration − A variable declaration with a variable name with an object type.
• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.
Syntax to Create a Java Object

Consider the below syntax to create an object of the class in Java:

Class_nameobject_name=newClass_name([parameters]);
Accessing Instance Variables and Methods
Instance variables and methods are accessed via created objects. To access an
instance variable, following is the fully qualified path −
/* First create an object */
ObjectReference = new Constructor();

/* Now call a variable as follows */


ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

8. How to Access Specifies in class & objects.


In Java, Access modifiers help to restrict the scope of a class, constructor,
variable, method, or data member. It provides security, accessibility, etc to the user
depending upon the access modifier used with the element. Let us learn about Java
Access Modifiers, their types, and the uses of access modifiers in this article.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
9. Explain about Constructors in Java with Example.
Java constructors or constructors in Java is a terminology used to construct something
in our programs. A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used to set initial
values for object attributes.
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 the constructor, memory for the object
is allocated in the memory. It is a special type of method that is used to initialize the object.
Every time an object is created using the new() keyword, at least one constructor is called.
Example of Java Constructor
Below is the implementation of Java Constructors:

// Java Program to demonstrate


// Constructor
importjava.io.*;

// Driver Class
classGeeks {

// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
}

// main function
publicstaticvoidmain(String[] args)
{
Geeks geek = newGeeks();
}
}

Output
Constructor Called
10.Write about creating package and accessing a package.
Java package is a mechanism of grouping similar type of classes, interfaces, and
sub-classes collectively based on functionality.
Creating a Package in Java
Creating a package in Java is a very easy task. Choose a name for the package and include
a package command as the first statement in the Java source file. The java source file can
contain the classes, interfaces, enumerations, and annotation types that you want to include in
the package. For example, the following

1packageMyPackage;
The package statement simply specifies to which package the classes defined belongs to.
packageMyPackage;
publicclassCompare {
intnum1, num2;
Compare(intn, intm) {
num1 = n;
num2 = m;
}

11.Write about creating a file using file Output Stream in java.


FileOutputStream class belongs to byte stream and stores the data in the form of
individual bytes.
1. Reading data: First of all, data should be read from the keyboard. For this
purpose, associate the keyboard to some input stream class. The code for using
DataInputSream class for reading data from the keyboard is as:
DataInputStream dis =new DataInputStream(System.in);
Here System.in represent the keyboard which is linked with DataInputStream
object
2. Send data to OutputStream: Now , associate a file where the data is to be
stored to some output stream. For this , take the help of FileOutputStream which
can send data to the file. Attaching the file.txt to FileOutputStream can be done
as:
FileOutputStreamfout=new FileOutputStream(“file.txt”);
3. Reading data from DataInputStream: The next step is to read data from
DataInputStream and write it into FileOutputStream . It means read data from
dis object and write it into fout object, as shown here:
4. ch=(char)dis.read();
fout.write(ch);
5. Close the file: Finally, any file should be closed after performing input or output
operations on it, else the data of the may be corrupted. Closing the file is done
by closing the associated streams. For example, fout.close(): will close the
FileOutputStream ,hence there is no way to write data into the file.

12. Write about Stream Classes in java.


Types of streams:
• Byte Stream: It provides a convenient means for handling input and output of byte.
• Character Stream: It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
1. Byte Stream:
Byte Stream Classes are used to read bytes from an input stream and write bytes to
an output stream.

• InputStream Classes - These classes are subclasses of an abstract class, InputStream


and they are used to read bytes from a source(file, memory or console).
• OutputStream Classes - These classes are subclasses of an abstract class,
OutputStream and they are used to write bytes to a destination(file, memory or
console).

13.Explain the Exception Handling Errors in Java Program.


In Java, errors and exceptions are both types of throwable objects, but they represent
different types of problems that can occur during the execution of a program.
Errors are usually caused by serious problems that are outside the control of the program,
such as running out of memory or a system crash. Errors are represented by the Error class
and its subclasses
14.Write about Thread Class Methods in java.

Thread is a line of execution within a program. Each program can have multiple
associated threads. Each thread has a priority which is used by the thread scheduler
to determine which thread must run first. Java provides a thread class that has
various method calls in order to manage the behavior of threads.

15. Explain the exception & Thrown Clause in java.

An exception in Java is an event that occurs during the execution of a program, that disrupts
the normal flow of the program's instructions. This can be caused by a variety of factors, such
as:
Input errors: If the user enters invalid data, the program may throw an exception.
System errors: If the program tries to access a file that doesn't exist, or if there is a problem
with the network connection, the program may throw an exception.
Programming errors: If the programmer makes a mistake in the code, the program may throw
an exception.
When an exception is thrown, the program stops executing the current code and jumps to a
special block of code called an exception handler. The exception handler is responsible for
dealing with the exception and getting the program back on track.
try {
// Code that may throw an exception
} catch (Exception e) {
// Code to handle the exception
}
The throw keyword in Java is used to throw an exception explicitly from a method or any
block of code. When an exception is thrown, the flow of program execution transfers from
the try block to the catch block. An exception can be either checked or unchecked.
Additionally, the throw keyword is majorly used to throw custom exceptions. We use the
throw keyword within a method.
Syntax
The syntax for using the throw keyword to throw exceptions is:
throw Instance

Here, the exception i.e, Instance must be of type Throwable or a subclass of Throwable. For
example:
throw throwableObject;
ESSAY QUESTIONS:
8 MARKS
1. Write about Data Types in Java with Example.
Data Types in Java
Data types in Java are divided into 2 categories:
1. Primitive Data Types
2. Non-Primitive Data Types

ExampleGet your own Java Server

intmyNum=5;// Integer (whole number)

floatmyFloatNum=5.99f;// Floating point number

charmyLetter='D';// Character

booleanmyBool=true;// Boolean

StringmyText="Hello";// String

Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:

• Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).
• Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types starts with
an uppercase letter.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc

2. Explain about Operators in Java with Example.

Java divides the operators into the following groups:

• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y


++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x

A list of all assignment operators:


Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3


Java Comparison Operators
Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make decisions.
Operator Name Example Try it

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


3. Write about Parts of Java Program.

class definition - Your java programs will always start with a class definition.
Begin with the word "class" followed by the name of the program. Use curly braces
to start and end the class definition. In the example shown here the name of the
program would be HelloWorld.

class HelloWorld {
....
} // end class HelloWorld

main method - In java there are many different kinds of classes. A class with a
main method is a program. The main method is where program execution starts and
stops. Even though the main method can ask other classes, objects, methods or parts
of the java language to help, the overall execution of your program begins and ends
in the main method. This is the general structure of a main method in java.

public static void main(String[] args) {


....
} // end main method

variables - A variable is a symbol or name that stands for a value. When we declare
a variable we ask the computer to set aside a place in memory where we can store a
particular piece of information. Whenever you use the name of a variable in your
code, the program refers to the value stored there.
int myVar;
myVar = 6;
System.out.println(myVar);

java statements - A statement represents an action to be carried out. Statements in


java are like sentences in english. We terminate statements in java using a
semicolon the same way that we end sentences in english using a period.

Some Types of Java Statements :

print statements : for outputting information to the screen or to an output file. Note
that we have not covered file output yet - you do not need to know this right now.
System.out.println("Goodnight");
System.out.print("Goodnight");
fileOut.println("Goodnight");
fileOut.print("Goodnight");

variable declarations : for creating variables (note that all variables except for
booleans are empty when when first created).
int myInteger;
float myFloat;
String myString;

assignment statements : for putting values into variables.


myInteger = 65 + 6;
myFloat = 4.0f;
myString = "Canada";

variable declarations with an assignment : for creating variables and assigning


them an initial value.
int myInteger = 65 + 6;
float myFloat = 4.0f;
String myString = "Canada";

4. Explain about the Control Structures in java with Example.


Types of Control Statements in Java
• Decision-Making Statements
• Looping Statements
• Jump Statements
Let’s understand these three types of Control Statements in detail!
1. Decision-Making Statements
Decision-making statements in Java are constructs used to control the flow of execution
based on certain conditions. They allow a program to execute different parts of code
depending on whether a condition (or set of conditions) is true or false. The decision-making
statements in Java are primarily of 3 types, namely: if, if-else and switch statements.
Let's discuss each one of them in detail.
1.1 'if' Statement in Java
The if statement in Java evaluates a boolean condition. If the condition is true, the block of
code inside the if statement is executed. It's the simplest form of decision-making in
programming, allowing for the execution of certain code based on a condition.
Syntax
if (condition) {
// Code to execute if the condition is true
}

1.2 'if-else' Statement in Java


The if-else statement in Java is used for multiple conditions. It comes after an if statement
and before an else statement. If the if condition is false, the program checks the if-
else condition. If the if-else condition is true, its code block is executed.
Syntax
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
1.3 'switch' Statement in Java
The switch statement in Java allows for the selection of a block of code to be executed
based on the value of a variable or expression. It is an alternative to a series of if statements
and is often more concise and easier to read.
Syntax
switch (expression) {
case value1:
// Code to be executed if expression equals value1
break;
case value2:
// Code to be executed if expression equals value2
break;
// ...
default:
// Code to be executed if expression does not match any case
2. Looping Statements
Looping statements in Java are used to execute a block of code repeatedly based on a given
condition or set of conditions. These statements are fundamental to Java programming,
allowing for iteration over data structures, repetitive tasks, and more. The main types of
looping statements in Java are for loop, while loop and do-while loop.
Let's discuss each one of them in detail.
2.1 'for loop' in Java
The for loop in Java is a control structure that allows repeated execution of a block of code
for a specific number of times. It is typically used when the number of iterations is known
beforehand.
Syntax
for (initialization; condition; update) {
// code block to be executed
}
Here,
• Initialization: Typically used to initialize a counter variable.
• Condition: The loop runs as long as this condition is true.
• Update: Updates the counter variable, usually incrementing or decrementing
2.2 'while loop' in Java
A while loop in Java repeatedly executes a block of code as long as a specified condition
remains true. It is ideal for situations where the number of iterations is not predetermined.
Syntax
while (condition) {
// code block to be executed
}
Here,
• Condition: The loop continues to run as long as this condition evaluates to true.
• Code Block: The statements inside the loop execute repeatedly until the condition
becomes false.
2.3 'do-while loop' in Java
The do-while loop in Java is a post-tested loop, meaning it executes the body of the loop at
least once before checking the condition. This loop is useful when you need to ensure that the
loop body is executed at least once, regardless of whether the condition is true or false. After
the body of the loop has executed, the condition is tested. If the condition is true, the loop
will execute again. This process repeats until the condition becomes false.
Syntax
do {
// Statements to execute
} while (condition);
Here,
• do: This keyword starts the do-while loop.
• Statements to execute: These are the actions you want to perform. This block of
code is executed on each iteration of the loop, and it is guaranteed to run at least
once.
• while: This keyword is followed by a condition in parentheses.
• condition: A Boolean expression that is evaluated after the loop body has
executed. If this condition evaluates to true, the loop will execute again. If it
evaluates to false, the loop will terminate, and control passes to the statement
immediately following the loop.

5. Explain about Arrays and Types of Arrays in Java with Example.

There are two types of arrays in Java they are −

Single dimensional array − A single dimensional array of Java is a normal array where, the
array contains sequential elements (of same type) –
The general form of a one-dimensional array declaration is
-- type var-name[];
-- type[] var-name;
int[] myArray = {10, 20, 30, 40}

Multi-dimensional array − A multi-dimensional array in Java is an array of arrays.


A two dimensional array is an array of one dimensional arrays and a three
dimensional array is an array of two dimensional arrays.
Syntax of Java Multidimensional Array
There are 2 methods to declare Java Multidimensional Arrays as mentioned below:
-- datatype [][] arrayrefvariable;
-- datatype arrayrefvariable[][];

6. What is String? Explain the Creating Strings in java with Example.

A string is an object that represents a sequence of char values. It's a class in


Java that uses the objects to create and implement strings
Ways of Creating a String
There are two ways to create a string in Java:
• String Literal
• Using new Keyword
Syntax:
<String_Type><string_variable> = "<sequence_of_string>";
1. String literal
To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).
Example:
String demoString = “GeeksforGeeks”;
2. Using new keyword
• String s = new String(“Welcome”);
• In such a case, JVM will create a new string object in normal (non-pool) heap
memory and the literal “Welcome” will be placed in the string constant pool.
The variable s will refer to the object in the heap (non-pool)
Example:
String demoString = new String (“GeeksforGeeks”);

Strings can be created by instantiating the String class. Following are a


few Constructors in Java in the String class used for string creation.
Constructors Description
String() Creates an empty string
It creates a string object with the contents from the character array
String(char[] arr)
passed.
String(char[] arr, int offset, It creates a string object with the contents as that of the
int num) subsequence of the array passed.
String(String obj) Creates a String object with contents of the String object passed.

7. Explain about Inheritance and Types of Inheritance in Java with Example.

Inheritance in Java is a fundamental Object-Oriented Programming (OOP) concept that


allows one class to inherit fields and methods from another class. Inheritance enables code
reuse and establishes a parent-child relationship between classes, where the parent class is
referred to as the superclass and the child class as the subclass.

The 5 types of inheritance related to Java are given below:


• Single-level inheritance
• Multi-level Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
• Hybrid Inheritance

REFER CLASS NOTES FOR EXAMPLES


8. Write about Method Overloading & Method operators in Java.

Method overloading is the process of overloading the method that has the same name but
different parameters. C++ provides this method of overloading features. Method overloading
allows users to use the same name to another method, but the parameters passed to the
methods should be different.

Example
add(int a, int b)
add(double a, double b)

Operator overloading is used to overload or redefines most of the operators available in


C++. It is used to perform the operation on the user-defined data type.
class className {
... .. ...
public
returnType operator symbol (arguments) {
... .. ...
}
... .. ...
};
return Type is the return type of the function.
operator is a keyword.
symbol is the operator we want to overload. Like: +, <, -, ++, etc.
arguments is the arguments passed to the function.

9. Write about Abstract Method & Abstract Class in Java.

Abstract Classes and Methods


Data abstraction is the process of hiding certain details and showing only essential
information to the user.
Abstraction can be achieved with either abstract classes or interfaces (which you will learn
more about in the next chapter).
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to access it, it must
be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a body. The
body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods:

abstract class Animal {

public abstract void animalSound();

public void sleep() {

System.out.println("Zzz");

From the example above, it is not possible to create an object of the Animal class:
Animal myObj = new Animal(); // will generate an error
Another way to achieve abstraction in Java, is with interfaces.
An interface is a completely "abstract class" that is used to group related methods with
empty bodies

// interface

interface Animal {

public void animalSound(); // interface method (does not have a body)

public void run(); // interface method (does not have a body)

10. What is Packages & Types of Packages in java?

A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code. Packages
are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
Syntax
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the java.util package. This package also contains date and time facilities, random-
number generator and other utility classes.
To import a whole package, end the sentence with an asterisk sign (*). The following
example will import ALL the classes in the java.util package:

import java.util.*;

User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to
store them. Just like folders on your computer:
Example
└── root
└── mypack
└── MyPackageClass.java

package mypack;

class MyPackageClass {

public static void main(String[] args) {

System.out.println("This is my package!");

11. How to reading Data from a file using files Input Stream in java.
The FileInputStream class reads the data from a specific file (byte by byte). It is usually
used to read the contents of a file with raw bytes, such as images.
To read the contents of a file using this class −
FileInputStream inputStream = new FileInputStream("file_path");
or,
File file = new File("file_path");
FileInputStream inputStream = new FileInputStream(file);
The read() method of InputStream class reads a byte of data from the input stream. The
next byte of data is returned, or -1 if the end of the file is reached and throws an exception
if an I/O error occurs. Refer to the program.
Step 1: Attach a file to a FileInputStream as this will enable us to read data from the file as
shown below as follows:
FileInputStream fileInputStream =new FileInputStream(“file.txt”);
Step 2: Now, to read data from the file, we should read data from the FileInputStream as
shown below:
ch=fileInputStream.read();
Step 3(a): When there is no more data available to read further, the read() method returns -
1;
Step 3(b): Then, we should attach the monitor to the output stream. For displaying the data,
we can use System.out.print.
System.out.print(ch);
Original File content: (“file.txt”)

12. Write about reading a file Using File reader in java.

The FileReader class extends the InputStreamReader class and is specifically


designed for reading character-based data from a file. It is an ideal choice when
working with text files and allows for efficient reading of characters from a file. To
use the FileReader class, you need to create an instance of it and provide the file
path as a parameter. This establishes a connection between the file reader object and
the specified file, enabling you to read characters from it.

1. Import the necessary classes: BufferedReader, FileReader, and IOException.


2. Define a class named FileReaderExample.
3. Inside the main method, we declare a String variable named filePath and assign it the
absolute path to the "example.txt" file on the system.
4. Use a try-with-resources statement to automatically close
the FileReader and BufferedReader instances when we're done using them.
5. Inside the try block, create a FileReader object, passing the filePath to its constructor.
6. Create a BufferedReader object, passing the FileReader object as its argument, which
allows us to read the file line by line efficiently.
7. Declare a String variable named line to store each line of the file.
8. Enter a loop that continues as long as the line is not null.
9. Inside the loop, read a line from the file using the readLine method of
the bufferedReader object.
10. If the line is not null, print it to the console using System.out.println().
11. If any exception occurs during file reading, catch it in the catch block and print an
error message.

The java.io.FileReader class in Java provides a convenient way to read character-


based data from a file. By creating a FileReader object and using its read() method,
you can read the contents of a file character by character. Remember to handle
potential exceptions by wrapping the code in a try-catch block and closing the file
reader object after reading the file.

13. What is Exception Handling? Explain the Types of Exception in java.

Exception Handling in Java is one of the effective means to handle runtime errors .
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
• Error: An Error indicates a serious problem that a reasonable application should not try
to catch.
• Exception: Exception indicates conditions that a reasonable application might try to
catch.

Exceptions can be categorized in two ways:


1. Built-in Exceptions
• Checked Exception
• Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions
are suitable to explain certain error situations.
• Checked Exceptions: Checked exceptions are called compile-time exceptions because
these exceptions are checked at compile-time by the compiler.

• Unchecked Exceptions: The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile time. In simple
words, if a program throws an unchecked exception, and even if we didn’t handle or
declare it, the program would not give a compilation error.
Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Methods to print the Exception information:
1. printStackTrace()
This method prints exception information in the format of the Name of the exception:
description of the exception, stack trace.

14. Explain about the Single Tasking &Multi tasking in java.

A single-tasking program, also known as a single-threaded program, is a type of


computer program that can execute only one task at a time. In a single-tasking
environment, the program sequentially performs each task or operation before moving on
to the next one. Once a task is initiated, the program must complete it or reach a pause
point before starting another task.

Single-tasking programs do not have the capability to execute multiple tasks concurrently
or in parallel. In a single-tasking program, the execution of one task must be completed or
suspended before the next task can begin. This limitation can sometimes result in slower
overall performance, especially in situations where tasks may take a long time to
complete or involve waiting for external resources or user input.
Multitasking: Multitasking is when a CPU is provided to execute multiple tasks at
a time. Multitasking involves often CPU switching between the tasks, so that users
can collaborate with each program together. Unlike multithreading, In
multitasking, the processes share separate memory and resources. As multitasking
involves CPU switching between the tasks rapidly, So the little time is needed in

order to switch from the one user to next.

15. How to creating a Thread and Running it in java.

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

1. Extending the Thread class:


This is the simplest way to create a thread. You can create a class that extends
the Thread class and override the run() method. The run() method contains the code that you
want to execute in the thread.
2. Implementing the Runnable interface:
This is a more flexible way to create a thread. You can create a class that implements
the Runnable interface. The Runnable interface contains a single
method, run(). The run() method contains the code that you want to execute in the thread.
Once you have created a thread, you can start it by calling
the start() method. The start() method will cause the thread to begin executing
the run() method.
Here is an example of how to create a thread by extending the Thread class:
public class MyThread extends Thread {
public void run() {
System.out.println("MyThread is running");
}
}

public class Main {


public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}

You might also like