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

JAVA Internship PROGRAMING

Java, created by James Gosling and initially named OAK, is an open-source programming language designed for developing web, desktop, enterprise, mobile, and embedded applications. It operates on a multi-operating system environment and is known for its core feature 'WORA' (write once, run anywhere). Java consists of three main categories: J2SE for client-side applications, J2EE for server-side applications, and J2ME for mobile applications.

Uploaded by

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

JAVA Internship PROGRAMING

Java, created by James Gosling and initially named OAK, is an open-source programming language designed for developing web, desktop, enterprise, mobile, and embedded applications. It operates on a multi-operating system environment and is known for its core feature 'WORA' (write once, run anywhere). Java consists of three main categories: J2SE for client-side applications, J2EE for server-side applications, and J2ME for mobile applications.

Uploaded by

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

JAVA PROGRAMING

Overview of Java
JAVA introduction:-
Author : James Gosling
Vendor : Sun Micro System
Project name : Green Project
Type : open source & free software
Initial Name : OAK language
Present Name : java
Extensions : java & .class & .jar
Initial version : jdk 1.0 (java development kit)
Présent version : java 10/11c
Operating System : multi Operating System
Implementation Lang : c, cpp……
Symbol : coffee cup with saucer
Objective : To develop web applications
SUN : Stanford Universally Network
Slogan/Motto : WORA(write once run anywhere)
Features of Java
Importance of core java:-

1) Java is used to develop Desktop Applications such as Media Player, Antivirus etc.

2) Java is Used to Develop Web Applications such as durgajobs.com, irctc.co.in etc.

3) Java is Used to Develop Enterprise Application such as Banking applications.

4) Java is Used to Develop Mobile Applications.

5) Java is Used to Develop Embedded System.

6) Java is Used to Develop Smartcards.

7) Java is Used to Develop Robotics.

8) Java is used to Develop Games etc.


Technologies Depends on Core java

Advance
Java

Hadoop
and Big Android
data
Core
Java

Selenium Cloud
Testing Computing
Java categories

Java divided into three categories, they are


• J2SE (Java 2 Standard Edition)
• J2EE (Java 2 Enterprise Edition)
• J2ME (Java 2 Micro or Mobile Edition)

J2SE
• J2SE is used for developing client side applications.

J2EE
• J2EE is used for developing server side applications.

J2ME
• J2ME is used for developing mobile or wireless application by making use of a
predefined protocol called WAP(wireless Access / Application protocol).
Object Oriented Languages Comparison
Objective
Feature C++ C Ada Java

Encapsulation Yes Yes Yes Yes


Inheritance Yes Yes No Yes
Multiple Inherit. Yes Yes No No
Polymorphism Yes Yes Yes Yes
Binding (Early/Late) Both Both Early Late
Concurrency Poor Poor Difficult Yes
Garbage Collection No Yes No Yes
Genericity Yes No Yes No
Class Libraries Yes Yes Limited Yes
Steps for Setting up Java Environment for Windows
Basic of Java
 Java is a platform independent, more powerful, secure, high performance, multithreaded

programming language. Here we discuss some points related to java.

 Define byte

Byte code is the set of optimized instructions generated during compilation phase and it is more

powerful than ordinary pointer code.

 Define JRE

The Java Runtime Environment (JRE) is part of the Java Development Kit (JDK). It contains set of

libraries and tools for developing java application. The Java Runtime Environment provides the

minimum requirements for executing a Java application.

 Define JVM

JVM is set of programs developed by sun Micro System and supplied as a part of jdk for reading

line by line line of byte code and it converts into native understanding form of operating system.

Java language is one of the compiled and interpreted programming language.


JDK JVM AND JRE
JDK JVM and JRE
• JVM
JVM (Java Virtual Machine) is a software. It is a specification that provides
runtime environment in which java bytecode can be executed. It not
physically exists.

JVMs are not same for all hardware and software, for
example for window os JVM is different and for Linux VJM is different.
JVM, JRE and JDK are platform dependent because configuration of each
OS differs. But, Java is platform independent.
JDK
• The Java Development Kit (JDK) is primary components. It physically exists.
It is collection of programming tools and JRE, JVM.
JRE
The Java Runtime Environment (JRE) is part of the Java Development
Kit (JDK). It contains set of libraries and tools for developing java application.
The Java Runtime Environment provides the minimum requirements for
executing a Java application. It contains set of libraries + other files that JVM
uses at runtime.
JRE
JVM Architecture in Java
JVM (Java Virtual Machine) is a software. It is a specification that provides
Runtime environment in which java bytecode can be executed
Working of Java
Platform Independent
Java Environment/Life Cycle of
Java Code
Runtime
Compile-time Environment Class
Environment Java
Loader
Class
Bytecode Libraries
Java Verifier
Source
(.java)

Just in
Java
Time
Interpreter Java
Java Compiler
Byte codes Virtual
Java move locally machine
Compiler or through
network
Runtime System

Java
Bytecod Operating System
e
(.class )
Hardware
First Java Program
Requirements for java Program
 For executing any java program we need given things.
 Install the JDK any version if you don't have installed it.
 Set path of the jdk/bin directory.
 Create the java program
 Compile and run the java program

Steps For compiling and executing the java program


 Java is very simple programming language first we write a java program and save it with program
class name.
 create a java program with "First" name so we save this program with "First.java" file name. We can
save our java program anywhere in our system or computer.
Structure of Java Program
Main() Method in Java
Public
public is a keyword in a java language whenever if it is preceded by main() method the scope is
available anywhere in the java environment that means main() method can be executed from
anywhere. main() method must be accessed by every java programmer and hence whose access
specifier must be public.
Static
static is a keyword in java if it is preceded by any class properties for that memory is allocated only
once in the program. Static method are executed only once in the program. main() method of java
executes only once throughout the java program execution and hence it declare must be static.
Void
void is a special datatype also known as no return type, whenever it is preceded by main() method
that will be never return any value to the operating system. main() method of java is not returning
any value and hence its return type must be void.
String args[]
String args[] is a String array used to hold command line arguments in the form of String values.
Create First Program
Example
class First
{
public static void main(String[] args)
{
System.out.println("Hello Java");
System.out.println("My First Java Program");
}
}
Compile and Execute Java Code
To compile: javac First.java
To execute: java First Output
Hello Java
MyFirst Java Program
Java Language
• Character set
• Keyword
• Identifiers
• Variables
• Data Types
• Literals
• Operators
• Control Statements
Character Set
• It is a list of characters which developer can use for writing java code.
• Java character set allows the following 3 types

1: Digits:- (0-9)
2: Alphabets:- (A-Z,a-z)
3:Special symbols:- (+,-,/,*……..etc)
Keywords
Primitive Data Type Userdefined Access Exceptio Control Statements Modifiers Miscellaneous DataLiteral
data type Modifiers ns values
Handling

byte class Private try if static new null

short interface Protected catch Else final void true

Int enum Public finally For abstract extends false

long throw Do volatile implements

float throws While synchronized this

double Switch transient super

char Case native instanceof

boolean Default strictfp const(resereved


)

Break assert

Continue import

Return package
And goto (reservered)
IDENTIFIERS
• It is a name giving to variable,method,class,interface etc…
• It should contains alphabets,digitsand only 2 symbols.(_ underscore and $ dollar).
• 1st character should be alphabet, _ or $and it cannot be a digit.
• It can not have space.
• It can not be a keyword.
• Identifiers are casesensitive.

valid Identifiers invalid identifiers

AVERAGE 123abc

abc123 if

$test &abc

if9 abc 123

_123 student name


Examples
class Test1
class Test
{
{
public static void main(String args[])
public static void main(String args[])
{
{
int String=10;
int x=10;
System.out.println(String);
}
}
}
}
Note : Not recommended
class Test2
{
public static void main(String args[])
{
int Runnable=100;
System.out.println(Runnable);
}
}
Note : Not recommended
Variable
 Variable is a named memory that may be assigned a value
 Value in a variable can be changed or modified
Syntax:
Datatype variableName = value
int a=10;
double d=10;
Rules:
 Every variable name should start with either alphabets or underscore ( _ ) or
dollar ( $ ) symbol.
 No space are allowed in the variable declarations.
 Except underscore ( _ ) no special symbol are allowed in the middle of variable
declaration
 Variable name always should exist in the left hand side of assignment
operators.
 Maximum length of variable is 64 characters.
 No keywords should access variable name.
Data Types

Primitive Type Derived Types User Defined Data Types


Primitive Type

Numeric Boolean Character


Datatype Datatype Datatype

Integer Floating
Data Type Data Type
Numeric Datatype
Integer Datatype

byte

short

int

long
byte DataType short DataType int DataType
 Size: 8bits  Size: 2 bytes  Size: 4 bytes
 Max-Size: 127  Range:- -32768 to  Range:-
 Min-Size:-128 32767 -2147483648 to
 Range:-128 to 127 Ex: short s=32767; 2147483648
Ex: byte b=100; Ex: int i=100;
boolean DataType
byte b=127; float DataType
 Size: not applicable
 Size: 4 byte
 Range:-not applicable
 Range: -3.4e38 to
long DataType Ex: boolean b=true;
 Size: 8 byte 3.4e38
 Range:- -2pow(63) Ex: float f=10.10;
double DataType
to 2 pow(63)-1 char DataType
 Size: 8 bytes
Ex: long  Size: 2 bytes
 Range:--1.7e308 to
l=10000000;  Range:- 0 to 65535
1.7e308
Ex: char ch=‘a’;
Ex: double d=1254.215;
Literals
• It is a value.

• Literal value should be stored in corresponding data type.

• It can be one of the following 5 types

a)Integer literal

b)Floating point literal

c)Boolean literal

d)Character literal

e)String literal
Operators in Java

Operator is a special symbol that tells the compiler to perform specific


mathematical or logical Operation. Java supports following lists of operators.

Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Ternary or Conditional Operators
Operators in Java
Control Statements in Java

Decision
Looping
making
Statements
Statements

Transfer Statements
Decision making Statements Looping Statements
 if  while
 if-else  do-while
 switch  for

 for each
Transfer Statements
• break
• continue
• return
• try
• catch
• final
System.out.println() in Java
• In java language print() and println() are the predefined non-static method of printStream class used to
display value or message either in the same line or line by line respectively. PrintStream class is having fixed
object reference in the System class (existing as a static properties) so that either print() or println() method
can be called with following syntax..

Syntax
System.out.print("--------------");
System.out.println("------------");
/* "out" is Object reference of printStream class existing in system class as a static
property. */
Java Variables
Variables are used to store the values. By storing that values we are
achieving the functionality of the project.
 While declaring variable we must specify the type of the variable by using
data type’s concept.

In the java language we are having three types of variables

1. Local variables

2. Instance variables

3. Static variables
Class vs. Object:-

Class is a group of objects that have common property.


Java is classes based based language we are able to design the program by
using classes and objects.
Object is a real world entity. Object orientation is methodology to design a
program by using classes and objects.
Object is physical entity where as class is a logical entity.
A class is a template or blue print from which type of objects are created.
Object is nothing but instance of a class.
Every objects contains 3 characteristics
1. State(represent data of an object)
2. Behavior(represent behavior of an object)
3. Identity(used to identify the objects uniquely).

PEN(object):-
State:- name raynolds,color red etc……
Behavior:- used to write
A simple class example

class Student. Student std=new


{ Student();
String name;
int rollno;
int age;
}
Methods in Java
Method describe behavior of an object. A method is a collection of statements that are
group together to perform an operation.
Syntax :

return-type methodName(parameter-
list)
{
//body of method
}
Example of a Method

public String getName(String st)


{
String name=“Welcome To Inventron";
name=name+st;
return name;
}
Parameter Vs. Argument
Method overloading
If two or more method in a class have same name but different parameters, it is known
as method overloading.
Method overloading is one of the ways through which java supports polymorphism.
Example class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is
called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is
called.
}
Constructors in Java
A constructor is a special method that is used to initialize an object.
Every class has a constructor,
If we don't explicitly declare a constructor for any java class the compiler builds a
default constructor for that class.
A constructor does not have any return type.
A constructor has same name as the class in which it resides. Constructor in Java can
not be abstract, static, final or synchronized. These modifiers are not allowed for
constructor.

class Car There are two types of Constructor


{
Default Constructor
String name ;
Parameterized constructor
String model;
Car( ) //Constructor
Car c = new Car() //Default constructor
{ invoked Car c = new Car(name);
name =""; //Parameterized constructor invoked
model="";
}
}
Constructor Overloading
Constructor overloading you have multiple constructor with different signature but only
difference is that Constructor doesn't have return type in Java.
class Cricketer { Class Test {
String name; public static void main (String[]
String team; args)
int age; {
Cricketer () {
name ="";
Cricketer c1 = new Cricketer();
team =""; Cricketer c2 = new Cricketer("sachin",
age = 0; "India", 32);
} Cricketer c3 = new Cricketer(c2 );
Cricketer(String n, String t, int a){ System.out.println(c2);
name = n; System.out.println(c3);
team = t;
age = a;
c1.name = "Virat";
} c1.team= "India";
Cricketer (Cricketer ckt) { c1.age = 32;
name = ckt.name; System .out. println(c1);
team = ckt.team; }
age = ckt.age;
}
}
public String toString()
{
return "this is " + name + " of "+team;
Output
} ……………
}
this is sachin of india
this is sachin of india
this is virat of india
Modifiers in Java
Default : Default has scope only inside the same package
Public : Public has scope that is visible everywhere
Protected : Protected has scope within the package and all sub classes
Private : Private has scope only within the classes
Rules For Access Modifiers
Object Oriented Concepts

Main Features of OOPS


Inheritance
Polymorphism
Encapsulation
Abstraction
Inheritance
Inheritance is one of the key features of Object Oriented Programming. Inheritance
provided mechanism that allowed a class to inherit property of another class.
When a Class extends another class it inherits all non-private members including
fields and methods.
Inheritance in Java can be best understood in terms of Parent and Child
relationship, also known as Super class(Parent) and Sub class(child) in Java language.

Purpose of Inheritance

1. It promotes the code reusability i.e. the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
Aggregation (HAS-A)
class Student {
String name;
Address ad;
}
Method Overriding
1. When a method in a sub class has same name, same number of arguments and
same type signature as a method in its super class, then the method is known as
overridden method.
2. Method overriding is also referred to as runtime polymorphism.
3. The key benefit of overriding is the abitility to define method that's specific to a
particular subclass type.

class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}
class Dog extends Animal {
public void eat() //eat() method overriden by Dog
class.
{
System.out.println("Dog eat meat");
}
}
Difference between Overloading and Overriding

Method Overloading Method Overriding


Parameter must be different and name Both name and parameter must be
must be same. same.

Compile time polymorphism. Runtime polymorphism.


Increase readability of code. Increase reusability of code.
Access specifier can be changed. Access specifier cannot be more
restrictive than original method(can be
less restrictive).
Java Package
1. Package are used in Java, in-order to avoid name conflicts and to control access of
class, interface and enumeration etc.
2. A package can be defined as a group of similar types of classes, interface,
enumeration or sub-package.
3. Using package it becomes easier to locate the related classes and it also provides
a good structure for projects with hundreds of classes and other files.

Types of Packages: Built-in and User defined


•Built-in Package: Existing Java package for example java.lang, java.util etc.
•User-defined-package: Java package created by user to categorize their project's classes and interface.
Import statements in Java
Import is a keyword in java language used to import the
predefined properties of java API into current working java
program.

Syntax
import package1.package2.......*;
Array In Java
• Array is a collection of similar type of data. It is fixed in size that means you can't increase the
size of array at run time. It is collection of homogeneous data elements. It store the value on
the basis of index value.

Advantage of Array
One variable can store multiple value: The main advantage of array is we can represent
multiple value under the same name.
Code Optimization: No, need to declare a lot of variable of same type data, We can retrieve
and short data easily.
Random access: We can retrieve any data from array with the help of index value.
Disadvantage Of Array
The main limitation of array is Size Limit when once we declare array there is no chance to
increase and decrease the size of array according to our requirement, Hence memory point of
view array concept is not recommended to use. To over come this limitation in java introduce
collection concept.

Types of Array
There are two types of array in java.
 Single Dimensional Array
 Multidimensional Array
Single dimension array declaration. 2D Array declaration.
Syntax Syntax
1. int[][] a;
1. int[] a;
2. int a[][];
2. int a[]; 3. int [][]a;
3. int []a; 4. int[] a[];
5. int[] []a;
Note: At the time of array declaration we can not specify the size of array.
6. int []a[];
For Example int[5] a; this is wrong.
Array creation
Every array in a java is an object, Hence we can create array by using new keyword.
Syntax
int[] arr = new int[10]; // The size of array is 10
or
int[] arr = {10,20,30,40,50};

Accessing array elements


Access the elements of array by using index value of an elements.

Syntax
arrayname[n-1];
Access Array Elements
int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[2]);
Example Of Array

public class ArrayEx Note:


{ 1) At the time of array creation we must be specify
public static void main(String
the size of array otherwise get an compile time error.
[]args)
For Example
{
int[] a=new int[]; Invalid.
int arr[] = {10,20,30};
for (int i=0; i < arr.length; i++)
int[] a=new int[5]; Valid

{ 2) If we specify array size as negative int value, then


System.out.println(arr[i]); we will get run-time error,
} NegativeArraySizeException.
}
3) To specify array size the allowed data types are
}
byte, short, int, char If we use other data type then
we will get an Compile time error.
4) The maximum allowed size of array in java is
2147483647 (It is maximum value of int data type)
Difference Between Length and Length() in Java

length: It is a final variable and only applicable for array. It represent size of array.
Example
int[] a=new int[10];
System.out.println(a.length); // 10
System.out.println(a.length()); // Compile time error

length(): It is final method applicable only for String objects. It represent number
of character present in String.
Example
String s="Java";
System.out.println(s.length()); // 4
System.out.println(s.length); // Compile time error
Final Keyword In Java
It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance. It is
used at variable level, method level and class level. In java language final keyword can be used in
following way.
Final at variable level
Final at method level
Final at class level
This Keyword In Java
this is a reference variable that refers to the current object. It is a keyword in java
language represents current class object
Usage of this keyword
 It can be used to refer current class instance variable.
 this() can be used to invoke current class constructor.
 It can be used to invoke current class method (implicitly)
 It can be passed as an argument in the method call.
 It can be passed as argument in the constructor call.
 It can also be used to return the current class instance.
Static Block In Java
Static block is a set of statements, which will be executed by the JVM before execution of main
method.
At the time of class loading if we want to perform any activity we have to define that activity
inside static block because this block execute at the time of class loading.
In a class we can take any number of static block but all these blocks will be execute from top
to bottom.

Syntax
static {
........ //Set of
Statements ........
}
Abstract class in Java
We know that every java program must start with a concept of class that is without classes
concept there is no java program perfect. In java programming we have two types of classes
they are
Concrete class
Abstract class

Concrete class in Java


A concrete class is one which is containing fully defined methods or implemented method.

class Helloworld {
void display()
Create an object
{
Helloworld obj=new Helloworld();
System.out.println("Good
obj.display();
Morning........");
}}
Abstract class in Java
A class that is declared with abstract keyword, is known as abstract class. An abstract class is
one which is containing some defined method and some undefined method. In java
programming undefined methods are known as un-Implemented or abstract method.

Syntax
Example
abstract class
abstract class Vachile
className
{
{
abstract void Bike();
......
}
}
Abstract Method
An abstract method is one which contains only declaration or prototype but it never contains body
or definition. In order to make any undefined method as abstract whose declaration is must be
predefined by abstract keyword.

Syntax
abstract ReturnType methodName(List of formal
parameter);

Example of abstract class


abstract class Vachile {
abstract void speed(); // abstract method
}
class Bike extends Vachile {
void speed() {
System.out.println("Speed limit is 40 km/hr.."); }
public static void main(String args[]) { Vachile obj = new Bike(); //indirect object
creation obj.speed(); } }
Create an Object of abstract class
An object of abstract class can not be created directly but it can be created
indirectly. It means you can create an object of abstract derived class. You can
see in above example
Example
Vachile obj = new Bike(); //indirect object creation
Important Points about abstract class
Abstract class of java always contains common features.
Every abstract class participate in inheritance.
Abstract classes definitions should not be made as final because abstract classes always
participate in inheritance classes.
An object of abstract class can not be created directly but it can be created indirectly.
All the abstract classes of java makes use of polymorphism along with method
overriding for business logic development and makes use of dynamic binding for
execution logic.
Advantage Of Abstract Class
Less memory space for the application
Less execution time
More performance
Interfaces
An Interface is a collection of public static final data members and public abstract methods
Notes
 We use implements keyword to implement interface by any class
 Interfaces are basically used to develop user defined data types.
 Interface is a keyword which is used for developing user defined data types
 we cannot create interface object directly but we can create indirectly
 all variables by default belongs to (no need to write explicitly )
 public static final xxx data members
 All methods by default belongs to (no need to write explicitly )
public abstract xxx xxxMethods()

An object of base interface contains the details about those methods which are declared in that interface
only but it does not contain details about those methods which are specially available in either in derived
classes or in derived interfaces.
Interfaces should not be final.(because implement’s not possible)
An interface does not contain Constructors. (because no need of create objects)
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.

5) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.

6) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
java.lang Package

We have mainly five classes in java.lang. Which are most commonly used in any java
program
1. Object
2. String
3. StringBuffer
4. StringBuilder
5. Wrapper Classes (AutoBoxing / AutoUnboxing)
Wrapper class
Wrapper class in java provides the mechanism to convert primitive into object
and object into primitive.Wrapper classes are basically used for converting the
string data into fundamental data type.
Primitive
Type Wrapper class String to Primitive Primitive to Wrapper

boolean Boolean P s booean parseBoolean(str) Boolean.valueOf(bo)

char Character p s char parseChar (str) Char. valueOf (char)

byte Byte p s byte parseByte (str) Byte. valueOf (byte)

short Short p s short parseShort (str) Short. valueOf (short)

int Integer p s int parseInt (str) Integer. valueOf (int)

long Long p s long parseLong (str) Long. valueOf (long)

float Float p s float parseFloat (str) Float. valueOf (float)

double Double p s double parseDouble(str) Double. valueOf (dou)


Object class Methods

1. Public String toString()

2. Public native int hashCode()

3. Public Boolean equals()


protected native Object clone() thows
4. CloneNotSupportedExcception

5. protected void finalize() throws Throwable


public final
6. Class getClass()

7. public final void wait() throws IntrupptedException

8. public final void wait(long timeout) throws IntrupptedException


wait(long timeout, int nanos) throws
9. public final void IntrupptedException
StringBuffer class Methods
Characteristi
c String StringBuffer StringBuilder

Constant String
Storage Area Pool Heap Heap

Mutable No Yes Yes

Thread Safe Yes Yes No

Performance Fast Very slowly Fast

Differences Between
String StringBuffer
StringBuilder
Java Exception Handling
Exception Handling

There are 5 keywords used in java exception handling.


1. try
2. catch
3. finally
4. throws
5. throw

•try
1. Try block is used to enclose the code that might throw an exception.
2. It must be used within the method
3. try block must be followed by either catch or finally block
4. If any exception is taking place the control will be jumped automatically to
appropriate catch block.
5. If any exception is taking place in try block, execution will be terminated and the rest
of the statements in try block will not be executed at all and the control will go to
catch block
•catch
1. Catch block is used to handle the Exception.
2. It must be used after the try block only
3. We can use multiple catch block with a single try.
4. If we write ‘n’ number of catch’s , then only one catch will be executing at any point
5. After executing appropriate catch block, control never goes to try block even if we
write return statement

3. Finally
1. This is the block which is executing compulsory whether the exception is taking place or
not.
2. This block contains statements like releases the resources are opening files, opening
databases, etc.
3. Writing the finally block is optional
4. Throws
This is the keyword which gives an indication to the calling function to keep the called function
under try and catch blocks.
It gives an information to the programmer that there may occur an exception so it is better for the
programmer to provide the exception handling code so that normal flow can be maintained

5. Throw
Throw keyword is used to explicitly throw an exception. In above we didn’t create any
Exception class Object in throws because JVM automatically creates Objects. If you want to
create Exception class object manually and throw exception using throw keyword

No. throw throws

Java throw keyword is used to explicitly throw Java throws keyword is used to declare an
1) an exception.
exception.

Checked exception cannot be propagated


2) using Checked exception can be propagated with throws.
throw only.

3) Throw is followed by an instance. Throws is followed by class.

4) Throw is used within the method. Throws is used with the method signature.

5) You cannot throw multiple exceptions. You can declare multiple exceptions
Java .io package
Java.io is a package which contains number of classes by using that classes we are able to
send the data from one place to another place.
In java language we are transferring the data in the form of two ways:-
1. Byte format
2. 2. Character format

Stream/channel:-
It is acting as medium by using steam or channel we are able to send particular data
from one place to the another place.
Streams are two types:-
1. Byte oriented streams.(supports byte formatted data to transfer)
2. Character oriented stream.(supports character formatted data to transfer)
Byte oriented streams:-
Java.io.FileInputStream
To read the data from the destination file to the java application we have to use
FileInputSream class.
To read the data from the .txt file we have to read() method.
Java.io.FileOutputStream:-
To write the data to the destination file we have to use the FileOutputStream.
To write the data to the destination file we have to use write() method.
import java.io.*;

class Test {
static FileInputStream fis;
static FileOutputStream fos;
public static void main(String[] args) {
try{
fis=new FileInputStream("get.txt");
fos=new FileOutputStream("set.txt",true);
int c;
while ((c=fis.read())!=-1) {
fos.write(c);
}
fis.close();
fos.close();
}
catch(IOException io){
System.out.println("getting IOException"); } } }
Collections(java.util)
Limitations of array:-

1) Array is indexed collection o fixed number of homogeneous data elements

2) Arrays can hold homogeneous data only

3) Once we created an array no chance of increasing o decreasing size of array

Ex:-
Student[ ] s=new Student[100];
S[0]=new Student();
S[1]=new Student();
S[2]=new Customer();------compilation error
Collection Frameworks
Collections:-

1) collection can hold both homogeneous data and heterogeneous data

2) collections are growable in nature

3) Memory wise collections are good. Recommended to use.

4) Performance wise collections are not recommended to use .

Collections:-
If we want to represent group of as a single entity then we should go for collection.

In the collection framework we having 9 key interfaces:-

1. Collection 2. List

3. Set 4. SortedSet

5. NavigablaSet 6. Queue

7. Map 8. SotedMap 9. NavigableMap


Java.util.collection

1. Boolean add(Object o) - add a single object to collection

2. Boolean addAll(Collection c) - add a collection Object to collection

3. Boolean remove(Object o) - removes a single object to collection

4. Boolean removeAll(Collection c) - removes a collection Object to collection

5. Boolean retainAll(Collection c) - Except give collection Object remove remaining


object

6. Boolean contains(Object o) - Check give object is there or not

7. Boolean containsAll(Collection c) - Check given collection objects are there or


not

8. Void isEmpty() - check is empty or not


java.util.List
List is child interface of collection
•If we want to represent group of individual objects as a single entity where
duplicates are allowed & insertion order must be preserved then we should go
for List
•We can preserve insertion order via index & differentiate duplicate objects using
index
• Index will play very important role in List
ArrayList

•The underlying data structure is ResizableArray or Growable Array

•Duplicates are allowed

•Insertion order is preserved

•Heterogeneous(different datatypes) Objects are allowed

•Null is insertion is allowed

•ArrayList implements Serializable, Clonable & RandomAccess

Creates an Empty ArrayList Object with default initial capacity 10.Once ArrayList
reaches its max capacity the new Arraylist object is created with newcapacity =
(currentcapacity *3/2)+1 & old one will give to Garbage collector
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList l = new ArrayList<>();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l); // [A, 10, A, null]
l.remove(2);
System.out.println(l); // [A, 10, null]
l.add(2, "M");
System.out.println(l); // [A, 10, M, null]
l.add("N");
System.out.println(l); // [A, 10, M, null, N]
}
}
LinkedList
Underlying data structure is DoubleLinkedList
Insertion order is preserved
Duplicates are allowed
 Heterogeneous objects are allowed
Null insertion is allowed
LinkedList implements Serializable & Clonable interfaces but not RandomAccess
 Best Choice for Insertion/Deletion, Worst for Retrieval operation
public class LinkedListDemo {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.add("A");
l.add(10);
l.add("A");
l.add(null);
System.out.println(l); // [A, 10, A, null]
l.set(0, "Satya"); // replaces
System.out.println(l); // [Satya, 10, A, null]
l.add(0, "Johnny"); // just add
System.out.println(l); // [Johnny, Satya, 10, A, null]
l.removeFirst();
System.out.println(l); // [Satya, 10, A, null]
System.out.println(l.getFirst());// Satya
} }
Vector
The underlying data structure is ResizableArray or Growable
Array
Duplicates are allowed
Insertion order is preserved
 Heterogeneous(different datatypes) Objects are allowed
 Null is insertion is allowed
Vector implements Serializable, Clonable & RandomAccess
 Vector is Synchronized

Creates an Empty Vector Object with default initial capacity 10.Once Vector
reaches its max capacity the new Vector object is created with
newcapacity = (currentcapacity*2) & old one will give to Garbz collector.
public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector();
for (int i = 1; i <=10; i++) {
v.addElement(i);
}
System.out.println("Before adding 11th
element -Capacity:"+v.capacity()); //
v.addElement("Satya");
System.out.println(v);
System.out.println("After adding 11th
element -Capacity:"+v.capacity());
System.out.println("size : "+v.size());
}
}
Stack
The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class
Vector with five operations (below 5 methods) that allow a vector to be treated as a
stack
1. Object push(Object o) -Insert an object into top of the stack
2. Object pop() -Removes & returns from top of the stack
3. Object peak() -Just returns Object from top of the stack
4. Boolean empty() -returns TRUE if stack is empty
5. int search(Object o) - returns offset if available otherwise -1
java.util.Set
 Set is child interface of collection
 If we want to represent group of individual objects as a single entity where
duplicates are Not allowed & insertion order Not be preserved then we should go
for List
Set Interface doesn’t contain any new method & we have to use only collection
interface methods
HashSet
The underlying datastructure is Hashtable
 Duplicate Objects are Not Allowed
Insertion Order is Not preserved & it is based hash code of Objects
 Null Insertion is possible(Only once)
 Heterogeneous Objects are allowed
Implements Serializable & Clonable but not RandomAccess Interface
HashSet is the Best Choice for Search Operation
public class HashSetDemo {
public static void main(String[] args) {
HashSet h = new HashSet();
h.add("A");
h.add("B");
h.add("C");
h.add(10);
h.add(null);
System.out.println(h.add("A"));//False
System.out.println(h);
}
}
LinkedHashSet
LinkedHashSet is similar to HashSet (including constructors & methods) only difference
is it preserves Insertion Order.
public class HashSetDemo {
public static void main(String[] args) {
LinkedHashSet h = new LinkedHashSet();
h.add("A");
h.add("B");
h.add("C");
h.add(10);
h.add(null);
System.out.println(h.add("A"));
System.out.println(h);
}
}
java.util.SortedSet (Interface)
Is the child interface of Set
If we want to represent a group of individual objects according to some sorting order
without duplicates then we should go for SortedSet
SortedSet Interface defines following 6 methods.

TreeSet
Underlying D.S is BalancedTree
Duplicate Objects are Not Allowed
Insertion order Not Preserved but we can sort elements
Heterogeneous Objects are Not Allowed , if try it throws ClassCastException at
Runtime
 Null Insertion allowed(Only once)
TreeSet implements Serializable & Clonable but not RandomAccess
 All objects are inserted based on some sorting order either default or
customized sorting order
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet t = new TreeSet();
t.add("A");
t.add("N");
t.add("Z");
t.add("h");
t.add("X");
t.add("i");
//t.add(10);
//Exception in thread "main" java.lang.ClassCastException:
//java.lang.String cannot be cast to java.lang.Integer
//t.add(null); // java.lang.NullPointerException
System.out.println(t);
}
}
Map:-

1. Map is a child interface of collection.

2. Up to know we are working with single object and single value where as in
the map collections we are working with two objects and two elements.

3. The main purpose of the collection is to compare the key value pairs and
to perform necessary operation.

4. The key and value pairs we can call it as map Entry.

5. Both keys and values are objects only.

6. In entire collection keys can’t be duplicated but values can be duplicate

You might also like