New Core Java

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

What is Java?

Java is a popular programming language, created in 1995.


It is owned by Oracle, and more than 3 billion devices run Java
It is open-source and free.
It has a huge community support (tens of millions of developers)
Write Once, Run Anywhere.
Java runs on a variety of platforms, such as Windows, Mac OS, and the
various versions of UNIX.
Java Version History

 JDK Alpha and Beta (1995)  Java SE 7 (28th July 2011)


 JDK 1.0 (23rd Jan 1996)  Java SE 8 (18th Mar 2014)
 JDK 1.1 (19th Feb 1997)  Java SE 9 (21st Sep 2017)
 J2SE 1.2 (8th Dec 1998)  Java SE 10 (20th Mar 2018)
 J2SE 1.3 (8th May 2000)  Java SE 11/12/13/14(2020)
 J2SE 1.4 (6th Feb 2002)
 J2SE 5.0 (30th Sep 2004)
 Java SE 6 (11th Dec 2006)
Features of Java

 Simple
 Object-Oriented
 Platform independent
 Secured
 Interpreted
 High Performance
 Multithreaded
Installing Java in your machine

• Downloading Java Development Kit (JDK) from Oracle


• Java Runtime Environment (JRE) is usually included in the JDK
installation file.

5
Installing Java in your machine

• Setting JAVA_HOME (Windows):


• E.g., C:\Program Files\Java\jdk1.8.0_45
• Setting path and classpath

6
First java program

class Demo
{
public static void main(String args[])
{
System.out.println(“Hello World”);
}

}
Java Development Process

.java => .class => JVM execution

8
Data Types
Variables

 A variable is a container which holds the value while


the program is executed.
 A variable is assigned with a data type.

data type variable Name = initial Value;

Ex. int data=20;


Types Variables
Type of Variables

1) Local Variable inside the body of


the method

inside the class but


2) Instance Variable
outside the body of
the method

3) Static variable declared as static


12
Example

class Demo
{
int data=50;//instance variable

static int Val=100;//static variable

void method()
{
int count=90;//local variable
}
}

13
Operators

Operator is a symbol which is used to perform operations.

Unary postfix expr++ expr--


prefix ++expr --expr
Arithmetic multiplicative */%
additive +-
Relational comparison < > <= >=
equality == !=
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Keywords
If-else Statement

if statement
if-else statement
if-else-if ladder
nested if statement
Flow diagram

if( condition ) {
// statement
} else {
// statement
}
 Example
Ex. Even odd number

int num=10;

if(num%2==0)
{
System.out.println(“Even Number”);
}
else
{
System.out.println(“Odd Number”);
}
if-else-if
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
else
{

//code to be executed if all the conditions are false


}
Switch

switch(expression)
{
case value1:
//code to be executed;
break;

case value2:
//code to be executed;
break;
......

default:
code to be executed if all cases are not matched;
}
Example

int number=40;

switch(number)
{
case 10:
System.out.println("10");
break;
case 20:
System.out.println("20");
break;
case 30:
System.out.println("30");
break;
default:
System.out.println("Not match");
}
For loop

for(initialization ; condition ; inc/dec)


{
//code to be executed
}
While

while(condition)
{
//code to be executed
}
int i=1;
while(i<=10){
System.out.println(i);
i++;
}
do-while

Syntax:- Example:-

int i=1;
do
do{
{
System.out.println(i);
//code to be executed
i++;
} while(condition);
}while(i<=10);
Arrays

 fixed-size sequential collection of elements of the same type.

 collection of similar type of data items stored at contiguous memory locations.

 store the primitive type of data such as int, char, double, float, etc.

 each data element can be randomly accessed by using its index number.

 The lowest address corresponds to the first element and the highest address to the last element.

Code Optimization Ease of traversing


Advantages
Ease of sorting Random Access
Types of Array

One dimensional array Two dimensional array

Multi-dimensional array
One dimensional array

import java.util.Scanner;

public class sample


{
System.out.println("Array elements are:");
public static void main(String[] args)
for(int i=0;i<arr.length;i++)
{
{
int arr[]=new int[5];
System.out.println(arr[i]);
}
Scanner sc=new Scanner(System.in);
}
}
System.out.println("Enter the array elements");

for(int i=0;i<arr.length;i++)
{
arr[i]=sc.nextInt();
}
Two dimensional array

import java.util.Scanner;

public class sample


{
public static void main(String[] args)
System.out.println("Array elements are:");
{
for(i=0;i<2;i++)
int arr[][]=new int[2][2];
{
int i,j;
for(j=0;j<2;j++)
{
Scanner sc=new Scanner(System.in);
System.out.print(arr[i][j]);
System.out.println("Enter the array elements");
}
}
for(i=0;i<2;i++)
{
}
for(j=0;j<2;j++)
}
{
arr[i][j]=sc.nextInt();
}
}
Multi-dimensional array

int arr[][][]=new int[2][2][2];


Strings

One-dimensional array of characters terminated by a null character '\0'.

The character array or the string is used to manipulate text such as word or sentences.
String Object

By String Literal By new keyword

String str="welcome"; String s=new String("Welcome");

Java String literal is created by using double quotes.


Memory allocation in String

33
Example

public class String_example


{
public static void main(String[] args)
{
String str1="hello";
char ch[]= {'w','o','r','l','d'};

System.out.println(str1);
System.out.println(ch);
}
}
replace()
charAt()

toUpperCase()
concat()
String Functions

toLowerCase()
equals()

trim()
equalsIgnoreCase()

indexOf()
length() substring()
concat()
charAt()
//immutable string
str1.concat("world");
String str1="hello";
System.out.println(str1);
System.out.println(str1.charAt(0));
//solution
str1=str1.concat("world");
System.out.println(str1);

equals() equalsIgnoreCase()

String str1="hello"; String str1="hello";


String str2="HELLO"; String str2="HELLO";

System.out.println(str1.equals(str2)); System.out.println(str1.equalsIgnoreCase(str2));
indexOf()
length()
String str1="hello";
String str1="hello";
System.out.println(str1.indexOf('e'));
System.out.println(str1.length());

substring() trim()

String str4="good afternoon";


String str3=" hello world ";
System.out.println(str4.substring(4));
System.out.println(str3.trim());
System.out.println(str4.substring(5,7));
toLowerCase()
toUpperCase()

String str1="hello"; String str1="hello";


str1.toLowerCase(); str1.toUpperCase();

System.out.println(str1); System.out.println(str1);

replace()

String str1="hello";
System.out.println(str1.replace("ello", "ii"));

System.out.println(str1);
OOP (Object-Oriented Programming )

 Object
 The main aim of object-oriented  Class
programming is to implement real-world
entities,  Abstraction
 for example, object, classes, abstraction,  Encapsulation
inheritance, polymorphism, etc.  Inheritance
 Polymorphism

Classes and Objects are basic concepts of Object Oriented


Programming which revolve around the real life entities.
Class
 Collection of objects is called class.
 It is a logical entity.
 A class can also be defined as a blueprint from which you can
create an individual object.
 Class doesn't consume any space.
 Ex. Student, Vehicle, Shape
Fields

Methods
Class

Constructors
Object

 In object-oriented programming technique, we design a program using objects


and classes.
 An object in Java is the physical as well as a logical entity, whereas, a class in Java
is a logical entity only.
 An entity that has state, behaviour and identity is known as an object.
 The object is an instance of a class.
Object
Example

Age
Colour
State height

Dog

Behaviour Bark();
Sleep();
Eat ();
class <class name>{
Syntax:- field;
method;
}

New keyword:-  The new keyword is used to allocate


memory at runtime.
 All objects get memory in Heap
memory area.
Example

class Student{
int id;
String name;
}
class Test{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name=“Karan";
System.out.println(s1.id+" "+s1.name);
}
}
HEAP Memory
Constructor
 a constructor is a block of codes similar to the method.
 It is called when an instance of the class is created.
 At the time of calling constructor, memory for the object is allocated in the
memory.
 It is a special type of method which is used to initialize the object.
 Every time an object is created using the new keyword, at least one
constructor is called.
 It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
Rules for creating 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.
 we can have private, protected, public or default
constructor in Java.
Types of Java constructors
Example

public static void main(String args[]){


//creating objects
Student s1=new Student(); //default
Student s2=new Student(101,”Tom”);//parameterized
Default Constructor

 The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type.
class sample
{
sample()
{
System.out.println("I am default constructor");
}

public static void main(String args[])


{
sample m1=new sample();
}
}

Output I am default constructor


Parameterized Constructor

 The parameterized constructor is used to provide different values to distinct objects.

class sample{
int id; public static void main(String args[])
String name; {
sample m1=new sample(101,"abc");
sample(int i, String n) m1.show();
{ }
id = i; }
name = n;
}
void show()
{
System.out.println("Id="+id); Id=101
System.out.println("Name="+name); Output
Name=abc
}
Copy Constructor

 There is no copy constructor in Java. we can copy the values from one object to another.

class sample{ void show()


int id; {
String name; System.out.println("Id="+id); Output
System.out.println("Name="+name);
sample(int i, String n) }
{
id = i; public static void main(String args[])
name = n; { Id=101
} sample m1=new sample(101,"abc"); Name=abc
m1.show(); Id=101
sample(sample s) Name=abc
{ sample m2=new sample(m1);
id = s.id; m2.show();
name = s.name; }
} }
Inheritance

 Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviour's of a parent object.
 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.
 represents the IS-A relationship which is also known as a parent-
child relationship
Why use inheritance in java

 For Code Reusability.


extends keyword

Syntax  new class that derives from an existing


class.
class Superclass_name{  "extends" is to increase the functionality.
}

class Subclass-name extends Superclass-name


{
//methods and fields
}
IS –A Relation

 Parent Class (Super Class) – Child Class (Sub Class)


 Subclass inherits properties from the parent class.

Parent

Child
Types of inheritance

Single

inheritance Multilevel

Hybrid
NOTE:-Multiple Inheritance is
Not possible.

Hierarchical
 Hierarchical

Class A Class B

Class A

Class B Class A Class C


Class B
 Single
Class A
Class c
Class B Class C
 Multilevel
 Hybrid
Class D
Interface

 The interface in Java is a mechanism to achieve abstraction

 There can be only abstract methods in the Java interface, not method body.

 Used to achieve abstraction and multiple inheritance

 Java Interface also represents the IS-A relationship.

Why use Interface

 It is used to achieve abstraction.

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


Example

interface test
{
void payment();
}

class sample implements test


{
public void payment()
{
System.out.println(“Net banking");
}

public static void main(String args[])


{
sample s = new sample();
s.payment();
}
}
Class A
Interface A
extends
Interface A
extends

Class B implements
Interface B

Class B
Access Modifiers

specifies the accessibility or scope of a field, method,


constructor, or class.
 We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
Access Modifiers
Private

 The private access modifier is accessible only within the class.

public class sample extends Parent


class Parent
{
{
public static void main(String[] args)
private int a=10;
{
private void display()
sample s=new sample();
{
s.a; //error
System.out.println("Private method");
s.display(); //error
}
}
}
}
Public

 The public access modifier is accessible everywhere.

public class sample extends Parent


class Parent
{
{
public static void main(String[] args)
public void display()
{
{
sample s=new sample();
System.out.println("Public method");
s.display();
}
}
}
}
Protected

 The protected access modifier is accessible within class, package and outside the class, package but
through inheritance only.

public class sample extends Parent


class Parent
{
{
public static void main(String[] args)
protected void display()
{
{
sample s=new sample();
System.out.println("Protected method");
s.display();
}
}
}
}
Default

 If you don't use any modifier, it is treated as default by default.

public class sample


{
void display()
{
System.out.println(“Default method");
}

public static void main(String[] args)


{
sample s=new sample();
s.display();
}
}
this keyword

this can be used to refer current class instance variable.


this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
Variable

 The this keyword can be used to refer current class instance variable.

class sample{
int id;
String name;
public static void main(String args[])
sample(int id, String name) {
{ sample m1=new sample(101,"abc");
this.id = id; m1.show();
this.name = name; }
} }
void show()
{
System.out.println("Id="+id); Id=101
Output
System.out.println("Name="+name); Name=abc
}
Method

 If you don't use the this keyword, compiler automatically adds this keyword while invoking the method.

class demo
{
void method1() class sample
{ {
System.out.println("I am method 1"); public static void main(String args[])
} {
demo d=new demo();
void method2() d.method2();
{ }
System.out.println("I am method 2"); }
this.method1();
}
} I am method 2
Output
I am method 1
Constructor

 It is used to reuse the constructor.

class demo
{
class sample
demo()
{
{
public static void main(String args[])
System.out.println("I am demo constructor");
{
}
demo d=new demo(10);
}
demo(int a)
}
{
this();
System.out.println("A="+a);
}
} I am demo constructor
Output
A=10
Static

 static keyword is mainly used for memory management.

 static is used for a constant variable or a method that is same for every instance of a class.

 When a member of the class is declared as static, it can be accessed before the objects of its
class are created, and without any object reference.

Nested
Variable Method Block
Class
Static Variable

 The static variable can be used to refer to the common property of all objects.

 The static variable gets memory only once in the class area at the time of class loading.
class Emp_stat
{
int id;
String name;
static String company_name="Wipro";
public class static_variable
Emp_stat(int id,String name) {
{ public static void main(String[] args)
this.id=id; {
this.name=name; Emp_stat e=new Emp_stat(1,"abc");
} e.emp_details();

public void emp_details() Emp_stat e1=new Emp_stat(2,"pqr");


{ e1.emp_details();
System.out.println("Id="+id); }
System.out.println("Name="+name); }
System.out.println("Company name="+company_name);
}
}
Static Method

 A static method can be invoked without the need for creating an instance of a class.

 A static method can access static data member and can change the value of it.
class Abcd
{ public void emp_details()
int id; {
String name; System.out.println("Id="+id);
static String company_name="Wipro"; System.out.println("Name="+name);
System.out.println("Company
static void display() name="+company_name);
{ }
System.out.println("I am static method"); }

company_name="amdocs"; public class static_variable


} {
public static void main(String[] args)
Abcd(int id,String name) {
{ Abcd.display();
this.id=id;
this.name=name; Abcd a=new Abcd(1,"abcd");
} a.emp_details();
}
}
Static Block

 Is used to initialize the static data member.

 It is executed before the main method at the time of classloading.


class A1
{
static
{
System.out.println("I am static block");
}

public void display()


{
System.out.println("Display method");
}
}

public class static_block {

public static void main(String[] args) {

A1 a=new A1();
a.display();
}
}
Super Keyword

 The super keyword refers to superclass (parent) objects.

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

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

 The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Super variable

 Access the data member or field of parent class

 It is used if parent class and child class have same fields.


Example
class demo
{
String name="Abc";
}

class sample extends demo{ Output

String name="Xyz";

void show()
{
System.out.println("Name="+super.name); Name=Abc
System.out.println("Name="+name); Name=Xyz
}

public static void main(String args[]) {


sample s1=new sample();
s1.show();
}
}
Super Method

 Used to invoke parent class method

 It should be used if subclass contains the same method as parent class.

 It is used if method is overridden


Example
class demo
{
void show()
{
System.out.println("Super class method");
} Output
}

class sample extends demo{


void show()
{
super.show(); Super class method
System.out.println("Sub class method"); Sub class method
}

public static void main(String args[]) {


sample s1=new sample();
s1.show();
}
}
Super Constructor

 Used to invoke the parent class constructor.

Note: super() is added in each class constructor automatically by compiler if there is no super()
Example
class demo
{
demo()
{
System.out.println("Super constructor");
} Output
}

class sample extends demo{

sample()
{ Super constructor
super(); Sub class constructor
System.out.println("Sub class constructor");
}

public static void main(String args[]) {


sample s1=new sample();
}
}
Final Keyword

Variable It will be constant

Final Method you cannot override it.

Class you cannot extend it.


Final Variable

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

public class sample


{
final int a=10;//final variable
void display()
{
a=20; //error
}

public static void main(String[] args)


{
sample s=new sample();
s.display();
}
}
Final Method

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

public class sample extends Parent


class Parent {
{ void display()
final void display() {
{ System.out.println("final method");
System.out.println("final method"); }
}
} public static void main(String[] args)
{
sample s=new sample();
s.display();
}
}
Final Class

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

final class Parent


{ }

public class sample extends Parent


{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
Polymorphism

Polymorphism in Java is a concept by which we can


perform a single action in different ways.
Greek words: "poly" means many and "morphs" means
forms.
 Perform a single action in different ways.
One thing can behave or perform differently in different
situation.
Example
Compile-
time/Static/Method
Overloading

Polymorphism

Runtime/Dynamic/
Method Overriding
Method Overloading

 If a class has multiple methods having same name but different in


parameters, it is known as Method Overloading.

2 ways (same Method Overloading is not


possible by changing the
class) return type of the method
only.

By changing number of By changing the data


arguments type
Example

Class Demo{

int sum(int a , int b){ return a;}

int sum(float c , int d){ return c;}


Change Data
void sum(float a,float b){} type

float sum(float a,float b){return a;}


}
Method Overriding

 If subclass (child class) has the same method as declared


in the parent class, it is known as method overriding in
Java.

Rules for Java Method Overriding


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

class calculate{ class addition extends


//method overring calculate{

float run(int a,int c) @Override


{ float run(int b,int d)
return c; {
} return d;
} }
Abstraction

 Abstraction is a process of hiding the implementation


details and showing only functionality to the user.
 Another way, it shows only essential things to the user and
hides the internal details.
 We can achieve Abstraction by using ABSTRACT CLASS and
INTERFACE.
 EX. Sms ,ATM, Cell phone.
Abstraction
Rules

 An abstract class must be declared with an abstract keyword.

 It can have abstract and non-abstract methods.

 It cannot be instantiated.

 It can have constructors and static methods also.

 It can have final methods


Example 1

abstract class demo


{
abstract void show();
} Output
class sample extends demo{
void show()
{
System.out.println("Abstract class method");
}
Abstract class method
public static void main(String args[])
{
sample s1=new sample();
s1.show();
}
}
Example 2

abstract class demo


{
abstract void payment(); class sample
} {
public static void main(String args[])
class wallet extends demo{ {
void payment() wallet w=new wallet();
{ w.payment();
System.out.println("Wallet payment success");
} netbanking n=new netbanking();
} n.payment();
}
class netbanking extends demo{ }
void payment()
{
System.out.println("Netbanking payment success");
Wallet payment success
} Output
Netbanking payment success
}
abstract class VS interface

abstract interface
abstract and non-abstract methods. can have only abstract methods
can have final, non-final, static and non-static only static and final variables.
variables.
abstract class can be extended using keyword interface can be implemented using keyword
"extends". "implements".

A Java abstract class can have class members like Members of a Java interface are public by default.
private, protected, etc.

Example: Example:
public abstract class Shape{ public interface Shape{
public abstract void draw(); void draw();
} }
Encapsulation

 Encapsulation in Java is a process of wrapping code


and data together into a single unit.
 We can create a fully encapsulated class in Java by
making all the data members of the class private.
 Now we can use setter and getter methods to set
and get the data in it.
Example
Aggregation (HAS - A)

 Aggregation is a term which is used to refer one way relationship between two objects

 In Java, aggregation represents HAS-A relationship, which means when a class contains
reference of another class known to have aggregation.

 If a class have an entity reference, it is known as Aggregation.

When use Aggregation ?

 Code reuse is also best achieved by aggregation when there is no is-a relationship.
Example

public class Address


{
String state;
String city;

public Address(String state , String city)


{
this.state = state;
this.city = city;
}
}
public class Employee
{
String name;
Address address;
public static void main(String[] args)
public Emp(String name, Address address) { {
this.name = name;
this.address=address; Address a1=new Address(“MH","Pune");
}

void display() Employee e1=new Employee(“Abc",a1);


{
System.out.println(name); e1.display();
System.out.println(address.state); }
System.out.println(address.city); }
}
Package
Ex. Lang ,util ,sql
Built-in Packages
,io

Package
User-defined Ex. Employee or
Packages Com.bean

 A package in Java is used to group related classes


 a folder in a file directory.
 Java package is used to categorize the classes and interfaces so that
they can be easily maintained.
How to access package from another package?

import package.*;

3 ways Import package.classname;

fully qualified name.


Import package.*

package pack2;
package pack1;
import pack1.*;
public class test1
class demo
{
{
public void show()
public static void main(String args[])
{
{
System.out.println(“pack1 – test1");
test1 t1= new test1();
}
t1.show();
}
}
}
Import package.classname

package pack1;

public class test1 package pack2;


{ import pack1.test1;
public void show()
{ class demo
System.out.println(“pack1 – test1"); {
} public static void main(String args[])
} {
test1 t1= new test1();
public class test2 t1.show();
{ }
public void display() }
{
System.out.println(“pack1 – test2");
}
}
Fully qualified name

package pack2;
package pack1;
class demo
public class test1
{
{
public static void main(String args[])
public void show()
{
{
pack1.test1 t1= new pack1.test1();
System.out.println(“pack1 – test1");
t1.show();
}
}
}
}
Exception
Exception Handling
Handling

 The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
 In Java, an exception is an event that disrupts the normal flow of the program.
 It is an object which is thrown at runtime.
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException etc.
Types of Java Exceptions
Checked
Exception

Unchecked
Type Exception

Error
Hierarchy of Java Exception classes
Java Exception Keywords

try

catch

5 keywords
finally

throw

throws
try & catch blocks
Example
public class Demo{
public static void main(String args[]){
try{

int data=5/0;
}

catch(ArithmeticException e){

System.out.println(e);
}
System.out.println(“Last line");
}
}
finally block

 Java finally block is always executed whether


exception is handled or not.
 Java finally block follows try or catch block.
Example

class Demo{
public static void main(String args[]){
try
{ }
catch()
{ }
finally
{
System.out.println("finally block is always executed");
}
}
}
throw keyword

public class throw_keyword {


void check(int num)
{
if(num>=0)
 The throw keyword in {
Java is used to throw new ArithmeticException("Number is positive");
explicitly throw an exception }
from a method or any block else
of code. {
System.out.println("Number is negative");
 The throw keyword is mainly }
used to throw custom }
exceptions.
public static void main(String[] args)
{
throw_throws t1=new throw_throws();
t1.check(-10);
}
}
Example 2

public class throw_keyword {


static void check(int num)
{
if(num>=0)
{
throw new ArithmeticException("Number is positive");
}
else
{
System.out.println("Number is negative");
}
}

public static void main(String[] args)


{
check(-10);
}
}
throws keyword

 The throws keyword is used to declare which exceptions can be thrown from a method

 while the throw keyword is used to explicitly throw an exception within a method or block of
code.

 The throws keyword is used in a method signature and declares which exceptions can
be thrown from a method.

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

public class sample


{
public static void main(String args[]){
try
Class demo
{
{
demo d=new demo();
void show() throws IOException
d.show();
{
}
throw new IOException(“test");
catch(Exception e)
}
{
}
System.out.println("exception handled");
}
}
}
throw vs throws

No. throw throws

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

2) Throw is followed by an new instance. Throws is followed by class.

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

4) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException
Multithreading
 Multithreading in Java is a process of executing multiple
threads simultaneously.
 A thread is a lightweight sub-process, the smallest unit of
processing.
 Java Multithreading is mostly used in games, animation, etc.

Process-based
Multitasking
(Multiprocessing)
MultitaskingType

Thread-based
Multitasking
(Multithreading)
What is Thread in java

 A thread is a lightweight subprocess, the


smallest unit of processing. It is a separate
path of execution.
 Threads are independent. If there occurs
exception in one thread, it doesn't affect
other threads.
 It uses a shared memory area.
Life Cycle of a Thread
Creating Thread

By extending Thread class By implementing Runnable interface


By extending Thread class

public class sample extends Thread


{
public void run()
{
System.out.println("Thread is running");
}

public static void main(String[] args)


{
sample s=new sample();
s.start();
}
}
By implementing Runnable interface

public class sample implements Runnable


{
public void run()
{
System.out.println("Thread is running");
}

public static void main(String[] args)


{
sample s=new sample();
Thread t1 =new Thread(s);
t1.start();
}
}
Thread Priority

MIN_PRIORITY NORM_PRIORITY MAX_PRIORITY


(1) (5) (10)
Thread priority

class sample extends Thread{


public void run()
{
System.out.println(“Thread name:"+Thread.currentThread().getName());
System.out.println(“Thread priority:"+Thread.currentThread().getPriority());
}

public static void main(String args[]) {

sample m1=new sample();


sample m2=new sample();

m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);

m1.start();
m2.start();
}
}
sleep() method

 The sleep() method is a static method of Thread class and it makes the thread sleep/stop working for
a specific amount of time.

 The sleep() method throws an InterruptedException if a thread is interrupted by other threads, that
means Thread.

 The sleep() method of Thread class is used to sleep a thread for the specified amount of time.
Example

public class thread_sleep extends Thread


{
public void run()
{
for(int i=1;i<=10;i++) public static void main(String[] args)
{ {
try thread_sleep t1=new thread_sleep();
{ thread_sleep t2=new thread_sleep();
Thread.sleep(1000);
} t1.start();
catch(Exception e) t2.start();
{ }
System.out.println(e); }
}

System.out.println(i);
}
}
yield() method

 The yield() method of thread class causes the currently executing thread object to temporarily
pause and allow other threads to execute.

 This method does not return any value.

 A yield() method is a static method of Thread class and it can stop the currently executing thread
and will give a chance to other waiting threads of the same priority.

 If in case there are no waiting threads or if all the waiting threads have low priority then the same
thread will continue its execution.

 The advantage of yield() method is to get a chance to execute other waiting threads so if our
current thread takes more time to execute and allocate processor to other threads.
Example

public class sample extends Thread


{
public void run()
{
for(int i=0; i<5 ; i++)
{
System.out.println(Thread.currentThread().getName() + " in control");
}
}
public static void main(String[]args)
{
sample t1 = new sample();
sample t2 = new sample();

t1.start();
t2.start();
for (int i=0; i<5; i++)
{
t1.yield();
System.out.println("yeild"+Thread.currentThread().getName() + " in control");
}
}
}
Difference between sleep() & yield() method

 sleep() method takes duration as argument and ensures that the current thread suspends its execution for the
specified time.
 yield() method is merely a hint to the scheduler that the current thread is willing to yield its current use of a
processor. Scheduler can even ignore this hint to yield.

 When sleep() method is called current thread will definitely go to sleep for the specified time.
 In case of yield() method first of all it is just a hint which can be ignored, even if the current thread yields the
CPU it can start running again if there is no other thread with the same or more thread priority.

 sleep() method throws InterruptedException if sleeping thread is interrupted so call to sleep() method should
either be enclosed in try-catch block or it should be declared using throws clause.
 yield() method doesn’t throw InterruptedException.
Collections

 Collection in Java is a framework that provides an architecture to


store and manipulate the group of objects.
 Java Collection means a single unit of objects.
 perform on a data such as searching, sorting, insertion, and
deletion.
 The java.util package contains all the classes and interfaces for the
Collection framework.
Set

List
interfaces
Queue
Vector
ArrayList
Deque
LinkedList

PriorityQueue
classes

HashSet

LinkedHashSet TreeSet
Hierarchy of Collection Framework
ArrayList

 Array lists are created with an initial size. When this size is exceeded, the collection is automatically
enlarged.

 ArrayList class uses a dynamic array for storing the elements. It is like an array, but there is no size
limit.
Important Points

 ArrayList class can contain duplicate elements.

 ArrayList class maintains insertion order.

 ArrayList class is non synchronized.

 ArrayList allows random access because array works at the index basis.

 manipulation is little bit slower than the LinkedList because a lot of shifting needs to
occur if any element is removed from the array list.
Example

import java.util.*;

public class sample


{
public static void main(String args[]) Output
{
ArrayList<String> list=new ArrayList<String>();

list.add("Abc");
list.add("Lmn");
list.add("Pqr");
[Abc, Lmn, Pqr]
System.out.println(list);
}
}
Iterator

 An Iterator is an object that can be used to loop through collections, like ArrayList and
HashSet.

 It is called an "iterator" because "iterating" is the technical term for looping.

 To use an Iterator, you must import it from the java.

while loop for loop forEach() method


LinkedList

 LinkedList should be used where modifications to a collection are frequent like addition/deletion
operations.

 LinkedList is much faster as compare to ArrayList in such cases.


Important Points

 LinkedList class can contain duplicate elements.

 LinkedList class maintains insertion order.

 Manipulation is fast because no shifting needs to occur.


Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
LinkedList<String> list=new LinkedList<String>(); Output
list.add("Abc");
list.add("Lmn");
list.add("Pqr");

Iterator<String> itr=list.iterator();
while(itr.hasNext()) Abc
{ Lmn
System.out.println(itr.next()); Pqr
}
}
}
List

 In Java, a list interface is an ordered collection of objects in which duplicate values can be stored.

 List in Java provides the facility to maintain the ordered collection.

 We can also store the null elements in the list.

 The List interface is found in the java.util package and inherits the Collection interface.
Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
List<String> list=new ArrayList<String>(); Output
list.add("Abc");
list.add("Lmn");
list.add("Pqr");
list.add(null);

for(String str:list) Abc


{ Lmn
System.out.println(str); Pqr
} null
}
}
Convert Array to List

import java.util.*;

public class sample


{
public static void main(String args[])
{
Output
String a[]={"Abc","Lmn","Pqr","Xyz"};

System.out.println("Array="+Arrays.toString(a));

List<String> list=new ArrayList<String>();

for(String str:a) Array=[Abc, Lmn, Pqr, Xyz]


{
list.add(str); List=[Abc, Lmn, Pqr, Xyz]
}

System.out.println("List="+list);
}
}
Convert List to Array

import java.util.*;

public class sample


{
public static void main(String args[])
{
Output
List<String> list=new ArrayList<String>();
list.add("abc");
list.add("lmn");
list.add("pqr");

String[] arr= list.toArray(new String[list.size()]);


List=[abc, lmn, pqr]
System.out.println("List="+list);
System.out.println("Array="+Arrays.toString(arr)); Array=[abc, lmn, pqr]
}
}
 Get() and Set() method

list.set(1,“qwerty"); list.get(1)

 Collections.sort() method
Output
List<String> list=new ArrayList<String>();
list.add("lmn");
list.add("pqr");
list.add("abc");

Collections.sort(list);
abc
lmn
for(String str:list)
pqr
{
System.out.println(str);
}
HashSet

 Java HashSet class is used to create a collection that uses a hash table for storage.

 The important points about Java HashSet class are: HashSet stores the elements by using a
mechanism called hashing.

 HashSet contains unique elements only.

 In hashing, the informational content of a key is used to determine a unique value, called its hash
code.
Important Points

 HashSet stores the elements by using a mechanism called hashing.

 HashSet contains unique elements only.

 HashSet allows null value.

 HashSet doesn't maintain the insertion order.

 HashSet is the best approach for search operations.


Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
HashSet<String> s=new HashSet(); Output
s.add("Liam");
s.add("Noah");
s.add("Oliver");
s.add("Elijah");

Iterator<String> i=s.iterator(); Oliver


while(i.hasNext()) Liam
{ Noah
System.out.println(i.next()); Elijah
}
} Notice, the elements iterate in an unordered
} collection.
LinkedHashSet

 The LinkedHashSet class of the Java collections framework provides functionalities of both the
hashtable and the linked list data structure.

 It implements the Set interface.

 Elements of LinkedHashSet are stored in hash tables similar to HashSet.


Important Points

 LinkedHashSet class contains unique elements.

 LinkedHashSet class provides all optional set operation and permits null elements.

 LinkedHashSet class maintains insertion order.


Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
LinkedHashSet<String> set=new LinkedHashSet(); Output
set.add("Liam");
set.add("Noah");
set.add("Oliver");
set.add("Elijah");

Iterator<String> i=set.iterator(); Liam


while(i.hasNext()) Noah
{ Oliver
System.out.println(i.next()); Elijah
}
}
}
TreeSet

 TreeSet is one of the most important implementations of the SortedSet interface in Java that
uses a Tree for storage.

 The ordering of the elements is maintained by a set using their natural ordering.

 The objects of the TreeSet class are stored in ascending order.


Important Points

 TreeSet class contains unique elements only like HashSet.

 TreeSet class access and retrieval times are quiet fast.

 TreeSet class doesn't allow null element.

 TreeSet class maintains ascending order.


Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
TreeSet<String> al=new TreeSet<String>(); Output
al.add(“Amrut");
al.add(“Tester");
al.add(“Hybrid");
al.add(“Suyesh");

Iterator<String> itr=al.iterator();
Elijah
while(itr.hasNext()) Liam
{ Noah
System.out.println(itr.next()); Oliver
}
}
}
Map Interface

 A map contains values on the basis of key, i.e. key and value pair.

 Each key and value pair is known as an entry.

 A Map contains unique keys.

 A Map is useful if you have to search, update or delete elements on the basis of a key.
Important Points

 A Map doesn't allow duplicate keys, but you can have duplicate values.

 HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn't allow
any null key or value.
Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
Map<Integer,String> map=new HashMap<Integer,String>(); Output
map.put(101,"Abc");
map.put(102,"Lmn");
map.put(103,"Pqr");

for(Map.Entry m:map.entrySet())
{ 101 Abc
System.out.println(m.getKey()+" "+m.getValue()); 102 Lmn
} 103 Pqr
}
}
HashMap

 It allows us to store the null elements as well, but there should be only one null key.

 HashMap class implements the Map interface which allows us to store key and value pair
Important Points

 HashMap contains values based on the key.

 HashMap contains only unique keys.

 HashMap may have one null key and multiple null values.

 HashMap maintains no order.


Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
HashMap<Integer,String> map=new HashMap<Integer,String>(); Output
map.put(1,"Abc");
map.put(2,"qwerty");
map.put(3,"xyz");
map.put(4,"lmn");

for(Map.Entry m : map.entrySet())
{ 1 Abc
System.out.println(m.getKey()+" "+m.getValue()); 2 qwerty
} 3 xyz
} 4 lmn
}
Hashtable

 The Hashtable class implements a hash table, which maps keys to values.

 Any non-null object can be used as a key or as a value.

 It is similar to HashMap, but is synchronized.


Important Points

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

 Hashtable class contains unique elements.

 Hashtable class doesn't allow null key or value.


Example

import java.util.*;

public class sample


{
public static void main(String args[])
{
Hashtable<Integer,String> ht=new Hashtable<Integer,String>(); Output
ht.put(10,"Abc");
ht.put(20,"Lmn");
ht.put(30,"Xyz");
ht.put(40,"Pqr");

for(Map.Entry m:ht.entrySet()) 10 Abc


{ 20 Lmn
System.out.println(m.getKey()+" "+m.getValue()); 30 Xyz
} 40 Pqr
}
}
Difference between HashMap & Hashtable

HashMap Hashtable
1) HashMap is non synchronized. It is not-thread safe and Hashtable is synchronized. It is thread-safe and can be
can't be shared between many threads without proper shared with many threads.
synchronization code.

2) HashMap allows one null key and multiple null values. Hashtable doesn't allow any null key or value.

3) HashMap is fast. Hashtable is slow.


4) We can make the HashMap as synchronized by calling this Hashtable is internally synchronized and can't be
code unsynchronized.
Map m = Collections.synchronizedMap(hashMap);

5) HashMap is traversed by Iterator. Hashtable is traversed by Enumerator and Iterator.


6) Iterator in HashMap is fail-fast. Enumerator in Hashtable is not fail-fast.
7) HashMap inherits AbstractMap class. Hashtable inherits Dictionary class.
Generics

 Java Generic methods and generic classes enable programmers to specify, with a single method
declaration, a set of related methods, or with a single class declaration, a set of related types,
respectively.

 Generics also provide compile-time type safety that allows programmers to catch invalid types at
compile time.
Generic Methods Rules

 All generic method declarations have a type parameter section delimited by angle brackets (< >)
that precedes the method's return type ( < E > ).

 E is meant to be an Element

 A generic method's body is declared like that of any other method. Note that type parameters
can represent only reference types, not primitive types (like int, double and char).
Example

public static void main(String args[])


import java.util.*; {

public class sample Integer[] intArray = { 1, 2, 3, 4, 5 };


{ Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
public static < E > void display( E[] arr) Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };
{
for(E element : arr) System.out.println("Integer Array=");
{ display(intArray);
System.out.println(element);
} System.out.println("\nDouble Array=");
} display(doubleArray);

System.out.println("\nCharacter Array=");
display(charArray);
}
}
Output
Integer Array=
1
2
3
4
5

Double Array=
1.1
2.2
3.3
4.4

Character Array=
H
E
L
L
O
Non-generic Collection Generic Collection

Syntax ArrayList list = new ArrayList(); ArrayList list = new ArrayList();

Can hold any type of data. Can hold only the defined type
Type-safety
Hence not type-safe. of data. Hence type safe.

Individual type casting needs to


Type casting No type casting is needed.
be done at every retrieval.

Checked for type safety at Checked for type safety at


Compile-Time Checking
runtime. Compile-time.
JDBC

 JDBC stands for Java Database Connectivity.


 JDBC is a Java API to connect and execute the query with the
database.
 JDBC API uses JDBC drivers to connect with the database.
 We can use JDBC API to access tabular data stored in any relational
database.
 By the help of JDBC API, we can save, update, delete and fetch
data from the database
 The java.sql package contains classes and interfaces for JDBC API.
JDBC Interface with Application

JDBC API

JAVA DATABASE
JDBC DRIVER
APPLICATION
Database Connectivity Steps

Register the driver class


Class.forName("com.mysql.jdbc.Driver");

Create the connection object


Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3308/databasename",“username“ ,”pass“);

Create the Statement object


Statement stmt=con.createStatement();

Execute the query


ResultSet rs=stmt.executeQuery("select * from emp");
Java I/O (Input/Output)

 Java IO is an API that comes with Java which is targeted at reading and writing data (input and
output).

 For instance, read data from a file or over network, and write to a file or write a response back over
the network.

 The java.io package contains all the classes required for input and output operations.

 We can perform file handling in Java by Java I/O API.


FileOutputStream Class

 FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing data to
file.

 FileOutputStream is a subclass of OutputStream. To write primitive values into a file, we


use FileOutputStream class
Example
import java.io.FileOutputStream;

public class sample{


public static void main(String[] args){
try
{
FileOutputStream fout=new FileOutputStream("D:\\files\\demo.txt");
String s="I am file output stream";

byte b[]=s.getBytes();
fout.write(b);
fout.close();

System.out.println("Done");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FileInputStream Class

 Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data
(streams of raw bytes)
Example- Read Single Character

import java.io.FileOutputStream;

public class sample{


public static void main(String[] args){
try
{
FileInputStream fin=new FileInputStream("D:\\files\\demo.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example- Read All Characters

import java.io.FileInputStream;

public class sample{


public static void main(String[] args){
try
{
FileInputStream fin=new FileInputStream("D:\\files\\demo.txt");
int i=0;
while((i=fin.read())!=-1)
{
System.out.print((char)i);
}
fin.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
BufferedOutputStream Class

 Java BufferedOutputStream class is used for buffering an output stream.

 It internally uses buffer to store data. It adds more efficiency than to write data directly into a
stream.
Example

import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
FileOutputStream fout=new FileOutputStream(" D:\\files\\demo.txt ");
BufferedOutputStream bout=new BufferedOutputStream(fout);

String s="BufferedOutputStream";
byte b[]=s.getBytes();
bout.write(b);
bout.flush();
bout.close();
fout.close();
}
catch(Exception e)
{
System.out.println(e);
}
} }
BufferedInputStream Class

 A BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the
input and to support the mark and reset methods.

 When the BufferedInputStream is created, an internal buffer array is created.

 When the bytes from the stream are skipped or read, the internal buffer automatically refilled from
the contained input stream

 When a BufferedInputStream is created, an internal buffer array is created.


Example

import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
FileInputStream fin=new FileInputStream(" D:\\files\\demo.txt ");
BufferedInputStream bin=new BufferedInputStream(fin);

int i;
while((i=bin.read())!=-1)
{
System.out.print((char)i);
}
bin.close();
fin.close();
}
catch(Exception e){
System.out.println(e);
}
} }
FileWriter Class

 Java FileWriter class of java.io package is used to write data in character form to file.

 FileWriter is meant for writing streams of characters.

 For writing streams of raw bytes, consider using a FileOutputStream.


Example

import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
FileWriter fw=new FileWriter(" D:\\files\\demo.txt ");
fw.write("I am FileWriter");
fw.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
FileReader Class

 FileReader makes it possible to read the contents of a file as a stream of characters.

 It works much like the FileInputStream except the FileInputStream reads bytes, whereas
the FileReader reads characters.

 The FileReader is intended to read text, in other words.


Example

import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
FileReader fr=new FileReader(" D:\\files\\demo.txt ");

int i;
while((i=fr.read())!=-1)
{
System.out.print((char)i);
}

fr.close(); }
catch(Exception e)
{
System.out.println(e);
}
}
}
BufferedWriter Class

 BufferedWriter is a sub class of java.io.Writer class.

 BufferedWriter writes text to character output stream, buffering characters so as to provide for the
efficient writing of single characters, arrays, and strings.

 Java BufferedWriter class is used to provide buffering for Writer instances. It makes the performance
fast.
Example

import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
FileWriter writer = new FileWriter(" D:\\files\\demo.txt ");
BufferedWriter buff = new BufferedWriter(writer);

buff.write("I am BufferedWriter");
buff.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
BufferedReader Class

 Java BufferedReader class is used to read the text from a character-based input stream.

 It can be used to read data line by line

 It makes the performance fast. It inherits Reader class.


Example 1
import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
FileReader fr= new FileReader(" D:\\files\\demo.txt ");
BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1){
System.out.print((char)i);
}
br.close();
fr.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Example 2
import java.io.*;

public class sample {


public static void main(String[] args) {
try
{
String name;

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("What is your name ?");


name=br.readLine();

System.out.println("I am "+name);
}
catch(Exception e)
{
System.out.println(e);
}
}
}

You might also like