0% found this document useful (0 votes)
193 views123 pages

Java

Java is a general purpose, concurrent, class-based, object-oriented programming language designed to have few implementation dependencies so that code can run on any platform. When Java code is compiled, it is compiled into bytecode that can be run by a Java Virtual Machine (JVM) on any device, allowing code to "write once, run anywhere" without recompilation. The JVM allocates resources like memory and processes Java programs like other applications. It includes a just-in-time compiler to compile bytecode into native machine code for execution.

Uploaded by

shanmugaraja85
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
193 views123 pages

Java

Java is a general purpose, concurrent, class-based, object-oriented programming language designed to have few implementation dependencies so that code can run on any platform. When Java code is compiled, it is compiled into bytecode that can be run by a Java Virtual Machine (JVM) on any device, allowing code to "write once, run anywhere" without recompilation. The JVM allocates resources like memory and processes Java programs like other applications. It includes a just-in-time compiler to compile bytecode into native machine code for execution.

Uploaded by

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

JAVA PROGRAMMING

Java is a general purpose, concurrent, class based, object oriented


programming languages that is specially designed to have as few
implementation dependencies possible.
It is intended to let application developers “write once run
anywhere” (WORA) meaning that code that runs on one platform
does not need to be recompiled to run on another.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


PLATFORM
2

 Ex : windows + Intel,
Linux + atom.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


JVM and JAVA PROCESS:
3

Resource – machine, memory, time allocation

Process – program in execution (VLC player, Antivirus, programs)

Java process – java compiler produced from source code to byte code,
but machine can read only machine code, that’s why java developers
developed by one virtual machine that machine called JVM(Java
Virtual Machine).

When you installed jdk(java development kit) that includes java virtual
machine

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


JDK and JRE
4

JRE = JVM + LIB

JDK = JRE + Development tools

JDK = JVM + LIB + Development tools

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


COMPARE JAVA AND OTHER PROCESS
5

C language – Compiler – Source code to Machine code


Java Language – Compiler – Source to Class file - Class file to m/c code

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


JVM
6

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


JVM WORKS
7

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


INTERPRETER
8

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


How to see class file and source file
9

Workspace/ project name/bin/.class file (after compilation)

Workspace/ project name/src/.java file ( before and after compilation)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


JVM COMPONENTS
10

Editor – To type your program into a notepad or IDE (eclipse, net beans)
Compiler – To convert your high level language program into native
machine code
Linker – To combine different program files reference in your main
program together
Loader – to load the files from your secondary storage device like HDD,
CD, and Flash drive into RAM for execution, the loading is automatically
done when you execute your code.
Execution – Actual execution of the code, which is handled by your OS
and Processor with this background.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Java vs. other programming languages
11

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Advantages of java
12

Java language has both compiled and interpreted


Easy to learn
Object oriented
Platform independent
Security
Portable
Robust
Multithreaded
Architecture neutral
High performance
Distributed

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Object Oriented Programming
13

Types of languages:

High level language - OOPS Concept based languages ( JAVA, C++)

Middle level language – Procedure Oriented languages (C, PASCAL)

Low level language – Assembly language

Very low level language – Pure machine language

C programming – it one of the procedure oriented language ex: Car


driving module, does not have any safety and code hidden.

OOPS – develop and maintain easy, solve real-time problems.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


OOPS CONCEPT
14

Object - Runtime entity

Class - Collection related objects, Logical entity.


- It includes data member, constructor, and method.
Abstraction – hiding the implementation details and showing the
functionality only
-eliminating redundant data
-Ex: compare friends and bank.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


OOPS CONCEPT
15

Inheritance – Derived from parent class (Super class) to child class(Sub


class)

Types – single, multilevel, hierarchical,

Multiple, hybrid ( Not support in java)

Interface – Replacing multiple inheritances, it has only method with or


without arguments, doesn’t have method derivation.

Encapsulation – wrapping the code into single unit, data security.

Polymorphism – same method or object performing the different


behavior.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Helloworld in JAVA
16

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Helloworld in JAVA
17

public class Helloworld {

public static void main(String args[])

/* public - Access specifies , Static - Access modifier (equally sharing memory for main),
Void – return type, does not return anything for main, Main – first compiler search and
start with main method, String args[] – storing array, this is no appear nothing print
in console. */

System.out.println(“ Helloworld”);

/* System – Source file, Out – variable, Println – printing the given line, “ Helloworld”
– storing array and saving string datatype */

}
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
Creating own method: (User defined method)
18

public class Helloworld {

void print()

System.out.println(“ Helloworld”);

/* typing without main() , no appear java application at compile


time */

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Creating own method: (User defined method)
19

public class Helloworld {

void print() {

System.out.println(“ Helloworld”);

public static void main(String args[]) {

/* nothing in console, so need to create an object.*/

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Creating own method: (User defined method)
20

public class Helloworld {

void print() {

System.out.println(“ Helloworld”);

public static void main(String args[]) {

Helloworld h = new Helloworld();

h.print();

/* Helloworld- Class name, h – object, new – is a keyword, allocate memory for object at
runtime, Hellworld – constructor */

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Creating own method: (User defined method)
21

public class Helloworld {


void print() {
int a = 20;
int b = 10;
int c = a + b;
System.out.println(“ sum”+ “ “ + c);
}
}
public static void main(String args[]) {
Helloworld h = new Helloworld();
h.print();
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Creating own method: (User defined method)
22

Another way
public class Helloworld {
void print(int a, int b) {
int c = a + b;
System.out.println(“ sum”+ “ “ + c);
}
}
public static void main(String args[]) {
Helloworld h = new Helloworld();
h.print(10,20);
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Different between Access specifiers and Access modifier:
23

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Access Specifiers
24

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Before appear in class
25

Before appear in class you use only three access possibilities:

Public (Access Specifies)

Final (Access modifiers)

Abstract (Access modifiers)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Private :( Access specifies)
26

-It is good example of encapsulation {

Ex: Privateex ad = new privateex();

Class privateex { ad.testDemo(); // private method can’t be accessed (not

Private int x =34; visible)

Public void showdemo() ad.x=50; // private variable can’t be accessed (not visible)

{ ad.showdemo(); // run properly, it is visible but it has x not


visible
System.out.println(“the variable is:” + x);
}
}
}
Private void testdemo() {
Ex: Bank accounts (deposit accounts)
System.out.println(“it can’t be accessed by other class”);

Class accessex {

Public static void main (String args[])

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Protected :( Access specifier)
27

- Only provide method and variable Class childAccess extends protectedex {

- Methods and variable access through }


subclass only ( that means inheritance Class proc {
concept) Public static void main (String args[]) {
Ex: childAccess ca = new childAccess ();
Class protectedex { ca.showdemo();
Protected int x =34; ca.x=34;
// if apply private instead of protected }
Public void showdemo() { }
System.out.println(“the variable is:” + x);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Static keyword (Access modifier):
28

-instance of the class or objects sharing the memory System.out.println(“roll no” + “ “ +”name”+ “ “ +

from the static area values. ”College”);

Public class stat { }

int roll no; // instance or global variable Public static void main(String args[])

String name; // instance or global variable // college = “SASTRA”; /*re assign possible in the

Static string college = “ PREC”; // instance or global static variable*/

static variable Stat s1 = new stat(111, “karan”);

Stat(int r, String n) { Stat s2 = new stat(222, “ajay”);

Roll no = r; // local variable s1.display();

name = n; // local variable s2.display();

} }

void display() { }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Final keyword (Access modifier)
29

Class – do not inherit Void display() {

variable – do not reassign, do not change the value System.out.println(“roll no” + “ “ +”name”+”

methods – do not overload, override “+”College”);

(that means do not support polymorphism) }

Public static void main(String args[])

Public class fin{ // college = “SASTRA”; /*does not support reassign the

Int roll no; // instance or global variable final variable, static reference only support static*/

String name; // instance or global variable fin s1 = new fin(111, “karan”);

final string college = “ PREC”; // instance or global final fin s2 = new fin(222, “ajay”);
variable s1.display();

fin(int r, String n) { s2.display();

Roll no = r; // local variable }

name = n; // local variable }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


IF LOOP
30

it is a cyclic process based on condition

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


IF LOOP
31

public class ifloop {

public static void main(String args[]) {

int a =0;

if(a==0)// apply 1 and check

system.out.println(“entering into the loop”);

system.out.println(“rest of the code”);

}
 Conditional stmt.docx

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


IFELSE CONDITION
32

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


IFELSE CONDITION
33

public class ifelse { {

public static void main(String args[]) system.out.println(“he is a not adult”);

{ }

int a =17; system.out.println(“rest of the code”);

if(a<=18) }

{ }

system.out.println(“he is a adult”);

else

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


WHILE LOOP
34

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


DO-WHILE LOOP
35

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


DIFFERENCE B/W IF AND WHILE
36

if – if(10===10)

while – while(10==10)// infinity loop occur

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


While loop example
37

public class whileloop x++;

{ system.out.println(“\n”);

public static void main(String args[]) }

{ }

int x =10; }

while (x<20) {

system.out.println(“value of x “ + x);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Do-While loop example
38

public class Dowhileloop } while (x<20)

{ }

public static void main(String args[]) }

int x =10;

system.out.println(“value of x “ + x);

x++;

system.out.println(“\n”);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Super keyword
39

The super is a reference variable that is used to refer immediate parent


class object

Usage:

Used to refer immediate parent class instance variable

Super () is used to invoke immediate parent class constructor

Super is used to invoke immediate parent class method

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Super variable
40

class vehicle //System.out.println(super.speed);

{ /* will print speed of the vehicle */

int speed = 50; }

class bike extends vehicle public static void main(string args[])

{ bike b = new bike();

int speed = 100; b.display();

void display() }

{ }

System.out.println(speed);

/* will print speed of the bike */

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


super()
41

class person { }

void message() { public static void main(String args[])

System.out.println(“welcome”); {

} student s1 = new student();

} s1.display();

class student extends person { }

void display() { }

message(); /* will invoke parent class


message() method */

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


super()
42

class person { super.message(); /* will invoke parent class

void message() { message() method */

System.out.println(“welcome”); }

} public static void main(String args[])

} {

class student extends person { student s1 = new student();

void message() { s1.display();

System.out.println(“welcome to java”); }

} }

void display() {

message(); /* will invoke current class message()

method */

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Super keyword constructor
43

- explicit constructor occur means program compile constructor first


then execute main function

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Super keyword constructor
44

class Vehicle { super();

vehicle() System.out.println(“Bike is created”);

{ }

System.out.println(“Vehicle is public static void main(String args[])


created”); Bike b = new Bike();
} }
} }
class Bike extends Vehicle {

Bike() {

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


This Keywords
45

this keyword is a reference variable that refers to the current object

difference between global and local variables

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


This Keywords
46

public class thisk { }

int id ; // global variable void display() {

String name; // global variable System.out.println(id+ “ “ + name);

thisk(int id, String name) { }

id = id; public static void main(String args[]) {


/* local variable assign to the instance variable */ thisk tk1 = new thisk(111, “ scion”);
name = name; thisk tk2 = new thisk(222, “ armada”);
/* local variable assign to the instance variable */
tk1.dispaly();
// this.id = id;
tk1.dispaly();
/* local variable assign to the instance variable */
}
//this.name = name;
/* local variable assign to the instance variable */

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Constructor
47

constructor is a special type of method that is used to initialize the


object,
constructor is invoked at the time of object creation

compiler first search and compile main function, when constructor


appear first constructor call then call to main function.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Types of constructor
48

Default constructor (No- arg constructor)

Parameterized constructor (arg/ parameter passing)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Default constructor (No- arg constructor)
49

class defaultcons {
defaultcons() {
System.out.println(“Bike is created”);
}
public static void main(String args[])
defaultcons b = new defaultcons();
}
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Default constructor (No- arg constructor)
50

class defaultcons { defaultcons s2 = new defaultcons();

int id; s1.display();

String name; s2.display();

// default or empty constructor here }

void display() { }

System.out.println(id+“ ”+name);

public static void main(String args[])

defaultcons s1 = new defaultcons();

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Parameterized constructor
51

class paramcons { }

int id; public static void main(String args[])

String name; paramcons s1 = new

paramcons(int i , name n ); { paramcons(111,”scion”);

id = i ; paramcons s2 = new

name = n; paramcons(222,”armada”);

} s1.display();

void display() { s2.display();

System.out.println(id+“ ”+name); }}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


INHERITANCE
52

-subclass(childclass, derived class) derived from superclass(Parent


class, base class)

types:

single

multilevel

hierarchy

multiple (not support)

hybrid (not support)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


INHERITANCE EX.
53

public class inher { salary is” + p.salary);

int salary = 50000; System.out.println(“programmer

} bonus is” + p.bonus);

class pro extends inher { }

int bonus = 20000; }

} example:

public static void main(String args[]) -software version 2 derived some

pro p = new pro(); properties from version 1.

System.out.println(“programmer

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Multilevel inheritance
54

Class A {
}
Class B extends class A {
}
Class C extends class B {
}
Class D extends class C {
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Multilevel inheritance EX.
55

public class multi { public class void main(String args[])

int salary = 50000; pay1 p = new pay1();

} System.out.println(“programmer salary is” +

class bon extends multi { p.salary);

int bonus = 20000; System.out.println(“programmer bonus is” +

} p.bonus);

class pay extends bon { System.out.println(“programmer bpay is” + p.bpay);

int bpay = 10000; System.out.println(“programmer npay is” + p.npay);

} }

class pay1 extends pay { }

int npay = 5000;

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Polymorphism
56

-Same method or object performs different behavior.

Types:

Compile time – method overloading

Runtime – method overriding

Use: code reusability.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Method overloading
57

same name with different arguments

all the methods appear in same class or single class

Error occur in compile time, easy to find, that’s why called compile time

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Method overloading ex
58

class methodoverload { class overload {

void test() { public static void main(String args[])

System.out.println(“No arguments”); {

} methodoverload obj = new methodoverload();

void test(int a) { obj.test();

System.out.println(‘the value a:” + a); obj.test(10);

} obj.test(10,20);

void test(int a, int b) { }

System.out.println(“Sum of two numbers:” + }


(a+b));

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Method overriding
59

same method name and same arguments appear in different classes

Error occur in run time

difficult to find the error, difficult to solve the error, so JVM handle this
type of error, that’s why it’s called runtime

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Method overriding ex
60

class Animals { }

public void move() { class Testdog {

System.out.println(“Animals can move”); public static void main(String args[]) {

} Dog b = new Dog();

} b.move(); // latest method access, then

class Dog extends Animals { override in parent class method

public void move() { }

System.out.println(“Dogs can walk and }

run”); Ex: software updating

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Interface
61

overcome the multiple inheritance

only create method and argument

no using implementation

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Why multiple inheritances not support in java
62

diamond problem occur in C++ program

Child class derived properties from ancestor class- it is confused take path then
escape from the program, that’s why developed interface.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


create interface
63

Example:

create interface then type

Interface Printable {

void print() // if need arguments using here

void hai()

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


create class
64

create class then type obj.print();

class Inter implements Printable { obj.hai();

public void print() { }

System.out.println(“ I am a print”); }

} ** More methods using in class but

public void hai() { using must interface methods

System.out.println(“ I am a hai”); Ex: Interface- ISO, Class – Your Company

} Teamleader – ISO, Class – employee

public static void main(String args[])

Inter obj = new Inter();

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Abstraction
65

Abstraction – elimination

Impossible create object for abstraction and interface

accessing both interface and abstraction from other class using


keyword

Must using abstract class abstract methods in subclass, optionally using


abstract class ordinary methods in subclass.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Difference
66

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Abstract class Ex
67

abstract class abstrac { System.out.println(“ hai I am

abstract void run(); // if need passing running”);

arguments }

// check - create another abstract class public static void main(String args[])

void print() { Im obj = new Im();

System.out.println(“ hello”); obj.run(); // abstract method

} // obj.print();

class Im extends abstrac { }

void run() { }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


String in Java
68

string is a sequence of character but java string is a object

string class used to create String object

in java strings are basically immutable

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


immutable
69

immutable – String object getting only one reference(Assignment), again does not
change the values.
ex:
public class Stringimmutable {
public static void main(String args[]) {
String s = new String(“host name”);
s.concat(“come”);
System.out.println(“Value is” + s);
}
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


String creation
70

Two ways of creating String:


String literal:
String s = “hello”; //(no new string object)
By new keyword:
String s = new String(“hello”); //(new string object)
Real-time ex:
In networking concepts many program written in String.
Once allocating the hostname does not change by other persons,
that’s why strings constructing immutable.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


immutable
71

Why immutable:
Java uses the string literal concept, suppose there are 5 reference
variable, all the refers to a one object “scion”, if one reference
variable changes the value of object, it will be affected to the entire
reference variable.
How to overcome immutable:
stack memory raises when string is immutable because lot of objects
using in string program
using stringbuffer and stringbuilder overcome the immutable.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Stringbuffer class
72

the stringbuffer is used to create mutable (modified) String, the


Stringbuffer class is same as String class except it is mutable (ie) it can
be changed.

it is thread safe (process allocating threads)

slow process

best quality

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example
73

public class Stringmutable {

public static void main(String args[]) {

StringBuffer s = new StringBuffer(“host name”);

s.append(“hai”);

s.append(“come”);

System.out.println(“ “ + s);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Stringbuilder class
74

the Stringbuilder is used to create mutable (modified) String, it is same


as the Stringbuffer class except it is not thread safe

fast process

low quality

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example
75

public class Stringmutable {

public static void main(String args[]) {

StringBuilder s = new StringBuilder(“host name”);

s.append(“hai”);

s.append(“come”);

System.out.println(“ “ + s);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


String manipulation
76

package string;

Class Stringmani {

public static void main(String args[]) {

String v1 = new String(“Scion”);

String v2 = new String(“Armada”);

String v3 = new String(“kings”);

System.out.println(“String1” + v1);

System.out.println(“String2” + v2);

System.out.println();

System.out.println(“String1 uppercase” + v1.touppercase());

System.out.println(“String2 lowercase” + v2.tolowercase());

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


String manipulation
77

System.out.println(“Str2 replace ‘a’ into ‘*’:” + v2.replace(‘a’,’*’));

System.out.println(“Concatenation of str1&str2” + v1.concat(v2));

System.out.println(“Trim” + (v1.trim()).concat(v2));

System.out.println(“Str1 & Str2 equal:” + v1.equals(v2)); //case sensitive

System.out.println(“Str1 & Str2 equal ignorecase:” + v1.equalsignorecase(v2)); // it is not case sensitive

System.out.println(“Strlength” + v2.length());

System.out.println(“comparison of str1 and str2” + v1.compare(v2));

System.out.println(“str1 in 2nd & 4th position substring:” + v1.substring(2,4));

System.out.println(“str2 index of a:” + v2.indexof(a));

System.out.println(“str2 index of a in 2:” + v2.indexof(a,2));

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Exception handling
78

 Using more than one function using a program, any one function

affected then all the functions affected without exception handling

 good practice of using exception handling in programming

 interview point of view this concept most important

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Exception handling syntax
79

Exception syntax:

try {

//find the error throw to catch block

catch

handle the error

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


example for exception
80

public class exception { {

public static void main(String args[]) { System.out.println(“Array index bound:” +e);

try { }

// try block already known all the error and finally {


which type of error System.out.println(“I always Executed”);
int data = 50/0; }
int c[] = {1}; // int array c has length of 1. System.out.println(“Rest of the code”);
C[42] = 99; }
} catch(Arithmetic Exception e) { }
System.out.println(“Divide by 0:” +e);

} catch(Array IndexOutOfBound Exception e)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Finally block
81

-Whatever happen in exception handling in a program finally


block execute method or print the message on the output screen

ex.

using login form in online banking within finally block

con.close();

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Difference b/w throw & throws
82

throw

each method create try,catch block,

implicitly throw function happen

but here explicitly written throw for how this function performing

throws

using reduced redundancy

do not create try,catch block for each methods individually

using throws concept passing the exception to main method

there main method create a single try block and multiple catch block for solving the
exception

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Difference b/w throw & throws
83

public class throww { }

static void demo { public static void main(String args[]) {

//throws NullPointerException try

try {

{ demo();

throw new NullPointerException(“Pointer null”); }

} catch(NullPointerException e) {

catch(NullPointerException e) { System.out.println(“caught:” + e);

System.out.println(“caught inside demo program” ); }

throw e; }

// throw new NullPointerException(“demo”); }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Java I/O (Input/output) handling
84

I/O is used to process the input and produce the output based on
the input.

Java uses the concept of stream to make I/O operations fast.

java.io package contains all the classes required for I/P and O/P
operations.

The bulk data processing through file input streaming and file
output streaming.

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Output Stream
85

import java.io.FileOutputStream; fout.close();

public class Fileout { System.out.println(“Success….”);

public static void main(String args[]) }

{ catch (Exception e) {

try { System.out.println(e);

FileOutputStream fout = new }


FileOutputStream(“D:filein.txt”); }
String s = “ hai I am scion”; }
byte b[] = s.getbytes();

fout.write(b);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Input Stream
86

import java.io.FileInputStream; System.out.println((char) i);

public class Filein { fin.close();

public static void main(String args[]) }

{ catch(Exception e) {

try { System.out.println(e);

FileInputStream fin = new }


FileInputStream(“D:filein.txt”); }
int i ; }
while((i = fin.read())!= -1)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Garbage collector
87

Real-time scenario: Dustbin (replaces old, fill new)

Same concept using programming memory

Ex: Website- memory clearing the unlived process

This process done by JVM

Creating objects stored in heap memory

Generations- all objects are stored in generation

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Memory converts process from young to old
88

All living objects convert from young to old

Unused objects (no one use) are removed from memory using garbage
collector

When unused objects comes to live that time garbage collector allocate
memory for unused objects

Permanent - this place completely used for Java process,

- This is populating at runtime.

- Java classes always going to permanent

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Marking in memory spaces
89

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Normal & Compacting Deletion
90

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Both younger and older generation common occur
91

When garbage collector runs that time regular works stop that means
stop the world event (STW), all application stop.
Ex: Anna University marks uploaded
Time taken is more for older generation compare than younger
generation, because older generation remove and search large amount
of data.
Overcome the world event (STW)
Developer wants garbage collector running at the same time program
also running
Ex: Sweep in road

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Types of Garbage Collector
92

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Java Collection Framework (JCF)
93

passing data in network

like a container

put data and get data

collection ex: shop- saris model, design and companies

JCF provides architecture to store and manipulate the group


of objects

Methods:

Searching, Sorting, Insertion, Deletion

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Java Collection Framework (JCF)
94

 Simply collection means group of objects


 Collection Represent a Single unit of objects

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


MAP
95

Iterated Interface

It is provides the facility of iterating the elements in forward direction


only

Methods of iterated interface

public Boolean hasNext()

public object next()

public void remove()

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Types of MAP
96

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example
97

package collection; Set set = hm.entryset();

import java.util.*; Iterator i = set.iterator();

public class hashmap { //hashmap – this is class // Display elements

public static void main(String args[]) { while(i.hasNext()) {

Hashmap hm = new Hashmap(); // Hashmap- this is java function map.Entry me = (map.entry) i.next();

//Treemap hm = new Treemap (); System.out.println(me.getKey()+”:”);

//LinkedHashmap hm = new LinkedHashmap (); System.out.println(me.getValue());

// put the elements to the map }

hm.put(100, “Gowtham”); // multiple value pass in the quotes }

// multiple (,) not possible in java API that means multi keymap System.out.println();

hm.put(101, “Vinoth”); }

hm.put(102, “Saran”); }

hm.put(103, “Ravi”);

hm.put(103, “R”); // Duplicate key value, Print this value only. Hash- Not maintain order

// Get a set of entries Tree – Maintain order

//SCION
using iterated
RESEARCHfunction
ANDonlyDEVELOPMENT
possible in Set so get the permission Sign in Shine out
from Set
Another way possible using this type
- For each loop method
98

package collection; map.put(103, “Ravi”);

import.org.apache.commons.collections.map.mu map.put(103, “R”);


ltikeymap; for( Integer Key : map.Keyset()) {
import.java.util; System.out.println(“Key=” + Key);
public class fore { }
public static void main(String args[]) { // Iterating over values only
Hashmap <Integer,String> map = new for( Integer String : map.Values()) {
Hashmap(); System.out.println(“Values=” + Value);
map.put(100, “Gowtham”); }
map.put(101, “Senthil”); }
map.put(102, “Saran”); }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Collections – List
99

it is one of the interface

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Array List
100

Use dynamic array for storing algorithm

Can contain duplicate

Not synchronized

Maintain order

Random Access

manipulation slow because a lot of shifting needs to be occurred

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Array List
101

package.com.datadotz.collection.arraylist; al.add(“Ravi”);

import java.util.ArrayList; al.add(“Ajay”);


import java.util.Iterator; al.add(“Ajay”);
public class Arraylistdemo { Iterator itr = al.iterator();
public static void main (String args[]) while(itr.hasNext()) {
{ System.out.println(itr.next());
Arraylist al = new Arraylist(); }
al.add(“Ravi”); }
al.add(“Vijay”); }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


iterating the elements of collection by for each loop
102

public static void main (String args[]) {


Arraylist al = new Arraylist();
al.add(“Ravi”);
al.add(“Vijay”);
al.add(“Ravi”);
al.add(“Ajay”);
al.add(“Ajay”);
for (object obj:al)
System.out.println(obj);
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


User defined objects
103

Class Student { Student s2 = new Student(102,”Ravi”,21);

int rollno; Student s1 = new Student(103,”Jay”,25);

String name; ArrayList al = new ArrayList();

int age; al.add(s1);

Student(int rollno, String name, int age) { al.add(s2);

this.rollno = roll no; al.add(s3);

this.name = name; Iterartor itr = al.Iterartor();

this.age = age; while(itr.hasNext()) {

} Student st = (Student) itr.next();

} System.out.println(st.rollno+ “ ” + st.name + “ “

Class Simple { +st.age);

public static void main(String args[]) { }

Student s1 = new Student(101,”Sonoo”,23); } }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example of addAll(Collection, method)
104

Class Simple { while(itr.hasNext()) {

public static void main(String args[]) System.out.println(itr.Next());


{ }

ArrayList al = new ArrayList(); }

al.add(“sonoo”); }

al.add(“jay”);

al.addAll(al2);

Iterator itr = al.Iterator();

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example of removeAll() method
105

class Simple { System.out.println(“Iterating the

public static void main(String args[]) { elements after removing the elements

ArrayList al = new ArrayList(); of al2….”);

al.add(“Ravi”); Iterartor itr = al.Iterartor();

al.add(“scion”); while(itr.hasNext()) {

al.add(“armada”); System.out.println(itr.next());

ArrayList al2 = new ArrayList(); }

al2.add(“Ravi”); }

al2.add(“scion”); }

al.removeAll(al2);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example of retainAll() method
106

class Simple { System.out.println(“Iterating the elements

public static void main(String args[]) { after removing the elements of al2….”);

ArrayList al = new ArrayList(); Iterartor itr = al.Iterartor();

al.add(“Ravi”); while(itr.hasNext()) {

al.add(“scion”); System.out.println(itr.next());

al.add(“armada”); }

ArrayList al2 = new ArrayList(); }

al2.add(“Ravi”); }

al2.add(“scion”);

al.retainAll(al2);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Linked List Class
107

uses doubly linked list to store the elements

can contain duplicate elements

maintain insertion order

not synchronized

no random access

manipulation fast, because no shifting needs to be occurred

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Example
108

public class LinkedListex { Iterartor itr = Llist.Iterartor();


public class void main(String args[]) { while(itr.hasNext()) {
//create an arraylist an object System.out.println(itr.next());
LinkedList Llist = new LinkedList(); }
Llist.add(“1”); }
Llist.add(“2”); }
Llist.add(“3”);
Llist.add(1,”Insert Element”);
System.out.println(“Linked contains”)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Time Difference between Array List and Linked list
109

public class listset { for(int i = 0; i<10000; i++) {

public class void main(String args[]) { Linkedlist al = new Linkedlist();

long StartTime1 = System.CurrentTimeMillis(); al.add(i);

for(int i = 0; i<10000; i++) { }

Arraylist al = new Arraylist(); long endTime2 = System.CurrentTimeMillis();

al.add(i); System.out.println(“The” + “time” + “taken” +

} (endTime2 – startTime2) + “ms”);

long endTime1 = System.CurrentTimeMillis(); }

System.out.println(“The” + “time” + “taken” + }

(endTime1 – startTime1) + “ms”);

long StartTime2 = System.CurrentTimeMillis();

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Set
110

simply it is a collection

Fingers = {index, middle, ring, pinky }

numbers = { 1,12,33,43}

remove the duplicates

distinct elements

both set and map same process happen in background

both does not allow duplicates

set have elements only but map have key and value (two elements)

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Ex:
111

public class Hashsetex { al.add(“scion”);

public class void main(String args[]) al.add(“saravan”);

{ al.add(“armada”);

// generics <String> Iterator<String> itr = al.iterator();

HashSet<String> al = new while(itr.hasNext()) {


HashSet<String>(); System.out.println(itr.next());
// TreeSet<String> al = new }
TreeSet<String>(); }
al.add(“shan”);

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Queue (FIFO)
112

methods of queue interface:

add(object)

offer(object)

remove()

poll()

element()

peek()

size()

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


EX:
113

Class Queueex { while(itr.hasNext()); {

public class void main(String args[]) { System.out.println(itr.next());

Priorityqueue<String> queue = new }


Priorityqueue<String>(); queue.remove();
queue.add(“A”); queue.poll();
queue.add(“B”); System.out.println(“after removing two elements:”);
queue.add(“C”); Iterator<String> itr2 = queue.iterator();
queue.add(“D”); while(itr2.hasNext()) {
queue.add(“E”); System.out.println(itr2.next());
System.out.println(“Head” + Queue.element()); }
System.out.println(“Head” + Queue.peek()); }
System.out.println(“Iterating the queue elements:”); }
Iterator itr = queue.iterator();

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Dequeue
114

public Class Dequeueex { the Dequeue

public class void main(String args[]) { System.out.println(“Dequeue peek:” +

Dequeue<String> queue = new queue.peek());

ArrayDequeue<String>(); // get the values does not remove the element from

queue.add(“A”); the Dequeue

queue.add(“B”); System.out.println(“Dequeue poll:” + queue.poll());

queue.add(“C”); // get the first value and remove that object from

queue.add(“D”); Dequeue

queue.add(“E”); System.out.println(“Final size of Dequeue:” +


queue.size());
System.out.println(“Initial size of Dequeue:” +
queue.size()); }

// get the values does not remove the element from }

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


(=) vs (==) in java
115

the equals method is actually meant to compare the contents of two


objects and not their location in memory

in java, when the “==” operation is used to compare two objects,


compare location not compare content

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


ex
116

public class Equalsex {

public class void main(String args[]) {

String obj1 = new String (“xyz”);

String obj2 = new String (“xyz”);

if(obj1.equals(obj2))

// if(obj1 == obj2)

System.out.println(“obj1= obj2 is true”);

else

System.out.println(“obj1= obj2 is false”);

}}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


CSV(comma separated value) file
117

import java.io.BufferReader; Stringline = “ “;


import try {
java.io.FileNotFoundException; br = new BufferReader(new
import java.io.FileReader; FileReader(CSVFile));
import java.io.IOException; while((Line = br.readLine()!= null)
public class Readcvs { {
public static void main(String //use comma as separator
args[]) { String[] country = line.split(“,”);
Readcvs obj = new Readcvs(); System.out.println(“Country [ code
obj.run(); = “ + country[4] + “, name = “ +
} country[5] + “]”);
public void run() { }
String CSVFile = “C:…….”; }
BufferedReader br = null; // continue next slide

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


CSV(comma separated value) file
118

catch(FileNotFoundException e) { }
e.printStackTrace(); }
} System.out.println(“Completed”);
catch(IOException e) { }
e.printStackTrace(); }
} I/P:
finally { create text file
if(br!=null) { “1.0.0.0”,”1.0.0”, “121”,
try { “167”,”IND”, “INDIA”
br.close();
}
catch(IOException e) {
e.printStackTrace();
}

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


XML (Extra markup language) Parsing
119

Describing the data

carrying the light weight file

Easy transaction in networking

<book> // root tag

<bid> 11 </bid> // nested tag

<bname> java prg </bname> // nested tag

</book> // root tag

data get from XML using one programming languages (like C,C++,Java)

both java and lib(DOM, SAX, JDOM, JAXB) files get data from XML

DOM and SAX include in JDK

JDOM and JAXB get from External download

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


JDOM
120

Simple

better than others

easy reading and writing

API- Straight forward

Install JDOM

Download copy and paste a newfolder lib1

projectname – properties – javabuildpath – projectname – lib1 –


jdom 2.0.5 jar – ok – ok

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Ex:
121

package com.jdomparser; }

import java.io.file; }

public class XMLReader { catch(JDOMException e) {

public static void main(String args[]) { e.printStackTrace();

//creating JDOM SAX(open and read XML files) }


parser catch(IOException e) {
SAXBuilder builder = new SAXBuilder(); e.printStackTrace();
//reading XML document }
Document XML = null;

try { // continue next slide


XML = builder.build(newFile(“sample.xml”));

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


Ex
122

// getting root element from XML document // reading attribute from Element using JDOM

Element root = XML.getrootElement(); System.out.println(“ISBN:” +

System.out.println(“Root element of XML document is :” book.getAttributeValue(“ISBN”));

+ root.getname()); System.out.println(“Author:” +

System.out.println(“Number of books in this XML :” + book.getChildText(“Author”));

root.getChildren().Size()); System.out.println(“Title:” +

List books = root.getChildren(); book.getChildText(“Title”));

System.out.println(“Pages:” +

// Iterating overall childs of XML book.getChildText(“Pages”));

Iterator itr = book.iterator(); System.out.println(“Language:” +


book.getChildText(“Language”));
while(itr.hasNext()) {
}
Element book = (Element) itr.next());

SCION RESEARCH AND DEVELOPMENT Sign in Shine out


XML Ex:
123

<? xml version = “1.0” encoding = “UTF-8” <book ISBN = “5678”>

?> <author>armada</author>

<books> <title>Software</title>

<book ISBN = “1234”> <pages>120</pages>

<author>SCION</author> <language>English</language>

<title>Java</title> </book>

<pages>180</pages> </books>

<language>English</language>

</book>

SCION RESEARCH AND DEVELOPMENT Sign in Shine out

You might also like