Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 314

Introduction of Java:

JAVA was developed by James Gosling at Sun Microsystems Inc in the year
1995, later acquired by Oracle Corporation. It is a simple programming language.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs. Java is a class-based, object-oriented
programming language.

Features of Java:

The primary objective of Java programming language creation was to make it


portable, simple and secure programming language.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

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 behaviour.

object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

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.

Example:

Windows, Unix. Linux….

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.
Portable:

Java is portable because it facilitates you to carry the Java bytecode to any
platform.
It doesn't require any implementation. Java programs can be easily moved
from one system to another system, anywhere and anytime.
We can change and upgrade system processor and system resources
without any changes in java.

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 designed as a distributed language for creating applications on


network.
It has ability to sharw both data and programs. Java applications can open
and access from remote objects easily and can do in local systems.
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:

Multithread means it can handle multiple tasks simultaneously,


java support the multithreaded programs, no need to wait until the previous
task is completed or not
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++.

Introduction:

The Java Development Kit (JDK) is software used for Java programming, along
with the Java Virtual Machine (JVM) and the Java Runtime Environment
(JRE). The JDK includes the compiler and class libraries, allowing developers
to create Java programs executable by the JVM and JRE.

Check if Java Is Installed:

Before installing the Java Development Kit, check if a Java version is already
installed on Windows. Follow the steps below:

1. Open a command prompt by typing cmd in the search bar and


press Enter.
2. Run the following command:
Download Java for Windows 10

Download the latest Java Development Kit installation file for Windows 10 to
have the latest features and bug fixes.

1. Using your preferred web browser, navigate to the Oracle Java


Downloads page.
2. On the Downloads page, click the x64 Installer download link under
the Windows category. At the time of writing this article, Java version 17
is the latest long-term support Java version.

Install Java on Windows 10

After downloading the installation file, proceed with installing Java on your
Windows system.

Follow the steps below:

Step 1: Run the Downloaded File

Double-click the downloaded file to start the installation.

Step 2: Configure the Installation Wizard

After running the installation file, the installation wizard welcome screen
appears.

1. Click Next to proceed to the next step.


How to set the Temporary Path of JDK in Windows

To set the temporary path of JDK, you need to follow the following steps:

o Open the command prompt


o Copy the path of the JDK/bin directory
o Write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin
Compile: javac filename.java

Ex: javac SampleOne.java

Run: java filename

Ex: java SampleOne


Java Architecture:

Java Architecture is a collection of components, i.e., JVM,


JRE, and JDK. It integrates the process of interpretation and
compilation. It defines all the processes involved in creating a Java
program. Java Architecture explains each and every step of how a
program is compiled and executed.

Java Architecture can be explained by using the following steps:

There is a process of compilation and interpretation in Java.


Java compiler converts the Java code into byte code.
After that, the JVM converts the byte code into machine code.
The machine code is then executed by the machine.
Components of Java Architecture:

The Java architecture includes the three main components:

Java Virtual Machine (JVM)


Java Runtime Environment (JRE)
Java Development Kit (JDK)

Java Virtual Machine: (JVM)

The main feature of Java is WORA.


WORA stands for Write Once Run Anywhere.
The feature states that we can write our code once and use it
anywhere or on any operating system.
Our Java program can run any of the platforms only because of
the Java Virtual Machine.
It is a Java platform component that gives us an environment to
execute java programs.
JVM's main task is to convert byte code into machine code.
JVM, first of all, loads the code into memory and verifies it.
After that, it executes the code and provides a runtime
environment.
Java Virtual Machine (JVM) has its own architecture, which is
given below:
JVM Architecture:

JVM is an abstract machine that provides the environment in which


Java bytecode is executed. The falling figure represents the architecture
of the JVM.

ClassLoader:

ClassLoader is a subsystem used to load class files. Class Loader first


loads the Java code whenever we run it.

Class Method Area:


In the memory, there is an area where the class data is stored during the
code's execution. Class method area holds the information of static
variables, static methods, static blocks, and instance methods.
Heap:

The heap area is a part of the JVM memory and is created when the
JVM starts up. Its size cannot be static because it increases or decrease
during the application runs.

Stack:

It is also referred to as thread stack. It is created for a single execution


thread. The thread uses this area to store the elements like the partial
result, local variable, data used for calling method and returns etc.

Native Stack:

It contains the information of all the native methods used in our


application.

Execution Engine:

It is the central part of the JVM. Its main task is to execute the byte
code and execute the Java classes. The execution engine has three main
components used for executing Java classes.

Interpreter:

It converts the byte code into native code and


executes. It sequentially executes the code. The interpreter
interprets continuously and even the same method multiple times.
This reduces the performance of the system, and to solve this, the
JIT compiler is introduced.

JIT Compiler:

JIT compiler is introduced to remove the drawback


of the interpreter. It increases the speed of execution and
improves performance.
Garbage Collector:

The garbage collector is used to manage the memory, and it is a


program written in Java. It works in two phases,
i.e., Mark and Sweep. Mark is an area where the garbage
collector identifies the used and unused chunks of memory. The
Sweep removes the identified object from the Mark

Java Native Interface:

Java Native Interface works as a mediator between Java method


calls and native libraries.

Java Runtime Environment:(JRE)

It provides an environment in which Java programs are


executed. JRE takes our Java code, integrates it with the required
libraries, and then starts the JVM to execute it. To learn more about the
Java Runtime Environment.

What is a Java runtime environment (JRE)

A Java runtime environment (JRE) is a set of components to create


and run a Java application. A JRE is part of a Java development kit
(JDK).

A JRE is made up of a Java virtual machine (JVM), Java class


libraries, and the Java class loader. JDKs are used to develop Java
software; JREs provide programming tools and deployment
technologies; and JVMs execute Java programs.
1.Class Loader:
At this step, the class loader loads various classes which are essential for
running the program. The class loader dynamically loads the classes in the Java
Virtual Machine.
When the JVM is started, three class loaders are used:

1. Bootstrap class loader


2. Extensions class loader
3. System class loader

2.Byte code verifier:


Byte code verifier can be considered as a gatekeeper. It verifies the bytecode so
that the code doesn't make any sort of disturbance for the interpreter. The code
is allowed to be interpreted only when it passes the tests of the Bytecode verifier
which checks the format and checks for illegal code.

3.Interpreter:
Once the classes get loaded and the code gets verified, then interpreter reads the
assembly code line by line and does the following two functions:

Execute the Byte Code


Make appropriate calls to the underlying hardware
Java Development Kit:

Java development Kit is a bundle of software development tools


and supporting libraries and combination of JRE and JVM.
It is a software development environment used in the
development of Java applications and applets.
Java Development Kit holds JRE, a compiler, an interpreter or
loader, and several development tools in it.

The Java Development Kit is an implementation of one of the Java Platform:


Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform

JDK contains:

Java Runtime Environment (JRE),


An interpreter/loader (Java),
A compiler (javac),
An archiver (jar) and many more. (java Archive it is file format Ex:Zip)
JDK:

The Java Development Kit (JDK) is a software development environment


which is used to develop java applications and applets.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022).
Popular JDKs:
Oracle JDK: the most popular JDK and the main distributor of Java11,
OpenJDK: Ready for use: JDK 15, JDK 14, and JMC,
Azul Systems Zing: efficient and low latency JDK for Linux os,
Azul Systems: based Zulu brand for Linux, Windows, Mac OS X,
IBM J9 JDK: for AIX, Linux, Windows, and many other OS,
Amazon Corretto: the newest option with the no-cost build of
OpenJDK and long-term support.

Java Garbage Collector:

Garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory


automatically. In other words, it is a way to destroy the unused objects.

Java manage the Memory Automatically.


The Garbage feature not available in C,C++
Garbage collector is a part of the JVM.
Garbage collector automatically destroy the object if it is no longer used.
JVM contains two types of memories Stack and Heap.
Stack memory is a faster than Heap memory.
Heap memory is a dynamic
Object variables are created in Heap memory

Ex: int a=10;

When object is unreferenced then the JVM send into garbage collector to
destroy the object.

we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection:
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.

finalize() method:

The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing.

Syntax:

protected void finalize()

……………….

……………….

gc() method:

The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.

Syntax:

public static void gc()

………………

………………

}
Example:

class TestGarbage1
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
Lexical Tokens/ Lexical Issues in java
A lexical token may consist of one or more characters, and every single character
is in exactly one token.

The tokens can be keywords, comments, numbers, white space, or strings. All
lines should be terminated by a semi-colon (;).

Verilog HDL is a case-sensitive language.


And all keywords are in lowercase.

White Space

White space can contain the characters for tabs, blanks, newlines, and form feeds.
These characters are ignored except when they serve to separate other tokens.
However, blanks and tabs are significant in strings.

Comments

There are two types to represent the comments, such as:

1. Single line comments begin with the token // and end with a carriage return.
For example, //this is the single-line syntax.
2. Multi-Line comments begin with the token /* and end with the token */
For example, /* this is multiline syntax*/

Numbers:

We can specify constant numbers in binary, decimal, hexadecimal, or octal


format. Negative numbers are represented in 2's complement form. The question
mark (?) character is the Verilog alternative for the z character when used in a
number. The underscore character (_) is legal anywhere in a number, but it is
ignored as the first character.

Integer Number
Real Numbers
Signed and Unsigned Numbers
Negative Numbers
Identifiers:
The identifier is the name used to define the object, such as a function, module,
or register. Identifiers should begin with alphabetical characters or underscore
characters.

For example, A_Z and a_z.

Identifiers are a combination of alphabetic, numeric, underscore, and $


characters. They can be up to 1024 characters long.

Identifiers must begin with an alphabetic character or the underscore


character (a-z A-Z_).
Identifiers may contain alphabetic characters, numeric characters, the
underscore, and the dollar sign (a-z A-Z 0-9 _ $).
Identifiers can be up to 1024 characters long.

Escaped Identifiers:
Verilog HDL allows any character to be used in an identifier by escaping the
identifier.

Escaped identifiers are including any of the printable ASCII characters in an


identifier.

The decimal values 33 through 126, or 21 through 7E in hexadecimal.

Escaped identifiers begin with the backslash (\). The backslash escapes the
entire identifier.

The escaped identifier is terminated by white space characters such as


commas, parentheses, and semicolons become part of the escaped
identifier unless preceded by white space.
Terminate escaped identifiers with white space. Otherwise, characters that
should follow the identifier are considered part of it.
Operators:

Operators are special characters used to put conditions or to operate the variables.
There are one, two, and sometimes three characters used to perform operations
on variables.

1. Arithmetic Operators:

These operators perform arithmetic operations. The + and -are used as either
unary (x) or binary (z-y) operators.

The operators included in arithmetic operation are addition, subtraction,


multiplication, division, and modulus.

2. Relational Operators:

These operators compare two operands and return the result in a single bit, 1 or
0. The Operators included in relational operation are:

== (equal to)
!= (not equal to)
(greater than)
>= (greater than or equal to)
< (less than)
<= (less than or equal to)

3. Bit-wise Operators:

Bit-wise operators do a bit-by-bit comparison between two operands. The


Operators included in Bit-wise operation are:

& (Bit-wise AND)


| (Bit-wiseOR)
~ (Bit-wise NOT)
^ (Bit-wise XOR)
~^ or ^~(Bit-wise XNOR)
4. Logical Operators:

Logical operators are bit-wise operators and are used only for single-bit operands.
They return a single bit value, 0 or 1. They can work on integers or groups of bits,
expressions and treat all non-zero values as 1.

Logical operators are generally used in conditional statements since they work
with expressions. The operators included in Logical operation are:

! (logical NOT)
&& (logical AND)
|| (logical OR)

5. Reduction Operators:

Reduction operators are the unary form of the bitwise operators and operate on
all the bits of an operand vector. These also return a single-bit value. The
operators included in Reduction operation are:

& (reduction AND)


| (reduction OR)
~& (reduction NAND)
~| (reduction NOR)
^ (reduction XOR)
~^ or ^~(reduction XNOR)

6. Shift Operators:

Shift operators are shifting the first operand by the number of bits specified by
the second operand in the syntax.

Vacant positions are filled with zeros for both directions, left and right shifts
(There is no use sign extension). The Operators included in Shift operation are:

<< (shift left)


>> (shift right)
7. Concatenation Operator:

The concatenation operator combines two or more operands to form a larger


vector. The operator included in Concatenation operation is:

{ }(concatenation)

8. Replication Operator:

The replication operator is making multiple copies of an item. The operator used
in Replication operation is:

{n{item}} (n fold replication of an item)

9. Conditional Operator:

Conditional operator synthesizes to a multiplexer. It is the same kind as is used


in C/C++ and evaluates one of the two expressions based on the condition. The
operator used in Conditional operation is:

(Condition) ?

Operands:

Operands are expressions or values on which an operator operates or works. All


expressions have at least one operand.

1. Literals

Literals are constant-valued operands that are used in Verilog expressions. The
two commonly used Verilog literals are:

String: A literal string operand is a one-dimensional array of characters


enclosed in double quotes (" ").
Numeric: A constant number of the operand is specified in binary, octal,
decimal, or hexadecimal number.

2. Wires, Regs, and Parameters:

Wires, regs, and parameters are the data types used as operands in Verilog
expressions. Bit-Selection "x[2]" and Part-Selection "x[4:2]"

Bit-selects and part-selects are used to select one bit and multiple bits,
respectively, from a wire, regs or parameter vector using square brackets "[ ]".
3. Function Calls:

In the Function calls, the return value of a function is used directly in an


expression without first assigning it to a register or wire.

It just places the function call as one of the types of operands. It is useful to know
the bit width of the return value of the function call.
Keywords
Qns:
What is a keyword and explain different types of keywords in
java
Keywords or Reserved words are the words in a language that are used for
some internal process or represent some predefined actions. These words are
therefore not allowed to use as variable names or objects.

1. abstract:

Java abstract keyword is used to declare an abstract class. An abstract class


can provide the implementation of the interface. It can have abstract and
non-abstract methods.

2. boolean:

Java boolean keyword is used to declare a variable as a boolean type. It can


hold True and False values only.
3. break:

Java break keyword is used to break the loop or switch statement. It breaks
the current flow of the program at specified conditions.

4. byte:

Java byte keyword is used to declare a variable that can hold 8-bit data
values.

5. case:

Java case keyword is used with the switch statements to mark blocks of
text.

6. catch:

Java catch keyword is used to catch the exceptions generated by try


statements. It must be used after the try block only.

7. char:

Java char keyword is used to declare a variable that can hold unsigned 16-
bit Unicode characters

8. class:

Java class keyword is used to declare a class.

9. continue:

Java continue keyword is used to continue the loop. It continues the current
flow of the program and skips the remaining code at the specified
condition.

10. default:

Java default keyword is used to specify the default block of code in a switch
statement.
11. do:

Java do keyword is used in the control statement to declare a loop. It can


iterate a part of the program several times.

12. double:

Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.

13. else:

Java else keyword is used to indicate the alternative branches in an if


statement.

14. enum:

Java enum keyword is used to define a fixed set of constants. Enum


constructors are always private or default.

15. extends:

Java extends keyword is used to indicate that a class is derived from


another class or interface.

16. final:

Java final keyword is used to indicate that a variable holds a constant value.
It is used with a variable. It is used to restrict the user from updating the
value of the variable.

17. finally:

Java finally keyword indicates a block of code in a try-catch structure. This


block is always executed whether an exception is handled or not.

18. float:

Java float keyword is used to declare a variable that can hold a 32-bit
floating-point number.
19. for:

Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the
number of iteration is fixed, it is recommended to use for loop.

20. if:

Java if keyword tests the condition. It executes the if block if the condition
is true.

21. implements:

Java implements keyword is used to implement an interface.

22. import:

Java import keyword makes classes and interfaces available and accessible
to the current source code.

23. instanceof:

Java instanceof keyword is used to test whether the object is an instance of


the specified class or implements an interface.

24. int:

Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.

25. interface:

Java interface keyword is used to declare an interface. It can have only


abstract methods.

26. long:

Java long keyword is used to declare a variable that can hold a 64-bit
integer.
27. native:

Java native keyword is used to specify that a method is implemented in


native code using JNI (Java Native Interface).

28. new:

Java new keyword is used to create new objects.

29. null:

Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.

30. package:

Java package keyword is used to declare a Java package that includes the
classes.

31. private:

Java private keyword is an access modifier. It is used to indicate that a


method or variable may be accessed only in the class in which it is declared.

32. protected:

Java protected keyword is an access modifier. It can be accessible within


the package and outside the package but through inheritance only. It can't
be applied with the class.

33. public:

Java public keyword is an access modifier. It is used to indicate that an


item is accessible anywhere. It has the widest scope among all other
modifiers.

34. return:

Java return keyword is used to return from a method when its execution is
complete.
35. short:

Java short keyword is used to declare a variable that can hold a 16-bit
integer.

36. static:

Java static keyword is used to indicate that a variable or method is a class


method. The static keyword in Java is mainly used for memory
management.

37. strictfp:

Java strictfp is used to restrict the floating-point calculations to ensure


portability.

38. super:

Java super keyword is a reference variable that is used to refer to parent


class objects. It can be used to invoke the immediate parent class method.

39. switch:

The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable
against multiple values.

40. synchronized:

Java synchronized keyword is used to specify the critical sections or


methods in multithreaded code.

41. this:

Java this keyword can be used to refer the current object in a method or
constructor.
42. throw:

The Java throw keyword is used to explicitly throw an exception. The


throw keyword is mainly used to throw custom exceptions. It is followed
by an instance.

43. throws:

The Java throws keyword is used to declare an exception. Checked


exceptions can be propagated with throws.

44. transient:

Java transient keyword is used in serialization. If you define any data


member as transient, it will not be serialized.

45. try:

Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.

46. void:

Java void keyword is used to specify that a method does not have a return
value.

47. volatile:

Java volatile keyword is used to indicate that a variable may change


asynchronously.

48. while:

Java while keyword is used to start a while loop. This loop iterates a part
of the program several times. If the number of iterations is not fixed, it is
recommended to use the while loop.
Sample program in Java:

In this section, we will learn how to write the simple program of Java. We can
write a simple hello Java program easily.

class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}

Save the above file as Simple.java.

To compile: javac Simple.java


To execute: java Simple

Output:
Hello Java

class keyword is used to declare a class in Java.


public keyword is an access modifier that represents visibility. It means it
is visible to all.
static is a keyword. If we declare any method as static, it is known as the
static method. The core advantage of the static method is that there is no
need to create an object to invoke the static method. The main() method is
executed by the JVM, so it doesn't require creating an object to invoke the
main() method. So, it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args or String args[] is used for command line argument
System.out.println() is used to print statement. Here, System is a class,
out is an object of the PrintStream class, println() is a method of the
PrintStream class. We will discuss the internal working
of System.out.println()
Data Types:
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

1. Primitive data types: The primitive data types include Boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Primitive Data Types:

Primitive data types are the building blocks of data


manipulation. These are the most basic data types available in Java language.

1. boolean data type


2. byte data type
3. char data type
4. short data type
5. int data type
6. long data type

1
7. float data type
8. double data type

Data Type Default Value Default size

boolean True/ false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

Int 0 4 byte

float 0.0f 4 byte

double 0.0d 8 byte

Long double Lf 16 byte

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.

Example:

Boolean one = false

Byte Data Type:


The byte data type is an example of primitive data type. It is an
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.

2
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.

Example:

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.

Example:

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.

Example:

int a = 100000, int b = -200000

Long Data Type:


The long data type is a 64-bit two's complement integer. Its
value-range lies between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1) (inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807.

Its default value is 0. The long data type is used when you need a range of
values more than those provided by int.

3
Example:

long a = 100000L, long b = -200000L

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.

Example:

float f1 = 234.5f

Double Data Type:


The double data type is a double-precision 64-bit 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.

Example:

double d1 = 12.3

Char Data Type:


The char data type is a single 16-bit Unicode character. Its
value-range lies between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char
data type is used to store characters.

Example:

char letter = 'A'

4
Variables:
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.

Variables

Local Instance Static


Variables Variables Variables

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.

5
public class LocalVariable
{
public static void main(String[] args)
{
int x=100;
int y=200;
int z=x+y;
System.out.println(z);
}
}

Output:

z=300

Note:

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

2) Instance Variable:

Instance variables are non-static variables. 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.

Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will be
used.
 Initialization of an instance variable is not mandatory. Its default
value is 0.
 Instance variables can be accessed only by creating objects.

6
class InstanceVariable
{
int count=0; //will get memory each time when the instance is created
InstanceVariable()
{
count++; //incrementing value
System.out.println(count);
}
public static void main(String args[])
{
InstanceVariable c1=new InstanceVariable(); //Creating objects1
InstanceVariable c2=new InstanceVariable(); //Creating objects2
InstanceVariable c3=new InstanceVariable(); //Creating objects3
}
}

Output:
1
1
1

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

class StaticVariable
{
static int count=10; //will get memory only once and retain its value
StaticVariable()
{
count++; //incrementing the value of static variable
System.out.println(count);
}
public static void main(String args[])
{
StaticVariable c1=new StaticVariable (); //creating objects1
StaticVariable c2=new StaticVariable (); //creating objects2
StaticVariable c3=new StaticVariable (); //creating objects3

}
}

Output:
11
12
13

8
variable naming conventions
Variables are tokens within the command statements that are to be replaced with
actual values immediately before the statement is run.
The standard naming conventions used in modern software development are as
follows:

Pascal case
camel case
snake case
kebab case
Pascal case:
Popularized by the Turbo Pascal programming language, Pascal case requires
the first letter of a variable be uppercase, along with the first letter of every new
word compounded together to create the variable.

Examples of Pascal case:

 ThisIsPascalCase
 AnotherPascalCaseExample
Camel case:
Camel case follows the same rules as Pascal case but drops the requirement to
capitalize the first letter. To differentiate between cases where the first letter is
or is not capitalized, software developers often use the terms "upper camel case"
and "lower camel case."

Upper camel case looks the same as Pascal case. Lower camel case is also
known as "dromedary case," as a dromedary camel has one less hump than the
two-humped Bactrian camel.

9
The following are examples of camel case:

 thisIsDromedaryCamelCase
 ThisIsUpperCamelCase
Snake and kebab case:
For those who appreciate more whitespace between concatenated words, there
is snake case and kebab case. Snake case separates words with underscores; it's
also called pothole case. When every letter is capitalized, it is known as
screaming snake case:

 this_is_snake_case
 THIS_IS_SCREAMING_SNAKE_CASE

Kebab case:

Kebab case follows the same rules as snake case, just with a dash instead of an
underscore. When all capital letters are used, it's known as a scream kebab.

 this-is-kebab-case
 THIS-IS-A-SCREAM-KEBAB

One of the problems with kebab case is that the dash can be confused with a
minus sign, which can create difficult-to-troubleshoot bugs in code.

10
Scope of Variables in Java:
In programming, scope of variable defines how a specific variable is accessible
within the program or across classes.

Scope of a Variable:

In programming, a variable can be declared and defined inside a class,


method, or block.
It defines the scope of the variable i.e. the visibility or accessibility of a
variable.

Variable declared inside a block or method are not visible to outside. If we


try to do so, we will get a compilation error.
We can declare variables anywhere in the program but it has limited scope.
A variable can be a parameter of a method or constructor.
A variable can be defined and declared inside the body of a method and
constructor.
It can also be defined inside blocks and loops.
Variable declared inside main() function cannot be accessed outside the
main() function

there are two types of variables based on their scope:

1. Member Variables (Class Level Scope)


2. Local Variables (Method Level Scope)

Member Variables (Class Level Scope)

These are the variables that are declared inside the class but outside any function
have class-level scope. We can access these variables anywhere inside the class.
Note that the access specifier of a member variable does not affect the scope
within the class.

11
Access Modifier Package Subclass Word

public Yes Yes Yes

protected Yes Yes No

private No No No

default Yes No No

Syntax:

public class DemoClass


{
//variables declared inside the class have class level scope
int age;
private String name;
void displayName()
{
//statements
}
int dispalyAge()
{
//statements
}
char c;
}

12
Example: 1

public class VariableScopeExample1


{
public static void main(String args[])
{
int x=10;
{
//y has limited scope to this block only
int y=20;
System.out.println("Sum of x+y = " + (x+y));
}
//here y is unknown
y=100;
//x is still known
x=50;
}
}

Output:
y=100;
^
symbol: variable y
location: class VariableScopeExample1
1 error

Note:
We see that y=100 is unknown. If you want to compile and run the above
program remove or comment the statement y=100. After removing the
statement, the above program runs successfully and shows the following
output.

13
Example Program:2 Instance Variable

public class Product


{
//variable visible to any child class
public String pName;
//variable visible to product class only
private double pPrice;
//creating a constructor and parsed product name as a parameter
public Product (String pname)
{
pName = pname;
}
//function sets the product price
public void setPrice(double pprice)
{
pPrice= pprice;
}
//method prints all product info
public void getInfo()
{
System.out.println("Product Name: " +pName );
System.out.println("Product Price: " +pPrice);
}
public static void main(String args[])
{
Product pro = new Product("Java Book");
pro.setPrice(6000);
pro.getInfo();
}
}

Output:
Product Name: Java Book
Product Price: 6000.0

14
Method Level Scope: (Local Variables)
These are the variables that are declared inside a method, constructor,
or block have a method-level or block-level scope and cannot be accessed
outside in which it is defined. Variables declared inside a pair of curly
braces {} have block-level scope.

Declaring a Variable Inside a Method

Example:
public class DemoClass1
{
void show()
{
//variable declared inside a method has method level scope
int x=100;
System.out.println("The value of x is: "+x);
}
public static void main(String args[])
{
DemoClass1 dc = new DemoClass1();
dc.show();
}
}

Output:
Value of x is: 100

15
Variable Inside Constructor:

public class VariableInsideConstructor


{
//creating a default constructor
VariableInsideConstructor()
{
int Salary=25000;
System.out.println("Salary is: "+ Salary);
}
//main() method
public static void main(String args[])
{
//calling a default constructor
VariableInsideConstructor VIC=new VariableInsideConstructor();
}
}

Output:
Salary is: 25000

16
Example:3

Variable Inside Block

public class VariableInsideBlock


{
public static void main(String args[])
{
int x=400;
{
//y has limited scope to this block only
int y=500;
System.out.println("Sum of x+y = " + (x+y));
y=10;
//gives error, already defined
int y=200;
}
//creates a new variable
int y;
}
}
Output:

int y=200;

1 error

Note:
We see that y=100 is unknown. If you want to compile and run the above
program remove or comment the statement y=100. After removing the
statement, the above program runs successfully and shows the following output.

17
Final Keyword In Java:
The final keyword in java is used to restrict the
user. The final keyword can be applied with the variables, a final variable that
have no value it is called blank final variable or uninitialized final variable.
The final keyword is used to denote the constants. The final keyword is usually
used with methods, classes, and variables. Whenever we define any variable or
class or method as final then the particular entity cannot be changed after has
been assigned.
1. Final Variable
2. Final Method
3. Final Class

There are two uses of a final class:

Usage 1:
One is definitely to prevent inheritance, as final classes cannot be
extended. For example, all Wrapper Classes like Integer, Float, etc. are final
classes. We can not extend them.

Usage 2:

The other use of final with classes is to create an immutable class like
the predefined String class. One cannot make a class immutable without making
it final.

18
Final variable:

If you make any variable as final, you cannot change the value of final variable
(It will be constant).

When a variable is declared with the final keyword, its value can’t be
modified, essentially, a constant.
This also means that you must initialize a final variable.
If the final variable is a reference, this means that the variable cannot be
re-bound to reference another object,
but the internal state of the object pointed by that reference variable can
be changed i.e. you can add or remove elements from the final array or
final collection.

Example:

class Bike9
{
final int speedlimit=90;//final variable
pvoid run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}
Output:

Compile time error

Here is a final variable speedlimit, we are going to change the value of this
variable, but It can't be changed because final variable once assigned a value
can never be changed.
19
final method:
The final method in java is the method that cannot be changed
or overridden once defined. Hence, we cannot modify a final method from
the subclass.

When a method is declared with final keyword, it is called a final method


in java. We cannot override the final method in java.
If we try to override the final method in java, we get a compilation error
because if we are declaring any method with the final keyword, we are
indicating the JVM to provide some special attention and make sure no
one can override it.
The methods that are required to follow the same implementation
throughout all the derived classes must be declared as a final method.
We define final method in java to restrict the unwanted and improper use
of method definition by the child class(es) while overriding the final
method.

class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("Running Safely Below 90kmph");
}
public static void main(String args[])
{
Honda Enfield= new Honda();
Enfield.run();

20
}
}
Output:
Compile time error

final class
If you make any class as final, you cannot extend it. A class declared with
the final keyword is known as the final class.
A final class can’t be inherited by subclasses.
By use of the final class, we can restrict the inheritance of the class.
We can create a class as a final class only if it is complete in nature,
which means it must not be an abstract class.
In java, all the wrapper classes are final classes like String, Integer, etc.
If we try to inherit a final class, then the compiler throws an error at
compilation time.
We can’t create a class as immutable without the final class.

Example Program:
final class Bike{}
class Honda1 extends Bike
{
void run()
{
System.out.println("Running Safely With @ 90kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile time error

21
Note:
Delete the final key word for getting output.
Output:
Running Safely With @ 90kmph

Example: 2 instance final Variable


class Tester
{
final int A = 10;
final int B=20;
final int C;
Tester()
{
C = 30;
}
public static void main(String[] args)
{
Tester tester1 = new Tester();
System.out.println("A = " + tester1.A + ", B = " + tester1.B + ", C = " + tester1.C);
}
}

Output:

A = 10, B = 20, C = 30

22
Operators in Java:
Java support the set operators, operator is an symbol that tells the computer
to perform certain mathematical and logical manipulations is used to perform
operations. For example: +, -, *, / etc.

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

Unary Operator (increment and Decrement)


Arithmetic Operator
Shift Operator,
Relational Operator
Bitwise Operator,
Logical Operator
Ternary Operator
Assignment Operator

Unary Operator:

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

incrementing/decrementing a value by one


negating an expression
inverting the value of a boolean

class OperatorExample
{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}

23
Output:
10
12
12
10

Example: 2
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);
//11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}
}
Output:
-11
9
false
true

24
Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction,


multiplication, and division. They act as basic mathematical operations.

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Output:
15
5
50
2
0
import java.io.*;
class Addition
{
public static void main(String[] args)
{
int num1 = 10, num2 = 20, sum = 0;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
sum = num1 + num2;
System.out.println("The sum = " + sum);
}
}
Output:
num1 = 10 num2 = 20
The sum = 30

25
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.

class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
Output:
40
80
80
240
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.

public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
Output:
2
5
2

26
Logical Operators:
These operators are used to perform “logical AND” and
“logical OR” operations, i.e., a function similar to AND gate and OR gate in
digital electronics. One thing to keep in mind is the second condition is not
evaluated if the first one is false, i.e., it has a short-circuiting effect. Used
extensively to test for several conditions for making a decision. Java also has
“Logical NOT”, which returns true when the condition is false and vice-versa
Conditional operators are:

&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa

AND Operator Example: Logical && vs Bitwise &

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}

Output:

false10

false

11

27
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.

class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}

Output:

truetrue

true

10

true

11

28
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.

class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
Output:
2

Assignment Operator:

Assignment operator is used to assigning a value to any variable. It has a right


to left associativity, i.e. value given on the right-hand side of the operator is
assigned to the variable on the left, and therefore right-hand side value must be
declared before using it or should be a constant. 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.

class OperatorExample
{
public static void main(String args[])
{
int x=100;
int y=200;
x+=50;
y-=50;
System.out.println(x);
System.out.println(y);
}

29
}
Output:
14
16

Relational Operators:
These operators are used to check for relations like
equality, greater than, and less than. They return boolean results after the
comparison and are extensively used in looping statements as well as
conditional if-else statements.

==, Equal to returns true if the left-hand side is equal to the right-hand
side.
!=, Not Equal to returns true if the left-hand side is not equal to the
right-hand side.
<, less than: returns true if the left-hand side is less than the right-hand
side.
<=, less than or equal to returns true if the left-hand side is less than or
equal to the right-hand side.
>, Greater than: returns true if the left-hand side is greater than the
right-hand side.
>=, Greater than or equal to returns true if the left-hand side is greater
than or equal to the right-hand side.

30
Example Program:
class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}

Output:
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false

31
Memory Management:
Memory management is the process of allocation
and de-allocation of objects, called Memory management. Java does memory
management automatically. Java uses an automatic memory management
system called a garbage collector. Thus, we are not required to implement
memory management logic in our application. Java memory management
divides into two major parts:

1. JVM Memory Structure


2. Working of the Garbage Collector

JVM Memory Structure:

JVM creates various run time data areas in a heap.


These areas are used during the program execution.
The memory areas are destroyed when JVM exits, whereas the data areas
are destroyed when the thread exits.

32
Heap Area:
Heap stores the actual objects. It creates when the JVM starts up.
The user can control the heap if needed. It can be of fixed or dynamic size.
When you use a new keyword, the JVM creates an instance for the object
in a heap.
While the reference of that object stores in the stack. There exists only one
heap for each running JVM process.
When heap becomes full, the garbage is collected.
The Java Virtual Machine has a heap that is shared among all Java Virtual
Machine threads.
The heap is the run-time data area from which memory for all class
instances and arrays is allocated.
The heap is created on virtual machine start-up. Heap storage for objects is
reclaimed by Garbage Collector.
Whenever we create any object in our program, the object is created in
heap and the stack (JVM/Native) stores the reference to it.

Method Area:
Method Area is a part of the heap memory which is shared among all the
threads.
It creates when the JVM starts up. It is used to store class structure,
superclass name, interface name, and constructors.
The JVM stores the following kinds of information in the method area

Stack Area:
Stack Area generates when a thread creates.
It can be of either fixed or dynamic size. The stack memory is allocated per
thread.

33
It is used to store data and partial results. It contains references to heap
objects.
It also holds the value itself rather than a reference to an object from the
heap.
The variables which are stored in the stack have certain visibility, called
scope.

Native method Stacks:

Also called as C stacks, native method stacks are not written in Java
language.

This memory is allocated for each thread when its created. And it can be
of fixed or dynamic nature.

Native methods are methods written in a language other than the Java
programming language.

It can be C, C++ or any other programming language.

Native method stacks are typically allocated per thread when each thread
is created.

Native method stacks either to be of a fixed size or to dynamically


expand and contract as required by the computation.

PC Registers:
Each thread has a Program Counter (PC) register associated with it.
PC register stores the return address or a native pointer.
It also contains the address of the JVM instructions currently being
executed.
Program Counter or PC register holds the address of JVM instruction
currently being executed for any particular thread.

34
An example of JVM instruction is d2f which converts a double value to
float value.
If the current method being executed is not one of JVM instruction set, it
has to be a native method.

Working of the Garbage Collector:

JVM controls the garbage collector.


JVM decides when to perform the garbage collection. We can also request
to the JVM to run the garbage collector.
But there is no guarantee under any conditions that the JVM will comply.
JVM runs the garbage collector if it senses that memory is running low.
When Java program request for the garbage collector, the JVM usually
grants the request in short order.
It does not make sure that the requests accept.
Every Java program has more than one thread.
Each thread has its execution stack. There is a thread to run in Java program
that is a main () method.
Now we can say that an object is eligible for garbage collection when no
live thread can access it.
The garbage collector considers that object as eligible for deletion.

35
Explain Conditional statements in Java with examples.
Conditional statements are mostly used in decision-making scenarios which means these
statements take a decision on the basis of some conditions. The conditional statements are
also referred as branching statements because the program takes a decision based on the
result of the assessed condition.
 if statement
 if-else statement
 if-else-if ladder
 nested if statement
 Switch Statement

if Statement:

The Java if statement tests the condition. It executes the if block if condition is true. If the
given condition is satisfied it will execute the true block statement only
Example Program:

class IfExample
{
public static void main(String[] args)
{
//defining an 'age' variable
int age=18;
//checking the age
if(age>18)
{
System.out.print("You are eligible to vote");
}
}
}

Output:
21
You are eligible to vote
if-else Statement:

The Java if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed. It will execute either true block statement or false block
statements.

Example Program:1

class IfExample
{
public static void main(String[] args)
{
int age=20; //defining an 'age' variable
if(age>18) //checking the age
{
System.out.print("You are eligible to vote");
}
else
{
System.out.println(“You are not eligible to vote”);
}
}
}
Output:
25
You are not eligible to vote
if-else-if ladder Statement:

The if-else-if ladder statement executes one condition from multiple statements. If the first
condition is satisfy it will execute the statement otherwise it will execute the next condition.
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}

Example Program:
import java.util.Scanner;
class if-else-if ladder
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a percentage");
float per = sc.nextFloat();
if(per>=70)
{
System.out.println("Distinction");
}
else if(per>=60)
{
System.out.println("First Class");
}
else if(per>=50)
{
System.out.println("Second Class");
}
else if(per>=40)
{
System.out.println("Pass");
}
else
{
System.out.println("Failed");
}
}
}

Output:

Enter a percentage:
62
First Class

Nested if statement:

The nested if statement represents the if block within another if block. Here, the inner if
block condition executes only when outer if block condition is true.
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Example program:
public class NestedIfExample2
{
public static void main(String[] args)
{
int age=25; //Creating two variables for age and weight
int weight=48;
if(age>=18) //applying condition on age and weight
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
}
Output:
16
You are not eligible to donate blood
Switch Statement:

The Java switch statement executes one statement from multiple


conditions. It is like if-else-if ladder statement. The switch statement works with byte, short,
int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since
Java 7, you can use strings in the switch statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
………
default:
code to be executed if all cases are not matched;
}
Example program:
class WeekDays
{
public static void main(String s[])
{
int day = 2;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
break;
}
}
}

Out put:
Tuesday
Explain about Iteration/ looping statements statements

For Loop:
Iteration statements are used to execute a particular set of instructions repeatedly until a
particular condition is met or for a fixed number of iterations.
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to false,
the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the body of
the for loop are executed,
• and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false,
the loop terminates.
Example: Display numbers from 1 to 5
class Main
{
public static void main(String[] args)
{
int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println(i);
}
}
}
Output:
1 2 3 4 5

Ex: 2---Display Sum of n Natural Numbers


class NaturalNumbers
{
public static void main(String[] args)
{
int sum = 0;
int n = 1000;
for(int i = 1; i <= n; ++i)
{
sum += i;
}
System.out.println("Sum = " + sum);
}
}

Output:
Sum=500500
While Loop:

The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.

The while loop is considered as a repeating if statement. If the number of iteration is not
fixed, it is recommended to use the while loop.

Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example: Sum of Positive Numbers Only

import java.util.Scanner;
class WhileLoop
{
public static void main(String[] args)
{
int sum = 0;
Scanner input = new Scanner(System.in);
System.out.println("Enter a number");
int number = input.nextInt();
while (number >= 0)
{
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum);
input.close();
}
}
Output:
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
do-while Loop:

The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iterations is not fixed and you must have to execute the
loop at least once, it is recommended to use a do-while loop.

Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop,
the do-while check the condition at the end of loop body. The Java do-while loop is
executed at least once because condition is checked after loop body.

Syntax:

Do
{
//code to be executed / loop body
//update statement
}
While (condition);

In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.
Example Program:
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}

Output:

10
For-each loop in Java:

The Java for-each loop or enhanced for loop is introduced since J2SE 5.0.
It provides an alternative approach to traverse the array or collection in Java.
It is mainly used to traverse the array or collection elements.
The advantage of the for-each loop is that it eliminates the possibility of bugs and
makes the code more readable.
It is known as the for-each loop because it traverses each element one by one.
The drawback of the enhanced for loop is that it cannot traverse the elements in
reverse order.
you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.
For-each is another array traversing technique like for loop, while loop, do-while
loop introduced in Java5.

1. It starts with the keyword for like a normal for-loop.


2. Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a colon,
which is then followed by the array name.
3. In the loop body, you can use the loop variable you created rather than using an
indexed array element.

4. It’s commonly used to iterate over an array or a Collections class (eg,


ArrayList).
Syntax:
for (type var : array)
{
statements using var;
}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
For-each loop Example: Traversing the collection elements

import java.util.*;
class ForEachExample2
{
public static void main(String args[])
{
ArrayList<String> list=new ArrayList<String>(); //Creating a list of elements
list.add("Vimal");
list.add("Sonoo");
list.add("Sameena");
for(String s:list) //traversing the list of elements using for-each loop
{
System.out.println(s);
}
}
}
Output:
Vimal n
Sonoo
Sameena
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 50, 80, 95, 99, 49,56,98 };
int highest_marks = maximum(marks);
System.out.println("The highest score is " + highest_marks);
}
}
public static int maximum(int[] numbers)
{
int max = numbers[0];
// for each loop
for (int num : numbers)
{
if (num > max)
{
max = num;
}
}
return max;
}
}

Output:
The highest score is 99
Explain about the jumping Statements/ control statements with example.
Jump Statements in Java

Introduction:
Jump statements are control statements that transfer execution control
from one point to another point in the program. There are two Jump statements that are
provided in the Java programming language:
1. Break statement.
2. Continue statement.
Or
The execution of a Java program is done in sequential order. Looping statements like for,
while, and do-while are used to execute a set of statements repeatedly. If such an
execution were to continue, it would go on forever. This can be prevented by adding
appropriate terminating conditions to the loop or by implementing jump statements. A
jump statement helps transfer the control of a program from one line of the code to
another and skip the ones in between.

1.Break Statement:
In java, the break statement is used to terminate the execution of the
nearest looping statement or switch statement. The break statement is widely used with
the switch statement, for loop, while loop, do-while loop.

Syntax:
break;

When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop. here is an example:
For( )//
{
For( ) For ( )

{ {
break;
break; }

} }
Example Program:

import java.io.*;
class Break
{
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
5
Example: 2
public class Break2
{
public static void main(String args[])
{
int i = 3;
switch(i)
{
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("Other");
}
}
}
Output :
Three
Goto:

The goto keyword is a commonly used jump statement in C/C++. However, Java
uses break statements to perform the same function as goto. Labels can be used to identify
blocks of code in Java. Any valid identifier followed by a semicolon represents a label.
We can break out of a labelled block by mentioning the label name after the break
keyword.

Example: Nested loop


public class Goto
{
public static void main(String[] args)
{
outer: // label for outer loop
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j == 2)
break outer;
System.out.println(" value of j = " + j);
}
} // end of outer loop
} // end of main()
}

Output:
0
1
2
Example:2
class MyClass
{
public static void main( String args[] )
{
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
break label; // exits the loop when it reaches 3
}
System.out.println(i);
}
}
}
Output:
0
1
2
Continue statement:
Continue is a jump statement used when a loop’s current iteration is
to be skipped. It allows the control to temporarily exit the loop and ignore the remaining
statements that follow. After this jump, the control immediately moves with the next
iteration of the same loop.

public class Continue


{
public static void main(String args[])
{
For( )
for (int i = 10; i > 0 ;i--) {
{
if (i%2 == 0) continue;
continue;
System.out.print(i+ " ");
}
}
}
}
Output:
9 7 5 3 1
Return statement:
The return keyword is used to transfer a program’s control from a
method back to the one that called it. Since the control jumps from one part of the
program to another, return is also a jump statement.

public class Return


{
public static int add(int a, int b) // parameter//
{
int sum = a+b;
return sum;
}
public static void main(String[] args)
{
int x = 5, y = 10;
int sum = add(x, y);
System.out.println("Sum of a and b: " + sum);
}
}
Output:
Sum of a and b : 15

Note:
Qns.
What is the difference between the break and continue statement?
A break statement terminates its loop and resumes execution out of it. On the other hand,
a continue statement temporarily exits the loop and resumes with the next iteration.
Qns.
Is goto used in Java?
Unlike C/C++, Java does not use goto as a jump statement, but still considers it a
keyword. This means that it cannot be used as an identifier. The use of goto in Java makes
the code complex and difficult to understand. Hence, the break statement handles the
function of goto in a simpler way.
What is an Array and explain different types of arrays in java
Arrays:

An array is a collection of similar type of elements which has


contiguous memory location. Java array is an object which contains elements
of a similar data type. Additionally, The elements of an array are stored in a
contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.

type var-name[];
OR
type[] var-name;

Disadvantages:

Size Limit:

We can store only the fixed size of elements in the array. It doesn't grow its size
at runtime.

Types of Array in java

There are two types of array.

Single Dimensional Array


Multidimensional Array
Single Dimensional Array/ One Dimensional:

One Dimensional Array in java is always used with only one subscript
( [ ] ).
One Dimensional Array in java is always used with only one subscript (
[]).
A one-dimensional array behaves likes a list of variables.
You can access the variables of an array by using an index in square
brackets preceded by the name of that array.
Index value should be an integer. Before using the array, we must declare
it.

type var-name[];
OR
type[] var-name;
Example Program:1

class OnedimenisionaArray
{
public static void main(String[] args)
{
int[] arr; // declares an Array of integers.
arr = new int[5]; // allocating memory for 5 integers.
arr[0] = 10; // initialize the first elements of the array
arr[1] = 20; // initialize the second elements of the array
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : " + arr[i]);
}
}

Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Multidimensional Arrays:
Multidimensional Arrays can be defined in simple
words as array of arrays. Data in multidimensional arrays are stored in tabular
form (in row major order).
data_type[1st dimension][2nd dimension][]..[Nth
dimension] array_name = new data_type[size1][size2]….[sizeN];
 data_type: Type of data to be stored in the array. For example: int, char,
etc.
 dimension: The dimension of the array created. For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, …, sizeN: Sizes of the dimensions respectively.
Two dimensional array:
2D array can be defined as an array of arrays. The
2D array is organized as matrices which can be represented as the collection of
rows and columns. The 2d array represents with two sub scripts.
Initializing 2D Arrays:

int arr[2][2] = {0,1,2,3};


int[][] twoD_arr = new int[10][20];

Two – dimensional Array (2D-Array)


Two – dimensional array is the simplest form of a multidimensional array. A
two – dimensional array can be seen as an array of one – dimensional array for
easier understanding.
Representation of 2D array in Tabular Format:
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’
columns where the row number ranges from 0 to (x-1) and column number
ranges from 0 to (y-1). A two – dimensional array ‘x’ with 3 rows and 3
columns is shown below:
Example:2
public class TwoDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][] = { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}

Output:
279
361
742
Multidimensional array:
Three – dimensional array is a complex form of a
multidimensional array. A three – dimensional array can be seen as an array of
two – dimensional array for easier understanding. Multi-dimensional array
represents with three subscripts. Elements in three-dimensional arrays are
commonly referred by x[i][j][k] where ‘i’ is the array number, ‘j’ is the row
number and ‘k’ is the column number.
Example:3

class MultiDimensional
{
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };

for (int i = 0; i < 2; i++)


{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
System.out.print(arr[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Output:
12
34
56
78
Practice Programs:1

public class ReverseArray


{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--)
{
System.out.print(arr[i] + " ");
}
}
}

Output:
Original array: 1 2 3 4 5
Array in reverse order:
54321
Example:2

public class EvenPosition


{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array present on even position: ");
//Loop through the array by incrementing value of i by 2
//Here, i will start from 1 as first even positioned element is present at position 1. for (int
i = 1; i < arr.length; i = i+2)
{
System.out.println(arr[i]);
}
}
}

Output:
Elements of given array present on even position:
2
4
Example:3
public class OddPosition
{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Elements of given array present on odd position: ");
//Loop through the array by incrementing value of i by 2
for (int i = 0; i < arr.length; i = i+2)
{
System.out.println(arr[i]);
}
}
}
Output:
Elements of given array present on odd position:
1
3
5
Example:4
public class OddEvenInArrayExample
{
public static void main(String args[])
{
int a[]={1,2,5,6,3,2};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++)
{
if(a[i]%2!=0)
{
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
{
System.out.println(a[i]);
}
}
}
}

Output:
Odd Numbers:
1
5
3
Even Numbers:
2
6
2
Example: add two matrices

public class MatrixAdditionExample


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//adding and printing addition of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}

Output:
268
486
469
Example: multiply two matrices

public class MatrixMultiplicationExample


{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}
}

Output:
6 6 6
12 12 12
18 18 18
Example: Transpose matrix

public class MatrixTransposeExample


{
public static void main(String args[])
{
//creating a matrix
int original[][]={{1,3,4},{2,4,3},{3,4,5}};

//creating another matrix to store transpose of a matrix


int transpose[][]=new int[3][3]; //3 rows and 3 columns

//Code to transpose a matrix


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
transpose[i][j]=original[j][i];
}
}

System.out.println("Printing Matrix without transpose:");


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(original[i][j]+" ");
}
System.out.println();//new line
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(transpose[i][j]+" ");
}
System.out.println(); //new line
}
}
}

Output:
Printing Matrix without transpose:
134
243
345
Printing Matrix After Transpose:
123
344
435
Class and Objects

A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created. It is a logical entity. It can't be physical.

Or

Collection of objects is called class. It is a logical entity. Once a class has been
defined, we can create any number of objects belongs to that class.

Each object associated with data and Methods.

For Example:

“Fruit” is a class and Mango, Apple and Banana are Objects.

Fields
Methods
Constructors
Blocks
Nested class and interface

Once a class has been defined, we can create any number of objects belongs to that
class. Each object associated with data and Methods.

For Example “Fruit” is a class and Mango, Apple and Banana are objects.

class <class_name>

field; method;

1
Example:1
class Student
{
int id; //field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
Output:
O
Null

Example: 2

class Student
{
int id;
String name;
}
class TestStudent3
{
public static void main(String args[])
{
Student s1=new Student(); //Creating objects
Student s2=new Student();
s1.id=101; //Initializing objects
s1.name="Sonu";
s2.id=102;
s2.name="Monu";
System.out.println(s1.id+" "+s1.name); //Printing data
System.out.println(“ \n”);
System.out.println(s2.id+" "+s2.name);
}
}
Output:
101 Sonu
102 Monu

2
Multiple Classes:

We can have multiple classes in different Java files or single Java file. If you define
multiple classes in a single Java source file, it is a good idea to save the file name
with the class name which has main() method.

//Java Program to demonstrate having the main method in


//another class
//Creating Student class.

class Student
{
int id=1122;
String name="Amith";
}
//Creating another class TestStudent1 which contains the main method
class Student123
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(" \n");
System.out.println(s1.name);
}
}
Output:
1122
Amith

3
Object in Java:

How to create the objects in different ways:

The Object is the real-time entity having some state and behavior. In Java, Object is
an instance of the class having the instance variables as the state of the object and
the methods as the behaviour of the object. The object of a class can be created by
using the new keyword in Java Programming language.

Objects are run time entities in an object-oriented System. They may represent a
person, place, Place, Bank Account, a table of data or anu other item. 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.

Java provides five ways to create an object.

1. Using new Keyword


2. Using clone() method
3. Using newInstance() method of the Class class
4. Using newInstance() method of the Constructor class
5. Using Deserialization

1.Using new keyword:


Using the new keyword in java is the most basic way to create an object. This is
the most common way to create an object in java. By using this method we can
call any constructor we want to call (no argument or parameterized constructors).

class Parul
{
// Declaring and initializing string
String name = " PARUL UIVERSITY @ Vadodara";
public static void main(String[] args) // Main driver method
{
Parul obj = new Parul(); // using new keyword
// Print and display the object
System.out.println(obj.name);
}
}
Output:
PARUL UIVERSITY @ Vadodara

4
2.Using Object Cloning – clone() method:

The clone() method is used to create a copy of an existing object, in order to


the clone() method the corresponding class should have implemented
a Cloneable interface which is again a Marker Interface.
Example:
public class CreateObjectExample3 implements Cloneable
{
protected Object clone() throws CloneNotSupportedException
{
//invokes the clone() method of the super class
return super.clone();
}
String str = "New Object Created";
public static void main(String[] args)
{
//creating an object of the class
CreateObjectExample3 obj1 = new CreateObjectExample3();
//try catch block to catch the exception thrown by the method
try
{
//creating a new object of the obj1 suing the clone() method
CreateObjectExample3 obj2 = (CreateObjectExample3) obj1.clone();
System.out.println(obj2.str);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}

Output:

New Object Created

5
3.Using newInstance() Method of Class class:

The newInstance() method of the Class class is also used to create an object. It calls
the default constructor to create the object. It returns a newly created instance of the
class represented by the object. It internally uses the newInstance() method of the
Constructor class.

Example:
public class CreateObjectExample4
{
void show()
{
System.out.println("A New Object Created.");
}
public static void main(String[] args)
{
try
{
//creating an instance of Class class
Class cls = Class.forName("CreateObjectExample4");
//creates an instance of the class using the newInstance() method
CreateObjectExample4 obj = (CreateObjectExample4) cls.newInstance();
//invoking the show() method
obj.show();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}

6
Output:

A New Object Created.

4.Using newInstance() Method of Constructor class:

It is similar to the newInstance() method of the Class class. It is known as a


reflective way to create objects. The method is defined in the Constructor class
which is the class of java.lang.reflect package. We can also call the parameterized
constructor and private constructor by using the newInstance() method.

import java.lang.reflect.*;
class Parul
{
// Member variables of this class
private String name;
// Constructor of this class
Parul() {}
// Method 1
// To set name of the string
public void setName(String name)
{
// This method refers to current object itself
this.name = name;
}
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try
{
Constructor<Parul> constructor= Parul.class.getDeclaredConstructor();
Parul r = constructor.newInstance();
// Custom passing
r.setName("PIET @ Parul University");
System.out.println(r.name);
}
// Catch block to handle the exceptions
catch (Exception e)
{

7
// Display the exception on console
// using printStackTrace() method
e.printStackTrace();
}
}
}

Output:

PIET @ Parul University

5.Using deserialization

Whenever we serialize and then deserialize an object, JVM creates a separate


object. In deserialization, JVM doesn’t use any constructor to create the object.
To deserialize an object we need to implement the Serializable interface in the
class.

Serialization
import java.io.*;
class Persist
{
public static void main(String args[])
{
Try
{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}
catch(Exception e)

8
{
System.out.println(e);
}
}
}

Output:

Success

Deserialization:

import java.io.*;
class Depersist
{
public static void main(String args[])
{
Try
{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:

111
Ram

9
What is a method in Java?

A method is a block of code or collection of statements or a set of code


grouped together to perform a certain task or operation.
It is used to achieve the reusability of code.
We write a method once and use it many times. We do not require to write
code again and again.
It also provides the easy modification and readability of code, just by
adding or removing a chunk of code.
The method is executed only when we call or invoke it.
The most important method in Java is the main() method.

Method Declaration:

The method declaration provides information about method attributes, such as


visibility, return-type, name, and arguments. It has six components that are known
as method header, as we have shown in the following figure.

10
Method Signature:

Every method has a method signature. It is a part of the method declaration. It


includes the method name and parameter list.

Access Specifier:

Access specifier or modifier is the access type of the method. It specifies the visibility
of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier
in our application.
Private: When we use a private access specifier, the method is accessible only
in the classes in which it is defined.
Protected: When we use protected access specifier, the method is accessible
within the same package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration,
Java uses default access specifier by default. It is visible only from the same
package only.

Return Type:

Return type is a data type that the method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name:

It is a unique name that is used to define the name of a method. It must be


corresponding to the functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name must be subtraction(). A
method is invoked by its name.

Parameter List:

It is the list of parameters separated by a comma and enclosed in the pair of


parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.

11
Method Body:

It is a part of the method declaration. It contains all the actions to be performed. It is


enclosed within the pair of curly braces.

What is a method and explain different types of Methods in Java

There are two types of methods in Java:

o Predefined Method
o User-defined Method

Predefined Method:

In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods.
It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any
point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
When we call any of the predefined methods in our program, a series of
codes related to the corresponding method runs in the background that is
already stored in the library.
Each and every predefined method is defined inside a class.
Such as print() method is defined in the java.io.PrintStream class.
It prints the statement that we write inside the method.
For example, print("Java"), it prints Java on the console

12
Example:1

public class mul


{
public static void main(String[] args)
{
int x=5;
System.out.println(x*1);
System.out.println(x*2);
System.out.println(x*3);
System.out.println(x*4);
System.out.println(x*5);
System.out.println(x*6);
System.out.println(x*7);
System.out.println(x*8);
System.out.println(x*9);
System.out.println(x*10);
}
}

Example:2

public class mul


{
static int mul(int a)
{
System.out.println(5*a);
return 5*a;
}
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
mul(i);
}
}
}

13
User-defined Method:

The method written by the user or programmer is known as a user-defined method.


These methods are modified according to the requirement.

How to Create a User-defined Method

Let's create a user defined method that checks the number is even or odd. First, we
will define the method.

//user defined method


public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}

We have defined the above method named findevenodd().


It has a parameter num of type int.
The method does not return any value that's why we have used void.
The method body contains the steps to check the number is even or odd.
If the number is even, it prints the number is even, else prints the number is
odd.

14
Example:
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from the user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
}

Output :
Enter the number: 12
12 is a even number

Types:
1.Static Methods: it is implement the behaviour of the class.

2. Instance Methods (Non-Static): it is used to implement behaviour of each instance


of class. (create with Object)

Static Method:

A static method in Java is a method that is part of a class rather than an instance
of that class.
Every instance of a class has access to the method.
Static methods have access to class variables (static variables) without using
the class's object (instance).
Only static data may be accessed by a static method

15
We can also create a static method by using the keyword static before the
method name.
The main advantage of a static method is that we can call it without creating
an object.
It can access static data members and also change the value of it. It is used to
create an instance method.
It is invoked by using the class name. The best example of a static method is
the main() method.

Example of static method

public class Display


{
public static void main(String[] args)
{
show();
}
static void show()
{
System.out.println("It is an example of static method.");
}
}
Output:
It is an example of static method

16
Non-Static Example:
class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"William");
System.out.println(" \n");
s2.insertRecord(222,"Smith");
s1.displayInformation();
s2.displayInformation();
}
}
Output:
111 William
222 Smith

17
import java.io.*;
class Geek
{
public static String geekName = "";
public static void geek(String name)
{
geekName = name;
}
}
class GFG
{
public static void main(String[] args)
{
// Accessing the static method geek()
// and field by class name itself.
Geek.geek("Abhinav");
System.out.println(Geek.geekName);
// Accessing the static method geek()
// by using Object's reference.
Geek obj = new Geek();
obj.geek("Amith");
System.out.println(obj.geekName);
}
}

Output:
Abhinav
Amith

18
Method Overloading:

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

If we have to perform only one operation, having same name of the methods increases
the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int, int) for two parameters,
and b(int, int, int) for three parameters

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

19
1.Method Overloading: changing no. of arguments:

In this example, we have created two methods, first add() method performs addition
of two numbers and second add method performs addition of three numbers.

class Adding
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adding.add(100,200));
System.out.println(Adding.add(100,200,300));
}
}
Output:
300
600

20
2.Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.

class Adding
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b, double c)
{
return a+b+c;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adding.add(100,200));
System.out.println(Adding.add(100.55,200.55,300.33));
}
}
Output:
300
601.4300000000001

21
Method Overriding:

If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation. The name and parameter of the
method are the same, and there is IS-A relationship between the classes, so there is
method overriding.

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.

Rules for Java Method Overriding


The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class

class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle //Creating a child class
{
public static void main(String args[])
{
Bike obj = new Bike(); //creating an instance of child class
obj.run(); //calling the method with child class instance
}
}

22
Output:
Vehicle is running
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.

Example:

class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike Is Running Safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike Is Running Safely

23
Constructor:

A constructor in Java is similar to a method that is invoked when


an object of the class is created. Unlike Java methods, a constructor has the same
name as that of the class and does not have any return type.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Default Constructor:

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

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

24
1.Parameterized Constructor:
A constructor which has a specific number of
parameters is called a parameterized constructor. The parameterized constructor is
used to provide different values to distinct objects. However, you can provide the
same values also.

Example:

class Student4
{
int id;
String name;
Student4(int i, String n) //creating a parameterized constructor
{
id = i;
name = n;
}
void display() //method to display the values
{
System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan"); //creating objects and passing values
Student4 s2 = new Student4(222,"Aryan"); //calling method to display the values of
object
s1.display();
s2.display();
}
}

Output:
111 Karan
222 Aryan

25
2.Constructor overloading in java:
The constructor overloading can be defined
as the concept of having more than one constructor with different parameters list, so
that every constructor can perform a different task.

public class Student5


{
int id;
String name;
int age;
Student5(int i, String n) //creating two arg constructor
{
id = i;
name = n;
}
Student5(int i, String n, int a) //creating three arg constructor
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan 25
Note: Class name and Method name both are same

26
Difference between constructor and method in Java

There are many differences between constructors and methods. They are given
below.

Java Constructor Java Method

A constructor is used to initialize the state of an A method is used to expose the


object. behavior of an object.

A constructor must not have a return type. A method must have a return
type.

The constructor is invoked implicitly. The method is invoked


explicitly.

The Java compiler provides a default The method is not provided by


constructor if you don't have any constructor in the compiler in any case.
a class.

The constructor name must be same as the class The method name may or may
name. not be same as the class name.

27
Encapsulation:

Wrapping up data and methods into a single unit is known as Encapsulation. The
data not accessible from out side the world and only access those methods, which
are wrapped in the class, it can access it.

Methods are interface between the object data and program.

Data
Informtion in And information out
Method

Example:

class Area
{
int length;
int breadth; // fields to calculate area
// constructor to initialize values
Area(int length, int breadth)
{
this.length = length;
this.breadth = breadth;
}
// method to calculate area
public void getArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
}
class Main
{
public static void main(String[] args)
{
// create object of Area
// pass value of length and breadth
Area rectangle = new Area(5, 6);
rectangle.getArea();
}
}
Output:
30

28
Polymorphism:

polymorphism is another important opps concepts, polymorphism means it is ability


to take more than one form, an operation may exhibit different behaviour in
different instances. The behaviour depends upon the types of data used in the
operation.

Example:
class Shape
{
void draw()
{
System.out.println("drawing...");
}
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("drawing circle...");
}
}

29
class Triangle extends Shape
{
void draw()
{
System.out.println("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}

Output

drawing rectangle...

drawing circle...

drawing triangle...

30
Abstraction:
Abstraction refers to the act of representing essential feature without
including the background details or explanation. Classes use the abstraction
concepts and defined a list of abstract attributes.

Example:
for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.

Example:

abstract class Bank


{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 5;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 9;
}
}
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new ICICI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}

31
}

Output:

SBI Rate of Interest is: 5 %


ICICI Rate of Interest is: 9 %

32
Inheritance:
Inheritance is an important pillar of OOP (Object-Oriented
Programming). It is the mechanism in java by which one class is allowed to inherit
the features (fields and methods) of another class. In Java, inheritance means
creating new classes based on existing ones. A class that inherits from another
class can reuse the methods and fields of that class.

Inheritance in Java: Why do we need it?


Code Reusability: The code written in the Superclass is common to all
subclasses. Child classes can directly use the parent class code.
Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which java achieves Run Time
Polymorphism.
Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface


only.

Single Inheritance Example:

When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

33
Example:

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

34
Multilevel Inheritance Example
When there is a chain of inheritance, it is known
as multilevel inheritance. Multilevel Inheritance in java involves inheriting a class,
which already inherited some other class. Multilevel Inheritance in Java is a type of
inheritance in which a class that is already inherited by another class, inherits another
class.

class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;

35
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
class Sports extends Marks //derived class
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(123);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68);
ob.putScore();
}
}
Output:
registration number= 123
marks= 78.0
score= 68.0

36
Hierarchical Inheritance:

When two or more classes inherits a single class, it is known as hierarchical


inheritance. In the example given below.

Syntax:

Class Parent
{
//Data members and member functions of Parent Class
}
Class Derived-1 : access modifier Parent
{
//Data members and member functions of Derived-1 class
}
Class Derived-2 : access modifier Parent
{
//Data members and member functions of Derived-2 class
}

37
Example:
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();

38
comm.methodStudent();
art.methodStudent();
}
}

Output:

The method of the class Student invoked.

The method of the class Student invoked.

The method of the class Student invoked.

39
What is a multiple inheritance:
When a class inherits properties from many classes, this is
known as multiple inheritance. Multiple Inheritance is not supported by Java. But using Interfaces,
Multiple Inheritance is possible in Java.

Example:
interface A
{
public abstract void execute1();
}
interface B
{
public abstract void execute2();
}
class C implements A,B
{
public void execute1()
{
System.out.println("Haii.. I am from execute1");
}
public void execute2()
{
System.out.println("Haii.. I am from execute2");
}
}
class Main
{
public static void main(String[] args)
{
C obj = new C(); // creating object of class C
obj.execute1(); //calling method execute1
obj.execute2(); // calling method execute2
}
}

40
Output:

Haii.. I am from execute1


Haii.. I am from execute2

41
Hybrid inheritance:

the hybrid inheritance is the composition of two or more types of inheritance. The
main purpose of using hybrid inheritance is to modularize the code into well-
defined classes. It also provides the code reusability.

Single and Multiple Inheritance (not supported but can be achieved through
interface)
Multilevel and Hierarchical Inheritance
Hierarchical and Single Inheritance
Multiple and Multilevel Inheritance.

class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");

42
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}

Output:

I am a daughter.

43
Super keyword:

The super keyword in java is a reference variable that is used to refer to parent
class objects. An understanding of Inheritance and Polymorphism is needed in
order to understand the super keyword. The keyword “super” came into the
picture with the concept of Inheritance. It is majorly used in the following
contexts:

Use of super with variables


Use of super with methods
Use of super with constructors
1. Use of super with variables:
This scenario occurs when a derived class and
base class has the same data members. In that case, there is a possibility of
ambiguity for the JVM. We can understand it more clearly using this code
snippet:

Example:

class Vehicle
{
int maxSpeed = 120;
}
class Car extends Vehicle // sub class Car extending vehicle
{
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
class Test // Driver Program
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:
Maximum Speed: 120

44
2. Use of super with methods:
This is used when we want to call the parent
class method. So whenever a parent and child class have the same-named methods
then to resolve ambiguity we use the super keyword. This code snippet helps to
understand the said usage of the super keyword.

Example:

class Person
{
void message()
{
System.out.println("This is person class\n");
}
}
// Subclass Student
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is
// only in Student class
void display()
{
// will invoke or call current
// class message() method
message();
// will invoke or call parent
// class message() method
super.message();
}
}
// Driver Program
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}

45
Output:

This is student class

This is person class

3. Use of super with constructors


The super keyword can also be used to access the parent class constructor. One
more important thing is that ‘super’ can call both parametric as well as non-
parametric constructors depending upon the situation. Following is the code
snippet to explain the above concept:

Example:

class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
// subclass Student extending the Person class
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
class Test // Driver Program
{
public static void main(String[] args)
{
Student s = new Student();
}
}

Output:

Person class Constructor


Student class Constructor

46
Topic:1
Nested classes:
Writing a class within another is allowed in Java.
The class written within is called the nested class, and the class that holds
the inner class is called the outer class.
Nested classes are divided into two categories: static and non-static.
Nested classes that are declared static are simply called static nested
classes.
Non-static nested classes are called inner classes.

Properties of Nested classes in Java:

In Java, a nested class is a class that is defined inside some other class.
Nested classes are used to group certain classes to improve the readability
of the code.
The scope of a nested class is the same as its outer class.
Nested classes can access any member of the outer class, even if the outer
class is private.

Types of Nested Classes:

A nested class can either be defined as a static type or a non-static type.

Static Nested Classes


Non-static Nested Classes (or Inner Classes) We can further divide the
Non-static Classes into -

 Member Inner Classes


 Local Inner Classes
 Anonymous Inner Classes
Static Nested Classes:

A static class is a class that is created inside a class.


A static variable is common to all the instances of that particular class.
Similarly, a static class can access all the instance functions of the outer
class.
we will have to make objects of child classes and refer to them.
We can access all the static functions of the outer class without object
creation.

Syntax:
class parent_class
{
static class static_child_class
{
// code
}
}

static_child_class obj = new static_child_class();


Example:
class parent_class
{
static String s = "Parul University @";
static class static_child_class // child class
{
void print (String x) // child class method
{
System.out.println(s + " " + x);
}
}
public static void main(String args[])
{
static_child_class obj = new static_child_class(); // child class object
String y = "Vadodara";
obj.print(y);
}
}
Output:
Parul University @ Vadodara

Non-static Nested Classes (Inner Classes):

A non-static nested class or inner class is a class within a class.


We do not define it as static so that it can directly use all the functions
and variables of the outer class.

From the inner class, if we want to access any static method of the outer class,
we do not need any object; we can call it directly.

1. Member Inner Classes


2. Local Inner Classes
3. Anonymous Inner Classes
Type Description

Member Inner A class created within class and outside method.


Class

Anonymous Inner A class created for implementing an interface or extending


Class class. The java compiler decides its name.

Local Inner Class A class was created within the method.

Static Nested A static class was created within the class.


Class

Nested Interface An interface created within class or interface.

Member Inner Classes:


A non-static class that is declared inside a class but outside the method
is known as member inner class in Java.
It is also known as regular inner class.
It can be declared with access modifiers like public, default, private and
protected.

Syntax:
class Outer
{
//code
class Inner
{
//code
}
}
Example:
class parent_class
{
String s = "Parul University:-";
class child_class // child class
{
void print(String x)
{
System.out.println(s + " " + x);
}
}
public static void main(String args[])
{
parent_class parentObj = new parent_class();// parent class object
child_class childObj = parentObj.new child_class (); // child class object
using parent class object
String y = "Vadodara @ Gujarat";
childObj.print(y); // calling methods of child class
}
}

Output:
Parul University:- Vadodara @ Gujarat
Local Inner Classes:
A Local Inner class is a class that is defined inside any
block, i.e., for block, if block, methods, etc. Similar to local variables, the
scope of the Local Inner Class is restricted to the block where it is defined.
Syntax:
class class_name
{
void method_name()
{
// code
if(conditions)
{
// or any other block like while, for, etc.
class localInnerClass
{
void localInnerMethod()
{
// code
}
}
}
// code
}
}
Example:
class parent_class
{
public static void main(String args[])
{
String p = "Parul University";
if (p.charAt(0) = = 'P')
{
class child_class // child class
{
void print(String x)
{
System.out.println(p + " " + x);
}
}
child_class childObj = new child_class(); // child class object
String y = "Vadodara @ Gujarat";
childObj.print(y); // calling child class method
// child_class is accessible till here only
}
// child_class is not accessible here
}
}
Output:
Parul University Vadodara @ Gujarat
Anonymous Inner Classes:

Anonymous Inner class is an inner class but without a name. It has only a
single object. It is used to override a method. It is only accessible in the block
where it is defined.

We can use an abstract class to define the anonymous inner class.


It has access to all the members of the parent class.
It is useful to shorten over code.
Basically, it merges the step of creating an object and defining the class.

Abstract is a keyword, its non-accessing modifier, its used for classes and
Methods.
Abstract Class: Abstract class is a restricted class that can’t be used to
create Object, it must be inherited from another class.
Abstract Methods: abstract method is used only in abstract class, it does
not have any body

Syntax:
abstractClass obj = new abstractClass()
{
void methods()
{
// code
}
};
Example:
abstract class Printer
{
abstract void print (String x);
}
class parent_class // Parent Class
{
public static void main(String args[])
{
Printer obj = new Printer() // Anonymous Inner Class
{
void print(String x)
{
System.out.println("Parul University, " + x);
}
};
String y = "Vadodara @ Gujarat";
obj.print(y);
}
}

Output:
Parul University, Vadodara @ Gujarat

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Topic:2
this keyword in Java:

In Java, this is a keyword which is used to refer current object of a class. we


can it to refer any member of the class. It means we can access any instance
variable and method by using this keyword.

The main purpose of using this keyword is to solve the confusion when we have
same variable name for instance and local variables.

We can use this keyword for the following purpose.

this keyword is used to refer to current object.


this is always a reference to the object on which method was invoked.
this can be used to invoke current class constructor.
this can be passed as an argument to another method.
Lets first understand the most general use of this keyword. As we said, it can be
used to differentiate local and instance variables in the class.

Example:
class ThisKeyWord
{
Double width, height, depth;
ThisKeyWord (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
public static void main(String[] args)
{
ThisKeyWord Obj = new ThisKeyWord(100,200,300);
System.out.println("width = "+ Obj.width);
System.out.println("height = "+ Obj.height);
System.out.println("depth = "+ Obj.depth);
}
}
Output:
width = 100.0
height = 200.0
depth = 300.0
Calling Constructor using this keyword:
We can call a constructor from inside the another function by using this
keyword

Example:
In this example, we are calling a parameterized constructor from the non-
parameterized constructor using the this keyword along with argument.

Example:

class ThisKeyWordConstructor
{
ThisKeyWordConstructor ()
{
this("CSE Dept @ Parul University "); // Calling constructor
}
ThisKeyWordConstructor(String str)
{
System.out.println(str);
}
public static void main(String[] args)
{
ThisKeyWordConstructor This = new ThisKeyWordConstructor();
}
}

Output:

CSE Dept @ Parul University


Accessing Method using this keyword:
This is another use of this keyword that allows to access method. We can access
method using object reference too but if we want to use implicit object
provided by Java then use this keyword.

Example:

In this example, we are accessing getName () method using this and it works
fine as works with object reference.

Example Program:

class ThisMethod
{
public void getName()
{
System.out.println("Department of CSE @ Parul");
}
public void display()
{
this.getName();
}
public static void main(String[] args)
{
ThisMethod Obj = new ThisMethod ();
Obj.display();
}
}

Output:

Department of CSE @ Parul

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Topic:3

What is Interface in Java?


Interface is basically a kind of a class.
Interface contains methods and variables.
Interface is a collection of abstract method and constants (Static and
Final)
Very interface in java is abstract by default.
So, no need to abstract key with an interface.
An Interface in Java programming language is defined as an abstract type
used to specify the behaviour of a class.
A class can implement multiple interfaces.
In Java, interfaces are declared using the interface keyword.
All methods in the interface are implicitly public and abstract.
Difference between Class and Interface:
Class Interface
In class, you can instantiate variable In an interface, you can’t instantiate
and create an object. variable and create an object.
Class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods

The access specifiers used with classes In Interface only one specifier is used-
are private, protected and public. Public.
Constructors can be included in a class but not an inheritance.
A method body can exist in a class. but it cannot exist in an interface.
Classes do not support multiple but it is supported by inheritance.
inheritance.

A Java class can implement multiple Java Interfaces.


It is necessary that the class must implement all the methods declared in
the interfaces.
Class should override all the abstract methods declared in the interface
The interface allows sending a message to an object without concerning
which classes it belongs.
Class needs to provide functionality for the methods declared in the
interface.
All methods in an interface are implicitly public and abstract
An interface cannot be instantiated
An interface reference can point to objects of its implementing classes
An interface can extend from one or many interfaces. Class can extend only
one class but implement any number of interfaces
An interface cannot implement another Interface. It has to extend another
interface if needed.
An interface which is declared inside another interface is referred as nested
interface
At the time of declaration, interface variable must be initialized. Otherwise,
the compiler will throw an error.
The class cannot implement two interfaces in java that have methods with
same name but different return type.

Example

Interface and Class:

interface Pet
{
public void test();
}
class Dog implements Pet
{
public void test()
{
System.out.println("Interface Method Implemented");
}
public static void main(String args[])
{
Pet p = new Dog();
p.test();
}
}
Output:

Interface Method Implemented


Interface and Multiple Classes Bank

interface Bank
{
float rateOfInterest(); SBI ICICI
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 7.15f;
}
}
class ICICI implements Bank
{
public float rateOfInterest()
{
return 8.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new ICICI ();
System.out.println("ROI: "+b.rateOfInterest());
}
}

Output:
ROI: 8.7
Multiple inheritance in Java by interface:
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
interface int1
{ int1 int2
int i=20;
void print();
}
Test
interface int2
{
void show();
}
class test implements int1, int2
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
test obj=new test();
obj.print();
obj.show();
obj.i=30;
System.out.println(obj.i);
}
}

Output:

Hello

Welcome

20
interface A
{
void print();
}
interface B
{
void show();
}
class C implements A, B
{
A B
public void print()
Interface Interface
{
System.out.println("Hello");
}
public void show() C
Class
{
System.out.println("Welcome to CSE");
}
public static void main(String args[])
{
C obj = new C();
obj.print();
obj.show();
}
}

Output:

Hello

Welcome to CSE
Example : 2

/*
* Interface extends multiple interfaces java example
*/

interface A
{
void printa();
A B
}
interface B
{
void printb(); C
}
interface C extends A,B
{ XYZ
void printc();
}
class XYZ implements C
{
public void printa()
{
System.out.println("im from interface A");
}
public void printb()
{
System.out.println("im from interface B");
}
public void printc()
{
System.out.println("im from interface C");
}
}
class Sample
{
public static void main(String[] args)
{
XYZ obj = new XYZ();
obj. printa();
obj. printb();
obj. printc();
}
}
Output:

im from interface A

im from interface B

im from interface C

*-*-*-**-*-*-*-*-*-*-*-*-*
Topic:4

Package:
A package can be defined as a group of similar types of classes, interface,
enumeration or sub-package.
Using package, it becomes easier to locate the related classes and it also
provides a good structure for projects with hundreds of classes and other
files.

A java package is a group of similar types of classes, interfaces and sub-


packages.
Package in java can be categorized in two form, built-in package and user-
defined package.
There are many built-in packages such as java, lang, awt, javax, swing,
.net, io, util, sql etc.

Adding a class to a Package:


We can add more classes to a created package by using package name at
the top of the program and saving it in the package directory.
We need a new java file to define a public class, otherwise we can add
the new class to an existing .java file and recompile it.
Packages avoid the name clashes.
The Package provides easier access control.
We can also have the hidden classes that are not visible outside and used
by the package.
It is easier to locate the related classes.
 Sub packages:
Packages that are inside another package are the subpackages.
These are not imported by default;
they have to imported explicitly.
Also, members of a sub-package have no access privileges, i.e., they are
considered as different package for protected and default access
specifiers.

 How to Create a package:


Creating a package in java is quite easy. Simply include a package
command followed by name of the package as the first statement in java
source file.

package mypackage;
public class student
{
Statement;
…………..
…………..
…………..
}
The above statement will create a package name mypackage in the
project directory.
Java uses file system directories to store packages.
For example, the .java file for any class you define to be part of
mypackage package must be stored in a directory called mypackage.
 Additional points about package:
A package is always defined as a separate folder having the same
name as the package name.
Store all the classes in that package folder.
All classes of the package which we wish to access outside the
package must be declared public.
All classes within the package must have the package statement as its
first line.
All classes of the package must be compiled before use (So that they
are error free)
The packages are classified into two types.

Built-in Packages
User-defined packages
1.Built-in Packages: (Pre-defined packages)
These packages consist of a large number of classes which
are a part of Java API. Some of the commonly used built-in packages are:

1) java.lang:
Contains language support classes (e.g classed which defines
primitive data types, math operations). This package is automatically imported
by default.
2)java.io:
Contains classed for supporting input / output operations. It will
perform Read/Write operations.

3)java.util:
Contains utility classes which implement data structures like
Linked List, Dictionary and support; for Date / Time operations.
Ex: java.util.*;
ex: java.util.scanner class
4)java.applet:
Contains classes for creating Applets.

5)java.awt:
Contain classes for implementing the components for graphical
user interfaces (GUI) like button, menus etc..

6)java.net:
Contain classes for supporting networking operations. Like Client
Server programs and networking operation in java

2.User-defined packages:
These are the packages that are defined by the user.
first we create a directory myPackage (name should be same as the name of
the package). Then create the MyClass inside the directory with the first
statement being the package names.

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

 How to compile Java packages:

This is just like compiling a normal java program.


If you are not using any IDE, you need to follow the steps given below to
successfully
compile your packages:
1. java -d directory javafilename
For example javac -d . Simple.java
The -d switch specifies the destination where to put the generated class
file.
You can use any directory name like /home (in case of Linux), d:/abc (in
case of windows) etc.
If you want to keep the package within the same directory, you can use .
(dot).
 How to run java package program:
You need to use fully qualified name e.g. mypack.Simple etc to run the
class.
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Example
Program: Creating Package
package Robo;
public class Add
{
int x,y;
public Add() // Constructor //
{
x=100;
y=200;
}
public void sum() // Method //
{
System.out.println("Addition of two numbers:="+(x + y));
}
}

import Robo.Add; // Main Program importing package //


class Sana
{
public static void main(String args[])
{
Add obj=new Add();
obj.sum();
}
}
Output:
Addition of two numbers: 300
Topic:5

 How to access package from another package:


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1. Using packagename.*;

All the classes and interfaces of this package can be accessed (imported)
from outside the packages.
If you use package.* then all the classes and interfaces of this package
will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of package that import the packagename.*:


//save by A.java
package pack;
public class A
{
public void msg( )
{
System.out.println("Hello java");
}
}
//save by B.java //
package mypack;
import pack.*; // it access all classes in a package //
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello java

2) Using packagename.classname:

If you import packageName.className, you can access the declared class


of this package.
If you import package.classname then only declared class of this package
will be accessible.

Example of package by import package.classname:


//save by A.java //
package pack; // creating package 1 //
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java //
package mypack; // creating package 2 //
import pack.A;

class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:
Hello
Note:
pack.A it access only class A, if you use java.util.* it will access all
java.util, we can access all Linkedlist, date, Calendar and Hash table.

3) Using fully qualified name:

If you use fully qualified name then only declared class of this package
will be accessible.
Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g.
java.util and java.sql packages contain Date class.

Example of package by import fully qualified name:


//save by A.java
package pack; // creating package 1 //
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
//save by B.java
package mypack; // creating package 2 //
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:
Hello
Note:

If you use import a package, sub packages will not be imported.


If you import a package, all the classes and interface of that package will
be imported excluding the classes and interfaces of the sub packages.
Hence, you need to import the sub package as well.

 Subpackage in java:
Package inside the package is called the subpackage. It
should be created to categorize the package further.

Let's take an example, Sun Microsystem has defined a package named


java that contains many classes like System, String, Reader, Writer,
Socket etc.
These classes represent a particular group e.g. Reader and Writer classes
are for Input/Output operation, Socket and Server Socket classes are for
networking etc and so on.
So, Sun has subcategorized the java package into sub packages such as
lang, net, io etc. and put the Input/Output related classes in io package,
Server and Server Socket classes in net packages and so on.

package com.javatpoint.core;
class Simple
{
public static void main(String args[])
{
System.out.println("Hello subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output: Hello subpackage
How to send the class file to another directory or drive:
There is a scenario, I want to put the class file of A.java source file in classes
folder of c: drive.

For example:
//save as Simple.java

package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile:
e:\sources> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
e:\sources> set classpath=c:\classes;.;
e:\sources> java mypack.Simple.

Another way to run this program by -classpath switch of java:


The -classpath switch can be used with javac and java tool.
To run this program from e:\source directory, you can use -classpath switch of
java that tells where to look for class file.
For example:
e:\sources> java -classpath
c:\classes mypack.Simple
Output:
Welcome to package.
Topics:6

 IO Package:

The java.io package is used to handle input and output operations.


Java IO has various classes that handle input and output sources.
A stream is a sequence of data.
Java input stream classes can be used to read data from input sources
such as keyboard or a file.
Similarly output stream classes can be used to write data on a display or
a file again.

I/O Streams in Java:

Before understanding IO streams, let us discuss streams.


A Stream is also a sequence of data.
It is neither a data structure nor it stores data.
Take an example of a river stream, where water flows from source to
destination. Similarly, these are data streams; data flows through one
point to another.

To handle these sequences, we introduce a term called IO streams.

The java.io package helps the user to perform all types of input-output
operations.
Java IO package is primarily focused on input-output files, network
streams, internal memory buffers, etc.
Data is read and written from Java
IO's InputStream and OutputStream classes.
In other words, IO streams in java help to read the data from an input
stream such as a file and write the data into an output stream such as the
standard display or a file again.
It represents source as input and destination as output. It can handle all
types of data, from primitive values to advanced objects.

There are 3 categories of classes in java.io package:

Input Streams.
Output Streams.
Error Streams.

Java supports three streams that are automatically attached with the console.

1. System.out: Standard output stream


2. System.in: Standard input stream
3. System.err: Standard error stream

Input Streams:

As we know input source consists of data that needs to be read in order to


extract information from it.
Input Streams help us to read data from the input source.
It is an abstract class that provides a programming interface for all input
streams.
Input streams are opened implicitly as soon as it is created.
To close the input stream by using the close() method on the source
object.
Output Streams:

The output of the executed program has to be stored in a file for further
use.
Output streams help us to write data to a output source (may be file).
Similarly like input streams output streams are also abstract classes that
provides a programming interface for all output streams.
The output stream is opened as soon as it is created and explicitly closed
by using the close() method.

Error Streams:

Error streams are the same as output streams.


In some ide’s error is displayed in different colors (other than the color of
output color).
It gives output on the console the same as output streams.

Why We Need IO Streams in Java?

In day-to-day work, we do not enter the input into the programs


manually.
Also, the result of the program needs to be stored somewhere for further
use.
So, IO streams in Java provide us with input and output streams that help
us to extract data from the files and write the data into the files.
Normally, we can create, delete, and edit files using Java.io.
In short, all the file manipulation is done using Java IO streams. Java IO
streams also handle user input functionality.

Useful methods of Input Stream:

1. public abstract int read() throws IOException:

The method above helps to return the data of the next byte in the input
stream.
The value returned is between 0 to 255.
If no byte is read, the code returns -1, which indicates the end of the file.

2. public int available() throws IOException:

The method above returns the number of bytes that can be read from
the input stream.

3. public void close() throws IOException:

The method above closes the current input stream and releases any
system resources associated with it.

4. public void mark(int readlimit):

It marks the current position in the input stream.


The readlimit argument tells the input stream to read that many bytes to
read before the mark position gets invalid.

5. public boolean markSupported():

It tells whether the mark() and reset() method is supported in a particular


input stream.
It returns true if the mark and reset methods are supported by the
particular input stream or else return false.

6. public int read(byte[ ] b) throws IOException;

The method above reads the bytes from the input stream and stores every
byte in the buffer array.
It returns the total number of bytes stored in the buffer array.
If there is no byte in the input stream, it returns -1 as the stream is at the
end of the file.
7. public int read(byte[ ] b , int off , len) throws IOException:

It reads up to len bytes of data from the input stream.


It returns the total number of bytes stored in the buffer.
Here the “off” is start offset in buffer array b where the data is written,
and the “len” represents the maximum number of bytes to read.

8. public void reset() throws IOException:

It repositions the stream to the last called mark position.


The reset method does nothing for input stream class except throwing an
exception.

9. public long skip(long n) throws IOException:

Output Stream:

It is an abstract superclass of the java.io package and writes data to an


output resource.
In other words, writing the data into the files.
We can create an object of the output stream class using
the new keyword.
The output stream class has several types of constructors.

Useful methods of OutputStream:

1. public void close() throws IOException:

This method closes the current output stream and releases any system
resources associated with it.
The closed stream cannot be reopened and operations cannot be
performed within it.
2. public void flush() throws IOException:

It flushes the current output stream and forces any buffered output to be
written out.

3. Public void write(byte[ ] b) throws IOException:

This method writes the b.length bytes from the specified byte array to the output
stream.

4. Public void write (byte[ ] b ,int off ,int len) throws IOException:

It writes upto len bytes of data to the output stream.


Here the “off” is the start offset in buffer array b, and the “len” represents
the maximum number of bytes to be written in the output stream.

5. Public abstract void write(int b) throws IOException.

The method above writes the specific bytes to the output stream. It
does not return a value.
Topics:7

Java.lang package in Java

1. Boolean:
The Boolean class wraps a value of the primitive type
boolean in an object.

2. Byte:
The Byte class wraps a value of primitive type byte in an
object.
3. Character – Set 1, Set 2:
The Character class wraps a value of the
primitive type char in an object.

4. Character.Subset:
Instances of this class represent particular subsets
of the Unicode character set.

5. Character.UnicodeBlock:
A family of character subsets
representing the character blocks in the Unicode specification.

6. Class – Set 1, Set 2 :


Instances of the class Class represent classes
and interfaces in a running Java application.

7. ClassLoader:
A class loader is an object that is responsible for
loading classes.

8. ClassValue:
Lazily associate a computed value with (potentially)
every type.

9. Compiler:
The Compiler class is provided to support Java-to-native-
code compilers and related services.

10. Double:
The Double class wraps a value of the primitive type double
in an object.
11. Enum:
This is the common base class of all Java language
enumeration types.

12. Float:
The Float class wraps a value of primitive type float in an
object.

13. InheritableThreadLocal:
This class extends ThreadLocal to provide
inheritance of values from parent thread to child thread: when a child
thread is created, the child receives initial values for all inheritable
thread-local variables for which the parent has values.

14. Integer :
The Integer class wraps a value of the primitive type int in
an object.

15. Long:
The Long class wraps a value of the primitive type long in an
object.
16. Math – Set 1, Set 2:
The class Math contains methods for performing
basic numeric operations such as the elementary exponential,
logarithm, square root, and trigonometric functions.

17. Number:
The abstract class Number is the superclass of classes
BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, and
Short.

18. Object:
Class Object is the root of the class hierarchy.

19. Package:
Package objects contain version information about the
implementation and specification of a Java package.

20. Process:
The ProcessBuilder.start() and Runtime.exec methods
create a native process and return an instance of a subclass of
Process that can be used to control the process and obtain
information about it.
21. ProcessBuilder:
This class is used to create operating system
processes.

22. ProcessBuilder.Redirect:
Represents a source of subprocess input or
a destination of subprocess output.

23. Runtime:
Every Java application has a single instance of class
Runtime that allows the application to interface with the
environment in which the application is running.

24. RuntimePermission:
This class is for runtime permissions.

25. SecurityManager:
The security manager is a class that allows
applications to implement a security policy.

26. Short:
The Short class wraps a value of primitive type short in an
object.

27. StackTraceElement:
An element in a stack trace, as returned by
Throwable.getStackTrace().

28. StrictMath- Set1, Set2:


The class StrictMath contains methods for
performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions.

29. String- Set1, Set2:


The String class represents character strings.
30. StringBuffer:
A thread-safe, mutable sequence of characters.
31. StringBuilder:
A mutable sequence of characters.
32. System:
The System class contains several useful class fields and
methods.

33. Thread:
A thread is a thread of execution in a program.

34. ThreadGroup:
A thread group represents a set of threads.

35. ThreadLocal:
This class provides thread-local variables.

36. Throwable:
The Throwable class is the superclass of all errors and
exceptions in the Java language.

37. Void:
The Void class is an uninstantiable placeholder class to hold a
reference to the Class object representing the Java keyword void.
Example:
public class Main
{
public static void main(String[] args)
{
// Creating objects
Boolean bool = new Boolean("False");
Byte by = new Byte("0001");
Character character = new Character('a');
Double doub = new Double("1.25");
Float fl = new Float("1.1");
Integer integer = new Integer("10");
Long l = new Long("1000000");
//printing result
System.out.println("Boolean: " + bool);
System.out.println("Byte: " + by);
System.out.println("Character: " + character);
System.out.println("Double: " + doub);
System.out.println("Float: " + fl);
System.out.println("Integer: " + integer);
System.out.println("Long: " + l);
}
}

Output:
Boolean: false
Byte: 1
Character: a
Double: 1.25
Float: 1.1
Integer: 10
Long: 1000000
Topics:8
Java.util Package:
1. AbstractCollection:
This class provides a skeletal implementation
of the Collection interface, to minimize the effort required to
implement this interface.

2. AbstractList:
This class provides a skeletal implementation of the
List interface to minimize the effort required to implement this
interface backed by a “random access” data store (such as an array).

3. AbstractMap<K,V>:
This class provides a skeletal implementation
of the Map interface, to minimize the effort required to implement
this interface.

4. AbstractMap.SimpleEntry<K,V>:
An Entry maintaining a key and
a value.

5. AbstractMap.SimpleImmutableEntry<K,V>:
An Entry
maintaining an immutable key and value.

6. AbstractQueue:
This class provides skeletal implementations of
some Queue operations.

7. AbstractSequentialList:
This class provides a skeletal
implementation of the List interface to minimize the effort required
to implement this interface backed by a “sequential access” data
store (such as a linked list).

8. AbstractSet:
This class provides a skeletal implementation of the
Set interface to minimize the effort required to implement this
interface.
9. ArrayDeque:
Resizable-array implementation of the Deque
interface.

10. ArrayList:
Resizable-array implementation of the List interface.

11. Arrays:
This class contains various methods for manipulating arrays
(such as sorting and searching).

12. BitSet:
This class implements a vector of bits that grows as needed.

13. Calendar:
The Calendar class is an abstract class that provides
methods for converting between a specific instant in time and a set
of calendar fields such as YEAR, MONTH, DAY_OF_MONTH,
HOUR, and so on, and for manipulating the calendar fields, such as
getting the date of the next week.

14. Collections:
This class consists exclusively of static methods that
operate on or return collections.
15. Currency:
Represents a currency.
16. Date:
The class Date represents a specific instant in time, with
millisecond precision.
17. Dictionary<K,V>:
The Dictionary class is the abstract parent of
any class, such as Hashtable, which maps keys to values.
18. EnumMap,V>:
A specialized Map implementation for use with
enum type keys.
19. EnumSet:
A specialized Set implementation for use with enum types.

20. EventListenerProxy:
An abstract wrapper class for an
EventListener class which associates a set of additional parameters
with the listener.
21. EventObject:
The root class from which all event state objects shall
be derived.
22. FormattableFlags:
FomattableFlags are passed to the
Formattable.formatTo() method and modify the output format for
Formattables.
23. Formatter:
An interpreter for printf-style format strings.
24. GregorianCalendar:
GregorianCalendar is a concrete subclass of
Calendar and provides the standard calendar system used by most of
the world.
25. HashMap<K,V>:
Hash table based implementation of the Map
interface.
26. HashSet:
This class implements the Set interface, backed by a hash
table (actually a HashMap instance).
27. Hashtable<K,V>:
This class implements a hash table, which maps
keys to values.
28. IdentityHashMap<K,V>:
This class implements the Map interface
with a hash table, using reference-equality in place of object-equality
when comparing keys (and values).
29. LinkedHashMap<K,V>:
Hash table and linked list implementation
of the Map interface, with predictable iteration order.
30. LinkedHashSet:
Hash table and linked list implementation of the
Set interface, with predictable iteration order.
31. LinkedList:
Doubly-linked list implementation of the List and
Deque interfaces.
32. ListResourceBundle:
ListResourceBundle is an abstract subclass
of ResourceBundle that manages resources for a locale in a
convenient and easy to use list.
33. Locale – Set 1, Set 2:
A Locale object represents a specific
geographical, political, or cultural region.
34. Locale.Builder:
Builder is used to build instances of Locale from
values configured by the setters.
35. Objects:
This class consists of static utility methods for operating
on objects.
36. Observable:
This class represents an observable object, or “data” in
the model-view paradigm.
37. PriorityQueue:
An unbounded priority queue based on a priority
heap.
38. Properties:
The Properties class represents a persistent set of
properties.
39. PropertyPermission:
This class is for property permissions.
40. PropertyResourceBundle:
PropertyResourceBundle is a concrete
subclass of ResourceBundle that manages resources for a locale
using a set of static strings from a property file.
41. Random:
An instance of this class is used to generate a stream of
pseudorandom numbers.
42. ResourceBundle:
Resource bundles contain locale-specific objects.
43. ResourceBundle.Control:
ResourceBundle.Control defines a set of
callback methods that are invoked by the ResourceBundle.getBundle
factory methods during the bundle loading process.
44. Scanner:
A simple text scanner which can parse primitive types and
strings using regular expressions.
45. ServiceLoader:
A simple service-provider loading facility.
46. SimpleTimeZone:
SimpleTimeZone is a concrete subclass of
TimeZone that represents a time zone for use with a Gregorian
calendar.
47. Stack:
The Stack class represents a last-in-first-out (LIFO) stack of
objects.
48. StringTokenizer:
The string tokenizer class allows an application
to break a string into tokens.
49. Timer:
A facility for threads to schedule tasks for future execution
in a background thread.
50. TimerTask:
A task that can be scheduled for one-time or repeated
execution by a Timer.
51. TimeZone:
TimeZone represents a time zone offset, and also figures
out daylight savings.
52. TreeMap<K,V>:
A Red-Black tree based NavigableMap
implementation.

53. TreeSet:
A NavigableSet implementation based on a TreeMap.
54. UUID:
A class that represents an immutable universally unique
identifier (UUID).
55. Vector:
The Vector class implements a growable array of objects.
56. WeakHashMap<K,V>:
Hash table based implementation of the
Map interface, with weak keys.

Topics:9

Wrapper classes in Java:

The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.

autoboxing and unboxing feature convert primitives into objects and


objects into primitives automatically.
The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.

The eight classes of the java.lang package are known as wrapper classes in
Java. The list of eight wrapper classes are given below:
Use of Wrapper classes in Java:

Change the value in Method:

Java supports only call by value. So, if we pass a primitive value, it will
not change the original value. But, if we convert the primitive value in an
object, it will change the original value.

Serialization:

We need to convert the objects into streams to perform the serialization. If


we have a primitive value, we can convert it in objects through the wrapper
classes.

Synchronization:

Java synchronization works with objects in Multithreading.

java.util package:

The java.util package provides the utility classes to deal with objects.

Collection Framework:

Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with
objects only.
Autoboxing:

The automatic conversion of primitive data type into its


corresponding wrapper class is known as autoboxing,

Example:

byte to Byte,
char to Character,
int to Integer,
long to Long,
float to Float,
boolean to Boolean,
double to Double and
short to Short.

Example:

class WrapperClass
{
public static void main(String args[])
{
//Converting int into Integer
int a=50;
Integer i=Integer.valueOf(a); //converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internal
ly
System.out.println(a +" "+ I +" "+ j );
}
}
Output:
50 50 50
Unboxing:

The automatic conversion of wrapper type into its corresponding primitive


type is known as unboxing.
It is the reverse process of autoboxing.
Since Java 5, we do not need to use the intValue () method of wrapper
classes to convert the wrapper type into primitives.

public class WrapperClass1


{
public static void main(String args[])
{
//Converting Integer to int
Integer a=new Integer(100);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
System.out.println(a +" " + i + " " + j );
}
}

Output:
100 100 100
Example:
public class WrapperExample3
{
public static void main(String args[])
{
byte b=100;
short s=1500;
int i=200;
long l=250;
float f=350.0F;
double d=400.0D;
char c='c';
boolean b2=true;
//Autoboxing: Converting primitives into objects
Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
System.out.println("***Printing object values***");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);
//Unboxing: Converting Objects to Primitives
byte bytevalue=byteobj;
short shortvalue=shortobj;
int intvalue=intobj;
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("*-*-*-*Printing primitive values-*-*-*");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}
}

Output:

***Printing object values***


Byte object: 10
Short object: 20
Integer object: 30
Long object: 40Float object: 50.0
Double object: 60.0
Character object: b
Boolean object: true
*-*-*-*Printing primitive values-*-*-*
byte value: 10short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: b
boolean value: true

*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*-*
Topics:10

Enumerations in java:
An enumeration (enum for short) in Java is a special
data type which contains a set of predefined constants.

The Enum in Java is a data type which contains a fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,


WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY).

Directions (NORTH, SOUTH, EAST, and WEST).

colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.

Java Enums can be thought of as classes which have a fixed set of


constants (a variable that does not change).
The Java enum constants are static and final implicitly.
Enums are used to create our own data type like classes.
The enum data type (also known as Enumerated Data Type) is used to
define an enum in Java.
Example:
class EnumExample1
{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER }
//creating the main method
public static void main(String[] args)
{
//printing all enum
for (Season s : Season.values())
{
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").
ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").
ordinal());
}
}

Output:
WINTER
SPRING
SUMMER
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Example: 2
enum players
{
sachin, dravid, virat, dhoni;
}
public class A
{
public static void main(String[] args)
{
players a1 = players.virat;

switch(a1)
{
case sachin:
System.out.println("Sachin is best bastman ever");
break;

case dravid:
System.out.println("Dravid is the best Test Batsman");
break;

case virat:
System.out.println("Virat is a Stylish Batsmen");
break;

case dhoni:
System.out.println("Dhoni is the best captain ever");
break;

}
}

Output:
Virat is a Stylish Batsmen
Example:3
enum players
{
sachin, virat, dhoni;
}
public class A
{
public static void main(String[] args)
{
players a1 = players.dhoni;
if(a1 == players.virat || a1 == players.sachin)
{
System.out.println("Sachin and Virat are greatest batsmen");
}
else
{
System.out.println("Dhoni is the best Captain");
}
}
}
Output:
Dhoni is the best Captain
Example:4
enum games
{
ludo, Chess, Badminton, Cricket;
}
public class A
{
public static void main(String[] args)
{
System.out.println("Using for each loop");
for (games index:games.values())
{
System.out.println(index);
}
}
}
Output:
Using for each loop
ludo
Chess
Badminton
Cricket
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**-*
End of The Chapter
Chapter: 7
Discuss about the String Class in Java

A string is a character or sequence of characters,


String is fixed length character it does not changed during the execution
of the program.
A character array is simply an array of characters that can be terminated
by a null character.
In the case of strings, memory is allocated dynamically.
a string is a class that defines objects that be represented as a stream of
characters.

The java.lang.String class provides many useful methods to perform


operations on sequence of char values.

What is String and How to create a string object 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.

Syntax:
<String_Type> <string_variable> = "<sequence_of_string>";

Example:

String str = "Parul";


String str = "Parul University";
The string can also be declared using a new operator i.e. dynamically
allocated.
In case of String are dynamically allocated they are assigned a new
memory location in the heap.
This string will not be added to String constant pool.

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal:

Java String literal is created by using double quotes.

For Example:

To make Java more memory efficient (because no new objects are


created if it exists already in the string constant pool).

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
The above example, only one object will be created.
Firstly, JVM will not find any string object with the value "Welcome" in
string constant pool that is why it will create a new object.
After that it will find the string with the value "Welcome" in the pool,
it will not create a new object but will return the reference to the same
instance.

Types of Literals in Java:


There are the majorly four types of literals in Java:
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

1.Integer Literals:

Integer literals are sequences of digits. There are three types of integer literals:

Decimal Integer:
These are the set of numbers that consist of digits from 0
to 9. It may have a positive (+) or negative (-) Note that between numbers
commas and non-digit characters are not permitted. For example, 5678,
+657, -89, etc.

Ex: int decVal = 26;


Octal Integer:
It is a combination of number have digits from 0 to 7 with
a leading 0. For example, 045, 026,

Ex:
int octVal = 067;
Hexa-Decimal:
The sequence of digits preceded by 0x or 0X is considered
as hexadecimal integers. It may also include a character
from a to f or A to F that represents numbers from 10 to 15, respectively.
For example, 0xd, 0xf,

Ex:
int hexVal = 0x1a;
Binary Integer:
Base 2, whose digits consists of the numbers 0 and 1 (you
can create binary literals in Java SE 7 and later). Prefix 0b represents the
Binary system. For example, 0b11010

Ex:
int binVal = 0b11010;

Character Literals:

A character literal is expressed as a character or an escape


sequence, enclosed in a single quote ('') mark. It is always a type of char.

For example:
'a', '%', '\u000d', etc.

String Literals:

String literal is a sequence of characters that is enclosed


between double quotes ("") marks. It may be alphabet, numbers, special
characters, blank space, etc.

For example:

"Jack", "12345", "\n", etc.


Boolean Literals:

Boolean literals are the value that is either true or false. It may
also have values 0 and 1. For example, true, 0, etc.

Ex:
boolean isEven = true;

Example:
public class Main
{
public static void main(String[] args)
{
//String literals
String testString1 = "Welcome";
String testString2 = "Welcome";
System.out.println(testString1 == testString2); // true
//String Object
testString2 = new String("Wel");
System.out.println(testString1 == testString2); // false
System.out.println(testString1.equals(testString2)); // false
}
}
Output:
true
false
false
2) By new keyword:

VM will create a new string object in normal (non-pool) heap memory,


the literal "Welcome" will be placed in the string constant pool.
the variable s will refer to the object in a heap

String str = new String("Parul University");

Example:

public class StringExample


{
public static void main(String args[])
{
String s1="CSE";//creating string by Java string literal
char ch[]={'D','e','p','t'};
String s2=new String(ch);//converting char array to string
String s3=new String("Parul University");
//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output:
CSE
Dept
Parul University
Example:

import java.io.*;
import java.lang.*;
class Test
{
public static void main(String[] args)
{
// Declare String without using new operator
String s = "PARUL UNIVERSITY @ VADODARA";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("Dept of CSE @ PARUL ");
System.out.println("String s1 = " + s1); // Prints the String
}
}
Output:

String s = PARUL UNIVERSITY @ VADODARA

String s1 = Dept of CSE @ PARUL


Example: 2
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myObj = new Scanner(System.in);
System.out.println("Enter Name, Age and Salary:");
// String input
String name = myObj.nextLine();
// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + Name);
System.out.println("");
System.out.println("Age: " + Age);
System.out.println("Salary: " + Salary);
}
}
Output:
Enter Name, Age and Salary:
Bavvy
21
50000
Name: Bavvy
Age: 21
Salary: 50000.0
String Methods:

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, It returns formatted string


Object... args) 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, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence> elements)

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, It replaces all occurrences of


CharSequence new) 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.
String Buffer Class:

Java StringBuffer class is used to create mutable (modifiable) String


objects.
We can insert character and substring in the middle of the String
The StringBuffer class in Java is the same as String class except it is
mutable i.e. it can be changed.

Constructors of StringBuffer Class

Constructor Description

StringBuffer() It creates an empty String buffer with the initial capacity


of 16.

StringBuffer(String str) It creates a String buffer with the specified string..

StringBuffer(int capacity) It creates an empty String buffer with the specified


capacity as length.
Methods of String Buffer class:

Modifier and Method Description


Type

public append(String s) It is used to append the specified string


synchronized with this string. The append() method
StringBuffer is overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, It is used to insert the specified string


synchronized String s) with this string at the specified
StringBuffer position. The insert() method is
overloaded like insert(int, char),
insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int It is used to replace the string from


synchronized startIndex, int specified startIndex and endIndex.
StringBuffer endIndex, String str)

public delete(int startIndex, It is used to delete the string from


synchronized int endIndex) specified startIndex and endIndex.
StringBuffer

public
synchronized reverse() It is used to reverse the string.
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least


minimumCapacity) equal to the given minimum.

public char charAt(int index) It is used to return the character at the


specified position.

public int length() It is used to return the length of the


string i.e. total number of characters.

public String substring(int It is used to return the substring from the


beginIndex) specified beginIndex.
substring(int It is used to return the substring from
public String beginIndex, int the specified beginIndex and endIndex.
endIndex)
Examples:

1) StringBuffer Class append() Method:

The append() method concatenates the given argument with this String

class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Dept of CSE"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}
Output:

Hello Dept of CSE

2) StringBuffer insert() Method

the insert() method inserts the given String with this string at the given position.

class StringBufferExample2
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:

HJavaello
3) StringBuffer replace() Method

the replace() method replaces the given String from the specified beginIndex and
endIndex.

class StringBufferExample3
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:
HJavalo

4) StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.

class StringBufferExample4
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.

class StringBufferExample5
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

Output:
olleH
6) StringBuffer capacity() Method

the capacity() method of the StringBuffer class returns the current


capacity of the buffer.
The default capacity of the buffer is 16.
If the number of character increases from its current capacity, it
increases the capacity by (oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.

class StringBufferExample6
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
Output:
16
16
34
7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the


given capacity is the minimum to the current capacity.
If it is greater than the current capacity, it increases the capacity by
(oldcapacity*2)+2.
For example if your current capacity is 16, it will be (16*2)+2=34.

Class StringBufferExample7
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append(“Hello”);
System.out.println(sb.capacity());//now 16
sb.append(“java is my favourite language”);
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
Output:
16
16
34
34
70
Note:

String Vs StringBuffer Vs StringBuilder In Java

String objects are immutable whereas StringBuffer and StringBuilder


objects are mutable.
StringBuffer and StringBuilder are same only difference is that
StringBuilder is not synchronized whereas StringBuffer is. As
StringBuilder is not synchronized, it is not thread safe but faster than
StringBuffer.
Use String, for a string which will be constant through out the
application.
Use StringBuffer, for a string which can change in multi-threaded
applications.
Use StringBuilder, for a string which can change in single-threaded
applications.
Example:1
public class Main
{
long startTime = 01;
long endTime = 01;
long timeDiff = 01;
// Concatenate operation using String
public void concatTest1(String website)
{
startTime = System.nanoTime();
website = website + ".com";
endTime = System.nanoTime();
timeDiff = endTime - startTime;
System.out.println("Concat time by String: " + timeDiff);
}
// Concatenate operation using StringBuilder
public void concatTest2(StringBuilder website)
{
startTime = System.nanoTime();
website.append(".com");
endTime = System.nanoTime();
timeDiff = endTime - startTime;
System.out.println("Concat time by StringBuilder: " + timeDiff);
}
// Concatenate operation using StringBuffer
public void concatTest3(StringBuffer website)
{
startTime = System.nanoTime();
website.append(".com");
endTime = System.nanoTime();
timeDiff = endTime - startTime;
System.out.println("Concat time by StringBuffer: " + timeDiff);
}
public static void main(String[] args)
{
Main object = new Main();
String website1 = "parul";
object.concatTest1(website1);
StringBuilder website2 = new StringBuilder("parul");
object.concatTest2(website2);
StringBuffer website3 = new StringBuffer("parul");
object.concatTest3(website3);
}
}

Output:

Concat time by String: 71484481


Concat time by StringBuilder: 7101
Concat time by StringBuffer: 3627
Example:1
Conversion between types of strings in Java

String to StringBuffer and StringBuilder

public class Main


{
public static void main(String[] args)
{
String stringObj = "paruluniversity";
System.out.println("String Object: " + stringObj);
// String to StringBuffer
StringBuffer stringBuffer = new StringBuffer(stringObj);
System.out.println("StringBuffer Object: " + stringBuffer);
stringBuffer.reverse();
System.out.println("StringBuffer Object after reverse operation: " +
stringBuffer);
//String to StringBuilder
StringBuilder stringBuilder = new StringBuilder(stringObj);
System.out.println("StringBuilder Object: " + stringBuilder);
stringBuilder.append(".com");
System.out.println("StringBuilder Object after append operation: " +
stringBuilder);
}
}
Output:
String Object: paruluniversity
StringBuffer Object: paruluniversity
StringBuffer Object after reverse operation: ytisrevinulurap
StringBuilder Object: paruluniversity
StringBuilder Object after append operation: paruluniversity.com
Example:3

StringBuffer and StringBuilder to String

public class Parul


{
void stringBufferToString(StringBuffer stringBuffer)
{
String stringObj = stringBuffer.toString();
System.out.println("Converted String from StringBuffer: " + stringObj);
}
void stringBuilderToString(StringBuilder stringBuilder){
String stringObj = stringBuilder.toString();
System.out.println("Converted String from StringBuilder: " + stringObj);
}
public static void main(String[] args)
{
StringBuffer stringBuffer = new StringBuffer("Dept of CSE");
StringBuilder stringBuilder = new StringBuilder("Dept of CSE @ Parul");
Parul University = new Parul();
University.stringBufferToString(stringBuffer);
University.stringBuilderToString(stringBuilder);
}
}

Output:
Converted String from StringBuffer: Dept of CSE
Converted String from StringBuilder: Dept of CSE @ Parul
Example:4

StringBuffer to StringBuilder or StringBuilder to StringBuffer

public class Main


{
void stringBufferToStringBuilder(StringBuffer stringBuffer)
{
String stringObj = stringBuffer.toString();
StringBuilder stringBuilder = new StringBuilder(stringObj);
System.out.println("Converted StringBuilder from StringBuffer: " +
stringObj);
}
void stringBuilderToStringBuffer(StringBuilder stringBuilder){
String stringObj = stringBuilder.toString();
StringBuffer stringBuffer = new StringBuffer(stringObj);
System.out.println("Converted StringBuffer from StringBuilder: " +
stringObj);
}
public static void main(String[] args)
{
StringBuffer stringBuffer = new StringBuffer("Parul");
StringBuilder stringBuilder = new StringBuilder("Parul University");
Main obj = new Main();
obj.stringBufferToStringBuilder(stringBuffer);
obj.stringBuilderToStringBuffer(stringBuilder);
}
}
Output:
Converted StringBuilder from StringBuffer: Parul
Converted StringBuffer from StringBuilder: Parul University

End of the Chapter


Chapter:8
Exception Handling:

An exception is an unexpected event that occurs during program


execution.
It affects the flow of the program instructions which can cause the
program to terminate abnormally.
An exception can occur for many reasons. Some of them are:

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

Exception Hierarchy:

All exception and error types are subclasses of class Throwable, which
is the base class of the hierarchy.
One branch is headed by Exception.
This class is used for exceptional conditions that user programs should
catch.
NullPointerException is an example of such an exception.
Another branch, Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time environment itself(JRE).
StackOverflowError is an example of such an error.
Types of Java Exceptions:

There are mainly two types of exceptions:


checked and unchecked.
An error is considered as the unchecked exception.
According to Oracle, there are two types of exceptions namely:
Exceptions can be categorized in two ways:

1) Built-in Exceptions
 Checked Exception
 Unchecked Exception

2).User-Defined Exceptions

Built-in Exceptions:

Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
The built-in-exceptions are classified into two types Checked exception
and unchecked exception.

1.Checked Exceptions:

Checked exceptions are called compile-time exceptions


Because these exceptions are checked at compile-time by the compiler.
Checked exception is also called IO exceptions.
Example:
import java.io.*;
class SCE // Main class
{
public static void main(String args[]) // Main driver method
{
// Reading content from file by passing local directory path
// where file should exists
FileInputStream CSE = new FileInputStream("/Desktop/CSE.txt");
// This file does not exist in the location
// This constructor FileInputStream
// throws FileNotFoundException which
// is a checked exception
}
}
Output:
javac /tmp/ekGroR0BeB/CSE.java
/tmp/ekGroR0BeB/CSE.java:16: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
= new FileInputStream("/Desktop/GFG.txt");
^
1 error

2.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.

Example:

import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
Output:

javac /tmp/ekGroR0BeB/FilenotFound_Demo.java
/tmp/ekGroR0BeB/FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

3) Error:

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Example:

public class ErrorExample


{
public static void main(String args[])
{
//method calling
recursiveDemo(10);
}
public static void recursiveDemo(int i)
{
while(i !=0)
{
//increments the variable i by 1
i=i+1;
//recursive called method
recursiveDemo(i);
}
}
}
Output:

java -cp /tmp/ekGroR0BeB ErrorExample


Exception in thread "main" java.lang.StackOverflowError
at ErrorExample.recursiveDemo(ErrorExample.java:15)
at ErrorExample.recursiveDemo(ErrorExample.java:15)
at ErrorExample.recursiveDemo(ErrorExample.java:15)
at ErrorExample.recursiveDemo(ErrorExample.java:15)
……………………………………………………………

……………………………………………………………

at ErrorExample.recursiveDemo(ErrorExample.java:15)

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’.
Example:
class MyException extends Exception
{
}
// A Class that uses above MyException
public class setText
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}

Output:
Caught
Null
Java Exception Keywords:
Java provides five keywords that are used to handle the exception.

Keyword Description

The "try" keyword is used to specify a block where we should place an


try exception code. It means we can't use try block alone. The try block must
be followed by either catch or finally.

The "catch" block is used to handle the exception. It must be preceded by


catch try block which means we can't use catch block alone. It can be followed
by finally block later.

finally The "finally" block is used to execute the necessary code of the program.
It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

The "throws" keyword is used to declare exceptions. It specifies that there


throws may occur an exception in the method. It doesn't throw an exception. It is
always used with method signature.
Example Program:1

Exception handling using try...catch

public class JavaExceptionExample


{
public static void main(String args[])
{
try
{
int data=100/0; //code that may raise exception
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:
java.lang.ArithmeticException:
/ by zero rest of the code...
Example Program:2 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("Finally Block Completed Successfully");
}
}
}
Output:
ArithmeticException => / by zero
This is the finally block
Example Program:3

Exception handling using Java throw


import java.io.*;
class Main
{
// declareing the type of exception
public static void findFile() throws IOException
{
// code that may generate IOException
File newFile = new File("test.txt");
FileInputStream stream = new FileInputStream(newFile);
}
public static void main(String[] args)
{
try
{
findFile();
}
catch (IOException e)
{
System.out.println(e);
}
}
}

Output:

java.io.FileNotFoundException: test.txt (No such file or directory)


Exception handling using Java throw

Example:4

public class Main


{
static void checkAge(int age)
{
if (age < 21)
{
throw new ArithmeticException("Access denied - You must be at
least 22 years old.");
}
else
{
System.out.println("Access Granted - You are Eligible for Indian
Civil Services");
}
}
public static void main(String[] args)
{
checkAge(15); // Set age to 15 (which is below 21...)
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException:
Access denied - You must be
at least 22 years old.
at Main.checkAge(Main.java:7)
at Main.main(Main.java:16)
Example:5

public class TestThrow


{
//defining a method
public static void checkNum(int num)
{
if (num < 1)
{
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else
{
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args)
{
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}

Output:
Exception in thread "main" java.lang.ArithmeticException:
Number is negative, cannot calculate square
at TestThrow.checkNum(TestThrow.java:5)
at TestThrow.main(TestThrow.java:14)
Example:6

public class TestThrows


{
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
//main method
public static void main(String[] args)
{
TestThrows obj = new TestThrows();
try
{
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e)
{
System.out.println("\nNumber cannot be divided by 0");
}
System.out.println("Rest of the code..");
}
}

Output:
Number cannot be divided by 0
Rest of the code..
Example:6
public class TestThrowAndThrows
{
// defining a user-defined method
// which throws ArithmeticException
static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}
End of the Chapter
Chapter: 9
Threads:

What is a Thread in Java?


A thread in Java is the direction or path that is taken while a program is
being executed.
Generally, all the programs have at least one thread, known as the main
thread,
that is provided by the JVM or Java Virtual Machine at the starting of the
program’s execution.
At this point, when the main thread is provided, the main() method is
invoked by the main thread.
A thread is an execution thread in a program.
Multiple threads of execution can be run concurrently by an application
running on the Java Virtual Machine.
The priority of each thread varies. Higher priority threads are executed
before lower priority threads.
Thread is critical in the program because it enables multiple operations to
take place within a single method.
Each thread in the program often has its own program counter, stack, and
local variable.

Uses of Threads:

java Threads Threads allows a program to operate more efficiently by


doing multiple things at the same time. ...
Creating a Thread There are two ways to create a thread. ...
Running Threads If the class extends the Thread class, the thread can be
run by creating an instance of the class and call its start () method: ...

1
Life cycle of a Thread in Java:(Imp)

The Life Cycle of a Thread in Java refers to the state transformations of a


thread that begins with its birth and ends with its death.
When a thread instance is generated and executed by calling the start()
method of the Thread class,
the thread enters the runnable state.
When the sleep() or wait() methods of the Thread class are called, the
thread enters a non-runnable mode.
Thread returns from non-runnable state to runnable state and starts
statement execution.
The thread dies when it exits the run() process. In Java, these thread state
transformations are referred to as the Thread life cycle.

There are basically 5 stages in the lifecycle of a thread, as given below:

1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead

2
1.New State: Born State:

As we use the Thread class to construct a thread entity,

the thread is born and is defined as being in the New state.

That is, when a thread is created, it enters a new state, but the start()
method on the instance has not yet been invoked.

2.Runnable State:

A thread in the runnable state is prepared to execute the code.

When a new thread's start() function is called, it enters a runnable state.

In the runnable environment, the thread is ready for execution and is


awaiting the processor's availability (CPU time).

That is, the thread has entered the queue (line) of threads waiting for
execution.

3.Running State:

Running implies that the processor (CPU) has assigned a time slot to the
thread for execution.
When a thread from the runnable state is chosen for execution by the
thread scheduler, it joins the running state.
In the running state, the processor allots time to the thread for execution
and runs its run procedure.
This is the state in which the thread directly executes its operations.
Only from the runnable state will a thread enter the running state.

3
4.Blocked State:

When the thread is alive, i.e., the thread class object persists,

but it cannot be selected for execution by the scheduler.

It is now inactive.

5.Dead State:

When a thread's run() function ends the execution of sentences,

it automatically dies or enters the dead state.

That is, when a thread exits the run() process, it is terminated or killed.

When the stop() function is invoked, a thread will also go dead.

4
Types of Threads:
How many types of threads are there in Java?
There are two types of threads in an application - User thread and daemon
thread.

Java offers two types of threads:


The threads are classified into user threads and daemon threads.
User threads are high-priority threads.
The JVM will wait for any user thread to complete its task before
terminating it.
On the other hand, daemon threads are low-priority threads whose only
role is to provide services to user threads.

Threads

User Thread daemon threads

1) User Thread :

User threads are threads which are created by the application or user.
They are high priority threads.
JVM (Java Virtual Machine) will not exit until all user threads finish their
execution.
JVM wait for these threads to finish their task.
These threads are foreground threads.

5
2)Daemon Thread:

Daemon threads are threads which are mostly created by the JVM.
These threads always run in background.
These threads are used to perform some background tasks like garbage
collection and house-keeping tasks.
These threads are less priority threads.
JVM will not wait for these threads to finish their execution.
JVM will exit as soon as all user threads finish their execution.
JVM doesn’t wait for daemon threads to finish their task.

Commonly used Constructors of Thread class:


1. Thread()
2. Thread(String name)
3. Thread(Runnable r)
4. Thread(Runnable r, String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run()
method on the thread.
3. public void sleep(long miliseconds): Causes the currently executing
thread to sleep (temporarily cease execution) for the specified number of
milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the
specified miliseconds.
6. public int getPriority(): returns the priority of the thread.
6
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently
executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to
temporarily pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user
thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been
interrupted.

7
Creating a Thread in Java:

A thread in Java can be created in the following two ways:


1.Extending java.lang.Thread class
2. Implementing Runnable interface

1.Extending java.lang.Thread class:

In this case, a thread is created by a new class that extends the Thread
class, creating an instance of that class.

The run() method includes the functionality that is supposed to be


implemented by the Thread.

Here, start() is used to create a new thread and to make it runnable.

The new thread begins inside the void run() method.(Heart of a Thread)

Example:

class threadEx extends Thread


{
public void run()
{
System.out.println("This is my First Thread and its Running ...");
}
public static void main(String args[])
{
threadEx t1=new threadEx();
t1.start();
}
}
Output:

This is my First Thread and it’s Running ...

8
2.Implementing Runnable interface:

This is the easy method to create a thread among the two.

In this case, a class is created to implement the runnable interface and


then the run() method.

The code for executing the Thread should always be written inside the
run() method.

Example Program:
class ThreadEx2 implements Runnable
{
public void run()
{
System.out.println("My thread is running...");
}
public static void main(String args[])
{
ThreadEx2 Th1=new ThreadEx2();
Thread t1 =new Thread(Th1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Output:

My thread is running...
Note:
If you are not extending the Thread class, your class object would not be treated
as a thread object. So you need to explicitly create the Thread class object. We
are passing the object of your class that implements Runnable so that your class
run () method may execute.

9
3).Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors
defined above.

Example Program:

public class MyThread1


{
// Main method
public static void main(String argvs[])
{
// creating an object of the Thread class using the constructor Thread(String
name)
Thread th= new Thread("My first thread………");
// the start() method moves the thread to the active state
th.start();
// getting the thread name by invoking the getName() method
String str = th.getName();
System.out.println(str);
}
}

Output:

My first thread………

10
4) Using the Thread Class: Thread(Runnable r, String name)

public class MyThread2 implements Runnable


{
public void run()
{
System.out.println("Now the thread is running ....");
}
// main method
public static void main(String argvs[])
{
// creating an object of the class MyThread2
Runnable r1 = new MyThread2();
// creating an object of the class Thread using Thread(Runnable r, String name)
Thread th1 = new Thread(r1, "My new thread");
// the start() method moves the thread to the active state
th1.start();
// getting the thread name by invoking the getName() method
String str = th1.getName();
System.out.println(str);
}
}

Output:

My new thread

Now the thread is running ....

11
Example:

class ThreadLifeCycle implements Runnable


{
public void run()
{

// try-catch block
try
{
// moving thread t2 to the state timed waiting
Thread.sleep(100);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t1 while it invoked the method join() on
thread t2 -"+ ThreadState.t1.getState());

// try-catch block
try
{
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
// ThreadState class implements the interface Runnable
class ThreadState implements Runnable
{
public static Thread t1;
public static ThreadState obj;

// main method
public static void main(String argvs[])
{
// creating an object of the class ThreadState
obj = new ThreadState();

12
t1 = new Thread(obj);

// thread t1 is spawned
// The thread t1 is currently in the NEW state.
System.out.println("The state of thread t1 after spawning it - " + t1.getState());

// invoking the start() method on


// the thread t1
t1.start();

// thread t1 is moved to the Runnable state


System.out.println("The state of thread t1 after invoking the method start() on it
- " + t1.getState());
}

public void run()


{
ThreadLifeCycle myObj = new ThreadLifeCycle();
Thread t2 = new Thread(myObj);

// thread t2 is created and is currently in the NEW state.


System.out.println("The state of thread t2 after spawning it - "+ t2.getState());
t2.start();

// thread t2 is moved to the runnable state


System.out.println("the state of thread t2 after calling the method start() on it - "
+ t2.getState());

// try-catch block for the smooth flow of the program


try
{
// moving the thread t1 to the state timed waiting
Thread.sleep(200);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 after invoking the method sleep() on
it - "+ t2.getState() );

13
// try-catch block for the smooth flow of the program
try
{
// waiting for thread t2 to complete its execution
t2.join();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
System.out.println("The state of thread t2 when it has completed it's execution -
" + t2.getState());
}

}
Output:

The state of thread t1 after spawning it - NEW

The state of thread t1 after invoking the method start() on it - RUNNABLE

The state of thread t2 after spawning it - NEW

the state of thread t2 after calling the method start() on it - RUNNABLE

The state of thread t1 while it invoked the method join() on thread t2 -


TIMED_WAITING

The state of thread t2 after invoking the method sleep() on it -


TIMED_WAITING

The state of thread t2 when it has completed it's execution - TERMINATED

14
Multithreading in Java:
Multithreading in java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve
multitasking.
we use multithreading than multiprocessing because threads use a shared
memory area.
They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Advantages of Java Multithreading:

1) It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
2) You can perform many operations doesn't affect other together, so it

saves time.

3) Threads are independent, so it threads if an exception

occurs in a single thread.

Multitasking:

Multitasking is a process of executing multiple tasks simultaneously.


We use multitasking to utilize the CPU. Multitasking can be achieved in
two ways:

1.Process-based Multitasking (Multiprocessing)

2.Thread-based Multitasking (Multithreading)

15
1. Process-based Multitasking (Multiprocessing)

Each process has an address in memory. In other words, each process


allocates a separate memory area.
A process is heavyweight.
Cost of communication between the process is high.

Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)

Threads share the same address space.


A thread is lightweight.
Cost of communication between the thread is low.

 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:

1. Extending the Thread class


2. Implementing the Runnable Interface

1.Extending the Thread class :

Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class.
This class overrides the run() method available in the Thread class.
A thread begins its life inside run() method.

16
We create an object of our new class and call start() method to start the
execution of a thread.
Start() invokes the run() method on the Thread object.

Example:1

class MultithreadingDemo extends Thread


{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread
{
public static void main(String[] args)
{

17
int n = 10; // Number of threads
for (int i = 0; i < n; i++)
{
MultithreadingDemo object= new MultithreadingDemo();
object.start();
}
}
}

Output:

Thread 17 is running

Thread 13 is running

Thread 10 is running

Thread 16 is running

Thread 18 is running 10 threads

Thread 15 is running Running….

Thread 11 is running

Thread 14 is running

Thread 12 is running

Thread 19 is running

18
2.Implementing the Runnable Interface:

Thread creation by implementing the Runnable Interface.


We create a new class which implements java.lang.Runnable interface
and override run() method.
Then we instantiate a Thread object and call start() method on this
object.

Example:
// Java code for thread creation by extending
// the Thread class

class MultithreadingDemo extends Thread


{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
// Main Class
public class Multithread

19
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}

Output:

Thread 11 is running
Thread 16 is running
Thread 10 is running
Thread 12 is running
Thread 14 is running
Thread 17 is running
Thread 15 is running
Thread 13 is running

20
Example:1

import java.util.Scanner;

class Main

public static void main(String[] args)

// creates an object of Scanner

Scanner input = new Scanner(System.in);

System.out.print("Enter your name: ");

// takes input from the keyboard

String name = input.nextLine();

// prints the name

System.out.println("My name is: " + name);

// closes the scanner

input.close();

Output:

Enter your name: Bavvy

My name is: Bavvy

21
Example:2

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
// creates an object of Scanner
Scanner input = new Scanner(System.in);
System.out.print("Enter your name: ");
// reads the entire line
String Str1 = input.nextLine();
String Str2 = input.nextLine();
String Str3 = input.nextLine();
System.out.println("Using nextLine: " + Str1);
System.out.println("Using nextLine: " + Str2);
System.out.println("Using nextLine: " + Str3);
input.close();
}
}
Output:
Enter your names: Naga Malleswara Rao
Vidhya Bhavani
Bavvy
Using nextLine: Naga Malleswara Rao
Using nextLine: Vidhya Bhavani

Using nextLine: Bavvy

import java.util.Scanner;

22
Example: 3

class Main

public static void main(String[] args)

// creates a Scanner object

Scanner input = new Scanner(System.in);

System.out.println("Enter Your Age..: ");

// reads an int value

int data1 = input.nextInt();

System.out.println("My Age is..: " + data1);

input.close();

Output:

Enter Your Age..: 25


My Age is..: 25
End of the Chapter

23
What is a Collection in Java?

Def:
Collection:
Any group of individual objects are grouped into a single
object is known as Collection.
Frame Work:
Frame work is a set of classes and interface, which provides
ready-made Architecture in order to implement new feature of class.
Collection of Frame Work:
Collection of frame work defined in JDK1.2
in which holds collection of classes and interface in it. It is used to store
and manipulating a group of objects.
in Java collection is a framework that provides an architecture to store and
manipulate the group of objects.
A Collection in Java is an object which represents a group of objects,
known as its elements.
It is a single unit. They are used to standardize the way in which objects
are handled in the class.

What is Java Collections Framework?


The Collections Framework is a hierarchy of classes and interface that
provides an easy management of a group of objects.
The java.util package contains the powerful tool of Collections
Framework.
It provides a ready-made architecture for interfaces and classes and used
for storing and manipulating a group of objects.
It was defined in JDK 1.2 version which is one of the most used
frameworks till date.
All collections framework contains interfaces, classes and algorithms.
Collection in Java Collections Framework
Collection in Java is a class. Collections Framework is a
framework.
It is a single unit which contains They are used to manipulate
and manipulates a group of objects. collections

Differences between the Collection and Collections Framework in Java

The following are the differences between Collection in Java and Collections
Framework.

Advantages of the Collections Framework:

As mentioned above, the Collections Framework in Java carries a lot of


advantages.

Provides high-performance and high efficiency. This is due to the fact


that various implementations of each interface are interchangeable, so
programs can be written by switching implementations.
Some methods of each interface of the Collections Framework have
a uniform implementation.
The Collections API has basic interfaces like Set, Map and List, so the
classes that implement them have a few common set of methods.
Reduces the programming effort by providing useful data structures and
algorithms.
We don't have to write our own data structure as it has already been
provided to us.
Facilitates code reusability. Collections Framework provides common
classes and interfaces that can be used with different types of collections.
Hierarchy of Collections Framework:

Class:
A class is a collection of similar types of objects. It is an implementation
of the collection interface.

Interface:

An interface is the abstract data type.


It is at the topmost position in the framework hierarchy.
it is a group of related method with empty bodies. Abstraction is a process
of hiding the implementation details from the user by only providing the
functionality.
Using interfaces, we can achieve (complete) abstraction.
extends:
It is a keyword which is used to develop inheritance between two
classes and two interfaces. Inheritance in Java refers to the concept that one can
create new classes that are built upon existing classes.
implements:
implements is also a keyword used to develop inheritance between
class and interface. A class implements an interface.

Methods of the Collection Interface:

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

1 public boolean add(E e) It is used to insert an element in this


collection.

2 public boolean It is used to insert the specified collection


addAll(Collection<? extends E> elements in the invoking collection.
c)

3 public boolean remove(Object It is used to delete an element from the


element) collection.

4 public boolean It is used to delete all the elements of the


removeAll(Collection<?> c) specified collection from the invoking
collection.

5 default boolean removeIf It is used to delete all the elements of


(Predicate<? super E> filter) the collection that satisfy the specified
predicate.

6 public boolean It is used to delete all the elements of


retainAll(Collection<?> c) invoking collection except the specified
collection.

7 public int size() It returns the total number of elements in


the collection.
8 public void clear() It removes the total number of elements
from the collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified


containsAll(Collection<?> c) collection in the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 It converts collection into array. Here,


public <T> T[] toArray(T[] a) the runtime type of the returned array is
that of the specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with


parallelStream() the collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the


collection as its source.

17 default Spliterator<E> spliterator() It generates a Spliterator over the


specified elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of the


collection.
Iterator interface:

There are 3 methods in the Iterator interface:

public Object next()- It returns the next element in the collection. It throws
the exception of NoSuchElementException if there is no next element.
public void remove()- It removes the current element from the collection.
public boolean hasNext()- It returns true, if there are more elements in the
collection. Else, returns false.

List Interface:

List interface is the child interface of Collection interface.


It inhibits a list type data structure in which we can store the ordered
collection of objects.
It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector,
and Stack.
1. Array List:

you must've figured it out from the name itself, that ArrayList is similar
to Arrays.
They are also called as dynamic arrays.
That means, it does not have a fixed size.
Its size can be increased or decreased if elements are added or removed.
Since the ArrayList cannot be used for primitive data types like int, char
etc. , we need to use a wrapper class.

Dept of CSE
Example:
import java.util.*;

public class ArrayListInterface

public static void main(String args[])

// create an ArrayList of String type

ArrayList<String> str = new ArrayList<String>();

// Initialize an ArrayList with add()

str.add("CSE");

str.add("IT");

str.add("CIVIl");

str.add("MECHANICAL");

str.add("BDA");

// to print the ArrayList

System.out.println("ArrayList is" + str);

Output:

ArrayList is [CSE, IT, CIVIl, MECHANICAL, BDA]


2. LinkedList:

The LinkedList class extends the AbstractSequentialList and it also extends


the List, Deque and Queue interface.
By this, we get a linked-list data structure.
Linked List is a linear data structure where the elements are called as
nodes.
each node has two fields- data and next. Data stores the actual piece of
information and next points to the next node. 'Next' field is actually the
address of the next node.
Elements are not stored in a contiguous memory, so direct access to that
element is not possible.
LinkedList uses Doubly Linked List to store its elements while ArrayList
internally uses a dynamic array to store its elements. LinkedList is
faster in manipulation of data as it is node based which makes it unique.
LinkedList is non-synchronised means multiple threads at a time can
access the code.
This means if one thread is working on LinkedList, other threads can also
get a hold of it.
Multiple operations on LinkedList can be performed at a time.
For example, if addition is being performed by one thread, other operation
can be performed by some other thread too.
Syntax:

LinkedList list=new LinkedList();

LinkedList list=new LinkedList(c);

Example:

import java.util.*;

public class LinkedListFrames

public static void main(String args[])

//creating a LinkedList

LinkedList<String> list= new LinkedList<String>();

//displaying the initial size

System.out.println("Size at the beginning "+list.size());

//add elements

list.add("Java");

list.add("C++");

list.add("JavaScript");

list.addFirst("C#");

list.addLast("MongoDB");

list.add(2,"Python");

//displaying the LinkedList


System.out.println("Original Linked List " + list);

//displaying the size

System.out.println("Size after addition "+list.size());

//remove element at index 5

list.remove(5);

list.remove("C#");

//display the new LinkedList

System.out.println("New Linked List "+ list);

//display the new size

System.out.println("Size after removal "+list.size());

Output:

Size at the beginning 0

Original Linked List [C#, Java, Python, C++, JavaScript, MongoDB]

Size after addition 6

New Linked List [Java, Python, C++, JavaScript]

Size after removal 4


3. Vector

Like ArrayList, Vectors in Java are used for dynamic arrays.


It extends the AbstractList and implements the List interface.
Vector is synchronised. Synchronised means only one thread at a time can
access the code.
This means if one thread is working on Vector, no other thread can get a
hold of it. Only one operation on vector can be performed at a time.
For example, if addition is being performed by one thread, other operation
cannot be performed until the first one is over.
Before the introduction of the Collection Framework, Vectors were
categorised as Legacy Classes(Classes which were a part of the earlier
release of Java but now they are re-constructed).

CSE Parul

Methods to create the constructor of Vectors:

1. Using the default method:

Vector<Data-type> v = new Vector<Data-Type>();

2. By specifying the desired size:

In this method, we specify the size.

Vector<Data-type> v = new Vector<Data-Type>(int size);


3. Using size and increment attributes:

This method is used to create a vector whose initial capacity is declared


by size and the increment is declared by incr. Here, the increment is the
value that specifies the number of elements to allocate each time that vector
gets resized upward.

Vector<Data-type> v = new Vector<Data-Type>(int size, int incr);

4. Creating a Vector from Collection:

Vector<Data-type> v = new Vector<Data-Type>(Collection C);

Example:
import java.util.*;

public class Parul

public static void main(String args[])

//creating a Vector

Vector<Integer> v= new Vector<Integer>();

//displaying the size

System.out.println("Size at the beginning "+v.size());

//add elements

v.add(55);

v.add(66);

v.add(77);

v.add(99);
//displaying the Vector

System.out.println(v);

//displaying the size

System.out.println("Size after addition "+v.size());

//remove element at index 3

v.remove(3);

//display the new Vector

System.out.println(v);

//display the new size

System.out.println("Size after removal "+v.size());

Output:

Size at the beginning 0

[55, 66, 77, 99]

Size after addition 4

[55, 66, 77]

Size after removal 3


4. Stack:

Stack class extends the Vector class and it is its subclass.


It works on the principle of Last-In, First-Out.
In order to put an object on the top of the stack, we call the push() method.
To remove and return the top element in the stack, we call pop() method.
There are other methods like peek(), search() and empty() which are used
to perform operations on the stack.

1. Creating a default stack

This creates an empty stack.


Example:

import java.util.*;

public class Parul1

public static void main(String args[])

//creating a Stack

Stack<Integer> s= new Stack<Integer>();

//displaying the initial size

System.out.println("Size at the beginning "+s.size());

//push elements

s.push(99);

s.push(88);

s.push(77);

s.push(66);

s.push(55);

//displaying the Stack

System.out.println("New Stack" + s);

//displaying the size

System.out.println("Size after addition "+s.size());

//pop the element and display it

System.out.println("Popped element " + s.pop());


//display the new Stack

System.out.println("New Stack after popping"+ s);

//display the new size

System.out.println("Size after removal "+s.size());

//peek method to find the top-most element and display it

System.out.println("Top-most element " + s.peek());

//the size remains the same as peek does not remove the element

System.out.println("Size after Peek "+s.size());

Output:

Size at the beginning 0

New Stack [99, 88, 77, 66, 55]

Size after addition 5

Popped element 55

New Stack after popping [99, 88, 77, 66]

Size after removal 4

Top-most element 66

Size after Peek 4


Queue Interface:

The Queue Interface extends the Collection interface.


It uses the principle of First-In, First-Out (FIFO).
A Queue is an ordered list where there is a need to maintain the order of
the elements.
It has classes like PriorityQueue and ArrayDeque.
The most famous implementation is that of PriorityQueue.

Priority Queue:

The PriorityQueue class extends AbstractQueue and implements the


Queue Interface.
As the name suggests, they follow the principle of priority of the elements.
We know that we follow First-In,First-Out for queues, but at times, the
elements needs to be processed in terms of their priority. This is where the
PriorityQueue comes into play.
It does not allow null values to be stored inside it.
The add() method is used to add an element while the poll() method is used
to remove the top-most element. While, peek() is used to display the top-
most element.
Methods to initialise a PriorityQueue using constructors:

1. Creating an empty PriorityQueue:

PriorityQueue<Data-Type> pq = new PriorityQueue<Data-Type>();

2. Creating a PriorityQueue with the specified size:

PriorityQueue<Data-Type> pq = new PriorityQueue<Data-Type>(int size);

3. Creating a PriorityQueue from Collection:

It will create a PriorityQueue with all the elements of Collection C.

PriorityQueue<Data-Type> pq = new PriorityQueue<Data-Type>


(Collection<Data-Type> C);
Example:

import java.util.*;

public class Parul2

public static void main(String args[])

// Creating a priority queue

PriorityQueue<Integer> pq = new PriorityQueue<Integer>();

//displaying the initial size

System.out.println("Size at the beginning "+pq.size());

// Adding elements using add()

pq.add(10);

pq.add(20);

pq.add(40);

pq.add(80);

//displaying the PriorityQueue

System.out.println("New PriorityQueue" + pq);

//displaying the size

System.out.println("Size after addition "+pq.size());

// Printing the top element of the PriorityQueue

System.out.println("Top-most element " +pq.peek());

// Printing the top element and removing it


System.out.println("Removing " +pq.poll());

//displaying the PriorityQueue

System.out.println("New PriorityQueue after removal" + pq);

//display the new size

System.out.println("Size after removal "+pq.size());

Output:

Size at the beginning 0

New PriorityQueue [10, 20, 40, 80]

Size after addition 4

Top-most element 10

Removing 10

New PriorityQueue

after removal[20, 40,80]

Size after removal 3


Set Interface:

The Set interface defines an unordered collection.


It extends the Collection Interface.
We cannot store duplicate values in this.
The Set Interface is implemented by popular classes like HashedSet,
LinkedHashSet and TreeSet.

Method to instantiate the Set Interface:

Set<Data-Type> hs = new HashSet<Data-Type>();

Set<Data-Type> lhs = new LinkedHashSet<Data-Type>();

Set<Data-Type> ts = new TreeSet<Data-Type>();


HashSet:

The HashSet class implements the Set Interface.


It uses a hash table for storage which uses a mechanism called Hashing.
In hashing, the informational content of a key determines a unique value,
called its hash code.
The hash code is then used as an index, at which the data associated with
the key is stored.
When we insert elements into the HashSet, it is not guaranteed that it gets
stored in the same order.
We can store Null values in this.
HashSet is non-synchronized means multiple threads at a time can
access the code.
This means if one thread is working on HashSet, other threads can also get
a hold of it. Multiple operations on HashSet can be performed at a time.

Methods to create the constructors of HashSet:

1. Creating an empty HashSet It is used to create an empty HashSet object in


which the default initial capacity is 16.

HashSet<Data-type> hs = new HashSet<Data-type>();

2. Creating a HashSet with a specified size It is used to create a HashSet with the
given size.

HashSet<Data-type> hs = new HashSet<Data-type>(int size);

3. Creating a HashSet with a specified size and fill ratio It is used to create a
HashSet with a given size and fill ratio.

HashSet<Data-type> hs = new HashSet<Data-type>(int size,float fillRatio);


4. Creating a HashSet from Collection It is used to create a HashSet which
contains all the elements from the collection.

HashSet<Data-type> hs = new HashSet<Data-type>(Collection C);

Example:

import java.util.*;

public class Parul4

public static void main(String args[])

//creating a HashSet

HashSet<String> str= new HashSet<String>();

//displaying the initial size

System.out.println("Size at the beginning "+str.size());

//add elements

str.add("Hi");

str.add("Hello");

str.add("Namaste");

str.add("Dept of CSE");

//displaying the HashSet

System.out.println(str);

//displaying the size


System.out.println("Size after addition "+str.size());

//remove element using value

str.remove("Dept of CSE");

//display the new HashSet

System.out.println(str);

//display the new size

System.out.println("Size after removal "+str.size());

Output:

Size at the beginning 0

[Hi, Hello, Namaste, Dept of CSE]

Size after addition 4

[Hi, Hello, Namaste]

Size after removal 3


LinkedHashSet:

The LinkedHashSet class extends the HashSet class.


It maintains a linked list of entries in the set and hence maintains
the order in which they were inserted.
LinkedHashSet is non-synchronized means multiple threads at a time
can access the code.
This means if one thread is working on LinkedHashSet, other threads can
also get a hold of it. Multiple operations on LinkedHashSet can be
performed at a time.
For example, if addition is being performed by one thread, other operation
can be performed by some other thread too.

The figure below shows the illustration of a LinkedHashSet


1. Creating an empty LinkedHashSet It is used to create an empty LinkedHashSet
object.

LinkedHashSet<Data-type> lhs = new LinkedHashSet<Data-type>();

2. Creating a LinkedHashSet with a specified size It is used to create a


LinkedHashSet with the given size.

LinkedHashSet<Data-type> lhs = new LinkedHashSet<Data-type>(int size);

3. Creating a LinkedHashSet with a specified size and fill ratio It is used to create
a LinkedHashSet with a given size and fill ratio. Fill ratio determines how full the
hash set can be before it is resized.

LinkedHashSet<Data-type> lhs = new LinkedHashSet<Data-type>(int size,float


fillRatio);

4. Creating a LinkedHashSet from Collection It is used to create a LinkedHashSet


which contains all the elements from the collection.

LinkedHashSet<Data-type> lhs = new LinkedHashSet<Data-type>(Collection


C);
Example:

import java.util.*;

public class Parul5

public static void main(String args[])

//creating a HashSet

LinkedHashSet<String> str= new LinkedHashSet<String>();

//displaying the initial size

System.out.println("Size at the beginning "+str.size());

//add elements

str.add("C Language");

str.add("C++");

str.add("Python");

str.add("Java");

str.add("Data Structure");

//displaying the LinkedHashSet

System.out.println(str);

//displaying the size

System.out.println("Size after addition "+str.size());

//remove element using value

str.remove("Data Structure ");


//display the new LinkedHashSet

System.out.println(str);

//display the new size

System.out.println("Size after removal "+str.size());

Output:

Size at the beginning 0

[C Language, C++, Python, Java, Data Structure]

Size after addition 5

[C Language, C++, Python, Java, Data Structure]

Size after removal 5

Note:

Explanation- In the above code, we created a LinkedHashSet and added elements


to it using the add() method, remove the elements by remove() method, and get
its size by size() method.
SortedSet Interface:

The SortedSet Interface extends the Set Interface.


It is similar to the Set Interface but plays a vital role to arrange data
in ascending or sorted manner.
The TreeSet class implements this interface.

The figure below illustrates the SortedSet Interface.

Method to instantiate the SortedSet Interface

SortedSet<Data-Type> ts = new TreeSet<Data-type>();


TreeSet:

The TreeSet class implements the Set Interface.


It uses a tree to store the elements.
TreeSet contains unique elements.
The access and retrieval time is very fast.
TreeSet is non-synchronized means multiple threads at a time can access
the code.
This means if one thread is working on TreeSet, other threads can also get
a hold of it.
Multiple operations on TreeSet can be performed at a time.
For example, if addition is being performed by one thread, other
operations can be performed by some other thread too.

Example

import java.util.*;

class Parul

public static void main(String[] args)

// Creating a TreeSet

Set<String> ts = new TreeSet<>();

//displaying the initial size

System.out.println("Size at the beginning "+ts.size());

// Elements are added using add() method

ts.add("India");
ts.add("USA");

ts.add("Uk");

ts.add("Saudi");

//displaying the TreeSet

System.out.println(ts);

//displaying the size

System.out.println("Size after addition "+ts.size());

// Duplicates will not get inserted into the TreeSet

ts.add("Japan");

// Elements get stored in Ascending order

System.out.println(ts);

Output:

Size at the beginning 0

[India, Saudi, USA, Uk]

Size after addition 4

[India, Japan, Saudi, USA, Uk]


Map Interface:

A map is an object that stores key and value pairs.


It contains unique keys as the same key cannot have multiple mappings.
Although a part of the Collections Framework, maps are not themselves
collections because they do not implement the Collection Interface.

Method to instantiate the Map Interface:

Map<Data-Type> hm = new HashMap<> ();

HashMap:

The HashMap class extends AbstractMap and implements the Map interface.

It uses a hash table for storing key-value pairs.

If we want to access a value in a** hash map**, we must know its key.

Example:

import java.util.*;

public class Parul6

public static void main(String args[])

// Creating a HashMap

HashMap<Integer, Double> hmp = new HashMap<Integer, Double>();

//adding key value pairs using put()


hmp.put(1, 1.1);

hmp.put(2, 2.2);

hmp.put(3, 3.3);

hmp.put(4, 4.4);

hmp.put(5, 5.5);

// Finding the value for a key using get()

System.out.println("The Value for 3 is " + hmp.get(3));

System.out.println("The Value for 5 is " + hmp.get(5));

Output:

The Value for 3 is 3.3

The Value for 5 is 5.5


Note:
When to use which Collection Framework?
Now that you are well versed with the Collections in Java and Collection
Framework, you might be facing the dilemma of when to use which collection
in Java. Don't worry, we will clear this confusion and get you set.

End of the Chapter

You might also like