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. */
[Link](“ 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()
[Link](“ 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() {
[Link](“ 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() {
[Link](“ Helloworld”);
public static void main(String args[]) {
Helloworld h = new Helloworld();
[Link]();
/* 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;
[Link](“ sum”+ “ “ + c);
}
}
public static void main(String args[]) {
Helloworld h = new Helloworld();
[Link]();
}
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;
[Link](“ sum”+ “ “ + c);
}
}
public static void main(String args[]) {
Helloworld h = new Helloworld();
[Link](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 { [Link](); // 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)
{ [Link](); // run properly, it is visible but it has x not
visible
[Link](“the variable is:” + x);
}
}
}
Private void testdemo() {
Ex: Bank accounts (deposit accounts)
[Link](“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 { [Link]();
Protected int x =34; ca.x=34;
// if apply private instead of protected }
Public void showdemo() { }
[Link](“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 [Link](“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 [Link]();
name = n; // local variable [Link]();
} }
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 [Link](“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 [Link]();
fin(int r, String n) { [Link]();
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
[Link](“entering into the loop”);
[Link](“rest of the code”);
}
Conditional [Link]
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[]) [Link](“he is a not adult”);
{ }
int a =17; [Link](“rest of the code”);
if(a<=18) }
{ }
[Link](“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++;
{ [Link](“\n”);
public static void main(String args[]) }
{ }
int x =10; }
while (x<20) {
[Link](“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;
[Link](“value of x “ + x);
x++;
[Link](“\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 //[Link]([Link]);
{ /* 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; [Link]();
void display() }
{ }
[Link](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[])
[Link](“welcome”); {
} student s1 = new student();
} [Link]();
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 { [Link](); /* will invoke parent class
void message() { message() method */
[Link](“welcome”); }
} public static void main(String args[])
} {
class student extends person { student s1 = new student();
void message() { [Link]();
[Link](“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() [Link](“Bike is created”);
{ }
[Link](“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 [Link](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 */
[Link]();
// [Link] = id;
[Link]();
/* local variable assign to the instance variable */
}
//[Link] = 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() {
[Link](“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; [Link]();
String name; [Link]();
// default or empty constructor here }
void display() { }
[Link](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”);
} [Link]();
void display() { [Link]();
[Link](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” + [Link]);
int salary = 50000; [Link](“programmer
} bonus is” + [Link]);
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.
[Link](“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();
} [Link](“programmer salary is” +
class bon extends multi { [Link]);
int bonus = 20000; [Link](“programmer bonus is” +
} [Link]);
class pay extends bon { [Link](“programmer bpay is” + [Link]);
int bpay = 10000; [Link](“programmer npay is” + [Link]);
} }
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[])
[Link](“No arguments”); {
} methodoverload obj = new methodoverload();
void test(int a) { [Link]();
[Link](‘the value a:” + a); [Link](10);
} [Link](10,20);
void test(int a, int b) { }
[Link](“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 {
[Link](“Animals can move”); public static void main(String args[]) {
} Dog b = new Dog();
} [Link](); // latest method access, then
class Dog extends Animals { override in parent class method
public void move() { }
[Link](“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 [Link]();
class Inter implements Printable { [Link]();
public void print() { }
[Link](“ I am a print”); }
} ** More methods using in class but
public void hai() { using must interface methods
[Link](“ 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 { [Link](“ 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();
[Link](“ hello”); [Link](); // abstract method
} // [Link]();
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”);
[Link](“come”);
[Link](“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”);
[Link](“hai”);
[Link](“come”);
[Link](“ “ + 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”);
[Link](“hai”);
[Link](“come”);
[Link](“ “ + 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”);
[Link](“String1” + v1);
[Link](“String2” + v2);
[Link]();
[Link](“String1 uppercase” + [Link]());
[Link](“String2 lowercase” + [Link]());
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
String manipulation
77
[Link](“Str2 replace ‘a’ into ‘*’:” + [Link](‘a’,’*’));
[Link](“Concatenation of str1&str2” + [Link](v2));
[Link](“Trim” + ([Link]()).concat(v2));
[Link](“Str1 & Str2 equal:” + [Link](v2)); //case sensitive
[Link](“Str1 & Str2 equal ignorecase:” + [Link](v2)); // it is not case sensitive
[Link](“Strlength” + [Link]());
[Link](“comparison of str1 and str2” + [Link](v2));
[Link](“str1 in 2nd & 4th position substring:” + [Link](2,4));
[Link](“str2 index of a:” + [Link](a));
[Link](“str2 index of a in 2:” + [Link](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[]) { [Link](“Array index bound:” +e);
try { }
// try block already known all the error and finally {
which type of error [Link](“I always Executed”);
int data = 50/0; }
int c[] = {1}; // int array c has length of 1. [Link](“Rest of the code”);
C[42] = 99; }
} catch(Arithmetic Exception e) { }
[Link](“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
[Link]();
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) { [Link](“caught:” + e);
[Link](“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.
[Link] 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 [Link]; [Link]();
public class Fileout { [Link](“Success….”);
public static void main(String args[]) }
{ catch (Exception e) {
try { [Link](e);
FileOutputStream fout = new }
FileOutputStream(“D:[Link]”); }
String s = “ hai I am scion”; }
byte b[] = [Link]();
[Link](b);
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
Input Stream
86
import [Link]; [Link]((char) i);
public class Filein { [Link]();
public static void main(String args[]) }
{ catch(Exception e) {
try { [Link](e);
FileInputStream fin = new }
FileInputStream(“D:[Link]”); }
int i ; }
while((i = [Link]())!= -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 = [Link]();
import [Link].*; Iterator i = [Link]();
public class hashmap { //hashmap – this is class // Display elements
public static void main(String args[]) { while([Link]()) {
Hashmap hm = new Hashmap(); // Hashmap- this is java function [Link] me = ([Link]) [Link]();
//Treemap hm = new Treemap (); [Link]([Link]()+”:”);
//LinkedHashmap hm = new LinkedHashmap (); [Link]([Link]());
// put the elements to the map }
[Link](100, “Gowtham”); // multiple value pass in the quotes }
// multiple (,) not possible in java API that means multi keymap [Link]();
[Link](101, “Vinoth”); }
[Link](102, “Saran”); }
[Link](103, “Ravi”);
[Link](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; [Link](103, “Ravi”);
[Link] [Link](103, “R”);
ltikeymap; for( Integer Key : [Link]()) {
[Link]; [Link](“Key=” + Key);
public class fore { }
public static void main(String args[]) { // Iterating over values only
Hashmap <Integer,String> map = new for( Integer String : [Link]()) {
Hashmap(); [Link](“Values=” + Value);
[Link](100, “Gowtham”); }
[Link](101, “Senthil”); }
[Link](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
[Link]; [Link](“Ravi”);
import [Link]; [Link](“Ajay”);
import [Link]; [Link](“Ajay”);
public class Arraylistdemo { Iterator itr = [Link]();
public static void main (String args[]) while([Link]()) {
{ [Link]([Link]());
Arraylist al = new Arraylist(); }
[Link](“Ravi”); }
[Link](“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();
[Link](“Ravi”);
[Link](“Vijay”);
[Link](“Ravi”);
[Link](“Ajay”);
[Link](“Ajay”);
for (object obj:al)
[Link](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; [Link](s1);
Student(int rollno, String name, int age) { [Link](s2);
[Link] = roll no; [Link](s3);
[Link] = name; Iterartor itr = [Link]();
[Link] = age; while([Link]()) {
} Student st = (Student) [Link]();
} [Link]([Link]+ “ ” + [Link] + “ “
Class Simple { +[Link]);
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([Link]()) {
public static void main(String args[]) [Link]([Link]());
{ }
ArrayList al = new ArrayList(); }
[Link](“sonoo”); }
[Link](“jay”);
[Link](al2);
Iterator itr = [Link]();
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
Example of removeAll() method
105
class Simple { [Link](“Iterating the
public static void main(String args[]) { elements after removing the elements
ArrayList al = new ArrayList(); of al2….”);
[Link](“Ravi”); Iterartor itr = [Link]();
[Link](“scion”); while([Link]()) {
[Link](“armada”); [Link]([Link]());
ArrayList al2 = new ArrayList(); }
[Link](“Ravi”); }
[Link](“scion”); }
[Link](al2);
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
Example of retainAll() method
106
class Simple { [Link](“Iterating the elements
public static void main(String args[]) { after removing the elements of al2….”);
ArrayList al = new ArrayList(); Iterartor itr = [Link]();
[Link](“Ravi”); while([Link]()) {
[Link](“scion”); [Link]([Link]());
[Link](“armada”); }
ArrayList al2 = new ArrayList(); }
[Link](“Ravi”); }
[Link](“scion”);
[Link](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 = [Link]();
public class void main(String args[]) { while([Link]()) {
//create an arraylist an object [Link]([Link]());
LinkedList Llist = new LinkedList(); }
[Link](“1”); }
[Link](“2”); }
[Link](“3”);
[Link](1,”Insert Element”);
[Link](“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 = [Link](); [Link](i);
for(int i = 0; i<10000; i++) { }
Arraylist al = new Arraylist(); long endTime2 = [Link]();
[Link](i); [Link](“The” + “time” + “taken” +
} (endTime2 – startTime2) + “ms”);
long endTime1 = [Link](); }
[Link](“The” + “time” + “taken” + }
(endTime1 – startTime1) + “ms”);
long StartTime2 = [Link]();
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 { [Link](“scion”);
public class void main(String args[]) [Link](“saravan”);
{ [Link](“armada”);
// generics <String> Iterator<String> itr = [Link]();
HashSet<String> al = new while([Link]()) {
HashSet<String>(); [Link]([Link]());
// TreeSet<String> al = new }
TreeSet<String>(); }
[Link](“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([Link]()); {
public class void main(String args[]) { [Link]([Link]());
Priorityqueue<String> queue = new }
Priorityqueue<String>(); [Link]();
[Link](“A”); [Link]();
[Link](“B”); [Link](“after removing two elements:”);
[Link](“C”); Iterator<String> itr2 = [Link]();
[Link](“D”); while([Link]()) {
[Link](“E”); [Link]([Link]());
[Link](“Head” + [Link]()); }
[Link](“Head” + [Link]()); }
[Link](“Iterating the queue elements:”); }
Iterator itr = [Link]();
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
Dequeue
114
public Class Dequeueex { the Dequeue
public class void main(String args[]) { [Link](“Dequeue peek:” +
Dequeue<String> queue = new [Link]());
ArrayDequeue<String>(); // get the values does not remove the element from
[Link](“A”); the Dequeue
[Link](“B”); [Link](“Dequeue poll:” + [Link]());
[Link](“C”); // get the first value and remove that object from
[Link](“D”); Dequeue
[Link](“E”); [Link](“Final size of Dequeue:” +
[Link]());
[Link](“Initial size of Dequeue:” +
[Link]()); }
// 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([Link](obj2))
// if(obj1 == obj2)
[Link](“obj1= obj2 is true”);
else
[Link](“obj1= obj2 is false”);
}}
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
CSV(comma separated value) file
117
import [Link]; Stringline = “ “;
import try {
[Link]; br = new BufferReader(new
import [Link]; FileReader(CSVFile));
import [Link]; while((Line = [Link]()!= null)
public class Readcvs { {
public static void main(String //use comma as separator
args[]) { String[] country = [Link](“,”);
Readcvs obj = new Readcvs(); [Link](“Country [ code
[Link](); = “ + 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) { }
[Link](); }
} [Link](“Completed”);
catch(IOException e) { }
[Link](); }
} I/P:
finally { create text file
if(br!=null) { “[Link]”,”1.0.0”, “121”,
try { “167”,”IND”, “INDIA”
[Link]();
}
catch(IOException e) {
[Link]();
}
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 [Link]; }
import [Link]; }
public class XMLReader { catch(JDOMException e) {
public static void main(String args[]) { [Link]();
//creating JDOM SAX(open and read XML files) }
parser catch(IOException e) {
SAXBuilder builder = new SAXBuilder(); [Link]();
//reading XML document }
Document XML = null;
try { // continue next slide
XML = [Link](newFile(“[Link]”));
SCION RESEARCH AND DEVELOPMENT Sign in Shine out
Ex
122
// getting root element from XML document // reading attribute from Element using JDOM
Element root = [Link](); [Link](“ISBN:” +
[Link](“Root element of XML document is :” [Link](“ISBN”));
+ [Link]()); [Link](“Author:” +
[Link](“Number of books in this XML :” + [Link](“Author”));
[Link]().Size()); [Link](“Title:” +
List books = [Link](); [Link](“Title”));
[Link](“Pages:” +
// Iterating overall childs of XML [Link](“Pages”));
Iterator itr = [Link](); [Link](“Language:” +
[Link](“Language”));
while([Link]()) {
}
Element book = (Element) [Link]());
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