SUNBEAM
Institute of Information Technology
cvammaens Placement Initiative
Cee
Day OI (5 hours)
+ Java Books:
= Core Java Vol | & 2 - Hoarsman
~ SCIP Programmer's guide - Khalid Mughal
- Java Programming Language - Jame Gonsiing
= Inside JVM -
+ Java Programming Language:
- Invented by "James Gosling"
~ Company "Sun Microsystem” > "Oracle Ine”
- Originally Java was invented for embedded systems. In fact first product developed using Java technology was a
“Remote Control” named as "*7”
= However in spite lot of efforts from Java team, Java was not considered by industry at that time,
- In 1990's people started using internet. However internet support was limited to static web pages.
- Around 1995 Java use applets as interactive java programs that can be executed on client browsers. In short span of
time, applets and hence Java become popular for internet.
= There are three main streams were developed using Java language:
1. Java SE
= Desktop based java applications (Console & GUI applications),
~ Core language part of Java ie. OOP and other features.
Versions pulished:
= Java 1.0
= Java 1.1
- J2SE 1.2> Added collection framework
-J28E 13
= J2SE 1.4 > another stable and popular Java
- JavaSE 5.0 > Added generics, annotations,
= JavaSE 6
= JavaSE 7 > Added Parallel programming,
-JavaSE 8
2. Java EE:
~ Web based / Enterprise application
- Servlets, JSP, EIB, Struts, Spring
- Versions published:
~J2BE 13
- 2B 14
—_—_————
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
Placement Initiative
~ JavaEE 6°
~JavaEE 7
3. Java ME:
~ Java for embedded devices.
+ C/C++ Compilation & Execution:
Lel.epp] > Compiler > [.obj] > Linker > Lexe]
Source Code _ Object Code Executable
Machine Instru Machine Instr
1
Operating Sys
I
Processor (HW)
+ Java Compilation & Execution:
Hellojava
Glass Helle {
public static void main(String[] args) {
system. out.printin("Hello, world!");
- COMPILATION COMMAND: javae Hello,java
- Name of ava file (with extension)
~ class file is always created as per class-name (not ,java file name).
= If single java file contains multiple java classes, then multiple cass files will be created.
- EXECUTION COMMAND: java Hello
- Name of .class file (without extension)
= Its expected that in this class, main() is prsent
[Helio,java| > Compiler > |Hello.class]
Source code Java Executable
Java Code Byte Code
‘SunBeam Institute of Information Technology, Pune, Karad|| & SUNBEAM
Institute of Information Technology
surseam accra sommes Placement Initiative
i YM
[Machine Instr]
1
Processox( HW)
+ JVM, JRE and JDK:
= Java Virtual Machine
- VM is hypothetical machine assumed by Java compiler an is emulated in software as part of JRE.
Machine level instructions of JVM are of one byte each instruction and hence it is called as "byte
- java ClassName
- Here "java'" is application launcher.
= JVM Architecture:
class —> Class Loader |
| Byte Code Verifier|
| > Processor(Hw)
Garbage Collector |
Java Runtime Environment:
- JRE is required for execution of java programs (.class) files,
JRE = 1VM + java tools + java libraries (jar)
- JRE can be downloaded ftom oracle site for particular OS platform. In other words, JRE is platform depenedent.
- Java Development Kit:
JDK is required for developing java applications,
- JDK = JRE + java dev tools (compiler, debugger...)
- JDK can be downloaded from oracle site for particular OS platform. In other words, JDK is platform depenedent.
SF | | Sunbeam Institute of information Technology, Pune, Karad
geSUNBEAM
Institute of Information Technology
—— —— Placement Initive
Crees
+ Java Features:
- Portable:
= Compile Once and Run Anywhere
- Java code is compiled into .class files. These .class files can be executed on any OS for which JRE is present.
- Even though same .class can run on many platforms (OS), for certain features behaviour will be OS
dependent e.g, File IO, Threads, Sockets, AWT,
~ Thus java is not purely "Platform Independent".
~ Architecture Neutral:
+ JVM GIT) convert byte code into native code as per underlying CPU architecture
~ So same java code can be executed on any CPU arch for which JRE is present.
+ Reading work:
Core Java Vol 1
- Java History
Java Buzewords
+ Java Code compilation and Execution:
- PATH is an Ennvironment Variable of the OS. It contains list of directories seperated by semicolon ; (on
windows) or colon : (on UNEX/Linux).
~ When any program is executed on command line without giving its full path, OS will search it into all
| directories mentioned in PATH variable.
|
~ If you want to execute any program without giving its full path, you must add its directory path into PATH
variable.
- To see current PATH variable:
[WIN) set PATH
[LINUX] echo SPATH
~To add a dir path in in PATH variable:
(WIN] set PATH=new_dir_path;2PATH%
{LINUX] export PATH=new_dir_path:SPATH.
- To permantly set PATH variable:
[WIN] My Computer > Properties > Advanced
> Environment Variable -> Select PATH -> click EDIT > add new_dir_path follwed by ; (do
not remove/overwrite existing PATH),
[LINUX] in bashre fie (in your home dir) add ema:
export PATH=new_dir_path:
~ To unset/nullify PATH variable:
[WIN] set PATH:
ILINUX]__export PATH=
‘SunBeam Institute of Information Technology, Pune, Karad@® SUNBEAM
= Institute of Information Technology
jean “remuanee =— cvomemne: Placement Initiative
Cee
- To add path of java compiler (javac) into PATH var:
[WIN] set PATH=C:Program Files\Javaljdk xya\bin;%PATH%
[LINUX] export PATHE/ustijavaljdk | xyz/bin:SPATH
= javac -d dirpath FileName.java
- In this example, given Java file will be compiled and .lass file(s) will be ereated in the give dirpath,
eg. javac-d. Hellojava
> will create Hello.class in current directory.
vac -d D:\temp Hi,java
> will create Hiclass in D:\temp directory.
- java ClassName
‘This will start java application laucher (java.exe), load JVM in it and it will execute given .class file,
After loading and verifying class, execution begin from main() method.
If proper main() is not found, JVM will throw error:
+ Hello world example:
import java.lang System;
class Hello {
public static void main(String{] args) {
System.out printin("Hello, world!");
}
«In java, global data/methods are not allowed. Even main() method must be declared within some class.
= When program execution begins, JVM calls/executes main() method.
= Here we expect that main() method should be invoked from outside the class (JVM) and hence we declare it as
public
= JVM invoke main() method directly without creating object ofthe class and hence main() should be declared
as static.
- main() does not return any value, so its return type is voi.
= main() method can take command line arguments and hence it has an aryument : String{] args
- System.out.printin("Hello, world!
- Here "System" is a pre-defined class
= "out" is publie static member of that class.
"out" is of type of "PrintStream" class.
‘SunBeam Institute of Information Technology, Pune, Karad2
G@ SUNBEAM
==, Institute of Information Technology
ree
printin() is a method i
by a newline character:
~ System.in encapsulates stdin.
~ System.out encapsulates stdout.
~ System.err encapsulate stderr
~ System.out print) can also be used to print formatted output on the sereen jus ike C language print()
function. Supported format specifiers are Yd, %f, 9s, %e:
+ Java primitive typ
- Primitive types are not classes in java to improve the performance.
«Integer types:
byte (1 byte) - unsigned : 0 to 248-1
short (2 byte) - signed : 2°15 to +2°15-1
sint (A byte) - signed :-2°31 to #2°31-1
slong (8 byte) - signed : -2°63 to +2°63-1
~ Real (numbers) types:
+ float bytes)
- double (bytes)
= character types:
char (2 bytes) : unicode characters :"A'
* String- set of characters,
= "Hello” - string const or string literal
~ boolean type:
=boolean (1 bit) : true or false
~ Since java is strictly type-checking only a few conversions are allowed (not all.
~ Conversion from boolean to integer type and vice-versa is not supported directly
~ Conversion from char to integer type and vice-versa is not supported directly.
~ Conversion from narrow data type to wider data type does not need type-casting. However conversion from
wider data type to narrow data type needs type-casting.
short a=
int b: WOKAY
int x= 10;
shorty=x; // ERROR
shortz=(short)x;—_// ALLOWEDSUNBEAM
Institute of Information Technology
conn ert sae svememencx Placement iniative
Creenoe
+ Java Classes and Objects:
~ Classis user-defined data type.
- Class contains fields and methods.
- Variables of class type are called as "Objects"
= In java, objects can be created only on heap using “new operator". In other words, objects cannot be created on stack.
- public static void main(Stringf) args) {
Person pl = new Person();
isa reference, keeping address of Person object created on heap.
«In java reference can be "null" or can be initialized after declaration.
«= If local reference is used before initialization, compiler will raise error
Person pl;
pl.displayO; 1! error
«= Accessing members on null reference will raise "NullPointerException’ (at runtime).
Person pI=nulls
pl.display(); // exception
= Methods:
- Constructor:
= Same name as that of class, no return type,
- Used to initialize fields
- If not implemented, each class will have a default paramterless constructor given by the'compiler.
- Parameterless constructor
- Parameterized constructor
Person() {
this("™, ", 0); call to param ctor
Person(String name, String address, int age) {
Was
«Tn java, one constructor of class can be accessed from another constructor of that class using "this" keyword
- However, such constructor call must be first line of the constructor; otherwise compiler raise error.
= In java, if fields are not initialized:
Primitive type variables will be initialized to default value e.g, int
‘SunBeam Institute of Information Technology, Pune, KaradG&G SUNBEAM
ey Institute of Information Technology
sumeamn we sane
Cees
reference variables will be initialized to null
+ In java, fields can be initialized at the point of declaration in the class.
class Person {
String nami
int age = 40;
+ Object initializer syntax/block:
class Person {
String name;
int age;
1 object initializer block
this.name = "something";
thisage = 10;
~ When a new object is created. all values initialized at point of declaration of fields will be assigned.
= Then object initializer block(s) will be executed in the order of their declaration in the class.
- Finally constructor
executed as per creation of the object.
pl = new Person(); paramless
p2= new Person(
",2); / parameterized
* Java uses Hungarian notation for class names, while camel notation for field/method names.
+ getters/inspectors:
int getAge() {
return this.age;
}
- setters/mutators:
void setAgetint age) {
SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology . a
a ——— comms Placement Intative
1 Creed
this.age
}
facilitators:
displayQ / accept)
+ User inpu
- Using
yner" class one can get input from end user.
= This class is defined in “java.util” package (not in default "java.tang” package).
- Hence before using this class, importing package is mandetory (as shown in example).
+ import java.util Scanner;
class Main (
public static void main(String[] args) {
Scanner se = new Scanner (System. in) ;
system.out.printf ("Enter full name : ");
String name = sc.nextLine() ;
system.out.printf("Enter name : ");
String name = sc.next();
system.out.printf ("Enter roll : ")
int roll = sc.nextint () ;
system.out.printf("Entex marks =");
double marks = sc-nextDouble();
sc.nexthine(); // flush \n char
System. out.print£("Enter School name
String school = sc.nexthine();
“
se.close();
Day 02 (5 hours)
+ Access Modifiers:
~ Class members ca
.ve one of the following access modifier:
1. public
protected
private
{te of Information Technology, Pune, Karad
‘age 8G&G SunBeEAam
=, ___Institute of Information Technology
mn Placement Initiative
Cees
4. default (package)
- Usually fields are declared as private and methods are declared public.
= class Person { 7
private String name;
private int age;
public Person() {
ee
)
public void display() (
uy
+ Compilation and Execution Standard Pract
{project}
I [sre}
1b java
I [elasses}
| class
0. Create directory structure as above & save java files into "src" directory.
1. Open command prompt and go to "sre" directory.
2.CMD> ——_javac-d ..\classes Main java
3. CMD> cd ..\classes,
4. CMD> java Main
+ static keyword in java:
~ Static members do not belong to the object, they belong to the class.
~ Static members can be accessed directly by using class name and dot () operator
~ Hence to access static members there is no need to create object of the class.
~ However, Like C++, java allows access to the static members using dot operator on objec
+ statie fields
+ Static fields do not contribute to size of object.
~ The data that is commion for all objects of the class should be declared as static.
+ static methods
- Static methods do not receive implicit "this" pointer and hence they cannot access non-static members of the
class directly.
‘SunBeam Institute of Infor
rion Technology, Pune, KaradSUNBEAM
Institute of Information Technology
cccoeseum Placement Initiative
~ Static methods can access static members ofthe class:
- Static methods are written to manipulate static fields in the class.
- Static methods are sometimes implemented as entry-point to the class. In other words, they are used to create
objects of class.
~ e.g. Calendar cal = Calendar. getinstance();
- Creating object using such static method in the class is called as "static factory pattern’
¥ static block
- class Sample {
aw
static {
(7 000
“
,
= When class is loaded first time into JVM, class-loader invokes static block(s) declared in the class.
- There can be one or more number of static blocks declared in the class.
= When class is accessed first time, all these static blocks will be invoked in the order of their
declaration in the class,
- Static blocks are used to perform one-time initialization for the "cla
- Initialization of static members when class is accessed first time.
- JDBC driver registration must be done once before establishing database connection,
eg. Singleton class:
class Singleton (
static Singleton obj = null;
public static Singleton getInstance() {
if (obj==null)
obj = new Singleton () ;
return obj;
,
// fields
private Singleton() {
)
// methods
class Singleton {
————$——————————
‘SunBeam Institute of Information Technology, Pune, Karad|
|
SUNBEAM
Institute of Information Technology
Cee
static Singleton obj = null;
static {
obj = new Singleton() ;
,
public static Singleton getInstance() {
return obj;
)
// fields
private Singleton() {
)
// methods
,
class Main {
: public static void main(String[] args) {
Singleton s1 = Singleton. getinstance() ;
Singleton s2 = Singleton.getInstance() ;
MD ve
)
+ static member class
- Will be discussed with "inner classes”.
+ Composition
- Represents “has-a" relationship between the objects
- class Date {
private int day, month, year;
We sas
)
= class Book {
private String name, author;
private double price;
private int pages;
private Date publish;
public Book() {
this.name = "";
this.author =
this.publish = new Date();
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
a ne ma seaman Placement initiative
a Cerro
public Book (String name, String author, double price, int pages, int
day, int month, int year) {
this.name = name;
this.author = author;
this price = price;
this pages = pages;
this.publish = new Date (day,month, year) ;
)
public Book (String name, String author, double price, int pages,
Date publish) {
this.name = name;
thie. author = author;
this.price = price;
this.pages = pages;
this.publish = publish;
>
public void display() {
system. out. printf ("#s\n$a\:
system. out. printf ("#£\néd\n", price, pages);
publish. display ();
", mame, author);
)
class Main {
public static void main(String[] args) (
Book bl = new Book();
bl.display();
Book b2 = new Book("booki", "aul", 100.00, 30, 1, 1, 2014);
b2. display ();
Date d = new Date(2,2,2014) ;
Book b3 = new Book("bk2", "au2", 200,00, 40, d);
b3.display();
Book b4 = new Book("bk4", "aud", 20.0, 10, new Date(3,32014));
b4.display();
ES
Fy | Sentear stitute oftnformation Technology, Pune, Karad
ageSUNBEAM
Institute of Information Technology
acacia ee Placement hitiative
Ceo
+ Arrays:
- In java, arrays are objects. So they must be created on heap using "new" operator
- Syntax
- antl] arr;
Just declares a reference to array of ints,
~ ant{] arr = new int(5];
= By default array elements are initialized to zero.
- int{] arr = new int{5] { 11, 22, 33, 44, 55};
= Initializing array elements at point of declaration.
Internally array is object of "java.lang.Array” class and it holds array elements and also a “length” field to
represent number of elements in the array.
~ To access array elements:
> for(is0; i < are length; i+)
system.out.printé("Sd\n", arr[i]) ;
for(int n : arr)
system.out.printé ("d\n") n)s
~ If you try to access array element at invalid index (index <0 or index >= length), then exception will be thrown.
= When we create array of objects, internally array of references is created. By default each reference is "null"
= Programmer must initialized each reference to a valid object to avoid "NullPointerException”
~ Date[] arr = new Date[5];
arr[0] = new Pate (1,1,2000) ;
arr[1] = new Date(1,1,2001) ;
arr[2] = new Date(1,1,2002);
arr[3] = new Date(1,1,2003) ;
arr[4] = new Date(1,1,2004) ;
for(int i=0; isarr.length; i++)
arr[il display ();
- Each java program receives a set of command line arguments given by user while executing program on
‘command line, in form of an array argument to mainQ function,
= Unlike C/C+, Oth element of the array is not name of executable / class fil.
- Main java > class Main >
public static void main(String{} args) {
for(int i=0; i
Satara
3 > Sangli
+ Ragged Arrays:
“In java, we can create array of aray ODIECTS size of each array object may of may not be Same
©
se lint ind; care tength? int)
for(int
; jcarx(i} lengths 344) (
system. out printé ("td "+ are(il(3))7
)
system.out.printin () i
Le
4+ Java Method Arguments:
~ in java primitive types are always passed by value
public static void swap(int 4 iat b) ¢
int t= a
aab A
bet
system.out.printé("a:8d, P aa\n", a, b)7//20 10
)
public static void main(String{} axgs) {
int x=10, y=207
system. out.printé("x:8d) ¥ aa\n", x, ¥)7//10 20
wap (x, ¥)
system.out.peinte("eitd, yia\n"s * y) i//10 20
)
Tip java objects are always passed by reference
in public stati void change (Date at
d.setDay (24)
}
public static void main (String{] args) (
pate di = new Date (12,6, 1980)
mation Technology, Pune, Kat
‘SunBeam Institute of Infor rad
—_—
rage 14SUNBEAM
Institute of Information Technology
S
Ree
"@l.display();-//-12/¢/1seem
change (di) ;
dl.display(); — // 24/6/1980
d
~ Variable Arity Method:
public static int add(int... azz)
int sumo;
for(int
# i public void display() (
class Employee -> public void display() (...
Person pl = new Employee () ;
pl.display(); _// Employee's display() is called
= While overriding a method, its access specifier can be widen in sub-class. Reverse is not allowed (compile time error).
- In other words, if method is "public" in super-class it must be overridden in sub-class as "public". Attempt to make it
protected or private in sub-class raise compile time erro.
- While overriding method in sub-class, return-type of method can remain same or can be of sub-class type (of return
type).
+ Package:
- Package is collection of sub-packages, classes and other types.
- Package is a physical container (Le, directory) containing sub-packages, classes and other types.
- A type/class can be added into the package by giving package declaration on the first line of ava file
package pha;
- Packages are used to avoid name-clashing (just like namespaces in C+).
= Class access modifiers:
1. default;
- Classes are accessible into the same package.
2. public:
Classes can be accessed in the same package as well as outside the package.
«To access a class outside the package, use import statment into that java file.
—_—_———
SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
~ import java.util Seanner:
~The one or more "import" statements can be written after "package" statement in te java file (if
present)
- One ,ava file can contain one or more java classes; however only one class can be "public" (in a
Jjava file).
class must match with java file name. Otherwise compiler will raise error.
+ Example of packages:
= Person,java
package pl
public class Person {
We
oot
- Mainjava
import pl Person;
diimport p1.*;
public class Main {
public static void main(String{] args) {
Person p! = new Person();
+ javac -d . Person.java
~ create "p|" package (dit) and Person.class file in that dir.
+ javac-d.. Mainjava
(pkgname
~ create Main.class in cur directory.
+ java Main (UNIX).
- will execute program.
~import pL.*s (class) am
= This will allow to access all public classes in "p1" package into the java file (in which above line is written).
~ This will not allow classes under sub-packages of "pI"
= However it is recommended practice to import each class individually as required,
= A class without any package cannot be accessed in class with some package.
Si :
‘SunBeam Institute of Information Technology, Pune, Karad e2¢ unBeam
|6& SUNBEAM
Institute of Information Technology
sumeeam a me
Placement Initiative
= Nested packages:
= It is possible to have package within another package. In fac, itis recommended practice to have hierarchial
package names.
- Example:
Person java
package com. sunbeam, wimc.pkgl:
public class Person {
Ww
package com. sunbeam. wime.pkg2;
import com. sunbeam. wimc.pkgl.Person;
public class Main {
aw
(CMD> javac -d. Person.java
CMD> javac-d . Main java
CMD> java com sunbeam. wime.pkg2.Main
* Note last command, where "Main" class is kept in some package. While executing giving full name of class
(pkgname + classname) is expected.
+ CLASSPATH:
- CLASSPATH is an environment variable containing list of directories separated by ; (win) or
(UNIX).
- Java tools (like java compiler, java app launcher, java debugger. ete) and JVM search java classes
(class) and packages into all directories mentioned in the CLASSPATH variable.
= To see current CLASSPATH variable:
[WIN] set CLASSPATH
[LINUX] echo SCLASSPATH.
- To add a dir path in in CLASSPATH variable:
—_——_
Institute of Information Technology, Pune, KaradSUNBEAM
G Institute of Information Technology
SUFEEAM "obj", return +1, else return «1
~ class Student implements Comparable {
public int compare To(Object obj) {
= (Student) obj;
iN{this roll == other.roll)
return 0;
if(this.roll > other.roll)
return +1;
| else
return -1;
}
= The sort() method can be called as follows:
Student(] arr = new Student (517
arr[0] = new Student(...);
| “ws
arr[4] = new Student(...);
Arrays sort (arr);
- Arrays sort() method sorts the array of objects. Whenever comparision of two objects is required during
sorting process, it internally calls compareTo() method on the object.
= If class is not inherited from Comparable interface, Arrays sort() throws ClassCastException.
+ user-defined sorting method!
=
SPaeEall ‘SunBeam Institute of Information Technology, Pune, Karad Page 31
age|
1
{
‘
|
|
i
SUNBEAM
— Institute of Information Technology
SUTBEAM se sexs” stm a Placement initiative
a. i Ma
ered
public static void sort (Object{] arr) (
for(int i=0; i 0) {
Object temp = arrfil;
arr[i] = arr[3]; I
arr{3] = temp;
+ Marker interfac
In java, interfaces may not have any method declarations (i.e. empty interfaces). Such interfaces are called as
"marker interfaces",
- They are used to indicate that the class is associated with certain functionality
~ e.g, Serializable is a marker interface. If class is inherited from "java.io.Seriablizable” interface, then JVM cf
convert object details into sequence of bytes (using ObjectOutputStream class's write object method). Ifclass is not
inhorited from Scrializable, JVM will throw exception.
~ e.g, Cloneable is a marker interface. If class is inherited from "Cloneable’, then Object class's clone method
can create copy of the object of that class. Otherwise it throws CloneNotSupportedException,
- example: class Date, class Person,
+ Exception Handling:
~ Runtime problems are known as exceptions. Exception handling is flexible way of handling runtime
problems in the execution of the program.
- When a function cannot handle a problem detected at runtime, it will "throw" it in form of object of class.
~ The calling function should use "try-catch" block for handling such runtime problems.
If no runtime problem occur. all statements in try block will be executed.
~ Ifruntime problem occurs, all statements thereafter in try block are skipped and catch block is executed.
~ In java, runtime problems can be thrown in form of objects ofthe classes inherited from
*java.lang, Throwable” cass.
-Ifex
= There two main types of Throwables: exception is ne
~ Error ~Ifime
~ Represents non-recoverable JVM-internal problems (usually). terminated.
‘SunBeam Institute of Information Technology, Pune, Karad Page FunBeamns
aSUNBEAM
Institute of Information Technology
cnaamumne Placement Initiative
ative
Cero
= Exception
Represents runtime problems that can be handled
There ar
= unchecked exceptions
‘wo types of exceptions:
- Mosily occur due to programmer/end user's mistakes.
~ All such exception classes are inherited from java. ang. RuntimeException.
= Compiler do not force to handle these exception.
-€.g, NullPointerEception, ArrayindexOurOfBounst'xception, etc.
~ checked exceptions
- Represents runtime problems raise within JVM or outside the VM.
= Compiler force to handle these exceptions in one of the following ways:
- Calling function should have try-catch block.
Calling function has throws clause specifying exception class.
ealled as) - All class inherited from java.lang Exception (except RuntimeException and its sub-classes)
represents checked exceptions.
JVM oa - e.g, lOException, SQLException, CloneNotSupportedException, ete
isnot | - Java Exception Hierarchy:
Throwable
e method | Brror
| OutOMemoryException
fete .
|- Exception
| IOException
oe | SQLException
|- CloneNotSupportedException
of class fon
|- RuntimeException
|- NullPointerException
cuted. | ArrayindexOutOfBoundsException
[+ ClassCastException
ete,
not handled by the calling function, then it will propogated to its calling function, However if
n() function.
= If main() function doesn’t handle the exception, it will be caught by the JVM; however progr
terminated,
= If exception i
‘exception is not handled in the entre chain of functions, finally itis given to'
|
|
6 sunBeam
= Institute of Information Technology
0
Coe
~ One try-block can have multiple catch blocks. However exception sut
and then exception super-class catch block. Otherwise compiler will raise error.
Ps
-class catch block should appear first
Placement Initiative
try (
Haw
} eateh(ArrayIndexOutOfBoundsException e) {
Wow
} catch(RuntimeException ) {
Wow
}eateh(Exception €) {
Ww
} catch(Throwable e) { I generic eateh
. Maw
try {
Hon
) eateh(Exception 6) {
Wow
} finally {
Mn
i
~ The finally block will always execute irrespective of exception occur of not.
statements), finally block is still executed.
= In java, finally block can be written after catch block(s) It is optional block.
- Even if control is returning/jumping from try or catch block (as a result of return, break or continue like
I
I
~The only case in which finally block will not be executed in execution System.exit() within try or catch block
= example:
class Main {
public static int divide(int num, int den) (
if (den==0)
eturn num / den;
y
public static void main(String[] args) {
int num, den, res;
‘SunBeam Institute of Information Technology, Pune, Karad
throw new RuntimeException("Den cant be 0.");
|
|
|
Page 34 StPrasanng Wadekny
6 sunBesam
Institute of Information Technology
sunBeAn amare ecmmenane Placement initiative
wa Core Java Notes
Scanner sc = new Scanner (System. in);
try (
pum = se.nextint ();
den = se.nextint () ;
res = divide(num, den) ;
System.out.print£ ("Result : #d\n", res);
) catch (Runtimezxception e) (
System. out.printin ("Error occured!") ;
} finally {
system.out.printin ("Always executed!") ;
,
~ java.tang, Throwable:
- public Throwable(String message);
- Throwable class object encapsulates a string message. which can be initialized via
parameterized constructor, Such constructor is present for all its derived exception types.
~ public String getMessageQ;
- Returns a message encapsulated by exception object.
public void printStackTrace();
- Displays info about exception - mainly exception class type and location in the code from
‘where it is generated (along with stack trace).
= public String toString);
- returns exception details in form of string which contains exception type. message.
~ User-defined exception class:
- example;
class MyException extends RuntimeException {
private String field;
private int value;
public MyException(String msg, String field, int value) {
super(msg);
this.field = field;
this.value = value;
}
1 getters
class Date {
| sunBeam Institute of Information Technology, Pune, Karad
Page 34|SUNBEAM
Institute of Information Technology
S
SUNBEAM a: accomememn — Placement Initiative
Cee
Ws
public void setYear(int year) {
iflyear <0)
throw MyExeeption( “invalid year”, "year", yea"):
this.year = year;
+
~ throws clause : Exception specification list
~ example:
class Temp {
public void fin throws IOException, ServietException {
”
. }
}
- If'a method is not handling generated checked excepion (using try-catch block), then it must write
throws clause in method prototype to indicate exception types it may throw.
- ifclass B extends A:
A> void fun() throws El, E2, E3;
then
B > void fun) throws El, E2, £3; // OK
OR
B > void fun() throws El, E25 NOK
BUT
B > void fun() throws El, E4; A Error
super-class method; but it cannot throw any additional exception,
if class D extends C:
C> void fun() throws IOException;
then
D> void fun() throws IOException; 1 OK
oR
D = void fun() throws EOFException;// OK
BUT
D> void fun() throws Exception; // or
In other words, an overridden method can throw exception of the same type or exception sub-class typ
corresponding to super-class method; however it cannot throw super-class of exception type
aT rrcT
‘SunBeam Institute of Information Technology, Pune, Karad Page 36
tn other words, an overridden sub-class method can throw same or fewer exceptions than correspondingsponding
lass typel
Page 36
SUNBEAM
Institute of Information Technology
siamo i cocrsmmmex Placement Initative
Coron
- multi-cateh block: (j2¢e 7)
~ example
try {
“
fun() ;
Vio
} catch (BOFException e) {
// igonore : do nothing
) cateh(TOException | SQLException e) (
system. out.printIn ("Error Occured!") ;
system.Exit(1);
} catch (Exception e) {
e.printstack?race();
)
= When we want to implement same logic to handle more than one exception, we can use multi-catch
block as shown in above example.
++ Wrapper classes:
- In java, primitive types are not classes i.e. primitive type variables are not objects.
= However sometimes. there is need to treat prmitive type values as java objects. E.g, java collections can work
only with objects (not with primitive types) :
~ Example: tll j2se 1.4
ArrayList obj = new ArrayList();
/ Ithas add method to add object of any type
1 void add(Object ob);
objadd(11); error: cannot add primitive type
obj-add(new Integer(11));// no error: Integer obj
- Thus "Integer" is wrapper class provided by java to treat “int” values as “objects”
- Java provides wrapper classes for all primitive types as follows:
- byte > Byte
= short > Short
+ int > Integer
= ong > Long
« float -> Float
- double > Double
——
‘SunBeam Institute of Information Technology, Pune, Karad6 sunBesam
= _institute of Information Technology _
=
~ char -> Character
- boolean -> Boolean.
+ Autoboxing:
~ example;
int mum = 100:
Integer num2 = num;
«This is valid syntax from J2SE 5.0 and onwards.
- Here primitive type value is automatically converted to corresponding wrapper class object type. This
feature is known as “autoboxing”.
~ example:
{nt num3 = num2;
- As shown in above example, even wrapper class object can be converted! back to the corresponding
primitive type value directly.
- However conversion from primitive type to wrapper object is not efficient (as internally memory is
allocated, as well as it takes tinue). Fui better performace autoboxing should avoided whereever possible,
~ example:
~ example:
‘ArrayList obj = new ArrayList();
‘obj.add(11); _ // valid from j2se5.0 - but slow
+ String class:
«String encapsulate set of characters and length. It provides numerous method for manipulating String data
- String is immutable object. Any meihod modifying string contents will not change the object's contents;
rather it creates a new String object with modified contents.
~ example:
public static void main(String[] args) {
String s1
System.out.printf("s1 : %s\n", 51);
52 sl.concat("Infotectr
System.out printf('sI : %s\n", s1);
System.out.printf("s2 : %sin", 82);
‘SunBeam", s2;
1g Compa
‘SunBeam Institute of Information Technology, Pune, Karad6& SunBeam
Institute of Information Technology
sunbeam ae noe seemmumes Placement Iitiative
Crees
~ Two object's equality can be checked using equals() method.
- They can also be compared using Comparable interface compareTo() method.
- Object references are compared using == operator. If this operator results true, both reference are
pointing to same object.
- String class overrides equals() method and implements Comparable interface.
String s1 = "sunbeam’, s2="infotech";
= Internally two String objects are created with different values.
“s > false
.equals(s2) false
- Siring si = "sunbeam", s2=new String("sunbeam");
- Use of new operator force to create a new object with simitar contents
si false
= sl.equals(s2) =
~ String s1 = "sunbeam", s2="sun
= To minimize memory requirement, java compiler adda single entry into "string table”
maintained in .class file. Obviously at runtime single string object is created and both
references point to the same.
-si==s2
~ sl equals(s2)
~ String s1 = "sunbeam", s beam";
- Java compiler itself ad "sun" and "beam to create a new string "sunbeam" and found that the
entry is already present in string table, So again single object is created and both references point to it.
~si==s2 true
~ sl.equals(s2) true
- Java does not support operator overloading; however +, += operators are built-in overloaded for String class.
- String methods:
- Stving(String 5);
- String(char (Jar;
= int length;
~ char charA(int index);
= boolean equals(Object str);
~ boolean equalstgnoreCase( String str:
= int compareTo(String st);
~ static String format(String fmt, .);
int indexOf(char ch);
= int indexOf(String subste);
ee
‘SunBeam Institute of Information Technology, Pune, KaradGwe Institute of Information Technology
er ad
~ String substring(int start, int end);
= String{] split(String regex);
- String concat(String s):
- String replace(String find, String replace);
- String toUpperCase():
~ String toLowerCase():
+ StringBuffer Class:
= Represents mutable string object i.e. any method modifing contents of object will modify contents ofthe same
object.
~ example:
public static void main(String] args) {
* StringBuffer s1 = new StringBuffer("sunbeam");
System.out.printf('s|: %sin’, .toString()s
sl.append("infotech");
System.out prnt{('s| : %sin", s1.toStringO);
}
characters in the
StringBuffer class encapsulates a string buffer which can dynamically grow as number 0
object are increased (appended).
“The number of characters present can he found using length() method, while maximum number of characters
that can be stored in internal buffer can be found using capacity(),
- Stringbuffer Methods:
- StringBuffer(String s)
int length
+ int capacity;
= char charAtfint index);
- StringBuffer append String 3);
- StringBuffer reverse();
et.
«All methods in StringBuffer class are synchronized, hence it can be safely manipulated in multi-threaded
program. However due to synchronization. efficiency reduces (slower).
+ Stringbuilder Class:
- Functionalitywise same as StringBuffer.
~ Added into J2SE 5.0.
= Its methods are not synchronized. So used in single threaded program to improve the performance.
+ Stringtokenizer Class:
‘SunBeam Institute of Information Technology, Pune, Karad® SUNBEAM
Institute of Information Technology
—e Placement initiative
Ceres
it string data into multiple pars. Nowdays splitQ/method is preferred over StringTokenizer.
+ java.util. Calendar class:
- Represents a calendar date and time.
object
= Calendar cal = Calendar getlnstance();
- By default object will contain current date and time values,
- Calendar is abstract class. On desktop (I2SE), it internally creates object of
java.util. GregorianCalendar class.
= To set calendar fields:
-cal.set(year, month, day);
cal.set(year, month, day, hour, min, see);
- Imp note: months are counted from 0 to 11
= To get value of individual field:
+ int dd = cal.get(Calendar DAY_OF MONTH):
~ int mm = cal.get(Calendar, MONTH) + 1;
~ int yy = cal.get(Calendar-YEAR);
+ Java.UtiLDate Class:
= Was used to represent a calendar day & time. Nowdays most of the functions from this class is deprecated.
= Currently this class is used to represent time duration in milliseconds from epoch time i.e. 1-JAN-1900
00:00:00.
- example:
Date d2 = new Date);
System.out printIn(d2.toString();
+ Nested Classes:
1, static member class:
- A class can be declared within another class with “static” keyword. In this case, the inner class is
treated as.a static member of the outer class.
= Inner class object is not dependent on outer class object.
«Inner class can access static members of outer class directly; however it cannot access non-static
members directly,
- If name of static member is same in inner and outer class.
inner class using syntax "Outer.member".
- static member class can have public, private, protected or default access modifier
«If static member is visible outside the Outer class (due to its access modifier), then it can be accessed
‘Outer.inner” outside the class,
using synta
eS
‘SunBeam Institute of Information Technology, Pune, Karad Page 41SUNBEAM
Institute of Information Technology Kao
S
suneeam
Ces
‘Outer.Inner
~ example:
class Outer {
static class Inner {
2, non-static member class:
« Non-statc inner class object can be created, ifand only i tis associated with some outer class object.
« Non-static member class can access static as well as non-state members ofthe quer class dreety
~ Non static member class have a hidden reference to the associated outer class objet ie, "Outer this".
« FFname of non-static member in outer class is same as that of inner cass, then i ean accessed in the inner
class using syntax "Outer.this.member"
“Object oFinner class can be created outside the Outer class using one ofthe following way
= Outer obj = new Outer;
Cuter. Inner refl = obj.new Inner);
~—Outerinner ref2~ new Outer().snew Inner;
“Inner class abject can be created inthe outer class non-static method directly
~ class Outer's non-state method:
void nsMethodd {
Inner obj new Inner);
his new Inner()s
Mnner obj
= example:
class Outer {
class Inner {
a
ist implements Iterable (
private static class Node (
Object data;
Node next;
public Node() {
‘SunBeam Institute of Information Technology, Pune, Karad6 sunBeam
Institute of Information Technology
,
this.next = null;
private Node head;
public List() {
this.head = null;
»
public void add(object val) {
Node newnode = new Node (val) ;
if (head==null)
head = newnode;
else {
Node trav = head;
while (trav.next!=nul1)
trav = trav-next;
trav.next = newnode;
private class Iter implements Iterator (
private Node nodeOb3;
public Iter() (
this.nodeobj = head;
,
public boolean hasNext() {
return nodeObj!=null ? true : false;
,
public Object next() (
Object val = nodeob3.data;
node0b} = nodeob3.next;
return val
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
mene om oesomaseac Placetnent Inittive
public void remove
y
public Iterator iterator() {
return this.new Iter ();
)
public class Main (
public static void main(String{] args) {
List obj = new List ();
ob3.add ("A") ;
‘ Te
List.Iter itr = obj.iterator();
while(itr.hasNext()) (
String val=(String) itr next () ;
system, out.printia (val) ;
}
fox (Object val : obj)
system.out.printin (val) ;
3. local class:
~ in java, clases can be defined within the method. Such classes are treated like local variables and
ate called as "local classes".
Their scope is limited to the method in which they are implemented. In other words, the class cannot
bbe accessed outside the enclosing method.
“Af class is implemented within static method, it behaves as static member class (i.e. ean access static
members of outer class directly)
«If cassis implemented within non-static method, it behaves as non-static member class (je. can
access static and non-static members of outer class directly)
- In both cases, local classes can access final local variables of the enclosing method.
~ example:
class Main {
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
Placement Intative
Cees
public static void main(String[] args)
Student[] arr = new Student[5]
arr[0] = new Student(...);
uw
class StudNameComparator implements Comparator {
public int compare (Object ol, Object 02) {
Student si=(Student) ol;
Student s2=(Student) 02;
int diff = s1.getName() .compare(s2.getName()) ;
return diff;
)
StudNameComparator cmp = new StudNameComparator () ;
Arrays.sort(arr, cmp) ;
for(Student s:arz)
system. out.printin(s) ;
?
~ We can create any number of objects of local class within enclosing method.
4, Anonymous Inner Class:
= example’
ClassName obj = new ClassName() {
b
= When you want to create single object ofa class inherited from some other classinterface and need to
invoke its overridden methods, anonymous class would be the best choice.
«= In above syntax example, internally a new class is created inherited from "ClassName" and then its object is
created, which is accessed by "obj" reference.
- Obviously with “obj” reference we can access only overridden methods of that inherited anonymous class
= Usually such classes are written in some method and hence their behaviour is same as "local classes".
~ example:
Rerays sort (are, new Comparator () (
public int compare (Object 01, Object 02) {
Student s1 = (Student) ol;
Student s2 = (Student) 02;
EES
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
w@® Institute of Information Technology
SURDEAM sp access samc
ee erica
int diff = sl.getName() .compareTo(s2.getName()) 7
return diff;
Placement initiative
ne
+ Generis in Java:
_ When same logic need to be implemented for different datatypes, generic (template) programming can Pe
used in java.
_ Example: All data structures (e.g, Stack, Queve, List, Tree, et) logie remains same irespective of which
type of objects are used in that data structure.
- Limitations of generics in Java:
1. Cannot be used with primitive types.
. Cannot create array of generic type (T).
3. Type of generic type cannot be properly detected at runtime using reflection. Also cannot work
‘well with “instanceof” operator.
~ Efficiency of generic types is same as efficiency of corresponding "Object" based types in Java.
= Advantages:
1. The same generic class can be reused for different class types.
2. Generic classes are type-safe. If different type of elements is added in the generic collection,
compile time error is raised.
- Generics were added in Java 5.0 version. Till Java 1.4 all collection classes were used as "Object"
collections. However 5.0 onwards, all collection classes refined to take generic parameters.
x14; ArrayList list = new ArrayList();
ExS,0: ArrayListePersort list = new ArrayListQ;
Ex7 : ArrayList list ~ new ArrayList>0;
example
class Stack {
private T[] arr;
private int top;
‘
(vt) array newinstance(type, size);
public Stack (Class type, int siz
top = <1:
»
public void push(T ele) (
arr[++top] = ele,
y
public void pop() {
SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
Institute of Information Technology
Caron
‘top-=;
public T peek() {
return arr[top] ;
)
public boolean empty() {
return top==-1;
>
public boolean full() {
xeturn top==arr.length-1;
)
public class Main {
public static void main(stringl] args) {
Stack s1 = new Stack<>();
s1.push (11);
s1.push (22) ;
int ele;
ele = s1.peek();
s1.pop() ;
System. out.print£ ("popped :
>
- Generic Interface
- predefined java.util. Comparable interface:
public interface Comparable {
int compareTo(T 0);
- implementing Comparable in Student class:
aa\s
class Student implements Comparable {
uv
public int compareTo(Student other) {
iffthis.rol
return 0;
ther. roll)
return this.roll > other.roll +1
}
_
‘SunBeam Institute of Information Technology, Pune, Karad
Placement InitiativeG sunBesam
es Institute of Information Technology
SUTBEAM ss suncnammsatss oes Seem Placement initiative
3
- Generic Metho
By default all methods in generic class are generic methods
However it is possible to implement generic method in non-generic
class.
example
class Util {
public static void swap(? ol, T 02) (
Te = ol; ,
o2 = 02;
o2 = t:
System. out.print£("o1:8s, o2:%s\n", ol, 02);
)
class Main {
public static void main(String{] args) {
String sl="sunbean", s:
Util. swap (s1,s2) ;
Ws
"infotech";
+ Java Collection Framework:
~ Collection Framework = Interfaces + Implementations + Algorithms
+ Java Collection Hierarchy:
~All collection interfaces and classes are kept under java.util package.
+ Collection
|: SetsE>
|- HashSet
| LinkedHashSet
| TreeSet
| List
|; ArrayList
| LinkedList
|r Vectorse>*
I+ Stack
SunBeam Institute of Information Technology, Pune, Karad@ 2UNBEAM
— Institute of Information Technology
suTmeAm ee oe scuriemmanee Placement Initiative
Cerne
‘QueuesE>
| PriorityQueue
KV>
HashMap
LinkedHashMap
TreeMap
- Hashtable *
Before J2SE 1.2 only Vector and Hashtable were supported. When collection framework is introduces
with SAVA2, these classes are modified to be compatible with collection framework interfaces.
+ Java Collection Interfaces:
1, Collection
= Root of collection hierarchy.
- Most of the classes inherited from Collection interiace.
2. Set
- [sa collection which allows duplicate values, bidirectional traversing and random access.
4, QueuesE>
- Isa collection which provide data structure queue functionality.
5. MapeK,V>
- Not inherited from Collection interface
= Stores data in key, value pair so that fora given key, value can be searched in fastest possible tine.
+ interface Collection:
extends Iterable
- Iterator iterator();
- All classes inherited from Collection interface, i implement Iterator.
They all can be traversed using for-each loop.
= boolean add(E ele);
= boolean contains(E ele);
~ boolean remove(E ele);
= boclean isEmpty
= int size();
- boolean addAll(Collection 0);
__————
‘SunBeam Institute of Information Technology, Pune, Karad(
G@ SUNBEAM
Institute of Information Technology
GURBEAM somammmmene ecm cnr em Placement lniatve
~ boolean containsAlli Collection ¢);
- boolean removeAli(Collection ©);
- boolean retainAll(Collection ©);
= void clear();
+ interface Set
~ HashSet
- Elemenis are stored in any order (based on hashcode).
- Faster/E(Micient search.
- Equality is based on hashCode() and equals() method.
~ LinkedHashSet
Elements are stored inthe order of insertion,
~ Equality is based on hashCode() and equals() method.
~ TreeSet
Elements are stored in the sorted order.
- Equality and comparision is based on compareTo() method of Comparable interface.
=In other words, objects to be added into TreeSet® should implement Comparable interface;
otherwise ClassCastException will be thrown.
= Note that TreeSet> does not depend on equals() and hashCode() method of the containing
objects
~ As a standard practice, if equalsQ and compareTo() both are implemented, then both should
perform comparision on the same fields.
+ interface List
+ Since itis inherited from Collection interface, it has all methods discussed in Collection.
+ List provides additional searching mechanisms:
= int indexOMObject 0);
~ Compare given object with all objects in the list using equals() method and if found,
return “index” of that element, Ifnot found return -
~ As list can have duplicate elements, this method returns first occurance of the element
~ example:
roll
senextintO);
= new Student);
ssetRoll(roll);
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
@® Institute of Information Technology
Placement initiative
Cer
index = list.indexOfs);
iffindex!=-1)
‘System. out-printin("Found’):
else
System.out.printin(*Not Foun!)
int lastindexOMObject 0);
1 with all objects in the list in the reverse order using equals() method.
~ Compare given obj
If found return index of object, else return -1
As list can have duplicate elements, this method retums last occurance of the element.
+ Random access:
Element at any index can be accessed/teplaced directly.
E get(int index);
= Returns object at given index. Throws exception for invalid index.
~ example:
index = se.nextInt();
5 list.get(index);
System.out.printin(s);
E set(int index, E newEle)
- Set a new object at given index (replacing old object).
~ example:
index = se.nextInt();
new StudentQs
saccept()
list.set(index, s);
- E remove(int index);
= deletes element at given index and all elements after that index will be shifted to index-1
+ Bi-directional Traversing:
implements iterator for traversing. This iterator is inherited from ListIterator= interface
« Listlterator< interface is inherited from Iterator<>. It has additional methods:
- boolean hasPrevious();
-E previous();
- void set(E ele);
Object of Listlterator<> can be received using listIterator() method of List interface.
= ListIterator> listlterator();
- Listlterator> listlterator(int index);
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM |
Institute of Information Technology
am Placement initiative
Cereb |
Forward traversing:
Listterator t= tists :
while(ite-hasNext(Q) {
Student s = itr.next(
System.out printin(s);
}
- Reverse traversin
Listlterator itr = list. listlterator list size());
while(it:hasPrevious() {
Student s= itr previous();
System.out.printin(s);
By default, iterator points fo stat ofthe lis, so revere traversal isnot posible
= Solin case of reverse traversing lis erator should begin fom end of ist (as shown n above example) |
+ Algorithms which can work on List iterface: |
~ Alll methods given here are static methods of java.util.Collections class.
- Sorting List:
= void sort(List' list);
~ The type T must be inherited from Comparable<>.
= void sort(List list, Comparator c);
~ Reversing List:
= void reverse(List list)
- Randomizing List:
= Void shutffle(List list);
~ Binary Seareh:
+ List should be initially sorted.
- The type T must be inherited from Comparable>.
- Void binarySearch(List list, T obj);
+ List Implementations:
~ ArrayList> class:
~ Internally implemented as doubly linked list of arrays. Each node contains multiple elements.
= It gives more efficient random access.
~ Insertion and deletion (at middle of list) is slower operation).
~ LinkedList> class:
~ Internally implemented as doubly linked list with head and tal pointer. ’
‘SunBeam Institute of Information Technology, Pune, KaradSUNBEAM
G Institute of Information Technology
Ceres
jon at ends of list are very fast. Also insertion and deletion at mi
woman: Placement Initiative
j
~ Insertion and delet of list ifefficient,
However random access is slower.
= Vector> class:
= Vector-> is implemented as dynamic array (contiguous memory). The array grows or shrink runtime
as per requirement.
- However Vector<> is synchronized class (all methods are synchronized),
= It is mainly preferred in multi-threaded program. However syne reduce the performance in single
threaded program.
- Stack> class:
Inherited from Vector.
- Provides last-in-first-out behaviour using methods: push). popQ, peekO,
+ Queue interface:
~ Implementation class:
PriorityQueue>
+ Map interface:
= Map does not allow duplicate keys, If try to add duplicate key. new value will replace old value.
= methods:
V puttk key, V val;
= V get{K key):
= int sizes
+ void elearQs
- void removetK key):
- boolean containsKey(K key):
- boolean containsValue(V vale)
= SetcK> keySet(;
- Collection values();
Set entrySet();
- Implementation classes:
- HashMap:
~ Elements are stored in any order of the keys.
- Faster searching
LinkedPashMap-
= Elements are stored inthe order of insertion of keys
= TreeMap
- Elements are stored in the sorted order of keys.
~ The Key class must implement java.util Comparable,
‘SunBeam Institute of Information Technology, Pune, Karad6 SunBeam
Institute of Information Technology
SUNBEAM. socssnmammens: cmennanan a scement Initiative
performance in single threaded program.
* Note:
MapéInteger,Student> map = ...3
KEY : Integer
VALUE : Student
- KEY class ie. Integer class must implement Comparable interface for TreeMap<> and must implement
cequals() & hashCode() for HashMap<>, LinkedHashMap© and HashTable>.
* Note:
Map niap =.
KEY : Student
VALUE : ProgressCard
In this case Student class must implement Comparable interface for TreeMap© and must implement
equals() & hashCode() for HashMap<>. LinkedHashMap© and HashTable>.
+ Time Complexity:
It is approximate measure of time required to complete any algorithm.
- Many times time complexity is calculated from number of iterations done into the program.
- For example:
nia1t293%..¢n
- The program will be having loop repeated n times. So time required is proportional to “n", Thus time
complexity is of order of "n" and denoted as O(n).
- Here "O(n)" is known as Big O notation,
- Few Imp Time complexities:-
- Time required to add or delete element from stack or queue, is constant (independent of number of
elements). So time complexity is O(|).
+ Time required to add element at the end of linked list having only head pointer, depends on number of
elements (loop is repeated to traverse to last element). So time complexity is O(n).
- Time complexity of binary search:
ai
{where, iis num of iterations and n is number of elements in the sorted array]
Time complexity O(log r).
Time complexity of selection sort:
‘SunBeam Institute of Information Technology, Pune, KaradG SUNBEAM
= Institute of Information Technology
sunBeam caemane Placement inititive
ree ed
‘of comparisions = (n-1) + (n-2) +... #1
=n(wl)/2
So time complexity is O(n"2)
+ Hashing:
~ Hashing is used for fast searching,
~ The data is stored in form of key-value pair, so that for a given key value can be searched in fastest possible
time.
~ Ideal time complexity of searching in hash table is O(1).
~ Hash table is internally an array, holding data and data is accessed by proper index.
~ The values are stored into the array, ata particular index. This indey is calculated from the given key using
‘some mathematical function, called as “hash function”.
- Simplest example:
-Si
~ Here array of “n" student objects can be created and information of student with roll number ":" can
student info so that it can searched for given roll number.
be stored! at index
This "r-1" is example of simple hash function
~hikey)=key-1 => results in index of hashtable.
~ Here student with roll "r* can be immediately found at index."
‘Time complexity of searching O(1).
- However inthe complex examples, multiple keys can result to same inde slot into the hashtable/aray. This is
called as “collision”
~ The collision can handled in one of the following ways:
1. Open Addressing:
If slot calculated using hash function is already occupied by some object, then another
‘mathematical function is used to find alternative slot for the object. This is called as "re-hashing"
~ Simplest re-hashing function would be "index+" ie. next slot of table (if empty). This
simplest mechanism of open addressing is known as "linear probing”
Load factor = num of elements / num of slots.
~ This mechanism can be used only if Load factor <
2. Chaining:
~ Each slot of hash-table holds a list of objects competing for the same slot. This list
known
"bucket"
| ~ As numi
from O(1),
F collisions are increased, the time complexity of searching will be deviated (increased)
+hashCode() method:
‘SunBeam Institute of Information Technology, Pune, Karad Page 5,G& sunBeam
a Institute of Information Technology
SURBEAM (seaman senses nse Placement Initiative
Core Java Notes
- java.util. Object class has hashCode() method, which can be overridden into the derived to return hash
code/value of the object.
- This hash code determines the slot of the hashtable, in which object isto be stored.
- Ifnot overridden, Object class hashCode( is called, wiiich return hash value based on memory address of the
object
~ Rules of hashCode() method:
1. If two objects are equal (by equals() method), then their hash code must be same.
2. IPtwo objects are not equal (by equals() method), then their hash code may be same.
~ Hence hash code must be calculated on the same fields, on which equality is compared.
- Statistically itis proven that hash code calculated using prime numbers is uniformly distributed (more unique)
‘and hence most of the hash code calculations are done using prime numbers.
+ Reflection:
- Reflection technique is used to get information about the data type at runtime.
- Three applications/uses of reflection:
1. To get complete info about the type at runtime. It is used to develop intellisence feature, tools like
Javap.exe.
2. Use the retrieved information about the type to create object of class at runtinne and invoke its
methods. This is used in most of frameworks like struts, servlets, applets, etc internally.
3. Generate the java classes (byte code) at runtime and execute them. This can be done by using
ClassLoader.defineClass() method.
- Information about a type can be received in java.lang.Class object using one of the following way:
1. Class ¢ = obj-getCiass();
- Get the info of the class whose object is referred by “obj”.
2. Class ¢ = ClassName.class;
- Get the info of the class with name "ClassName".
3. Class ¢ = Class.forName(“pkg.ClassName");
- Get the info about the class whose name will be taken at runtime (in form of String)
~ This method loads the class in the JVM and return its information.
- java.lang.Class methods:
- String getName();
boolean isAbstract();
- boolean isinterface();
- boolean isEnum();
- Field{] getFieldsQ;
- Method{] getMethods()
- Constructor{} getConstructors();
- Annotation{] getAnnotations();
——————————
‘SunBeam Institute of Information Technology, Pune, Karad
‘& SuNBeam FR
Institute of Information Technology Placement Iniative
suneeam
Cree
+ GUI programming in JAVA:
- JAVA provides different classes for creating desktop GUL There are two main ways to create GUI on JAVA:
1, AWT-- Abstract Window Toolkit:
- Java Ul classes intemally depends on the Peer classes, which in turn use OS functions to create Ul.
~ e.g, java.awt, Button class intemally use "ButtonPeer", which in turn calls OS function ("CreateWindow on
Windows OS) to create button UL
- Due to this AWT Ul will be have different look & fe! on different platforms (0S).
~ Also intemal use of peer classes make them heavy components,
2. SWIN
- Java has another set of classes to create platform independent Ul, These classes are called as "SWING".
- The look & feel of UI remains same on all platforms.
wing components internally use MVC architecture i.e. each swing component (ui contol class)
internally use three objects to spit the functionality:
= Model : keep the data of the component e.g, Strings in the JComboBox.
- View : keep appearance related info of the component e.g. height, width, back color, fore color, et.
~ Controller : responsible for calling event handler when event occurs €. user click, selection changes
in combo box, ete. It also communicate between view and model
+ SWING:
+ Swing component heirarchy:
= Component : represents a UI control on the sereen. .
= Container : is collection of one or more components.
= Window.
- Container that can hold multiple components.
~ It has its own window ie. title bar and border.
Panel
~ Container that ean hold multiple components.
+ It does not have its own window. I is always present in some other window to group
components.
- JFrame:
- Frame has its own window.
So it is stand-alone desktop based application,
- Frame application has main() function,
= JApplet
~ Applet does not have its own window.
- So it always execute within browser window.
‘SunBeam Institute of Information Technology, Pune, Karad Page 57|
!
|
|
|
SUNBEAM
Institute of Information Technology
— cence veemmemmene+ Placement ntiatve
Coens
~ Applet does not have main() function. Its execution begin with init() method.
~ Swing components
= SLabel, JTextField, sTextArea, JButton, JComboBox, JListBox, 1CheckBox, et.
+ Event handling:
- User action is called as an event. e.g. key press, mouse click, et.
- We can handle these events to add functionality into the GUL
~ The standard way to handle events isto implement appropriate "Listener" interface.
- Example: Button élick handler:
* stepl: Implement ActionListener interface into some class (in one of the following ways)
~ Write a new class inherited from ActionListener interface.
- Implement ActionListener into the user-defined frame class itself
~ Anonymous inner class to implement ActionListener interface
* step2: Pass the object of class inherited from ActionListener to the addActionListener() method of
button object, when that button is created.
* step3: Into this event handling class write appropriate logic within actionPerfromed() method.
= When a button click event occurs, a first it is detected by OS and inform to the JVM. Then JVM pass
the event to the button object. Finally button object invokes actionPerformed() method of the listener
inherited class object(s) registered with it.
- Event objects:
~ Bach listener method receive an Event object inherited from "java.awt.Event" clas.
~ e.g, ActionEvent, WindowEvent, etc.
- This event object contains complete info about the event, which includes source of event (component
for which event occured) and additional info.
+ Adapter classes:
~ Certain listener interfaces have more than one methods. e.g. WindowListener has 7 methods,
‘MouseListener has 6 methods.
= Most of the cases programmer is interested in handling one or two methods from such interface.
However being an interface, it is compulsory for the user to implement all the methods.
~ To simplify this operation, java provides adapter classes for such interfaces. They are abstract classes
having empty/default implementations of all methods in such interface. e.g. WindowAdapter and MouseA dapter.
= So programmer can write his own class inherited from adapter class and override only those methods
in which he is interested.
—
‘SunBeam Institute of Information Technology, Pune, Karad Page 58Institute of Information Technology
@ SUNBEAM
UeeAM Placement Iniiatve
ered
~ Typically preferred approach is to create anonymous class inherited from adapter and add its object
with target compon:
-eg
In constructor of the user-defined frame class
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose()
+ Layout Managers:
Java has few builtin managers which are used to place components in the container in proper way.
= The layout manager can be set using Container’ setLayout() method. If layout manager is not given
(ie, set to null), then programmer must give appropriate x,y coordinates and width,height using setBounds() method of
the component.
this.setLayout(null);
There are few imp layout managers as follows:
1. FlowLayout:
= Add components in horizontal direction one after another, just like web page.
= this setLayout(new FlowLayout();
~ button = new Button("Caption");
this.add(button);
~ This is default layout of Panel and Applet class.
2. GridLayout:
- Add components in the grid defined by the programmer. Components will be places in appropriate cell (row &
col) one after another.
« this setLayout(new GridLayout(2,3));
= button = new Button("Caption");
this-add(button);
3. BorderLayout:
- Add components in certain direction or center of the container as shown in diag,
= this setLayout(new BorderLayout();
button = new Button("Caption");
this.add(button, BorderLayout. CENTER):
= This is default layout of Window and Frame class,
4. GridBagLayout:
Complicated layout manager which provides flexible way of adding components in the container.
‘SunBeam Institute of Information Technology, Pune, Karad Page 596& SuUNBeAam
Institute of Information Technology
SUPBEAM (sesnsanmanmerns wer eee Placement Iitiatve
Ceres
+ Applets:
+ Applet steps (on command line)
1. Write a java class inherited from java.awt. Applet class and override init() method. Write appropriate code in it.
2. To test applet with appletviewer tool, write comment before class (after import statements),
*