SlideShare a Scribd company logo
Core JAVA
By Sandesh Sharma
Contents

Primitive types

Wrappers

Static

String

Abstract

Interface

Collections

Equals

HashCode

Threads
Primitive types
• int 4 bytes
• short 2 bytes
• long 8 bytes
• byte 1 byte
• float 4 bytes
• double 8 bytes
• char Unicode encoding (2 bytes)
• boolean {true,false}
Behaviors is
exactly as in
C++
Note:
Primitive type
always begin
with lower-case
Wrappers
Java provides Objects which
wrap primitive types and supply
methods.
Example:
Integer n = new Integer(“4”);
int m = n.intValue();
Read more about Integer in JDK Documentation
Static

Member data - Same data is used for all the
instances (objects) of some Class.
Class A {
public int y = 0;
public static int x_ = 1;
};
A a = new A();
A b = new A();
System.out.println(b.x_);
a.x_ = 5;
System.out.println(b.x_);
A.x_ = 10;
System.out.println(b.x_);
Assignment performed
on the first access to the
Class.
Only one instance of ‘x’
exists in memory
Output:
1
5
10
a b
y y
A.x_
0 0
1
Static

Member function
− Static member function can access only static
members
− Static member function can be called without an
instance.
Class TeaPot {
private static int numOfTP = 0;
private Color myColor_;
public TeaPot(Color c) {
myColor_ = c;
numOfTP++;
}
public static int howManyTeaPots()
{ return numOfTP; }
// error :
public static Color getColor()
{ return myColor_; }
}
Static
Usage:
TeaPot tp1 = new TeaPot(Color.RED);
TeaPot tp2 = new TeaPot(Color.GREEN);
System.out.println(“We have “ +
TeaPot.howManyTeaPots()+ “Tea Pots”);
Static

Block
− Code that is executed in the first reference to the
class.
− Several static blocks can exist in the same class
( Execution order is by the appearance order in
the class definition ).
− Only static members can be accessed.
class RandomGenerator {
private static int seed_;
static {
int t = System.getTime() % 100;
seed_ = System.getTime();
while(t-- > 0)
seed_ = getNextNumber(seed_);
}
}
}
String is an Object
• Constant strings as in C, does not exist
• The function call foo(“Hello”) creates a String
object, containing “Hello”, and passes reference to it
to foo.
• There is no point in writing :
• The String object is a constant. It can’t be changed
using a reference to it.
String s = new String(“Hello”);
Abstract

abstract member function, means that the function
does not have an implementation.

abstract class, is class that can not be
instantiated.
AbstractTest.java:6: class AbstractTest is an abstract class.
It can't be instantiated.
new AbstractTest();
^
1 error
NOTE:
An abstract class is not required to have an abstract method in
it.
But any class that has an abstract method in it or that does
not provide an implementation for any abstract methods
declared
in its superclasses must be declared as an abstract class.
Abstract - Example
package java.lang;
public abstract class Shape {
public abstract void draw();
public void move(int x, int y) {
setColor(BackGroundColor);
draw();
setCenter(x,y);
setColor(ForeGroundColor);
draw();
}
}
package java.lang;
public class Circle extends Shape {
public void draw() {
// draw the circle ...
}
}
Interface
Interfaces are useful for the following:
• Capturing similarities among unrelated classes
without artificially forcing a class relationship.
• Declaring methods that one or more classes are
expected to implement.
• Revealing an object's programming interface
without revealing its class.
Interface

abstract “class”

Helps defining a “usage contract” between
classes

All methods are public

Java’s compensation for removing the
multiple inheritance. You can “inherit” as
many interfaces as you want.
*
- The correct term is “to implement”an interface
Interface
interface SouthParkCharacter {
void curse();
}
interface IChef {
void cook(Food food);
}
interface BabyKicker {
void kickTheBaby(Baby);
}
class Chef implements IChef, SouthParkCharacter {
// overridden methods MUST be public
// can you tell why ?
public void curse() { … }
public void cook(Food f) { … }
}
* access rights (Java forbids reducing of access rights)
When to use an interface ?
Perfect tool for encapsulating the
classes inner structure. Only the
interface will be exposed
Collections

Collection/container
− object that groups multiple elements
− used to store, retrieve, manipulate, communicate
aggregate data

Iterator - object used for traversing a collection and
selectively remove elements

Generics – implementation is parametric in the type of
elements
Java Collection Framework

Goal: Implement reusable data-structures and
functionality

Collection interfaces - manipulate collections
independently of representation details

Collection implementations - reusable data
structures
List<String> list = new ArrayList<String>(c);

Algorithms - reusable functionality
− computations on objects that implement collection
interfaces
− e.g., searching, sorting
− polymorphic: the same method can be used on many
different implementations of the appropriate collection
interface
Collection Interfaces
Collection
Set List Queue
SortedSet
Map
Sorted Map
Collection Interface

Basic Operations
− int size();
− boolean isEmpty();
− boolean contains(Object element);
− boolean add(E element);
− boolean remove(Object element);
− Iterator iterator();

Bulk Operations
− boolean containsAll(Collection<?> c);
− boolean addAll(Collection<? extends E> c);
− boolean removeAll(Collection<?> c);
− boolean retainAll(Collection<?> c);
− void clear();

Array Operations
− Object[] toArray(); <T> T[] toArray(T[] a); }
General Purpose Implementations
Collection
Set List Queue
SortedSet
Map
Sorted Map
HashSet HashMap
List<String> list1 = new ArrayList<String>(c);
ArrayListTreeSet TreeMapLinkedList
List<String> list2 = new LinkedList<String>(c);
final

final member data
Constant member

final member
function
The method can’t be
overridden.

final class
‘Base’ is final, thus it
can’t be extended
final class Base {
final int i=5;
final void foo() {
i=10;
//what will the compiler say
about this?
}
}
class Derived extends Base {
// Error
// another foo ...
void foo() {
}
}(String class is final)
final
final class Base {
final int i=5;
final void foo() {
i=10;
}
}
class Derived extends Base {
// Error
// another foo ...
void foo() {
}
}
Derived.java:6: Can't subclass final classes: class Base
class class Derived extends Base {
^
1 error
Exception - What is it and why do I care?
Definition: An exception is an event that occurs
during the execution of a program that disrupts
the normal flow of instructions.
• Exception is an Object
• Exception class must be descendent of
Throwable.
Exception - What is it and why do I care?
By using exceptions to manage errors, Java
programs have the following advantages over
traditional error management techniques:
1: Separating Error Handling Code from "Regular"
Code
2: Propagating Errors Up the Call Stack
3: Grouping Error Types and Error Differentiation
method1 {
try {
call method2;
} catch (exception) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
Propagating Errors Up the Call Stack
Why Override The Defaults
• For equals consider the default:
NaturalNumber n1 = new NaturalNumber2();
NaturalNumber n2 = new NaturalNumber2();
boolean b = n1.equals(n2);
• What is the value of b with the default implementation
of equals ?
Why Override The Defaults

For hashCode consider the default:
NaturalNumber n1 = new NaturalNumber2();
NaturalNumber n2 = new NaturalNumber2();
Set s = new Set4<>(); s.add(n1);
boolean b = s.contains(n2);
• What is the value of b with the default implementation of
hashCode ?
Threads Overview
– Threads allow the program to run tasks in parallel
– In many cases threads need to be synchronized,
that is, be kept not to handle the same data in memory
concurrently
– There are cases in which a thread needs to wait for
another thread before proceeding
Threads in Java
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("Thread1 ThreadId: " +
Thread.currentThread().getId());
// do our thing
PrintNumbers.printNumbers();
// the super doesn't anything,
// but just for the courtesy and good
practice
super.run();
}
}
Threads in Java
static public void main(String[] args) {
System.out.println("Main ThreadId: " +
Thread.currentThread().getId());
for(int i=0; i<3; i++) {
new Thread1().start(); // don't call run!
// (if you want a separate thread)
}
printNumbers();
}
Threads in Java
public class Thread2 implements Runnable {
@Override
public void run() {
System.out.println("Thread2 ThreadId: " +
Thread.currentThread().getId());
// do our thing
PrintNumbers.printNumbers();
}
}
Threads in Java
static public void main(String[] args) {
System.out.println("Main ThreadId: " +
Thread.currentThread().getId());
for(int i=0; i<3; i++) {
new Thread(new Thread2()).start();
// again, don't call run!
// (if you want a separate thread)
}
printNumbers();
}
thAnks
Question can be sent sandesh.sharma [at]jabong.com

More Related Content

What's hot

Java Generics
Java GenericsJava Generics
Java Generics
jeslie
 
Java Generics
Java GenericsJava Generics
Java Generics
Zülfikar Karakaya
 
Class method
Class methodClass method
Class method
kamal kotecha
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
knutmork
 
Java Generics
Java GenericsJava Generics
Java Generics
DeeptiJava
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
Roshan Deniyage
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
Shalabh Chaudhary
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
manish kumar
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingRanel Padon
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
Knoldus Inc.
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-libraryHariz Mustafa
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2Hariz Mustafa
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
Knoldus Inc.
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
Knolx session
Knolx sessionKnolx session
Knolx session
Knoldus Inc.
 

What's hot (20)

Java Generics
Java GenericsJava Generics
Java Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Class method
Class methodClass method
Class method
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java Day-4
Java Day-4Java Day-4
Java Day-4
 
Lecture 7 arrays
Lecture   7 arraysLecture   7 arrays
Lecture 7 arrays
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
Python Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator OverloadingPython Programming - VII. Customizing Classes and Operator Overloading
Python Programming - VII. Customizing Classes and Operator Overloading
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Lecture11 standard template-library
Lecture11 standard template-libraryLecture11 standard template-library
Lecture11 standard template-library
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Pattern Matching - at a glance
Pattern Matching - at a glancePattern Matching - at a glance
Pattern Matching - at a glance
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Knolx session
Knolx sessionKnolx session
Knolx session
 

Viewers also liked

Creación de archivos de clases en c#
Creación de archivos de clases en c#Creación de archivos de clases en c#
Creación de archivos de clases en c#
UVM
 
Objetos y arreglos en C#
Objetos y arreglos en C#Objetos y arreglos en C#
Objetos y arreglos en C#
UVM
 
Lenguaje de programacion c#
Lenguaje de programacion c#Lenguaje de programacion c#
Lenguaje de programacion c#XM Filial de ISA
 
Metodos Constructor Y Destructor
Metodos Constructor Y DestructorMetodos Constructor Y Destructor
Metodos Constructor Y Destructorrezzaca
 
1. teoría listas enlazadas
1. teoría listas enlazadas1. teoría listas enlazadas
1. teoría listas enlazadas
Sebastián Gómez
 
Pilas en Java
Pilas en JavaPilas en Java
Pilas en Java
VICTOR VIERA BALANTA
 
Grafos avanzado
Grafos avanzadoGrafos avanzado
Grafos avanzado
menamigue
 
Estructuras de datos y algoritmos
Estructuras de datos y algoritmosEstructuras de datos y algoritmos
Estructuras de datos y algoritmosRobert Rodriguez
 
Introducción a la programación y la informática. Tema 10
Introducción a la programación y la informática. Tema 10Introducción a la programación y la informática. Tema 10
Introducción a la programación y la informática. Tema 10
Andres Garcia Garcia
 
Tipos abstractos de datos
Tipos abstractos de datosTipos abstractos de datos
Tipos abstractos de datosJose Armando
 
programacion orientada a objetos
programacion orientada a objetosprogramacion orientada a objetos
programacion orientada a objetosale8819
 
Java pilas (Stacks) y colas (Queues)
Java pilas (Stacks) y colas (Queues)Java pilas (Stacks) y colas (Queues)
Java pilas (Stacks) y colas (Queues)
Juan Astudillo
 
Estructura de Datos Arreglos
Estructura de Datos ArreglosEstructura de Datos Arreglos
Estructura de Datos Arreglosguestc906c2
 

Viewers also liked (20)

Creación de archivos de clases en c#
Creación de archivos de clases en c#Creación de archivos de clases en c#
Creación de archivos de clases en c#
 
Objetos y arreglos en C#
Objetos y arreglos en C#Objetos y arreglos en C#
Objetos y arreglos en C#
 
C sharp fundamentos
C sharp fundamentosC sharp fundamentos
C sharp fundamentos
 
Lenguaje de programacion c#
Lenguaje de programacion c#Lenguaje de programacion c#
Lenguaje de programacion c#
 
Metodos Constructor Y Destructor
Metodos Constructor Y DestructorMetodos Constructor Y Destructor
Metodos Constructor Y Destructor
 
Tipos Primitivos y Elementos Léxicos de Java
Tipos Primitivos y Elementos Léxicos de JavaTipos Primitivos y Elementos Léxicos de Java
Tipos Primitivos y Elementos Léxicos de Java
 
Estructuras de datos
Estructuras de datosEstructuras de datos
Estructuras de datos
 
1. teoría listas enlazadas
1. teoría listas enlazadas1. teoría listas enlazadas
1. teoría listas enlazadas
 
Pilas en Java
Pilas en JavaPilas en Java
Pilas en Java
 
Grafos avanzado
Grafos avanzadoGrafos avanzado
Grafos avanzado
 
Estructuras de datos y algoritmos
Estructuras de datos y algoritmosEstructuras de datos y algoritmos
Estructuras de datos y algoritmos
 
Introducción a la programación y la informática. Tema 10
Introducción a la programación y la informática. Tema 10Introducción a la programación y la informática. Tema 10
Introducción a la programación y la informática. Tema 10
 
Taller 1 3
Taller 1 3Taller 1 3
Taller 1 3
 
áRboles binarios
áRboles binariosáRboles binarios
áRboles binarios
 
Listas enlazadas
Listas enlazadasListas enlazadas
Listas enlazadas
 
Tipos abstractos de datos
Tipos abstractos de datosTipos abstractos de datos
Tipos abstractos de datos
 
programacion orientada a objetos
programacion orientada a objetosprogramacion orientada a objetos
programacion orientada a objetos
 
Java pilas (Stacks) y colas (Queues)
Java pilas (Stacks) y colas (Queues)Java pilas (Stacks) y colas (Queues)
Java pilas (Stacks) y colas (Queues)
 
Estructura de Datos Arreglos
Estructura de Datos ArreglosEstructura de Datos Arreglos
Estructura de Datos Arreglos
 
Resumen
ResumenResumen
Resumen
 

Similar to Core java by a introduction sandesh sharma

Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
Woxa Technologies
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
Woxa Technologies
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
Java tutorials
Java tutorialsJava tutorials
Java tutorialssaryu2011
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
Khizar40
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
Neelkanth Sachdeva
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
Collections
CollectionsCollections
Collections
bsurya1989
 
Collections in java
Collections in javaCollections in java
Collections in javakejpretkopet
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Java 103
Java 103Java 103
Java 103
Manuela Grindei
 
Java
Java Java
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
GOKULKANNANMMECLECTC
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java conceptsChikugehlot
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
Mudit Gupta
 

Similar to Core java by a introduction sandesh sharma (20)

Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Collections
CollectionsCollections
Collections
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Java 103
Java 103Java 103
Java 103
 
Java
Java Java
Java
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Arrays and function basic c programming notes
Arrays and function basic c programming notesArrays and function basic c programming notes
Arrays and function basic c programming notes
 
Core java concepts
Core    java  conceptsCore    java  concepts
Core java concepts
 
Best practices in Java
Best practices in JavaBest practices in Java
Best practices in Java
 

More from Sandesh Sharma

I075306_Acceptance_Certificate
I075306_Acceptance_CertificateI075306_Acceptance_Certificate
I075306_Acceptance_CertificateSandesh Sharma
 
Spring, web service, web server, eclipse by a introduction sandesh sharma
Spring, web service, web server, eclipse by a introduction sandesh sharmaSpring, web service, web server, eclipse by a introduction sandesh sharma
Spring, web service, web server, eclipse by a introduction sandesh sharma
Sandesh Sharma
 
OOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharmaOOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharma
Sandesh Sharma
 
Automated code review process
Automated code review processAutomated code review process
Automated code review process
Sandesh Sharma
 
Service oriented architecture
Service oriented architectureService oriented architecture
Service oriented architecture
Sandesh Sharma
 
Maven
MavenMaven

More from Sandesh Sharma (6)

I075306_Acceptance_Certificate
I075306_Acceptance_CertificateI075306_Acceptance_Certificate
I075306_Acceptance_Certificate
 
Spring, web service, web server, eclipse by a introduction sandesh sharma
Spring, web service, web server, eclipse by a introduction sandesh sharmaSpring, web service, web server, eclipse by a introduction sandesh sharma
Spring, web service, web server, eclipse by a introduction sandesh sharma
 
OOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharmaOOP and java by a introduction sandesh sharma
OOP and java by a introduction sandesh sharma
 
Automated code review process
Automated code review processAutomated code review process
Automated code review process
 
Service oriented architecture
Service oriented architectureService oriented architecture
Service oriented architecture
 
Maven
MavenMaven
Maven
 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
Fwdays
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi"Impact of front-end architecture on development cost", Viktor Turskyi
"Impact of front-end architecture on development cost", Viktor Turskyi
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 

Core java by a introduction sandesh sharma

  • 3. Primitive types • int 4 bytes • short 2 bytes • long 8 bytes • byte 1 byte • float 4 bytes • double 8 bytes • char Unicode encoding (2 bytes) • boolean {true,false} Behaviors is exactly as in C++ Note: Primitive type always begin with lower-case
  • 4. Wrappers Java provides Objects which wrap primitive types and supply methods. Example: Integer n = new Integer(“4”); int m = n.intValue(); Read more about Integer in JDK Documentation
  • 5. Static  Member data - Same data is used for all the instances (objects) of some Class. Class A { public int y = 0; public static int x_ = 1; }; A a = new A(); A b = new A(); System.out.println(b.x_); a.x_ = 5; System.out.println(b.x_); A.x_ = 10; System.out.println(b.x_); Assignment performed on the first access to the Class. Only one instance of ‘x’ exists in memory Output: 1 5 10 a b y y A.x_ 0 0 1
  • 6. Static  Member function − Static member function can access only static members − Static member function can be called without an instance. Class TeaPot { private static int numOfTP = 0; private Color myColor_; public TeaPot(Color c) { myColor_ = c; numOfTP++; } public static int howManyTeaPots() { return numOfTP; } // error : public static Color getColor() { return myColor_; } }
  • 7. Static Usage: TeaPot tp1 = new TeaPot(Color.RED); TeaPot tp2 = new TeaPot(Color.GREEN); System.out.println(“We have “ + TeaPot.howManyTeaPots()+ “Tea Pots”);
  • 8. Static  Block − Code that is executed in the first reference to the class. − Several static blocks can exist in the same class ( Execution order is by the appearance order in the class definition ). − Only static members can be accessed. class RandomGenerator { private static int seed_; static { int t = System.getTime() % 100; seed_ = System.getTime(); while(t-- > 0) seed_ = getNextNumber(seed_); } } }
  • 9. String is an Object • Constant strings as in C, does not exist • The function call foo(“Hello”) creates a String object, containing “Hello”, and passes reference to it to foo. • There is no point in writing : • The String object is a constant. It can’t be changed using a reference to it. String s = new String(“Hello”);
  • 10. Abstract  abstract member function, means that the function does not have an implementation.  abstract class, is class that can not be instantiated. AbstractTest.java:6: class AbstractTest is an abstract class. It can't be instantiated. new AbstractTest(); ^ 1 error NOTE: An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class.
  • 11. Abstract - Example package java.lang; public abstract class Shape { public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor); draw(); setCenter(x,y); setColor(ForeGroundColor); draw(); } } package java.lang; public class Circle extends Shape { public void draw() { // draw the circle ... } }
  • 12. Interface Interfaces are useful for the following: • Capturing similarities among unrelated classes without artificially forcing a class relationship. • Declaring methods that one or more classes are expected to implement. • Revealing an object's programming interface without revealing its class.
  • 13. Interface  abstract “class”  Helps defining a “usage contract” between classes  All methods are public  Java’s compensation for removing the multiple inheritance. You can “inherit” as many interfaces as you want. * - The correct term is “to implement”an interface
  • 14. Interface interface SouthParkCharacter { void curse(); } interface IChef { void cook(Food food); } interface BabyKicker { void kickTheBaby(Baby); } class Chef implements IChef, SouthParkCharacter { // overridden methods MUST be public // can you tell why ? public void curse() { … } public void cook(Food f) { … } } * access rights (Java forbids reducing of access rights)
  • 15. When to use an interface ? Perfect tool for encapsulating the classes inner structure. Only the interface will be exposed
  • 16. Collections  Collection/container − object that groups multiple elements − used to store, retrieve, manipulate, communicate aggregate data  Iterator - object used for traversing a collection and selectively remove elements  Generics – implementation is parametric in the type of elements
  • 17. Java Collection Framework  Goal: Implement reusable data-structures and functionality  Collection interfaces - manipulate collections independently of representation details  Collection implementations - reusable data structures List<String> list = new ArrayList<String>(c);  Algorithms - reusable functionality − computations on objects that implement collection interfaces − e.g., searching, sorting − polymorphic: the same method can be used on many different implementations of the appropriate collection interface
  • 18. Collection Interfaces Collection Set List Queue SortedSet Map Sorted Map
  • 19. Collection Interface  Basic Operations − int size(); − boolean isEmpty(); − boolean contains(Object element); − boolean add(E element); − boolean remove(Object element); − Iterator iterator();  Bulk Operations − boolean containsAll(Collection<?> c); − boolean addAll(Collection<? extends E> c); − boolean removeAll(Collection<?> c); − boolean retainAll(Collection<?> c); − void clear();  Array Operations − Object[] toArray(); <T> T[] toArray(T[] a); }
  • 20. General Purpose Implementations Collection Set List Queue SortedSet Map Sorted Map HashSet HashMap List<String> list1 = new ArrayList<String>(c); ArrayListTreeSet TreeMapLinkedList List<String> list2 = new LinkedList<String>(c);
  • 21. final  final member data Constant member  final member function The method can’t be overridden.  final class ‘Base’ is final, thus it can’t be extended final class Base { final int i=5; final void foo() { i=10; //what will the compiler say about this? } } class Derived extends Base { // Error // another foo ... void foo() { } }(String class is final)
  • 22. final final class Base { final int i=5; final void foo() { i=10; } } class Derived extends Base { // Error // another foo ... void foo() { } } Derived.java:6: Can't subclass final classes: class Base class class Derived extends Base { ^ 1 error
  • 23. Exception - What is it and why do I care? Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. • Exception is an Object • Exception class must be descendent of Throwable.
  • 24. Exception - What is it and why do I care? By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques: 1: Separating Error Handling Code from "Regular" Code 2: Propagating Errors Up the Call Stack 3: Grouping Error Types and Error Differentiation
  • 25. method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } Propagating Errors Up the Call Stack
  • 26. Why Override The Defaults • For equals consider the default: NaturalNumber n1 = new NaturalNumber2(); NaturalNumber n2 = new NaturalNumber2(); boolean b = n1.equals(n2); • What is the value of b with the default implementation of equals ?
  • 27. Why Override The Defaults  For hashCode consider the default: NaturalNumber n1 = new NaturalNumber2(); NaturalNumber n2 = new NaturalNumber2(); Set s = new Set4<>(); s.add(n1); boolean b = s.contains(n2); • What is the value of b with the default implementation of hashCode ?
  • 28. Threads Overview – Threads allow the program to run tasks in parallel – In many cases threads need to be synchronized, that is, be kept not to handle the same data in memory concurrently – There are cases in which a thread needs to wait for another thread before proceeding
  • 29. Threads in Java public class Thread1 extends Thread { @Override public void run() { System.out.println("Thread1 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers.printNumbers(); // the super doesn't anything, // but just for the courtesy and good practice super.run(); } }
  • 30. Threads in Java static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread1().start(); // don't call run! // (if you want a separate thread) } printNumbers(); }
  • 31. Threads in Java public class Thread2 implements Runnable { @Override public void run() { System.out.println("Thread2 ThreadId: " + Thread.currentThread().getId()); // do our thing PrintNumbers.printNumbers(); } }
  • 32. Threads in Java static public void main(String[] args) { System.out.println("Main ThreadId: " + Thread.currentThread().getId()); for(int i=0; i<3; i++) { new Thread(new Thread2()).start(); // again, don't call run! // (if you want a separate thread) } printNumbers(); }
  • 33. thAnks Question can be sent sandesh.sharma [at]jabong.com