0% found this document useful (0 votes)
23 views

Installing Eclipse

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Installing Eclipse

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 236

How to Download and Install Eclipse to Run Java

Following is a step by step guide to download and install Eclipse IDE:

Step 1) Installing Eclipse

Open your browser and type https://www.eclipse.org/

Step 2) Click on “Download” button.

Step 3) Click on “Download 64 bit” button


Step 4) Click on “Download” button

Step 4) Install Eclipse.

1. Click on “downloads” in Windows file explorer.


2. Click on “eclipse-inst-win64.exe” file.

Step 5) Click on Run button


Step 6) Click on “Eclipse IDE for Java Developers”

Step 7) Click on “INSTALL” button


Step 8) Click on “LAUNCH” button.

Step 9) Click on “Launch” button.


Step 10) Click on “Create a new Java project” link.

Step 11) Create a new Java Project

1. Write project name.


2. Click on “Finish button”.
Step 12) Create Java Package.

1. Goto “src”.
2. Click on “New”.
3. Click on “Package”.
Step 13) Writing package name.

1. Write name of the package


2. Click on Finish button.

Step 14) Creating Java Class

1. Click on package you have created.


2. Click on “New”.
3. Click on “Class”.

Step 15) Defining Java Class.

1. Write class name


2. Click on “public static void main (String[] args)” checkbox.
3. Click on “Finish” button.
Helloword.java file will be created as shown below:

Step 16) Click on “Run” button.

Output will be displayed as shown below.


Java
1. Java - What, Where and Why?
2. What is Java
3. Where Java is used

Java Programming is a widely used robust technology. Let's start learning of java from basic
questions like what is java ,core java, where it is used, what type of applications are created in
java and why use java.

What is Java
Java is a programming language and a platform.

Java is a high level, robust, secured and object-oriented programming language.

Platform: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has its own runtime environment (JRE) and API, it is called platform.

Java Example
Let's have a quick look at java programming example. A detailed description of hello java
example is given in next page.

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

Output:
Hello java

Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javapoint.com etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games etc.
9.

Types of Java Applications


There are mainly 4 type of applications that can be created using java programming:

1) Standalone Application

It is also known as desktop application or window-based application. An application that we


need to install on every machine such as media player, antivirus etc. AWT and Swing are used
in java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates dynamic page, is called web application.
Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web applications in
java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.

4) Mobile Application

An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.

History of Java
1. Brief history of Java
2. Java Version History
Java history is interesting to know. The history of java starts from Green Team. Java team
members (also known as Green Team), initiated a revolutionary task to develop a language
for digital devices such as set-top boxes, televisions etc.

For the green team members, it was an advance concept at that time. But, it was suited for
internet programming. Later, Java technology as incorporated by Netscape.

James Gosling

Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. There are given the major points that describes the history of java.

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.

2) Originally designed for small, embedded systems in electronic appliances like set-top boxes.

3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.

4) After that, it was called Oak and was developed as a part of the Green project.

Why Oak name for java language?

5) Why Oak? Oak is a symbol of strength and choosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc.

6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Why Java name for java language?

7) Why they choosed java name for java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA" etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell and fun to say.

According to James Gosling "Java was one of the top choices along with Silk". Since java was
so unique, most of the team members preferred java.

8) Java is an island of Indonesia where first coffee was produced (called java coffee).

9) Notice that Java is just a name not an acronym.

10) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.

11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.

12) JDK 1.0 released in(January 23, 1996).

Java Version History

There are many java versions that has been released. Current stable release of Java is Java SE
8.

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 March, 2014)

Features of Java
1. Features of Java
1. Simple
2. Object-Oriented
3. Platform Independent
4. secured
5. Robust
6. Architecture Neutral
7. Portable
8. High Performance
9. Distributed
10. Multi-threaded

There is given many features of java. They are also known as java buzzwords. The Java
Features given below are simple and easy to understand.

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

Simple
According to Sun, Java language is simple because:

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

removed many confusing and/or rarely-used features e.g., explicit pointers, operator overloading
etc.

No need to remove unreferenced objects because there is Automatic Garbage Collection in java.

Object-oriented
Object-oriented means we organize our software as a combination of different types of objects that
incorporates both data and behaviour.

Object-oriented programming(OOPs) is a methodology that simplify 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
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 software-based platform. The Java
platform differs from most other platforms in the sense that it's a software-based platform that runs
on top of other hardware-based platforms.It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run


on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code is compiled by the
compiler and converted into bytecode.This bytecode is a platform independent code because it can
be run on multiple platforms i.e. Write Once and Run Anywhere(WORA).

Secured
Java is secured because:

• No explicit pointer
• Programs run inside virtual machine sandbox.
• Classloader- adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
• Bytecode Verifier- checks the code fragments for illegal code that can violate access right to
objects.
• Security Manager- determines what resources a class can access such as reading and writing
to the local disk.

These security are provided by java language. Some security can also be provided by application
developer through SSL,JAAS,cryptography etc.

Robust
Robust simply means strong. Java uses strong memory management. There are lack of pointers that
avoids security problem. There is automatic garbage collection in java. There is exception handling
and type checking mechanism in java. All these points makes java robust.

Architecture-neutral
There is no implementation dependent features e.g. size of primitive types is set.

Portable
We may carry the java bytecode to any platform.

High-performance
Java is faster than traditional interpretation since byte code is "close" to native code still somewhat
slower than a compiled language (e.g., C++)
Distributed
We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.

Multi-threaded

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

Simple Program of Java


1. Software Requirements
2. Creating Hello Java Example
3. Resolving javac is not recognized problem

We can write a simple hello java program easily after installing the JDK.

To create a simple java program, you need to create a class that contains main method. Let's
understand the requirement first.

Requirement for Hello Java Example


For executing any java program, you need to

• install the JDK if you don't have installed it, download the JDK and install it.
• set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
• create the java program
• compile and run the java program

Creating hello java example

Let's create the hello java program:

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

save this file as Simple.java


To compile: javac Simple.java

To execute: java Simple

Output:Hello Java

Understanding first java program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

• class keyword is used to declare a class in java.


• public keyword is an access modifier which represents visibility, it means it is visible to all.
• static is a keyword, if we declare any method as static, it is known as static method. The core
advantage of static method is that there is no need to create object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create 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 startup of the program.
• String[] args is used for command line argument. We will learn it later.
• System.out.println() is used print statement. We will learn about the internal working of
System.out.println statement later.

Internal Details of Hello Java Program


1. Internal Details of Hello Java

we have learned about the first program, how to compile and how to run the first java program.
Here, we are going to learn, what happens while compiling and running the java program.
Moreover, we will see some question based on the first program.

What happens at compile time?

At compile time, java file is compiled by Java Compiler (It does not interact with OS) and
converts the java code into bytecode.
What happens at runtime?
At runtime, following steps are performed:

Classloader: is the subsystem of JVM that is used to load class files.

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

Interpreter: read bytecode stream then execute the instructions.

→Can you save a java source file by other name than the class name?
Yes, if the class is not public. It is explained in the figure given below:

To compile: javac Hard.java

To execute: java Simple


→Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:

Difference between JDK, JRE and JVM


1. Brief summary of JVM
2. Java Runtime Environment (JRE)
3. Java Development Kit (JDK)

Understanding the difference between JDK, JRE and JVM is important in Java. We are having
brief overview of JVM here.

If you want to get the detailed knowledge of Java Virtural Machine, move to the next page.
Firstly, let's see the basic differences between the JDK, JRE and JVM.

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

JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.

The JVM performs following main tasks:

• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JRE
JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.

Implementation of JVMs are also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
JVM (Java Virtual Machine)
1. Java Virtual Machine
2. Internal Architecture of JVM

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

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

What is JVM?

It is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Sun and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.

What it does?

The JVM performs following operation:

• Loads code
• Verifies code
• Executes code
• Provides runtime environment

JVM provides definitions for the:

• Memory area
• Class file format
• Register set
• Garbage-collected heap
• Fatal error reporting etc.

Internal Architecture of JVM


Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.
1) Classloader:

Classloader is a subsystem of JVM that is used to load class files.

2) Class(Method) Area:

Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.

3) Heap:

It is the runtime data area in which objects are allocated.

4) Stack:
Java Stack stores frames.It holds local variables and partial results, and plays a part in method
invocation and return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.

5) Program Counter Register:

PC (program counter) register. It contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack:

It contains all the native methods used in the application.

7) Execution Engine:
It contains:

1) A virtual processor

2) Interpreter:Read bytecode stream then execute the instructions.

3) Just-In-Time(JIT) compiler:It is used to improve the performance.JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time needed
for compilation.Here the term ?compiler? refers to a translator from the instruction set of a Java
virtual machine (JVM) to the instruction set of a specific CPU.

Java OOPs Concepts


1. Object Oriented Programming
2. Advantage of OOPs over Procedure-oriented programming language
3. Difference between Objcet-oriented and Objcet-based programming language.

Object Oriented Programming is a paradigm that provides many concepts such as inheritance,
data binding, polymorphism etc.

Simula is considered as the first object-oriented programming language. The programming


paradigm where everything is represented as an object, is known as truly object-oriented
programming language.

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

OOPs (Object Oriented Programming System)


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

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

Object

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

Class

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

Inheritance

When one object acquires all the properties and behaviours of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism. For example:
to convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction

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

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

Encapsulation

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

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

Advantage of OOPs over Procedure-oriented programming language


1)OOPs makes development and maintenance easier where as in Procedure-oriented programming
language it is not easy to manage if code grows as project size grows.

2)OOPs provides data hiding whereas in Procedure-oriented prgramming language a global data can
be accessed from anywhere.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.

Introduction to Type Conversion in Java

ll.3 DATA TYPES.

Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to variables, you can store
integers, decimals, or characters in these variables.

There are two data types available in Java:

• Primitive Data Types


• Reference/Object Data Types

Primitive Data Types:

There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.

byte:

• Byte data type is an 8-bit signed two's complement integer.


• Minimum value is -128 (-2^7)
• Maximum value is 127 (inclusive)(2^7 -1)
• Default value is 0
• Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is
four times smaller than an int.
• Example: byte a = 100 , byte b = -50

short:

• Short data type is a 16-bit signed two's complement integer.


• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• Short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int
• Default value is 0.
• Example: short s = 10000, short r = -20000

int:

• Int data type is a 32-bit signed two's complement integer.


• Minimum value is - 2,147,483,648.(-2^31)
• Maximum value is 2,147,483,647(inclusive).(2^31 -1)
• Int is generally used as the default data type for integral values unless there is a concern about
memory.
• The default value is 0.
• Example: int a = 100000, int b = -200000

long:

• Long data type is a 64-bit signed two's complement integer.


• Minimum value is -9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
• This type is used when a wider range than int is needed.
• Default value is 0L.
• Example: long a = 100000L, int b = -200000L

float:

• Float data type is a single-precision 32-bit IEEE 754 floating point.


• Float is mainly used to save memory in large arrays of floating point numbers.
• Default value is 0.0f.
• Float data type is never used for precise values such as currency.
• Example: float f1 = 234.5f

double:

• double data type is a double-precision 64-bit IEEE 754 floating point.


• This data type is generally used as the default data type for decimal values, generally the default
choice.
• Double data type should never be used for precise values such as currency.
• Default value is 0.0d.
• Example: double d1 = 123.4

boolean:

• boolean data type represents one bit of information.


• There are only two possible values: true and false.
• This data type is used for simple flags that track true/false conditions.
• Default value is false.
• Example: boolean one = true

char:

• char data type is a single 16-bit Unicode character.


• Minimum value is '\u0000' (or 0).
• Maximum value is '\uffff' (or 65,535 inclusive).
• Char data type is used to store any character.
• Example: char letterA ='A'

Reference Data Types:

• Reference variables are created using defined constructors of the classes. They are used to
access objects. These variables are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy etc.
• Class objects, and various type of array variables come under reference data type.
• Default value of any reference variable is null.
• A reference variable can be used to refer to any object of the declared type or any compatible
type.
• Example: Animal animal = new Animal("giraffe");

Java Literals:

A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.

Literals can be assigned to any primitive type variable. For example:

byte a = 68;
char a = 'A'

byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8)
number systems as well.

Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems
for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

String literals in Java are specified like they are in most other languages by enclosing a sequence of
characters between a pair of double quotes. Examples of string literals are:

"Hello World"
"two\nlines"
"\"This is in quotes\""

String and char types of literals can contain any Unicode characters. For example:

char a = '\u0001';
String a = "\u0001";

Java language supports few special escape sequences for String and char literals as well. They are:

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t tab

\" Double quote

\' Single quote

\\ backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

Variables

In Java, all variables must be declared before they can be used. The basic form of a variable declaration
is shown here:
type identifier [ = value][, identifier [= value] ...] ;

The type is one of Java's datatypes. The identifier is the name of the variable. To declare more than one
variable of the specified type, use a comma-separated list.

Here are several examples of variable declarations of various types. Note that some include an
initialization.

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing
// d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

This chapter will explain various variable types available in Java Language. There are three kinds of
variables in Java:

• Local variables
• Instance variables
• Class/static variables

Local variables:

• Local variables are declared in methods, constructors, or blocks.


• Local variables are created when the method, constructor or block is entered and the variable
will be destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables so local variables should be declared and an initial
value should be assigned before the first use.

Example:

Here, age is a local variable. This is defined inside pupAge() method and its scope is limited to this
method only.

public class Test{


public void pupAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]){


Test test = new Test();
test.pupAge();
}
}

This would produce the following result:

Puppy age is: 7

Example:

Following example uses age without initializing it, so it would give an error at the time of compilation.

public class Test{


public void pupAge(){
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]){


Test test = new Test();
test.pupAge();
}
}

This would produce the following error while compiling it:

Test.java:4:variable number might not have been initialized


age = age + 7;
^
1 error

Instance variables:

• Instance variables are declared in a class, but outside a method, constructor or any block.
• When a space is allocated for an object in the heap, a slot for each instance variable value is
created.
• Instance variables are created when an object is created with the use of the keyword 'new' and
destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method, constructor
or block, or essential parts of an object's state that must be present throughout the class.

Example:

import java.io.*;
public class Employee{
// this instance variable is visible for any child class.
public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName){
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal){
salary = empSal;
}

// This method prints the employee details.


public void printEmp(){
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]){


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}

This would produce the following result:

name : Ransika
salary :1000.0

Scope vs. Lifetime

Scope refers to the range of code where you can access a variable. You can literally print out
your program, and draw a box to show where a variable is valid. It's textual in nature. We can
divide scope into
• method body scope Variable is accessible in method body only (local variables,
parameters)
• class definition scope Variable is accessible i class definition (instance variables)

Lifetime refers to the amount of time a variable (or object) exists. Since object variables are
both a box (holding a handle) and an object, the lifetimes may differ. An object variable could
disappear (for example, a local variable disappears once you exit the method where the local
variable is declared), yet the object still exists.

We can divide lifetime into categories too:

• method body lifetime Exists on method body entry, disappears on method body exit.
(local variables, parameters)
• class definition lifetime Exists as long as object is around (instance variables)
• [an error occurred while processing this directive]

Type Conversion and Casting in Java

Type conversion:

•In some cases we might want to assign value of one type to variable of another type. If both
the source and destination types are compatible, then java performs the conversion
implicitly(automatically).

•Examples of compatible types are int, long, short and byte. Also float and double are
compatible with each other.

•char and boolean are not compatible with each other.

•Implicit conversion is also called as coercion.

•Explicit conversion (casting incompatible types) is called casting.


Java’s automatic conversion (Coercion):

•Java automatically converts from one type to another only when the following two conditions
are satisfied:

1) Both types are compatible with each other.

2) The size of destination type is more than the source type.

•When the above two conditions are satisfied, java performs an implicit conversion. This is also
known as “Widening Conversion”.

•int can be auto converted to long since the size of long is 64, where as size of int is 32. Similarly
a byte can be auto converted or implicitly converted to int.

•int can also be implicitly converted to float and double.

Type Casting (Explicit Conversion):

•If we want to convert two types which are incompatible or if the size of destination type is less
than the size of source type, then we must do the conversion explicitly. This process is also
called as “type casting”.

•For example if we want to convert a int value to byte, java cannot do this automatically as the
size of int is 32 and size of byte is only 8. So, we must explicitly cast an int to byte. This is also
known as “narrowing conversion”
•Syntax for type casting is:

(destination type) value;

•Java promotes various types in expressions based on the following rules:

Type Casting/type conversion


Converting one primitive datatype into another is known as type casting (type conversion) in Java. You
can cast the primitive datatypes in two ways namely, Widening and, Narrowing.

Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the
casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both
datatypes should be compatible with each other.

Example

public class WideningExample {


public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);
}
}

Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as narrowing. In this case the
casting/conversion is not done automatically, you need to convert explicitly using the cast operator “(
)” explicitly. Therefore, it is known as explicit type casting. In this case both datatypes need not be
compatible with each other.

Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}

Output
Enter an integer value:
67
Character value of the given integer: C

Java Basics

===========
control flow statements

-----------------------

1. flow of execution in any programming is sequential.

2. the instructions will be executed from top to bottom, without skiping any instruction.

3. if we want distrub that flow of execution, then control flow statements.

1. Selection Statements

1. simple if

2. if else

3. else if

4. nested if

5. switch case

2. Iterative Statements or Loops

1. while loop

2. do while loop

3. for loop

4. for each loop

3. Transfer Statements

1. break

2. continue

Eg: accept a number and print "even" or "odd"

System.out.println("even number");

System.out.println("odd number");

we have to select only one statement based on the condition.


---> selection statements ----> part of CFS

Eg: 1...5

System.out.println(1);

System.out.println(2);

System.out.println(3);

System.out.println(4);

System.out.println(5);

Eg: 1...5000

System.out.println(i);

where i value is from 0 to 5000

repeat the statement ----> looping statements ---> part of CFS

Eg: 0.....500

--> when ever we are getting 420 can u pls stop the process

--> whenever we are getting 420 can u pls stop current iteration and starts from 421

transfer statements ----> part of CFS

Control Flow Statements


simple if

---------

if(condition)

true_block statements;

Eg: WJP to accept salary of an emp, and update salary based on gender

---------------------------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

String gender = obj.nextLine();

double salary = obj.nextDouble();

if(gender.equals("female"))

salary = salary + (salary * 0.2);


}

System.out.println("Updated Salary:"+salary);

male

1000

Updated Salary:1000.0

female

1000

Updated Salary:1200.0

if else:

--------

if(condition)

true_block statements;

else

false_block statements;
}

Eg: WJP to find biggest of two numbers

--------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int a = obj.nextInt();

int b = obj.nextInt();

if(a>b)

System.out.println(a+" is big");

else

System.out.println(b+" is big");

100

200

200 is big
100

50

100 is big

Eg: WJP to check whether the given two numbers are equal or not

---------------------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int a = obj.nextInt();

int b = obj.nextInt();

if(a==b)

System.out.println("both are equal");

else

System.out.println("both are not equal");

}
10

20

both are not equal

111

111

both are equal

Eg: WJP to incremenet salary of an emp if male then 5% or 6%.

-------------------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

String gender = obj.nextLine();

double salary = obj.nextDouble();

if(gender.equals("male"))

salary = salary + (salary * 0.5);

else

salary = salary + (salary * 0.6);


}

System.out.println("Updated Salary:"+salary);

male

10000

Updated Salary:15000.0

female

20000

Updated Salary:32000.0

Eg: WJP to check whether a person is eligible for vote or not

-------------------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

System.out.print("Enter your age:");

int age = obj.nextInt();

if(age>=18)

{
System.out.println("Eligible for vote");

else

System.out.println("Not eligible for vote");

Enter your age:10

Not eligible for vote

Enter your age:18

Eligible for vote

WJP to check whether the given year is leapyear or not.

-------------------------------------------------------

difference btween == and .equals()

== ---------> we can use only for data types

.equlas() ---------> we can use only for string comparison


else if

-------

if we have more than condition, then recommended to use else if

if(condition1)

TRUE_BLOCK_1

else if(condition2)

TRUE_BLOCK_2

else if(condition3)

TRUE_BLOCK_3

else

FALSE_BLOCK

Eg: WJP to find biggest of three numbers

----------------------------------------
import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int a = obj.nextInt();

int b = obj.nextInt();

int c = obj.nextInt();

if(a>b && a>c)

System.out.println(a+" is big");

else if(b>a && b>c)

System.out.println(b+" is big");

else

System.out.println(c+" is big");

10

20

30

30 is big

Eg: WJP to print grade of the student


-------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

System.out.println("Enter sub1 marks:");

int sub1 = obj.nextInt();

System.out.println("Enter sub2 marks:");

int sub2 = obj.nextInt();

System.out.println("Enter sub3 marks:");

int sub3 = obj.nextInt();

System.out.println("Enter sub4 marks:");

int sub4 = obj.nextInt();

System.out.println("Enter sub5 marks:");

int sub5 = obj.nextInt();

int total = sub1 + sub2 + sub3 + sub4 + sub5;

double per = total/500.0 * 100;

if(per>=75)

System.out.println("Grade A");

else if(per>=60)

System.out.println("Grade B");

else if(per>=50)

System.out.println("Grade C");

else if(per>=40)

System.out.println("Grade D");
else

System.out.println("Unable to issue degree");

Enter sub1 marks:

50

Enter sub2 marks:

60

Enter sub3 marks:

70

Enter sub4 marks:

80

Enter sub5 marks:

90

Grade B

nested if

---------

an if condition inside another if is called as nested if

Eg:

import java.util.Scanner;

class Test
{

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

System.out.println("Enter sub1 marks:");

int sub1 = obj.nextInt();

System.out.println("Enter sub2 marks:");

int sub2 = obj.nextInt();

System.out.println("Enter sub3 marks:");

int sub3 = obj.nextInt();

System.out.println("Enter sub4 marks:");

int sub4 = obj.nextInt();

System.out.println("Enter sub5 marks:");

int sub5 = obj.nextInt();

if(sub1>=40 && sub2>=40 && sub3>=40&&sub4>=40&&sub5>=40)

int total = sub1 + sub2 + sub3 + sub4 + sub5;

double per = total/500.0 * 100;

if(per>=75)

System.out.println("Grade A");

else if(per>=60)

System.out.println("Grade B");

else if(per>=50)

System.out.println("Grade C");

else if(per>=40)

System.out.println("Grade D");

else
System.out.println("Unable to issue degree");

else

System.out.println("student failed in atleast one sub");

Enter sub1 marks:

100

Enter sub2 marks:

85

Enter sub3 marks:

95

Enter sub4 marks:

75

Enter sub5 marks:

65

Grade A

switch case:

-----------

--> it is similar to else if

--> switch will for only for eqality purpose.


--> other than equality if we want to perform any other comparison then rec to go for else if

--> syntax

switch(choice)

case value1: stmt; break;

case value2: stmt; break;

case value3: stmt; break;

case value4: stmt; break;

case value5: stmt; break;

default: stmt;

Eg:

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int n = obj.nextInt();

switch(n)

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;

case 5: System.out.println("five"); break;

default: System.out.println("invalid");

one

two

three

four

five
6

invalid

---> break is optional.

---> if there is no break, then it will execute all the cases from matching case.

Eg:

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int n = obj.nextInt();

switch(n)

case 1: System.out.println("one");

case 2: System.out.println("two");

case 3: System.out.println("three");

case 4: System.out.println("four");

case 5: System.out.println("five");

default: System.out.println("invalid");

}
}

invalid

one

two

three

four

five

invalid

two

three

four

five

invalid

five
invalid

else if----> <,<=,>,>=,==,!= ----> slow

switch-----> == -----------------> fast

iterative statements

--------------------

if we want to repeat one or more statements

1. while loop-----> if we dn't know the number of iterations in advance

2. do while loop--> if we dn't know the number of iterations in advance, min 1 time execution

3. for loop-------> if we know the number of iterations in advance

4. for each-------> only for collection

while loop:

----------

while(condition)

TRUE_BLOCK_STATEMENTS

Eg:WJP to extract digits from the given number


----------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int n = obj.nextInt();

while(n!=0)

System.out.println(n%10);

n=n/10;

123

45678

5
4

Eg: WJP to find sum of all digits in the given number

-----------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int d,s,n = obj.nextInt();

s=0;

while(n!=0)

d=n%10;

s=s+d;

n=n/10;

System.out.println("sum of digits:"+s);

123

sum of digits:6

12345
sum of digits:15

do while loop:

-------------

do

statements

}while(condition);

Eg1:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a=95,b=100;

while(a<=b)

System.out.println(a++);//95,96,97,98,99,100

}
for loop:

--------

1. most commonly used looping statement in java.

2. if we know the number of iterations in advance.

3. syntax

for(intialization;condition;update)

statements

I--->1 ----------> only one time

C--->2,5,....

U--->4,7,....

B--->3,6,....

Eg1: WJP to print natural numbers from 0 to 10

----------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int i;

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

System.out.println(i);

Eg2: WJP to print even numbers from 0 to 10

-------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int i;

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

System.out.println(i);

6
8

10

Eg3: WJP to print odd numbers from 1 to 10

------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int i;

for(i=1;i<=10;i=i+2)

System.out.println(i);

9
for each loop:

-------------

--> for each loop is applicable only for collections.

--> Eg: Arrays,String[],List,Stack,Queue etc

--> 1.5 version of java

--> syntax

--> it is applicable, if the data is of same type.

for(each item in collection)

statements

Eg:

import java.util.Scanner;

class Test

public static void main(String[] args)

int[] a = {111,222,333,444,555};

for(int t:a)

System.out.println(t);

}
}

111

222

333

444

555

Eg:

import java.util.Scanner;

class Test

public static void main(String[] args)

String[] names = {"C","C++","JAVA","PYTHON"};

for(String t:names)

System.out.println(t);

}
C

C++

JAVA

PYTHON

transfer statements

-------------------

--> transfer the control flow one place to another place.

--> break: terminates the looping statement

--> continue: terminates current iteration and starts with new iteration

Eg:

import java.util.Scanner;

class Test

public static void main(String[] args)

int i;

for(i=1;i<=500;i++)

if(i==420)

break;

else

System.out.print("\t"+i);
}

Eg:

import java.util.Scanner;

class Test

public static void main(String[] args)

int i;

for(i=1;i<=500;i++)

if(i==420)

continue;

else

System.out.print("\t"+i);

arrays:

=======

introduction:

-------------

1. In the case of normal variables, the problem is


case1: declare a,b and cal sum -----------------> a+b

case2: declare a,b,c,d,e and cal sum -----------> a+b+c+d+e

case3: declare a1,a2,a3,.....a1000 and cal sum -> a1+a2+a3+....+a1000

2. an array is collection of similar type of elements.

3. advantage arrays

1. collection of elements will be under a common name.

2. no need to huge number of variables.

4. disadvantages arrays

1. if we know the size in advance, then only we have to use array.

2. it is collection of similar type of elements.

5. to overcome these problems, we have to gofor collections.

declaration of an array:

------------------------

datatype[] arrayname;

Eg:

int[] a;

int a[];

int []a;

Eg:

int[][] a;
int a[][];

int [][]a;

int[] a[];

int[] []a;

int []a[];

creation of an array in java:

-----------------------------

int a[];

a = new int[size];

Eg:

int[] a = new int[4];

int[][] a = new int[3][3];

int[] b = new int[]; ---------> invalid

int[] b = new int[0]; --------> valid

int[] b = new int[-12]; ------> no compile time error, execution fails

RuntimException: NegativeArraySizeException

index concept:

--------------

1. index is the special concept, which is used to access the array elements.

2. begin value for index is 0.

3. the end value for index is len of array-1.


4. index must be always int type only.

5. out of index then we wn't get any compile time error, but execution fails

RuntimeException: NegativeArraySizeException -----> NASE

RuntimeException: ArrayIndexOutOfBoundsException--> AIOOBE

initilization of array elements:

--------------------------------

int[] a = new int[3]; ---> index=0,1,2

System.out.println(a[0]) #0

System.out.println(a[1]) #0

System.out.println(a[2]) #0

int[] a = new int[3];

a[0] = 111;

a[1] = 222;

a[2] = 333;

System.out.println(a[0]) #111

System.out.println(a[1]) #222

System.out.println(a[2]) #333

System.out.println(a[3]) #AIOOBE

int[] a = {11,22,33,44,55};
size:5

array name:a

dimension:1

index: 0,1,2,3,4

How to find length of the array:

--------------------------------

length identifier.

int[] a = new int[5];

System.out.println(a.length); //5

int[] a = {1,2,3,4,5,6,7,8};

System.out.println(a.length); //8

How to read/write array elements

--------------------------------

Reading an array

import java.util.Scanner;

Scanner obj = new Scanner(System.in);

obj.nextInt()------> read int values


obj.nextDouble() --> read double values

obj.nextBoolean() -> read boolean values

obj.nextLine() ----> read String values

Write an array

1. for loop----------> if we want to access/manipulate on index

2. for each loop ----> if we want to access array elements

Eg1:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[] = new int[];

Test.java:6: error: array dimension missing

int a[] = new int[];

1 error
Eg2:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[] = new int[3];

for(int i:a)

System.out.println(i);

Eg3:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[] = new int[3];

a[1] = 777;
a[2] = 999;

for(int i:a)

System.out.println(i);

777

999

Eg4:

import java.util.Scanner;

class Test

public static void main(String[] args)

double a[] = new double[5];

for(double i:a)

System.out.println(i);

0.0

0.0

0.0

0.0
0.0

Eg5:

import java.util.Scanner;

class Test

public static void main(String[] args)

boolean a[] = new boolean[4];

for(boolean i:a)

System.out.println(i);

false

false

false

false

Eg6:

import java.util.Scanner;

class Test

public static void main(String[] args)


{

String a[] = new String[4];

for(String i:a)

System.out.println(i);

null

null

null

null

Eg7:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[] = new int[0];

System.out.println(a.length);

0
Eg8:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[] = new int[-5];

System.out.println(a.length);

Exception in thread "main" java.lang.NegativeArraySizeException

at Test.main(Test.java:6)

Eg9:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[] = new int[3];

System.out.println(a[0]);//0

System.out.println(a[1]);//0

System.out.println(a[2]);//0
System.out.println(a[3]);//AIOOBE

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at Test.main(Test.java:10)

Eg10:

import java.util.Scanner;

class Test

public static void main(String[] args)

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

System.out.println(a.length);//3

for(int i:a)

System.out.println("Element:"+i);

Element:1

Element:2
Element:3

Eg11:

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[][] = {{1,2,3},{4,5,6},{7,8,9}};//rows:3 and cols:3

for(int i:a)

System.out.println(i);

Test.java:7: error: incompatible types

for(int i:a)

required: int

found: int[]

1 error

Eg12:

import java.util.Scanner;

class Test
{

public static void main(String[] args)

int a[][] = {{1,2,3},{4,5,6},{7,8,9}};//rows:3 and cols:3

for(int i[]:a)

for(int j:i)

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

System.out.println();

123

456

789

import java.util.Scanner;

class Test

public static void main(String[] args)

int a[][] = {{1,2,3},{4,5,6},{7,8,9}};//rows:3 and cols:3

for(int i=0;i<a.length;i++)//3

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

System.out.println("row: "+i+"\tcol: "+j+"\telement: "+a[i][j]);

/*

row: 0 col: 0 element: 1

row: 0 col: 1 element: 2

row: 0 col: 2 element: 3

row: 1 col: 0 element: 4

row: 1 col: 1 element: 5

row: 1 col: 2 element: 6

row: 2 col: 0 element: 7

row: 2 col: 1 element: 8

row: 2 col: 2 element: 9

*/

row: 0 col: 0 element: 1

row: 0 col: 1 element: 2

row: 0 col: 2 element: 3

row: 1 col: 0 element: 4

row: 1 col: 1 element: 5

row: 1 col: 2 element: 6


row: 2 col: 0 element: 7

row: 2 col: 1 element: 8

row: 2 col: 2 element: 9

import java.util.Scanner;

class Test

public static boolean isPrime(int n)

int i,factors=0;

for(i=1;i<=n;i++)

if(n%i==0)

factors++;

if(factors==2)

return true;

else

return false;

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int n = obj.nextInt();

int i,s=0;

for(i=2;i<=n;i++)
{

if(isPrime(i))

s=s+i;

System.out.println("sum of prime numbers:"+s);

sum of prime numbers:10

10

sum of prime numbers:17

AP1) Read and Write array elements?

-----------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int size = obj.nextInt();

int i,a[] = new int[size];


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

for(i=0;i<a.length;i++)

a[i] = obj.nextInt();

System.out.println("The given array elements are:");

for(int t:a)

System.out.println(t);

Enter array elements:

10

20

15

25

The given array elements are:

10

20

15

25

8
AP2) Read array elements and calcualte sum of the given values

--------------------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int size = obj.nextInt();

int s=0,i,a[] = new int[size];

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

for(i=0;i<a.length;i++)

a[i] = obj.nextInt();

for(int t:a)

s=s+t;

System.out.println("The sum of given elements are:"+s);

Enter array elements:

10
3

The sum of given elements are:21

AP4) Read array elements and calcualte sum of even elements the given values

AP5) Read array elements and calcualte sum of odd elements the given values

AP6) Read array elements and calcualte sum of prime elements the given values

AP7) Read array elements and calculate max element in the given array

---------------------------------------------------------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int size = obj.nextInt();

int max,i,a[] = new int[size];

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

for(i=0;i<a.length;i++)

a[i] = obj.nextInt();

max=a[0];
for(int t:a)

if(max<t)

max = t;

System.out.println("The max value in given elements is:"+max);

Enter array elements:

10

-20

30

-40

50

-60

70

-80

The max value in given elements is:70

AP8) Read array elements and calculate min element in the given array

AP9) Read array elements and do sort operation. asending order.

---------------------------------------------------------------

import java.util.Scanner;

class Test
{

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int size = obj.nextInt();

int i,j,temp,a[] = new int[size];

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

for(i=0;i<a.length;i++)

a[i] = obj.nextInt();

System.out.println("Array elements before sorting:");

for(int t:a)

System.out.println(t);

//logic

for(i=0;i<a.length;i++)

for(j=i+1;j<a.length;j++)

if(a[i]>a[j])

temp = a[i];

a[i] = a[j];

a[j] = temp;

}
System.out.println("Array elements after sorting:");

for(int t:a)

System.out.println(t);

Enter array elements:

Array elements before sorting:

Array elements after sorting:

AP10) Read array elements and do sort operation. DESC order.


AP11) Read and Write a matrix

-----------------------------

[12]

[34]

[2][2]

i=0--->j=0------>(0,0)

i=0--->j=1------>(0,1)

i=1--->j=0------>(1,0)

i=1--->j=1------>(1,1)

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int i,j,a[][] = new int[3][3];

System.out.println("Enter array elements for 3x3 matrix:");


for(i=0;i<a.length;i++)

for(j=0;j<a[i].length;j++)

a[i][j] = obj.nextInt();

System.out.println("Matrix:");

for(i=0;i<a.length;i++)

for(j=0;j<a[i].length;j++)

System.out.print(" "+a[i][j]);

System.out.println();

Enter array elements for 3x3 matrix:

7
8

Matrix:

123

456

789

Enter array elements for 3x3 matrix:

Matrix:

100

010

001

AP12) Read and print transpose a matrix

---------------------------------------

import java.util.Scanner;

class Test
{

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int i,j,a[][] = new int[3][3];

System.out.println("Enter array elements for 3x3 matrix:");

for(i=0;i<a.length;i++)

for(j=0;j<a[i].length;j++)

a[i][j] = obj.nextInt();

System.out.println("Give Matrix:");

for(i=0;i<a.length;i++)

for(j=0;j<a[i].length;j++)

System.out.print(" "+a[i][j]);

System.out.println();

System.out.println("Transpose Matrix:");

for(i=0;i<a.length;i++)

for(j=0;j<a[i].length;j++)

{
System.out.print(" "+a[j][i]);

System.out.println();

Enter array elements for 3x3 matrix:

Give Matrix:

123

456

789

Transpose Matrix:

147

258

369
Enter array elements for 3x3 matrix:

Give Matrix:

100

010

001

Transpose Matrix:

100

010

001

AP13) matrix addition

---------------------

import java.util.Scanner;

class Test

public static void main(String[] args)

{
Scanner obj = new Scanner(System.in);

int i,j;

int a[][] = new int[3][3];

int b[][] = new int[3][3];

int c[][] = new int[3][3];

System.out.println("Enter array elements for 3x3 matrix A:");

for(i=0;i<a.length;i++)

for(j=0;j<a[i].length;j++)

a[i][j] = obj.nextInt();

System.out.println("Enter array elements for 3x3 matrix B:");

for(i=0;i<b.length;i++)

for(j=0;j<b[i].length;j++)

b[i][j] = obj.nextInt();

for(i=0;i<3;i++)

for(j=0;j<3;j++)

c[i][j] = a[i][j] + b[i][j];

}
}

System.out.println("Result Matrix:");

for(i=0;i<c.length;i++)

for(j=0;j<c[i].length;j++)

System.out.print(" "+c[j][i]);

System.out.println();

Enter array elements for 3x3 matrix A:

Enter array elements for 3x3 matrix B:

0
0

Result Matrix:

247

268

3 6 10

A14) matrix subtraction

A15) matrix multiplication

import java.util.Scanner;

class Test

public static void main(String[] args)

Scanner obj = new Scanner(System.in);

int i,j,k;

int a[][] = new int[3][3];

int b[][] = new int[3][3];

int c[][] = new int[3][3];

System.out.println("Enter array elements for 3x3 matrix A:");

for(i=0;i<a.length;i++)

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

a[i][j] = obj.nextInt();

System.out.println("Enter array elements for 3x3 matrix B:");

for(i=0;i<b.length;i++)

for(j=0;j<b[i].length;j++)

b[i][j] = obj.nextInt();

for(i=0;i<3;i++)

for(j=0;j<3;j++)

c[i][j] = 0;

for(k=0;k<3;k++)

c[i][j] = c[i][j] + (a[i][k] * b[k][j]);

System.out.println("Result Matrix:");

for(i=0;i<c.length;i++)

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

System.out.print(" "+c[i][j]);

System.out.println();

Enter array elements for 3x3 matrix A:

123

456

789

Enter array elements for 3x3 matrix B:

100

010

001

Result Matrix:

123

456

789

Constructors in Java

.......>In Java a constructor is a block of codes similar to the method.

............>It is called when an instance of the class is created.

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


-----------------> Rules for creating Java constructor

----------------------------->There are two rules defined for the constructor.

--->Constructor name must be the same as its class name

---->A Constructor must have no explicit return type

----->A Java constructor cannot be abstract, static, final, and synchronized

---------->Types of Java constructors

--------------.There are two types of constructors in Java:

--------------->1.Default constructor (no-arg constructor)

---------------->2.Parameterized constructor

Java Default Constructor

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

Example of default constructor

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

eg....

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

What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type.

Example of default constructor that displays the default values

eg---

class Student3{

int id;

String name;

//method to display the value of id and name

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

public static void main(String args[]){

//creating objects

Student3 s1=new Student3();

Student3 s2=new Student3();

//displaying values of the object

s1.display();

s2.display();

}
}

...

output---

0 null

0 null

.............................

Java Parameterized Constructor

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters.

We can have any number of parameters in the constructor

eg---

class Student4{

int id;

String name;

//creating a parameterized constructor

Student4(int i,String n){

id = i;

name = n;

//method to display the values

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

public static void main(String args[]){

//creating objects and passing values

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

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


//calling method to display the values of object

s1.display();

s2.display();

-----

output---

111 Karan

222 Aryan

--------------------------------------------------

Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.

eg----

//Java program to overload constructors

class Student5{

int id;

String name;

int age;

//creating two arg constructor

Student5(int i,String n){

id = i;

name = n;

//creating three arg constructor

Student5(int i,String n,int a){


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 0

222 Aryan 25

Method in Java

--------------------------

------------->A method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task.

-------------->It is used to achieve the reusability of code.

-------------->We write a method once and use it many times.

predefind method

ex----
public class Demo

public static void main(String[] args)

// using the max() method of Math class

System.out.print("The maximum number is: " + Math.max(9,7));

output---

The maximum number is: 9

----In the above example, we have used three predefined methods main(), print(), and max()

user defind method

ex-----

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 user

int num=scan.nextInt();

//method calling

findEvenOdd(num);
}

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

output----

Enter the number: 12

12 is even

---------- public int sum (int a, int b)

| | | |

access spcifiers rtn-type method 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.

java Enums
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),

season (SPRING, SUMMER, WINTER, and AUTUMN or FALL),

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

According to the Java naming conventions, we should have all constants in capital
letters.

So, we have enum constants in capital letters.

This key word

-.It is common for a class to contain instance variables and methods.

•It is also common for methods to have parameters.

•So, what happens when the names of instance variables and the parameters are
same?
•In the above case the parameters “hide” the instance variables. This is an
ambiguous situation.

•For example let’s have a look at the following piece of code…

class Box

int length, width, height;

void setDim(int length, int width, int height)

length = length;

width = width;

height = height;

•In the example we just saw, the names of instance variables and names of
parameters are same.

•How to solve this issue? There are two ways to solve this.

1) To change the names of parameters.

2) Using “this” keyword.

•The “this” keyword always refers to the current object.

•“this” can be used to resolve the naming conflicts between instance variables and
parameters.

•So, by using the “this” keyword, our program can be return as follows…

class Box

int length, width, height;


void setDim(int length, int width, int height)

this.length = length;

this.width = width;

this.height = height;

Exploring Methods of String Class

---String is a sequence of characters. In java, objects of String are immutable


which means a constant and cannot be changed once created.

-----------String class has a variety of methods for string manipulation. We will


discuss basic methods with examples.

string literal

String s = “GeeksforGeeks”;

String Methods

------------------------

string length(): defines the length of the string

String substring (int i):

Return the substring from the ith index character to end.

"GeeksforGeeks".substring(3); // returns “ksforGeeks”

String concat( String str):

Concatenates specified string to the end of this string.

String s1 = ”Geeks”;

String s2 = ”forGeeks”;
String output = s1.concat(s2); // returns “GeeksforGeeks”

Ex---prgm

public class StringMethodsDemo {

public static void main(String[] args) {

String targetString = "Java is fun to learn";

String s1= "JAVA";

String s2= "Java";

String s3 = " Hello Java ";

System.out.println("Checking Length: "+ targetString.length());

System.out.println("Replace function: "+ targetString.replace("fun",


"easy"));

System.out.println("Converting to lower case: "+


targetString.toLowerCase());

System.out.println("Converting to upper case: "+


targetString.toUpperCase());

System.out.println("Triming string: " + s3.trim());

System.out.println("searching s1 in targetString: " +


targetString.contains(s1));

System.out.println("searching s2 in targetString: " +


targetString.contains(s2));

char [] charArray = s2.toCharArray();

System.out.println("Size of char array: " + charArray.length);

System.out.println("Printing last element of array: " +


charArray[3]);

}
}

OUTPUT---

Checking Length: 20

Replace function: Java is easy to learn

Converting to lower case: java is fun to learn

Converting to upper case: JAVA IS FUN TO LEARN

Triming string: Hello Java

searching s1 in targetString: false

searching s2 in targetString: true

Size of char array: 4

Printing last element of array: a

----------------------------------------------------------

Recursion in Java

Recursion in java is a process in which a method calls itself continuously.

A method in java that calls itself is called recursive method.

------------------------------------------------------

public class Recursion{

static int count=0;

static void p(){

count++;

if(count<=5){
System.out.println("hello "+count);

p();

public static void main(String[] args) {

p();

------- output

hello 1

hello 2

hello 3

hello 4

hello 5

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory


automatically.

Advantage of Garbage Collection

It makes java memory efficient because garbage collector removes the


unreferenced objects from heap memory.

It is automatically done by the garbage collector(a part of JVM) so we don't need


to make extra efforts. In other words, it is a way to destroy the unused objects

public class TestGarbage{

public void finalize()


{

System.out.println("object is garbage collected");}

public static void main(String args[]){

TestGarbage s1=new TestGarbage();

TestGarbage s2=new TestGarbage();

s1=null;

s2=null;

System.gc();

output

object is garbage collected

object is garbage collected

Q1. Differentiate between the constructors and methods in Java?


Methods Constructors

1. Used to represent the behavior of an object 1. Used to initialize the state of an


object
2. Must have a return type 2. Do not have any return type

3. Needs to be invoked explicitly 3. Is invoked implicitly

4. No default method is provided by the compiler 4. A default constructor is provided


by the compiler if the class has
none
5. Method name may or may not be same as class 5. Constructor name must always
name be the same as the class name

Q2. What is the difference between break and continue statements?

break continue
1. Can be used in switch and loop (for,
1. Can be only used with loop statements
while, do while) statements

2. It causes the switch or loop


2. It doesn’t terminate the loop but causes the loop
statements to terminate the moment it
to jump to the next iteration
is executed
3. It terminates the innermost 3. A continue within a loop nested with a switch will
enclosing loop or switch immediately cause the next loop iteration to execute

Example break:
1
for (int i = 0; i < 5; i++)
2 {
3 if (i == 3)
4 {
5 break;
}
6
System.out.println(i);
7 }
8
Example continue:
1
for (int i = 0; i < 5; i++)
2 {
3 if(i == 2)
4 {
5 continue;
}
6
System.out.println(i);
7 }
8
Q3. What is the difference between this() and super() in Java?

In Java, super() and this(), both are special keywords that are used to call the constructor.

this() super()
1. this() represents the current instance of a 1. super() represents the current instance of a
class parent/base class
2. Used to call the default constructor of the 2. Used to call the default constructor of the
same class parent/base class
3. Used to access methods of the current
3. Used to access methods of the base class
class
4. Used for pointing the current class
4. Used for pointing the superclass instance
instance
5. Must be the first line of a block 5. Must be the first line of a block
Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs

(Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes
that are built upon existing classes.

When you inherit from an existing class, you can reuse methods and fields of the parent class.

Moreover, you can add new methods and fields in your current class also.

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


child relationship.

Why use inheritance in java


o 1.For Method Overriding

---→(so runtime polymorphism can be achieved).

2. For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
Note: The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.
java Inheritance Example

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

How to use inheritance in Java


The keyword used for inheritance is extends.
1. Single Inheritance: In single inheritance, subclasses inherit the features of one
superclass. In the image below, class A serves as a base class for the derived
class B.

2. Multilevel Inheritance: In Multilevel Inheritance, a derived class will be


inheriting a base class and as well as the derived class also act as the base class
to other class.
3. In the below image, class A serves as a base class for the derived class B,
which in turn serves as a base class for the derived class C.
4. Hierarchical Inheritance: In Hierarchical Inheritance, one class serves as a
superclass (base class) for more than one subclass.
5. In the below image, class A serves as a base class for the derived class B, C
and D

5. Multiple Inheritance (Through Interfaces): In Multiple inheritances, one class can


have more than one superclass and inherit features from all parent classes. Please note
that Java does not support multiple inheritances with classes. In java, we can achieve
multiple inheritances only through Interfaces.

5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types


of inheritance. Since java doesn’t support multiple inheritances with classes, hybrid
inheritance is also not possible with classes. In java, we can achieve hybrid inheritance only
through Interfaces.
Inheritance
Example prg:
---------------------
class one {
public void print_geek()
{
System.out.println("geeks");
}
}

// one class is created..


-------------------------------
Single Inheritance:
prgm--- two
---------------------------------
import java.io.*;
import java.lang.*;
import java.util.*;

class two extends one {


public void print_for() { System.out.println("for"); }

// Driver class

public static void main(String[] args)


{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
output--
Geeks
for
Geeks
-------------------
Multilevel Inheritance
prg--- three
----------------
import java.io.*;
import java.lang.*;
import java.util.*;

class three extends two {


public void print_geek()
{
System.out.println("Geeks");
}

public static void main(String[] args)


{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
------------
output
Geeks
for
Geeks

--------------------------
Hierarchical Inheritance
------------
class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}
class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}
--------------
Class A
Class B
Class A
Class C
Class A
Class D
-----------------------
super key word
------------------------
The super keyword in Java is a reference variable which is used to refer immediate parent
class object.
--------------------
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
--------------------------------------------------------------------------
1. super() represents the current instance of a parent/base class
2. Used to call the default constructor of the parent/base class
3. Used to access methods of the base class
4. Used for pointing the superclass instance
5. Must be the first line of a block
eg--prg----
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move();
// invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal obj = new Dog();
// Animal reference but Dog object
obj.move();
// runs the method in Dog class
}
}
output
-------------
Animals can move
Dogs can walk and run
Preventing inheritance

While one of Java's strengths is the concept of inheritance, in which one class can derive from
another, sometimes it's desirable to prevent inheritance by another class. To prevent
inheritance, use the keyword "final" when creating the class.

Why Prevent Inheritance?

The main reason to prevent inheritance is to make sure the way a class behaves is not corrupted
by a subclass.

Suppose we have a class Account and a subclass that extends it, OverdraftAccount. Class
Account has a method getBalance():

How to Prevent Inheritance


To stop a class from being extended, the class declaration must explicitly say it cannot be
inherited. This is achieved by using the "final" keyword:

public final class Account


{ statements
}

This means that the Account class cannot be a superclass, and the OverdraftAccount class can
no longer be its subclass.

Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption
by a subclass. For example, OverdraftAccount still could be a subclass of Account, but it should
be prevented from overriding the getBalance() method.

In this case use, the "final" keyword in the method declaration:

public class Account {

private double balance;

public final double getBalance()


{
return this.balance;
}
}

final is a non-access modifier for Java elements. The final modifier is used for finalizing the
implementations of classes, methods, and variables.

What are ways to Prevent Inheritance in Java Programming?

There are 2 ways to stop or prevent inheritance in Java programming.

By using final keyword with a class orBy using a private constructor in a class.

How to prevent class from being inherited in java is one of the important technical interview
questions for which we need to detail all possible solutions.

Problem Statement: Let’s say we have a class A and we don’t want to allow any other class to
be derived from it. What are the possible solutions?
Solution-1: Using final keyword

Using final keyword before a class declaration we can stop a class to be inherited by other
classes. For example,

public final class A

If we try to extend the class A which is final, compiler will flash an error i.e.
“The Type B cannot the subclass the final Class A”, if class B is trying to extend final class A.

public class B extends A{//Error :The Type B cannot the subclass the Final Class A

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class

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. It can be initialized in the constructor
only. The blank final variable can be static also which will be initialized in the static block
only. We will have detailed learning of these. Let's first learn the basics of final keyword.
1) Java final variable

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

Example of final variable

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

1) Java final variable

class Bike9{

final int speedlimit=90;//final variable


void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Compile by: javac Bike9.java


63.151/Bike9.java:4: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error

Java final method


If you make any method as final, you cannot override it.

Example of final method


1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4.
5. class Honda extends Bike{
6. void run(){System.out.println("running safely with 100kmph");}
7. public static void main(String args[]){
8. Honda honda= new Honda();
9. honda.run();
10. }
11. }

Compile by: javac Honda.java

63.151/Honda.java:6: error: run() in Honda cannot override run() in Bike


ly with 100kmph");}
^
overridden method is final
1 error

Java final class


If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){System.out.println("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda1();
8. honda.run();
9. }
10. }
Compile by: javac Honda1.java
3.133/Honda1.java:3: error: cannot inherit from final Bike
class Honda1 extends Bike{

Polymorphism

Polymorphism is briefly described as “one interface, many implementations”. Polymorphism


is a characteristic of being able to assign a different meaning or usage to something in different
contexts – specifically, to allow an entity such as a variable, a function, or an object to have
more than one form. There are two types of polymorphism:

1. Compile time polymorphism


2. Run time polymorphism
Compile time polymorphism is method overloading whereas Runtime time polymorphism is
done using inheritance and interface.

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an


overridden method is resolved at runtime rather than at compile-time. In this process, an
overridden method is called through the reference variable of a superclass. Let’s take a look at
the example below to understand it better.

1 class Car {
2 void run()
3 {
4 System.out.println(“car is running”);
5 }
6 }
7 class Audi extends Car {
8 void run()
9 {
10 System.out.prinltn(“Audi is running safely with 100km”);
11 }
12 public static void main(String args[])
13 {
14 Car b= new Audi(); //upcasting
15 b.run();
16 }
17 }

Method Overloading in Java


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 then it may be difficult for you as well as other
programmers to understand the behavior of the method because its name differs.
So, we perform method overloading to figure out the program quickly.

Advantage of method overloading


Method overloading increases the readability of the program.

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

Method Overloading
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
10. Output:
11. 22
12. 33

Method Overriding in Java


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

In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which
is already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

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

Example of method overriding

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.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
Test it Now

Output:

Bike is running safely


Java Abstract Class and Abstract Methods

----------------------------------------

Java Abstract Class

----------------------

The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes).

We use the abstract keyword to declare an abstract class

----------------

For example

------------

// create an abstract class

abstract class Language {

// fields and methods

...

// try to create an object Language

// throws an error

Language obj = new Language();

--------------------------------------

note:An abstract class can have both the regular methods and abstract methods

-----------------------------------------

for example
---------------------

abstract class Language {

// abstract method

abstract void method1();

// regular method

void method2() {

System.out.println("This is regular method");

---------------------------------------------------------------------------------

Java Abstract Method

--------------------------

A method that doesn't have its body is known as an abstract method.

We use the same abstract keyword to create abstract methods.

----------------------------------------------------------------

For example

-----------

abstract void display();

----------------------------

If a class contains an abstract method, then the class should be declared abstract.

Otherwise,

it will generate an error.

-------------------------------

Example: Java Abstract Class and Method


----------------------------------------------

abstract class Language {

// method of abstract class

public void display() {

System.out.println("This is Java Programming");

class Main extends Language {

public static void main(String[] args) {

// create an object of Main

Main obj = new Main();

// access method of abstract class

// using object of Main class

obj.display();

Output

----------------------

This is Java programming

------------------------------

Java Abstraction

The major use of abstract classes and methods is to achieve abstraction in Java.
Abstraction is an important concept of object-oriented programming

that allows us to hide unnecessary details and only show the needed information..

UNIT-III:

Interfaces- Interfaces vs Abstract classes, defining an interface, implement interfaces, accessing


implementations through interface references, extending interface, inner class.

Packages- Defining, creating and accessing a package, importing packages.

Interface in Java
An Interface means Any Service requirement Specification [SRS].

And

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

→ An interface is a reference type in Java. It is similar to class. It is a collection of abstract


methods.

→ A class implements an interface, thereby inheriting the abstract methods of the interface.

→ Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling

How to declare an interface?


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

A class that implements an interface must implement all the methods declared in the
interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface −

Example
Following is an example of an interface −

/* File name : NameOfInterface.java */


import java.lang.*;
// Any number of import statements

public interface NameOfInterface {


// Any number of final, static fields
// Any number of abstract method declarations\
}
How to declare an interface in Java?
By using the keyword interface you can declare a class type of interface. The syntax is
given below.

An example is given below.


The relationship between classes and interfaces

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it
is known as multiple inheritance.

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }

Output:Hello
Welcome

Multiple inheritance is not supported through class in java, but it


is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported
in the case of class

because of ambiguity. However, it is supported in case of an interface because there is no ambiguity.


It is because its implementation is provided by the implementation class. For example:

Interface inheritance

A class implements an interface, but one interface


extends another interface.

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10. public static void main(String args[]){
11. TestInterface4 obj = new TestInterface4();
12. obj.print();
13. obj.show();
14. }
15. }

Output:

Hello
Welcome

Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform
all the behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the
declaration.

Example
/* File name : MammalInt.java */
public class MammalInt implements Animal {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This will produce the following result −

Output
Mammal eats
Mammal travels

Difference Between Interface and Abstract Class in Java:


The main difference is to be answered in the interview is as follows

1. The interface is a fully un-implemented class used for declaring a set of operations
of an object.
2. An abstract class is a partially implemented class. It implements some of the
operations of the object those are declared in its interface. These implemented
operations are common for all next-level subclasses. The remaining operations are
implemented by the next level subclasses according to their requirement.
3. The interface allows us to develop multiple inheritances. So we must start object
design with an interface whereas abstract class does not support multiple
inheritances so it always comes next to the interface in the object creation process.

Interface in Java Abstract Class in java

The interface supports Multiple Abstract class does not support Multiple
Inheritance. Inheritance.

The interface doesn’t contain Data


Members. Abstract class contains Data Members.

The interface doesn’t contain


Constructors. Abstract Class contains Constructors.

An interface contains only incomplete An abstract class contains both complete and
members. incomplete members.

An interface cannot have access modifiers,


by default,
An abstract class can have access modifiers for
everything is assumed as public. the subs, functions, and properties.

Only a complete member of the abstract class

Members of the interface cannot be Static. can be Static.

Except above, the following are some of the differences.

Inner Classes in Java with Examples


In this article, I am going to discuss Inner Classes in Java with Examples. Please read
our previous article, where we discussed Constructors in Java. At the end of this article,
you will understand what are inner classes and their type and when and how to implement
this in Java Applications.
What are Inner Classes in Java?
The inner class is defined inside the body of another class (known as an outer class). The
class written within is called the nested class, and the class that holds the inner class is
called the outer class. Java inner class can be declared private, public, protected, or with
default access whereas an outer class can have only public or default access.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable. The Syntax is given below.

Types of Inner Classes in Java:


The inner classes are of four types. They are :
1. Nested Inner Class
2. Method Local Inner Class
3. Anonymous Inner Class
4. Static Nested Class

Nested Inner Class in Java:


A class created within the class and outside the method is known as Nested Inner Class
in Java. It can access the private instance variable of the outer class.
Method Local Inner Class in Java:
A class created within the method of the enclosing class is known as Method Local Inner
Class. Since the local inner class is not associated with Object,

Anonymous Inner Class in Java:


An inner class declared without a class name is known as an anonymous inner class in
Java. It is created for implementing an interface or extending a class.

Static Nested Class in Java:


Static nested classes are not technically inner classes. They are like static members of
the outer class. A static nested class is the same as any other top-level class and is nested
for only packaging convenience.

II-PART
Packages- Defining, creating and accessing a package, importing
packages.

1. What are Packages in Java?


2. Types of Packages in Java
3. User-Defined Packages in Java
4. How to Compile Java Package?
5. How to execute the Java Package Program?
6. How to access a package from another package in Java?
7. Subpackage in Java
8. Advantages of Packages in Java

What are Packages in Java?

The package is a collection of classes and interfaces in the form of .class files. It helps
organize your classes into a folder structure and makes it easy to locate and use them.
More importantly, it helps improve re-usability. Each package in Java has its unique name
and organizes its classes and interfaces into a separate namespace, or name group.
Although interfaces and classes with the same name cannot appear in the same package,
they can appear in different packages.
Packages are used for:
1. Preventing naming conflicts.
2. Making searching and usage of classes, interfaces, enumerations, and annotations
easier.
3. Offers access protection such as protected classes, default classes, and private
classes.
4. Packages can be considered as data encapsulation (or data-hiding).
5. With packages, you can organize your project better and easily locate related
classes.

Types of Packages in Java


We have the following two types of packages in Java:
1. In-Built Packages
2. User-defined Packages

In-Built Packages
In-Built Packages are the packages that are given by Sun Microsystems or some other
companies as a part of Java. We have the following three types of in-built packages:
1. Core Packages: Core Packages are predefined packages given by Sun
MicroSystems which begin with “java”.

2. Extended Packages: Extended packages are also predefined packages given by


Sun Microsystems which begin with “javax”.

3. Third-Party Packages: Third-Party Packages are also predefined packages that


are given by some other companies as a part of Java Software. Example:
oracle.jdbc, com.mysql, etc.

Some In-Built Packages in Java are:

1.java.lang :

This package is the collection of classes and interfaces using which we can perform basic
operations like parsing, storing strings, etc. This package is by default available for every
java program. Example: Object, String, Integer, etc.

2.java.io :

This package is the collection of classes and interfaces using which we can perform basic
input and output operations. Example: BufferedReader, Printstream, FileReader, etc.

3.java.util :

This package is the collection of classes and interfaces using which we can display the
date, store the group of objects(Collection API). Example: Date, Collection, ArrayList, etc.

4.java.text :

This package is the collection of classes and interfaces using which we can perform
operations like formatting the date, number, etc. Example: NumberFormat, DateFormat,
etc.

5.java.net :

This package is the collection of classes and interfaces using which we can develop
network-related applications. Example: Socket, ServerSocket, etc.
6.java.sql :

This package is the collection of classes and interfaces using which we can perform
JDBC-related operations like connecting to DB, creating the tables, inserting records, etc.
Example: Connection, Driver, DriverManager, etc.
7.java.awt :

This package is the collection of classes and interfaces using which we can develop GUI-
based applications. Example: Frame, Label, Button, etc.

8.javax.swing :

This package is the collection of classes and interfaces using which we can develop better
GUI-based Applications. Example: JFrame, JLabel, JButton, etc.

9.java.applet :

This package is the collection of classes and interfaces using which we can develop
applications that run in the browser. Example : Applet, AppletContext, etc.

User-Defined Packages in Java

In Java, we can also create user-defined packages according to our requirements. To


create the user-defined packages we have to use a java keyword called “package”. User-
defined packages contain only user-defined classes or interfaces in the form of .class files.
The syntax is given below.

Rules:
1. While writing the package name we can specify packages in any number of levels
but specifying one level is mandatory.
2. The package statement must be written as the first executable statement in the
program.
3. We can write at most one package statement in the program
Example: Program to demonstrate Packages in Java
package Demo;
public class PackageDemo {

public static void main(String args[]) {

System.out.println("Have a Nice Day...!!!");

How to Compile Java Package?


If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
Example:
javac –d . PackageDemo.java

Or
javac –d E: PackageDemo.java

Or
javac –d D:\practice PackageDemo.java
Here,
-d: This option is used to create the package based on the name specified in the program
using the package statements and locate the generated class into the package. E: or D:
– Specify the location where to locate the created package.
How to execute the Java Package Program?
You need to use a fully qualified name to run the class.
To Compile javac -d . PackageDemo.java

To Run: java mypack.PackageDemo

Output: Have a Nice Day…!!!


Note: In Java, for every java program following two packages are available by default:
1. java.lang
2. Current working directory

How to access a package from another package in Java?

We can use all the classes and interfaces are available in the above two packages but if
we want to use classes and interfaces that are available in the other packages we must
import them into our program by using any one of the following two ways:
1. Using Fully Qualified Name
2. Using import Statement
Using Fully Qualified Name

A fully Qualified Name means writing the class name using the package name directly.
Using this concept we can import only one class at a time. This concept will increase the
code size and decrease the readability of the program and this concept is not
recommended to use. The Syntax is shown in the below image.

Using the import statement


Using the import statement we can import either only one class or many classes from the
package. We have the following two types of import statements:
1. Implicit import
2. Explicit import

Implicit import :
By using implicit import we can import many classes from the package.
Syntax :
import package.*;
import package1.package2.*;
Example :
import java.io.*;
class ReadingData{
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
}
}
Here, the compiler will decide what class to be loaded in the program hence it is called
implicit import.

Explicit import :

By using explicit import we can import only one class from the package.
Syntax :
import package.ClassName;
import package1.package2.ClassName;
Example :
import java.io.BufferedReader;
import java.io.InputstreamReader;
import java.io.IOException;
class ReadingData{
Public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new
InputstreamReader(System.in));
}
}
Here, the programmer is specifying explicitly what classes to be loaded hence it is called
an explicit import.
Note: It is always recommended to use explicit import in the industry because it always
improves the readability of the program.

Rules for writing import statement:

1. Import statements must be written after the package statement and before the
class declaration.
2. We can write any number of import statements.
3.
Difference Between Implicit Import and Explicit Import

Using implicit import or explicit import both are the same but explicit import will take a little
bit more compilation time compared to implicit import but at run time there is no difference.
Advantages of Packages in Java

1. The package is used to categorize the classes and interfaces so that they can be
easily maintained.
2. Application development time is less because reuse the code
3. Application memory space is less (main memory)
4. Application execution time is less
5. Application performance is enhanced (improve)
6. Redundancy (repetition) of code is minimized
7. The package provides access protection
8. Package removes naming collision
UNIT-IV:

Exception handling-Benefits of exception handling, the classification of exceptions - exception


hierarchy, checked exceptions and unchecked exceptions, usage of try, catch, throw, throws
and finally, creating own exception subclasses.

Multithreading – Differences between multiple processes and multiple threads, thread life cycle,
creating threads, interrupting threads, thread priorities, synchronizing threads, inter- thread
communication, producer consumer problem

JAVA Exception handling

Exception

An exception is a problem that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore these exceptions are to be handled.
What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

An exception can occur for many different reasons, below given are some scenarios where
exception occurs.

1.A user has entered invalid data.

2.A file that needs to be opened cannot be found.

3.A network connection has been lost in the middle of communications or the JVM has run out
of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.

• Classification of exceptions


Built in exception in java

Following is the list of Java Unchecked RuntimeException.

1.ArithmeticException

Arithmetic error, such as divide-by-zero.


2 ArrayIndexOutOfBoundsException

Array index is out-of-bounds.

3ArrayStoreException

Assignment to an array element of an incompatible type.

4ClassCastException

Invalid cast.

5IllegalArgumentException

Illegal argument used to invoke a method.

6IllegalMonitorStateException

Illegal monitor operation, such as waiting on an unlocked thread.

7IllegalStateException

Environment or application is in incorrect state.

8IllegalThreadStateException

Requested operation not compatible with the current thread state.


9 IndexOutOfBoundsException

Some type of index is out-of-bounds.

10 NegativeArraySizeException

Array created with a negative size.

11 NullPointerException

Invalid use of a null reference.

12 NumberFormatException

Invalid conversion of a string to a numeric format.

13 SecurityException

Attempt to violate security.

14 StringIndexOutOfBounds

Attempt to index outside the bounds of a string.

15 UnsupportedOperationException

An unsupported operation was encountered.


Following is the list of Java Checked Exceptions Defined in java.lang.

Sr.No. Exception & Description

1 ClassNotFoundException

Class not found.

2 CloneNotSupportedException

Attempt to clone an object that does not implement the Cloneable interface.

3 IllegalAccessException

Access to a class is denied.

4 InstantiationException

Attempt to create an object of an abstract class or interface.

5 InterruptedException

One thread has been interrupted by another thread.

6 NoSuchFieldException

A requested field does not exist.

7 NoSuchMethodException
A requested method does not exist.

User defined exceptions

You can create your own exceptions in Java.



All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend
the RuntimeException class.
Syntax
Class myexception extends exception
{
//code
}
MyException ex = new MyException ();

If(condition……….){

throw ex;

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions.
Forexample, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime..

3) Error Error is irrecoverable. Some examples of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

1) Checked Exception : A checked exception is an exception that occurs at the compile


time, these are also called as compile time exceptions. These exceptions cannot simply be
ignored at the time of compilation, the Programmer should take care of handle these
exceptions
For example,

if you use FileReader class in your program to read data from a file, if the file specified in its
constructor doesn't exist, then an FileNotFoundException occurs, and compiler prompts the
programmer to handle the exception.

Example program:

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

If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Demo.java FilenotFound_Demo.java:

8: error: unreported exception FileNotFoundException;

must be caught or declared to be thrown FileReader fr = new FileReader(file);

^ 1 error

Note: Since the methods read and close of FileReader class throws IOException, you can observe
that compiler notifies to handle IOException, along with FileNotFoundException

2) Unchecked Exception
An Unchecked exception is an exception that occurs at the time of execution, these are also called as
Runtime Exceptions, these include programming bugs, such as logic errors or improper use of an API.
runtime exceptions are ignored at the time of compilation.

For example,
if you have declared an array of size 5 in your program, and trying to call the 6th element of the array
then an ArrayIndexOutOfBoundsExceptionexception occurs

Example program:

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

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

System.out.println(num[5]);

If you compile and execute the above program you will get exception as shown below.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:

5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Errors: These are not exceptions at all, but problems that arise beyond the control of the user or
the programmer. Errors are typically ignored in your code because you can rarely do anything about
an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time
of compilation.

Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

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

an exception code.

It means we can't use try block alone.

The try block must be followed by either catch or finally.


catch The "catch" block is used to handle the exception.

It must be preceded by 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.

throws The "throws" keyword is used to declare exceptions.

It specifies that there may occur an exception in the method. It doesn't throw an

• Exception Handling
• Syntax
• Code
• try { // protected code }
• catch(Exception _name exception_1)
• { // catch block
• }
• catch( Exception_ name exception_2)
• {
• // catch block
• }

The throws/throw Keywords:


If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught,
by using the throw keyword.

Try to understand the difference between throws and throw keywords, throws is used to postpone
the handling of a checked exception and throw is used to invoke an exception explicitly

The following method declares that it throws a RemoteException:

import java.io.*;

public class className { public void deposit(double amount) throws RemoteException

// Method implementation throw new RemoteException();

//Remainder of class definition

Java throw Exception


In Java, exceptions allows us to write good quality codes where the errors are checked
at the compile time instead of runtime and we can create custom exceptions making
the code recovery and debugging easier.

Java throw keyword


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

We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be related
to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is


mainly used to throw a custom exception. We will discuss custom exceptions later in
this section.
1. public class TestThrow1 {
2. //function to check if person is eligible to vote or not
3. public static void validate(int age) {
4. if(age<18) {
5. //throw Arithmetic exception if not eligible to vote
6. throw new ArithmeticException("Person is not eligible to vote");
7. }
8. else {
9. System.out.println("Person is eligible to vote!!");
10. }
11. }
12. //main method
13. public static void main(String args[]){
14. //calling the function
15. validate(13);
16. System.out.println("rest of the code...");
17. }
18. }

Output:

Example: Exception handling using try...catch


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

try {

// code that generate exception


int divideByZero = 5 / 0;
System.out.println("Rest of code in try block");
}

catch (ArithmeticException e) {
System.out.println("ArithmeticException => " + e.getMessage());
}
}
}
Run Code

Output

ArithmeticException => / by zero

In the example, we are trying to divide a number by 0 . Here, this code


generates an exception.
To handle the exception, we have put the code, 5 / 0 inside the try block.
Now when an exception occurs, the rest of the code inside the try block is
skipped.
The catch block catches the exception and statements inside the catch block
is executed.
If none of the statements in the try block generates an exception,
the catch block is skipped.

2. Java finally block


In Java, the finally block is always executed no matter whether there is an
exception or not.
The finally block is optional. And, for each try block, there can be only
one finally block.
The basic syntax of finally block is:

try {
//code
}
catch (ExceptionType1 e1) {
// catch block
}
finally {
// finally block always executes
}
Example: Java Exception Handling using finally block
class Main {
public static void main(String[] args) {
try {
// code that generates exception
int divideByZero = 5 / 0;
}

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

finally {
System.out.println("This is the finally block");
}
}
}
Run Code

Output

ArithmeticException => / by zero


This is the finally block

Unit-4
Multithreading – Differences between multiple processes and multiple
threads, thread life cycle, creating threads, interrupting threads, thread
priorities, synchronizing threads, inter- thread communication, producer
consumer problem.

What is Single-Tasking?

Single-Tasking means executing one task at a time. Here much of the processor
time will be wasted because waiting time is very high and the processor gives a
late response. Example: DOS

What is Multitasking?

Windows operating system is a multitasking operating system. It means it has the


ability to run multiple applications at the same time. For example, in my machine,
I can open the Google Chrome Browser, Microsoft word document, Notepad,
VLC Media Player, Windows Explorer, etc. at the same time. This is possible
because on my machine I have installed the Windows operating system and the
Windows operating system is a multitasking operating system.

How the operating system executes multiple applications at a time?

To execute all the above applications, the operating system internally makes use
of processes. A process is a part of the operating system (or a component under
the operating system) which is responsible for executing the program or
application. So, to execute each and every program or application, there will be a
process.
You can see this using the Task Manager. Just right-click on the Taskbar and
click on the Task Manager option which will open the Task Manager window.
From that window, just click on the “Processes” button as shown below.

As you can see from the above image, each application is executed by one
corresponding process. Along the same line, there are also multiple processes that
are running in the background which are known as the background processes.
These background processes are known as windows services and the Operating
system runs a lot of windows services in the background.

So, we have an operating system and under the operating system, we have
processes that run our applications. So under the process, an application runs. To
run the code of an application the process will make use of a concept called
Thread.

Types of Multi-Tasking

We can achieve multitasking in the following two ways:

1. Processor-based multitasking (Multiprocessing)


2. Thread-based multitasking (Multithreading)

Processor-based multitasking (Multiprocessing)

Processor-based multitasking means executing multiple tasks at the same time


simultaneously where each task is independent of other tasks having separate
memory and resources. Processor-based multitasking is an operating system
approach.

For example, while typing a java program we can listen to a song and at the same
time we can download a file from the internet, all these tasks are executed
simultaneously and there is no relationship between these tasks. All these tasks
have their own independent address space as shown below. This type of multi-
tasking is developed at the OS level.
Thread-based multitasking (Multithreading)

Thread-based multitasking means executing different parts of the same program


at the same time simultaneously where each task is independent sometimes or
dependent sometimes on other tasks which are having common memory and
resources.

Executing multiple tasks concurrently is called thread-based multitasking. Here


each task is a separate independent part of a single process. That part is called a
thread. This type of multitasking is developed at the programmatic level.
Example: Games, Web-based applications, etc. For better understanding, please
have a look at the below diagram.

Understanding some terminology:

Time Slice / Time Quantum:

For executing each task a unit of CPU time is given for its execution which is
called a time slice or time quantum. The thread scheduler runs each thread for a
short amount of time. Each thread alternatively gets a slice (quantum) of the
CPU’s time.
Thread Scheduler :

Thread Scheduler is the Operating System program that is responsible for


allocating the resources for threads and executing them. Thread Scheduler in java
is the part of the JVM that decides which thread should run. There is no guarantee
that which runnable thread will be chosen to run by the thread scheduler. Only
one thread at a time can run in a single process. The thread scheduler mainly uses
preemptive or time-slicing scheduling to schedule the threads.

Advantages of Multitasking:

Whether it is a process-based or thread-based multitasking the advantage of


multitasking is to improve the performance of the system by decreasing the
response time.

Note: In general process-based multitasking is called just multitasking and


thread-based multitasking is called multithreading.
The Difference between Multitasking and Multithreading is:

Multitasking is heavyweight because switching between contexts is slow as each


process is stored at a separate address as we already discussed. Multi-threading is
lightweight because switching between contexts is fast as each thread is stored in
the same address as we already discussed.

How can we create multiple threads in Java Program?

We can develop a multithread program in java very easily because java provides
in-build support for creating custom threads by providing API- Runnable, Thread,
ThreadGroup.

What are Java Threads?

We can consider JVM is also a process, when JVM is created in its java stack
area by default two threads are created with names

1. Main- to execute the java methods


2. Garbage collector- to destroy unreferenced objects
So by default java is a multithreaded programming language. All methods are
executed in the main thread in sequence in the order they are called from the main.
So by using a single thread JVM executes methods sequentially one after one.

What are Sequential execution and concurrent execution?

Sequential execution means single-thread execution and it takes more time to


complete all methods of execution. Whereas concurrent execution means
multithreading execution and it takes less time to complete all methods of
execution. To have concurrent execution developers must create user-defined
threads in the program.

Meaning of concurrent execution?

Executing multiple tasks in the “start-suspend-resume-end” fashion is called


concurrent execution. This means both tasks are started at different points in time
and one task is paused while another task is executed. In java, the JVM allows an
application to have multiple threads of execution running concurrently. When a
program contains multiple threads then the CPU can switch between the two
threads to execute them at the same time. The important point to be remembered
at a single instance time JVM cannot execute two tasks at a time.

What is Thread?

Generally, a Thread is a lightweight process. In simple words, we can say that a


Thread is a unit of a process that is responsible for executing the application code.
So, every program or application has some logic or code, and to execute that logic
or code, Thread comes into the picture.

By default, every process has at least one thread that is responsible for executing
the application code and that thread is called Main Thread. So, every application
by default is a single-threaded application.

A thread is a:

1. Facility to allow multiple activities within a single process


2. A thread is an independent sequential flow of execution/path.
3. A thread is a stack created in the java stack area.
4. Referred to as a lightweight process
5. A thread is a series of executed statements.
6. Each thread has its own program counter, stack, and local variables
7. It executes methods in sequence one after one.
8. A thread is a nested sequence of method calls
9. Its shares memory, files, and per-process state
10.Java uses threads by using a “Thread Class”.

Advantages of a single thread:

1. Reduces overhead in the application as a single thread execute in the


system
2. Also, it reduces the maintenance cost of the application.
Single Thread Example:

public class SingleThread {

public static void main(String[] args) {

System.out.println("Single Thread");

Output: Single Thread

What is Multithreading in Java?

It is a process of creating multiple threads in the Java Stack Area (JSA) for
executing multiple tasks concurrently to finish their execution in a short time by
using the processor’s ideal time effectively.
Multithreading means executing multiple threads at the same time simultaneously
where each thread is called a separated task of the program that executes
separately.

Java is a multi-threaded programming language which means we can develop a


multi-threaded program using Java. A multi-threaded program contains two or
more parts that can run concurrently and each part can handle a different task at
the same time making optimal use of the available resources especially when your
computer has multiple CPUs. Hence, it is also known as Concurrency in Java.

Advantages of Java Multithreading:

1. The users are not blocked because threads are independent, and we can
perform multiple operations at times
2. As such the threads are independent, the other threads won’t get affected if
one thread meets an exception.
3.
Why do we need multithreading in Java?

We need multithreading mainly for two reasons.

1. To complete the execution of independent multiple tasks in a short time


2. To effectively utilize the CPU’s ideal time.

What are the Different Ways to Create Custom Threads in Java?

In java, we can create user-defined threads in two ways

1. Implementing Runnable interface


2. Extending Thread Class
3.
In both approaches we should override the run() method in a subclass with the
logic that should be executed in the user-defined thread concurrently and should
call the start() method on the Thread class object to create a thread in the java
stack area.

1.Creating Thread by extending Thread class


If we want to create the threads using this approach, we have to follow the
following five steps:

Step-1: Creating a class that extends a Thread class

class Mythread extends thread{


}

Step-2 Overriding the run() method

public void run(){

//statements;

}
Here, the run() method is called the entry-point for the user-defined thread, and
all the jobs are done by the user-defined thread will be written here itself.

2.Creating Thread by implementing Runnable Interface

If we want to create the Thread using this approach we have to follow the
following five steps:

Step-1: Creating a class that implements the Runnable interface

class MyThread implements Runnable{


}

Step-2 : Overriding the run() method


public void run(){
//statements;
}

Step-3: Creating an object for user-defined Thread class


MyThread the = new MyThread();

Step-4: Attaching user-defined Thread with main ThreadGroup

Thread t = new Thread(mt);

Step-5: Starting user-defined Thread by calling the start() method


t.start();

Lets us create the thread in two ways

Example to create the Thread by extending the Thread class in Java

class MyThread12 extends Thread

public void run ()

for (int i = 1; i <= 10; i++)


{

System.out.println ("User Thread Value:" + i);

public class MyThread2

public static void main (String[]args)

MyThread12 mt = new MyThread12 ();

Thread t = new Thread (mt);

t.start ();

Output:

Example to create a thread by implementing the Runnable Interface in Java

class MyThread123 implements Runnable


{

public void run ()

for (int i = 1; i <= 10; i++)

System.out.println ("User Thread Value:" + i);

public class MyThread3

public static void main (String[]args)

MyThread123 mt = new MyThread123 ();

Thread t = new Thread (mt);

t.start ();

Output:
Difference between extending thread class and implementing a runnable
interface

If we create any thread by extending the Thread class then we have no chance of
extending from any other class. But if we create any thread by implementing the
Runnable interface then we have a chance for extending from one class. It is
always recommended to create the user define threads by implementing Runnable
Interface only.

Processes and Threads in Java

Single Application running in OS is a process.

A process can have multiple threads.

Java application running in a system is a process and can have

multiple threads inside it.

JVM is creating a thread to start executing the code in the main method and we call this
thread as Main Thread.

It is the Operating System that schedules the threads to be processed by the Processor.
So the scheduling behavior is dependent on the OS.

Again there is a Thread Scheduler inside JVM which coordinates with OS Scheduler.

Difference Between Process and Thread


Process:

1. The process is heavyweight or resource-intensive.


2. Process switching needs interaction with the operating system.
3. In multiple processing environments, each process executes the same code but
has its own memory and file resources.
4. If one process is blocked then no other process can execute until the first process
is unblocked.
5. Multiple processes without using threads use more resources.
6. In multiple processes, each process operates independently of the others.
Thread:

1. Thread is lightweight taking lesser resources than a process.


2. Thread switching does not need to interact with the operating system.
3. All threads can share the same set of open files and child processes.
4. While one thread is blocked and waiting, the second thread in the same task can
run.
5. Multiple threaded processes use fewer resources.
6. One thread can read, write, or change another thread’s data.

What is the Main Thread in Java?

For every Java program, there will be a default thread created by JVM which is nothing
but Main Thread. The entry point for Main Thread is the main() method.

Why is Main Thread so important?

1. Because this thread affects the other ‘child’ threads


2. Because it performs various shutdown actions
3. It is created automatically when your program is started.
Example to display the info of the currently Running Thread in Java
public class ThreadingDemo

public static void main (String[]args)

Thread ct = Thread.currentThread ();

System.out.println (ct);
System.out.println (ct.getName ());

System.out.println (ct.getPriority ());

System.out.println (ct.getThreadGroup ());

Output:

Thread Life Cycle in Java with Examples

A thread goes through various stages in its life cycle. According to Sun, there are only 4
states in the thread life cycle in java new, runnable, non-runnable, and terminated. There
is no running state. But for a better understanding of the threads, we are explaining it in
the 5 states. The life cycle of the thread in java is controlled by JVM.

For a better understanding please have a look at the below diagram. The java thread
states are as follows:

1. Newborn
2. Runnable
3. Running
4. Blocked (Non-Runnable)
5. Dead (Terminated)
Following are the stages of the life cycle –

New – A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread. It is also referred to as a born thread. In simple words, a thread
has been created, but it has not yet been started. A thread is started by calling its start()
method.

Runnable – The thread is in the runnable state after the invocation of the start() method,
but the thread scheduler has not selected it to be the running thread. A thread starts life
in the Ready-to-run state by calling the start method and waiting for its turn. The thread
scheduler decides which thread runs and for how long.

Running – When the thread starts executing, then the state is changed to a “running”
state. The scheduler selects one thread from the thread pool, and it starts executing in the
application.

Dead – This is the state when the thread is terminated. The thread is in a running state
and as soon as it is completed processing it is in a “dead state”. Once a thread is in this
state, the thread cannot even run again.
Blocked (Non-runnable state):

This is the state when the thread is still alive but is currently not eligible to run. A thread
that is blocked waiting for a monitor lock is in this state.

The non-runnable states can be characterized as follows:

1. Sleeping:- The thread sleeps for a specified amount of time.


2. Blocked for I/O:- The thread waits for a blocking operation to complete.
3. Blocked for Join completion: – The thread awaits completion of another thread.
4. Waiting for notifications: – The thread awaits a notification from another thread.
5. Blocked for lock acquisition: – The thread waits to acquire the lock of an object.

JVM executes a thread based on its priority and scheduling.

Example: Thread Life Cycle in Java

Here we are giving a simple example of the Thread life cycle. In this example, we will
create a Java class where we will create a Thread, and then we will use some of its
methods that represents its life cycle.

A1.java
class A1 extends Thread

public void run ()

System.out.println ("Thread A");

System.out.println ("i in Thread A ");

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


{

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

try

Thread.sleep (1000);

catch (InterruptedException e)

e.printStackTrace ();

Thread Scheduler in Java:

JVM implements one of the following scheduling strategies

• Preemptive scheduling: If a thread with a higher priority than the current running
thread, then the current running thread is preempted(moves to the ready-to-run
state) to let the higher priority thread execute.

• Time-sliced or Round-Robin scheduling: A running thread is allowed to execute


for a fixed length of time, after which it moves to the Ready-to-run state to wait its
turn to run again.

Thread Priority in Java:

Priority means the number of resources allocated to a particular thread. Every thread
created in JVM is assigned a priority. The priority range is between 1 and 10.

1. 1 is called minimum priority


2. 5 is called normal priority
3. 10 is called maximum priority
4.
The default priority of the main thread is 5, child thread will take the priority that is equal
to its parent thread priority. We can change the priority of any thread whether it may be
the main thread or a user-defined thread. It is recommended to change the priority by
using constants available in the Thread class as follows:

1. Thread.MIN_PRIORITY;

2. Thread.NORM_PRIORITY;

3. Thread.MAX_PRIORITY;

Example to understand Java Thread Priority:


public class ThreadPriority extends Thread

public void run ()

System.out.println ("running thread name is:" + Thread.currentThread ().getName ());

System.out.println ("running thread priority is:" + Thread.currentThread ().getPriority ());

public static void main (String args[])

ThreadPriority m1 = new ThreadPriority ();

ThreadPriority m2 = new ThreadPriority ();

m1.setPriority (Thread.MIN_PRIORITY);

m2.setPriority (Thread.MAX_PRIORITY);

m1.start ();

m2.start ();
}

Output:

Thread Synchronization in Java

The process of allowing multiple threads to modify an object in a sequence is called


synchronization.

We can allow multiple threads to modify the objects sequentially only by executing that
objects’ mutator methods logic in sequence from multiple threads.

This is possible by using an object locking concept.

Thread Synchronization is a process of allowing only one thread to use the object when
multiple threads are trying to use the particular object at the same time.

To achieve this Thread Synchronization we have to use a java keyword or modifier called
“synchronized”. Synchronization in java is the capability to control the access of multiple
threads to any shared resource. Java Synchronization is a better option where we want to
allow only one thread to access the shared resource.

General Syntax:

synchronized(objectidentifier)
{
// Access shared variables and other shared resources;
}

Why use Synchronization?

The synchronization is mainly used to :


1. If you start with at least two threads inside a program, there might be a chance
when multiple threads attempt to get to the same resource.
2. It can even create an unexpected outcome because of concurrency issues.

Types of Synchronization

There are basically two types of synchronization available. They are:

1. Process Synchronization: It means sharing system resources by processes in


such a way that, Concurrent access to shared data is handled thereby minimizing
the chance of inconsistent data.

2. Thread Synchronization: It means that every access to data shared between


threads is protected so that when any thread starts operation on the shared data,
no other thread is allowed access until the first thread is done.

Thread Synchronization in Java

There are two types of Thread Synchronization. They are:

1. Mutual Exclusive
2. Cooperation (Inter-Thread Communication) (I will discuss in the next article)
3.
Mutual Exclusive:
Mutual Exclusive helps keep threads from interfering with one another while sharing data.
Mutual Exclusion can be achieved in three ways in java:

1. Synchronized Method
2. Synchronized Block
3. Static Synchronization
Thread Synchronization using Synchronized Method in Java:
Method level synchronization is used for making a method code thread-safe, i.e. only one
thread must be executing this method code.

Syntax :

<access modifier> synchronized method ( parameter)

{
//synchronized code

In the case of the synchronized method, the lock object is:

1. class object – if the given method is static.


2. this object – if the method is non-static. ‘this’ is the reference to the current object
in which the synchronized method is invoked.
Example: Implementation of Synchronized Method in Java
public class Synchronization implements Runnable

int tickets = 3;

static int i = 1, j = 2, k = 3;

synchronized void bookticket (String name, int wantedtickets)

if (wantedtickets <= tickets)

System.out.println (wantedtickets + " booked to " + name);

tickets = tickets - wantedtickets;

else

System.out.println ("No tickets to book");

public void run ()

String name = Thread.currentThread ().getName ();

if (name.equals ("t1"))

bookticket (name, i);

else if (name.equals ("t2"))

bookticket (name, j);


}

else

bookticket (name, k);

public static void main (String[]args)

Synchronization s = new Synchronization ();

Thread t1 = new Thread (s);

Thread t2 = new Thread (s);

Thread t3 = new Thread (s);

t1.setName ("t1");

t2.setName ("t2");

t3.setName ("t3");

t1.start ();

t2.start ();

t3.start ();

Output:

Thread Synchronization using Synchronized Block in Java:


Block-level synchronization is used for making some amount of method code thread-safe.
If we want to synchronize access to an object of a class or only a part of a method to be
synchronized then we can use the synchronized block for it. It is capable to make any part
of the object and method synchronized.

Syntax:
synchronized (object reference expression) {
//code block

Example: Implementation of Synchronized Block in java


class A implements Runnable

int token = 1;

public void run ()

synchronized (this)

Thread t = Thread.currentThread ();

String name = t.getName ();

System.out.println (token + ".....alloted to " + name);

token++;

class SynchroBlock

public static void main (String[]args)

A a1 = new A ();

Thread t1 = new Thread (a1);


Thread t2 = new Thread (a1);

Thread t3 = new Thread (a1);

t1.setName ("t1");

t2.setName ("t2");

t3.setName ("t3");

t1.start ();

t2.start ();

t3.start ();

Output:

Inter-Thread Communication (Cooperation) in Java:

It is a mechanism of communication between two threads or multiple threads that acts on


the common object (owner). To perform the multiple actions at a time we need Inter-thread
communication.

For example online video players, audio players, etc. In both types of players generally,
there are two types of threads: Buffer Thread and Playing Thread.

The buffer Thread is responsible to download content from the server into a buffer memory
and whereas the playing thread is responsible to play content and these actions will be
done based on thread communication only.

Producer-Consumer Problem
Problem:

There are two processes, a producer and a consumer, that share a common buffer with a
limited size. The producer “produces” data and stores it in the buffer, and the consumer
“consumes” the data, removing it from the buffer. Having two processes that run in parallel,
we need to make sure that the producer will not put new data in the buffer when the buffer
is full and the consumer won’t try to remove data from the buffer if the buffer is empty.

Solution:

For solving this concurrency problem, the producer and the consumer will have to
communicate with each other. If the buffer is full, the producer will go to sleep and will wait
to be notified. After the consumer will remove some data from the buffer, it will notify the
producer, and then, the producer will start refilling the buffer again. The same process will
happen if the buffer is empty, but in this case, the consumer will wait to be notified by the
producer.

class ShowRoom

int value;

boolean pro_thread = true;

synchronized void produce (int i)

if (pro_thread == true)

value = i;

System.out.println ("Producer has produced Product " + value);

pro_thread = false;

notify ();

try

wait ();
}

catch (InterruptedException ie)

synchronized int consume ()

if (pro_thread == true)

try

wait();

catch (InterruptedException ie)

pro_thread = true;

notify ();

return value;

class Producer implements Runnable

ShowRoom sr;

Producer (ShowRoom sr)


{

this.sr = sr;

public void run ()

int i = 1;

for (i = 1; i <= 10; i++)

sr.produce (i);

try

Thread.sleep (1000);

catch (InterruptedException ie)

class Consumer implements Runnable

ShowRoom sr;

Consumer (ShowRoom sr)

this.sr = sr;

}
public void run ()

while (true)

int res = sr.consume ();

System.out.println ("Consumer has taken product " + res);

try

Thread.sleep (1000);

catch (InterruptedException ie)

public class ProducerConsumer

public static void main (String[]args)

ShowRoom sr = new ShowRoom ();

Producer p = new Producer (sr);

Consumer c = new Consumer (sr);

Thread t1 = new Thread (p);

Thread t2 = new Thread (c);

t1.start ();
t2.start ();

Output:
UNIT - 5

Java Collections Framework:


NOTE: What is an Array and its Limitation in Java?

What is an Array and its Limitation in Java?


An array is a collection of elements that are started in contiguous memory
locations.
Limitations of Array:
1. The size of an array is fixed, which means once array size is
decided it can’t be increased or decreased. Whit this
sometimes memory may be wasted or sometimes memory
may not be sufficient.
2. There are no predefined functions to perform operations
like insertion, deletion, searching, sorting, etc. So that as a
programmer we have to write our own logic.
3. Array stores only a group of similar elements because of
the problems in an array, Java comes up with a Collection
Framework.

Definition and need of Java Collections Framework:


A collection is a java object that is used to group
homogeneous and heterogeneous and duplicate and unique
objects without size limitation for carrying multiple objects at
a time from one application to another application among
multiple layers of MVC architecture as method arguments
and return type.

What are Collections?

Collections: It is a mechanism of collecting some group of


objects either statically or dynamically. Collections can hold a
group of objects. The size of the collection is not fixed, it
means when we are inserting and deleting the elements than
the size of the collection dynamically increased or decreased.
Every collection internally follows data structures and
contains predefined functions it means we don.t need to write
new logic for performing the operations like Insertion,
Deletion, Searching, Sorting, etc.

What is a Framework?

The framework is a semi-finished reusable application that


provides some common low- level services for serving
reoccurring problems and that can be customized according
to our requirements. For example:
1. The computer is a framework; it can be used by all people
according to their requirements.
2. Switchboard is a framework it can be used by all
people according to theirrequirement.
3. In java struts, hibernate, spring technologies are
frameworks, all thesetechnologies are used by different
companies for developing projects according to the
project requirements.
From Java Point of View, Framework means a collection/set
of well-defined classes and interfaces that provides ready-
made services support to our application. In order to
implement a new feature or a class, there is no need to
define a framework. However, an optimal object-oriented
design always includes a framework with a collection of
classes such that all the classes perform the same kind of
task.

Collection Object:

An object is said to be a collection object if it holds or stores


a group of other objects. The collection never stores any
primitive values, but if we want to store primitive values we
have to represent primitive values as objects.

Collection Class:

Collection class is a class whose object can store a group


of other objects. Example: ArrayList, HashSet, HashMap,
etc. All the collection classes are available in the “java.util”
(utility) package. All the collection interfaces and collection
classes together form a Collection Framework.
Java.util package contains several classes that collect
homogeneous and heterogeneous objects without size
limitation. These classes are usually called collection
framework classes. All the collection classes are classified
into the following four categories:
1. List: It is used to store a group of individual elements
where the elements can be duplicated.

2. Set: It is used to store a group of individual elements but


the elements can’t be duplicated.

3. Queue: It is used to hold multiple elements prior to


processing and is dedicated to storing all the elements
where the order of the elements matter.

4. Map: It is used to store the element in the form of key-


value pairs where the keys can’t be duplicated but values
can be duplicated.
Why these package classes are called Collection Framework?

This package class provides low-level services with well-


defined data structures to solve collecting a heterogeneous
dynamic number of objects as a single entity. Due to this
reason java.util package classes are collectively called the
collection framework.
All collection classes are implementing from
java.io.Serializable so the collection object along with all its
internal objects can be stored in a local file system or can
be sentacross the network to the remote computer. Here the
rule is objects stored in the collection are also should be
Serializable types to store collections in the file.
Collection stores a group of objects as follows:

Here objects o1, o2, o3, and o4 are stored two times
thereby we are wasting thememory within the JVM. To save
the memory within the JVM when the objects are stored in

the collection object, the JVM stores the references of the


objects within the collection objects instead of storing the
copy of objects directly.

Advantages of Java Collection Framework:


1. It is used as a temporary data storage (avoid hitting the
database for getting the same amount of data.
2. It reduces the complexity of the application (i.e. array code
is reduced). That means Reduces programming effort by
providing useful data structures andalgorithms so we don’t
have to write them by our self.
3. Increases performance by providing the high-performance
implementation of useful data structures and algorithms
because the various implementation ofeach interface
are interchangeable, programs can be easily tuned by
switching implementations.
4. We do not have to write code to implement these data
structures and algorithms manually.
5. Our code will be much more efficient as the collections
framework is highly optimized.

Collection Interfaces :

The Collection interface is the root interface of the collections


framework hierarchy. Java does not provide direct
implementations of the Collection interface but provides
implementations of its sub-interfaces like List, Set, and
Queue.
Collection Interface Hierarchy in Java

Collection Interface has the following three sub-interfaces:


1. List Interface
2. Set Interface
3. Queue Interface
Methods of Collection Interface in Java:

This interface contains various methods that can be directly


used by all the collectionswhich implement this interface. They
are:
1. add(Object): This method is used to add an object to the collection.
2. addAll(Collection c): This method adds all the
elements in the given collectionto this collection.
3. clear(): This method removes all of the elements from this collection.
4. contains(Object o): This method returns true if the
collection contains thespecified element.
5. containsAll(Collection c): This method returns true if
all the collection containsall of the elements in the given
collection.
6. equals(Object o): This method compares the specified
object with this collectionfor equality.
7. hashCode(): This method is used to return the hash
code value for thiscollection.
8. isEmplty() : this method return true if this collection contains no
elements.
9. iterator(): This method returns an iterator over the elements in this
collection.
10. max(): This method is used to return the maximum value
present in the collection.
11. parallelStream(): This method returns a parallel Stream
with this collection as its source.
12. remove(Object o): This method is used to remove the
given object from the collection. If there are duplicate
values, then this method removes the first occurrence of
the object.
13. removeAll(Collection c): This method is used to
remove all the objects mentioned in the given collection
from the collection.
14. removeIf(Predicate filter): This method is used to
removes all the elements of this collection that satisfy the
given predicates.
15. retainAll(Collection c): This method is used to retails
only the elements in this collection that are contained in
the specified collection.
16. size(): This method is used to return the number of elements in the
collection.
17. spliterator(): This method is used to create a Spliterator
over the elements in thiscollection.
18. stream(): This method is used to return a sequential
Stream with this collectionas its source.
19. toArray(): This method is used to return an array
containing all of the elements inthis collection.

What is the need for collection framework classes?

In java projects, collection framework classes are used to


store and transport objects of the same and different types
without size limitation.
Project code design with collection framework:
1. As we know every project has three layers Model, View,
and Controller. The model layer application collects data
from DB using ResultSet and stores it in the collection
object and returns this collection object to the controller
layer application.
2. Then the controller layer application reads data from the
collection object and fills it in view layer required code
using HTML components.
3. Finally, this HTML code is passed to the client browser
displays the result to the end-user.
Classes of List Interface

In order to use functionalities of the List interface, we can use these classes:
1. ArrayList
2. LinkedList
3. Vector
4. Stack
These classes are defined in the Collections framework and implement the
List interface.

ArrayList Collection in Java:

ArrayList is the implementation class of List Interface which


is used to store a group of individual objects where duplicate
values are allowed. ArrayList internally follows array
structure, which means in ArrayList all the elements are
stored in contiguous memory locations same as an array, but
ArrayList size is not fixed.
ArrayList is not a synchronized class. If any object is
synchronized we can access only one thread at a time but if
an object is not. synchronized then we can access multiple
threads.

Creating an ArrayList in Java

Syntax : ArrayList<Type> al = new ArrayList<Type>();

Here, Type indicates the type of ArrayList.


ArrayList
Constructors in
Java
ArrayList<E> al =
new
ArrayList<E>();

This constructor is used to create the new ArrayList with a


default capacity of 10 and the size of ArrayList is 0.
ArrayList<E> al = new ArrayList<E>(int capacity);

This constructor is used to create the new ArrayList with a


default capacity of 10 and the size of ArrayList is 0.
ArrayList<E> al = new ArrayList<E>(Collection obj);

This constructor is used to create the new ArrayList by


copying the elements of anyexisting Collection (List, Set).
Points to Remember:

1. size means the number of elements that are stored in Collection.


2. capacity means the memory allocated for elements.
3. <E> is called Generic Parameter type.
4. E is the element type that must be a reference type but not any primitive
type.
5.
Methods of ArrayList: We can use all Collections Method to work with the
ArrayList.

Sample Program to demonstrate ArrayList Collection in Java

import java.util.ArrayList;

import java.util.List;

public class ArrayListDemo

public static void main (String[]args)


{

// Creation of ArrayList

ArrayList <Integer> al = new ArrayList <Integer>();

//adding the elements into the list

al.add (10); //autoboxing

al.add (new Integer (20)); //manual boxing

al.add (30);
al.add (40);

al.add (50);

//Display elements of the List and its Size

System.out.println (al);

System.out.println (al.size ());

//inserting an element into the List at specified location

al.add (1, 77);

System.out.println (al);

System.out.println (al.size ());

//modifying the existing element of the List by specifying its value

al.remove (new Integer (30));

System.out.println (al);

System.out.println (al.size ());

//removing the element of the List by specifying its index position

al.remove (0);

System.out.println (al);
System.out.println (al.size ());

//Displaying elements of List 1 by 1 using for loop (accessing)

for (int i = 0; i < al.size (); i++)

System.out.println (al.get (i));

//Displaying elements of List 1 by 1 using forEach Loop (auto-unboxing)

for (int v:al)

System.out.println (v);

//Searching an element

System.out.println (al.contains (50));

//Copying
Output: the array list into another list

ArrayList < Integer > al1 = new ArrayList < Integer > (al);

System.out.println (al1);

}
Note: In add(), remove(), get(), set() methods if we write any
wrong index which is not available then it will throw a run time
exception called IndexOutOfBoundException. ArrayList
supports storing multiple null values.

LinkedList Collection in Java with Examples:

LinkedList is the implementation class of List Interface which


is also used to store a group of individual objects where
duplicate values are allowed. LinkedList internally follows a
doubly linked list structure where all the elements are stored
in the form of nodes that linked each other.
The LinkedList in Java is not a synchronized class. LinkedList
also supports multiple null values. This provides the
functionality of LinkedList Data Structure.
Each element in a linked list is known as a node. It consists of 3 fields:
1. Prev – stores an address of the previous element in the
list. It is null for the firstelement.
2. Next – Stores an address of the next element in the
list. It is null for the lastelement.
3. Data – Stores the actual data
Note: Elements in linked lists are not stored in sequence.
Instead, they are scatteredand connected through links (Prev
and Next).

Creation of LinkedList

Syntax : LinkedList<Type> ll = new LinkedList<Type>();

Here, Type indicates the type of LinkedList.


LinkedList Constructors

LinkedList<E> ll = new LinkedList<E>();

It is used to construct an Empty List.


LinkedList<E> ll = new LinkedList<E>(Collection obj);

It is used to construct a list containing the elements of the


specified collection, in the order, they are returned by the
collection’s iterator.
Note: There is no capacity concept for LinkedList.
Methods of LinkedList: We can use all Collections Method to work with the
LinkedList.

Sample Program to demonstrate LinkedList Collection in Java


import java.util.*;

class LinkedListDemo

public static void main (String[]args)

LinkedList < String > animals = new LinkedList <> ();

// Add elements to LinkedList

animals.add ("Dog");

animals.add ("Cat");

animals.add ("Horse");

System.out.println ("LinkedList: " + animals);


// Get the element from the linked list

String str = animals.get (1);

System.out.print ("Element at index 1: " + str);

System.out.println (" ");

//Iterator method

Iterator < String > itr = animals.iterator ();

while (itr.hasNext ())

System.out.println (itr.next ());

}
Output:

Difference Between ArrayList and LinkedList in Java:

ArrayList is slower in insertion and deletion of elements


because it internally requires shifting operations, but faster in
accessing the elements because ArrayList uses index
position for every element.

LinkedList is faster in insertion and deletion of elements


because it just requires modifying the links of nodes instead
of shifting operations, but slower in accessing the elements
because LinkedList does not use any index position.

Vector Collections in Java

Vector is an implemented class of List Interface. Vector class


methods are by default synchronized. It is used to store a
group of individual objects where duplicate values are
allowed.
Vector is exactly similar to ArrayList but ArrayList is not a
synchronized class where Vector is a synchronized class.
Vector is also called legacy class because it is available from
Java 1.0 Version. It is similar to the ArrayList, but with two
differences-
1. The vector is synchronized.
2. Java Vector contains many legacy methods that are not
part of a collections framework.
Note: It is recommended to use ArrayList in place of Vector
because vectors are not thread-safe and are less efficient.

Creation of Vector

Syntax : Vector<Type> vector = new Vector<Type>();

Here, Type indicates the type of Vector.


Vector Constructors

Vector<E> v = new Vector<E>();

This constructor creates a single dimension array with a default capacity of


10.
Vector<E> v = new Vector<E>(int capacity);

This constructor sets a given capacity as a current capacity to a single


dimension array.
Vector<E> v = new Vector<E>(Collection obj);

This constructor is used for migrating one collection with


another collection for transferring data.

Methods of Vector
We can use all Collections Method to work with the
LinkedList. We can also use legacy methods like
addElement(), removeElement(), setElement(),….
Sample Program to demonstrate Vector Collection in Java
import java.util.*;

class VectorDemo {

public static void main(String[] args) {

Vector<String> mammals= new Vector<>();

// Using the add() method


mammals.add("Horse");
mammals.add("Dog");
// Using index number

mammals.add(2, "Cat");

System.out.println("Vector: " + mammals);

// Using addAll()

Vector<String> animals = new Vector<>();

animals.add("Crocodile");

animals.addAll(mammals);

System.out.println("New Vector: " + animals);

// Using get()

String element = animals.get(2);


System.out.println("Element at index 2: " + element);

// Using iterator()

Iterator<String> iterate = animals.iterator();

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

while(iterate.hasNext()) {

System.out.print(iterate.next());

System.out.print(", ");

Output:

Stack Collection in Java:

In Java, Stack is a class that falls under the Collection


framework that extends the Vector class. The stack is a child
class of Vector and implements List Interface. The stack
stores a group of objects by using a mechanism called LIFO.
LIFE stands for Last In First Out, which means the last
inserted element deleted first.
The stack data structure has the two most important
operations that are push and pop. The push operation inserts

an element into the stack and the pop operation removes an


element from the top of the stack.

Creation of Stack

Syntax : Stack<Type> stacks = new Stack<Type>();

Here, Type indicates the Stack’s type.

S
t
a
c
k
C
o
n
s
t
r
u
c
t
o
r
p
u
b
l
i
c
S
t
a
c
k
(
)

The Stack class contains only the default constructor that creates an empty
stack.

Methods of Stack

We can use all Collection Methods. We can also use legacy


methods of Vector Class like addElement(),
removeElement(), setelementAt(), etc. But if we want to
follow the LIFO mechanism we should use Stack methods
like follows:
1. E push(E obj): This method will add new elements to the stack.
2. E pop(): This method deletes the top element available on Stack.
3. E peek(): This method just returns the top element available on Stack.
Sample Program to demonstrate Stack Collection in Java

import java.util.*;

public class StackDemo {

public static void main(String[] args) {

Stack<Double> s = new Stack<Double>();

s.push(10.2);

s.push(50.2);

s.push(30.2);

s.push(40.2);

s.push(70.2);

System.out.println(s);

System.out.println(s.pop());

System.out.println(s);

System.out.println(s.peek());

System.out.println(s);
Output:

ava Hashtable class


Java Hashtable class implements a hashtable, which maps
keys to values. It inheritsDictionary class and implements the
Map interface.

Points to remember
o A Hashtable is an array of a list. Each list is known as a
bucket. The position of the bucket is identified by calling
the hashcode() method. A Hashtable contains values
based on the key.
o Java Hashtable class contains unique elements.

o Java Hashtable class doesn't allow null key or value.

o Java Hashtable class is synchronized.

o The initial default capacity of Hashtable class is 11 whereas loadFactor


is 0.75.

Hashtable class declaration

Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V>


implements Map<K,V>, Cloneable,Serializable
Hashtable class Parameters

Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.

o V: It is the type of mapped values.

Java Hashtable Example

import java.util.*;

1. class Hashtable1{
2. public static void main(String args[]){
3. Hashtable<Integer,String>
hm=new Hashtable<Integer,String>(); 4.
hm.put(100,"Amit");
5. hm.put(102,"Ravi");

6. hm.put(101,"Vijay");
7. hm.put(103,"Rahul");
8. for(Map.Entry m:hm.entrySet()){
9. System.out.println(m.getKey()+" "+m.getValue());
10. }

11. }

12. }

Compile by: javac TestCollection16.java

13.Run by: java TestCollection16

14.103 Rahul
102 Ravi
101 Vijay
100 Amit

File Operations in Java


In Java, a File is an abstract data type. A named location
used to store relatedinformation is known as a File. There
are several File Operations like creating a new File,
getting information about File, writing into a File,
reading from aFile and deleting a File.
Method Return Type Description

canRead() Boolean The canRead() method is used to chec


we can read the
data of the file or not.

createNewFile() Boolean The createNewFile() method is used t


a new empty file.

canWrite() Boolean The canWrite() method is used to che


we can write the data into the file or no

exists() Boolean The exists() method is used to check w


the specified file is present or not.

delete() Boolean The delete() method is used to delete

getName() String The getName() method is used to find

getAbsolutePath() String The getAbsolutePath() method is use


to get the absolute pathname of the fil

length() Long The length() method is used to get th


size of the file in bytes.

list() String[] The list() method is used to get an arr


files available in the directory.
mkdir() Boolean The mkdir() method is used for
creating a new directory.

Before understanding the File operations, it is required that


we should have knowledge of Stream and File methods.
If you have knowledge about both of them,you can skip it.

Stream
A series of data is referred to as a stream. In Java, Stream
is classified into two types,i.e., Byte Stream and Character
Stream.
Byte Stream

Byte Stream is mainly involved with byte data. A file


handling process with a byte stream is a process in which
an input is provided and executed with the byte data.

Character Stream

Character Stream is mainly involved with character data.


A file handling process witha character stream is a process
in which an input is provided and executed with the
character data.

To get more knowledge about the stream, click here.

Java File Class Methods

File Operations
We can perform the following operation on a file:

o Create a File

o Get File Information

o Write to a File

o Read from a File

o Delete a File
Create a File

Create a File operation is performed to create a


new file. We usethe createNewFile() method of file.
The createNewFile() method returns true when it
successfully creates a new file and returns false when the
file already exists.

Let's take an example of creating a file to understand


how we can usethe createNewFile() method to perform
this operation.

CreateFile.java

1. // Importing File class


2. import java.io.File;
3. // Importing the IOException class for handling errors
4. import java.io.IOException;
5. class CreateFile {
6. public static void main(String args[]) {
7. try {
8. // Creating an object of a file
9. File f0 = new File("D:FileOperationExample.txt");
10. if (f0.createNewFile()) {
11. System.out.println("File " + f0.getName() + " is created
successfully.");
12. } else {
13. System.out.println("File is already exist in the directory.");
14. }

15. } catch (IOException exception) {


16. System.out.println("An unexpected error is occurred.");
17. exception.printStackTrace();
18. }

19. }

20. }

Output:

Explanation:

In the above code, we import the File and IOException class


for performing file operation and handling errors,
respectively. We create the f0 object of the File class and
specify the location of the directory where we want to
create a file. In the try block, we call the createNewFile()
method through the f0 object to create a new file

in the specified location. If the method returns false, it will


jump to the else section. Ifthere is any error, it gets handled
in the catch block.

Get File Information

The operation is performed to get the file information. We


use several methods to get the information about the file
like name, absolute path, is readable, is writable and
length.

Let's take an example to understand how to use file


methods to get the information of the file.

FileInfo.java

1. // Import the File class


2. import java.io.File;
3. class FileInfo {
4. public static void main(String[] args) {
5. // Creating file object
6. File f0 = new File("D:FileOperationExample.txt");
7. if (f0.exists()) {
8. // Getting file name
9. System.out.println("The name
of the file is: " + f0.getName());10.
11. // Getting path of the file
12. System.out.println("The absolute path of the
file is: " + f0.getAbsolutePath());13.
14. // Checking whether the file is writable or not
15. System.out.println("Is file
writeable?: " + f0.canWrite());16.
17. // Checking whether the file is readable or not
18. System.out.println("Is
file readable " + f0.canRead());19.
20. // Getting the length of the file in bytes
21. System.out.println("The size of the file in bytes is: " + f0.length());
22. } else {
23. System.out.println("The file does not exist.");
24. }

25. }

26. }

Write to a File

The next operation which we can perform on a file is


"writing into a file". In orderto write data into a file, we
will use the FileWriter class and its write() method
together. We need to close the stream using the close()
method to retrieve the allocated resources.

Let's take an example to understand how we can write data into a file.

WriteToFile.java

1. // Importing the FileWriter class


2. i
m
p
o
r
t
j
a
v
a
.
i
o
.
F
i
l
e
W
r
i
t
e
r
;
3
.
4. // Importing the IOException class for handling errors
5. i
m
p
o
r
t
j
a
v
a
.i
o
.I
O
E
x
c
e
p
ti
o
n
;
6
.
7. class WriteToFile {
8. public
static void
main(String[]
args) {9.
10. try {
11. FileWriter fwrite = new FileWriter("D:FileOperationExample.txt");
12. // writing the content into the FileOperationExample.txt file
13. fwrite.write("A named location used to store related information is referred
to as a File.")
;

14.14.
15. // Closing the stream
16. fwrite.close();
17. System.out.println("Content is successfully wrote to the file.");
18. } catch (IOException e) {
19. System.out.println("Unexpected error occurred");
20. e.printStackTrace();
21. }

22. }

23. }
Output:

Explanation:

In the above code, we import the java.io.FileWriter and


java.io.IOException classes.We create a class WriteToFile,
and in its main method, we use the try-catch block. In the
try section, we create an instance of the FileWriter class,
i.e., fwrite. We call the write method of the FileWriter class
and pass the content to that function which we want to
write. After that, we call the close() method of the
FileWriter class to close the file stream. After writing the
content and closing the stream, we print a custom
message.

If we get any error in the try section, it jumps to the catch


block. In the catch block, we handle the IOException and
print a custom message.
Read from a File

The next operation which we can perform on a file is "read


from a file". In order to write data into a file, we will use
the Scanner class. Here, we need to close the streamusing
the close() method. We will create an instance of the
Scanner class and use the hasNextLine() method
nextLine() method to get data from the file.

Let's take an example to understand how we can read data from a file.

ReadFromFile.java

1. // Importing the File class


2. import java.io.File;
3. // Importing FileNotFoundException class for handling errors
4. import java.io.FileNotFoundException;
5. // Importing the Scanner class for reading text files
6. i
m
p
o
r
t
j
a
v
a
.
u
t
i
l
.
S
c
a
n
n
e
r
;
7
.
8. class ReadFromFile {
9. public static void main(String[] args) {
10. try {
11. // Create f1 object of the file to read data
12. File f1 = new File("D:FileOperationExample.txt");
13. Scanner dataReader = new Scanner(f1);
14. while (dataReader.hasNextLine()) {
15. String fileData = dataReader.nextLine();
16. System.out.println(fileData);
17. }

18. dataReader.close();
19. } catch (FileNotFoundException exception) {
20. System.out.println("Unexcpected error occurred!");
21. exception.printStackTrace();
22. }

23. }

24. }
Output:

You might also like