SlideShare a Scribd company logo
1 of 33
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 Genericsjeslie
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummiesknutmork
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 
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 ScalaKnoldus Inc.
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin 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 glanceKnoldus 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
 
Grafos avanzado
Grafos avanzadoGrafos avanzado
Grafos avanzadomenamigue
 
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 10Andres 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 (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 sharmaSandesh 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 sharmaSandesh Sharma
 
Automated code review process
Automated code review processAutomated code review process
Automated code review processSandesh Sharma
 
Service oriented architecture
Service oriented architectureService oriented architecture
Service oriented architectureSandesh Sharma
 

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

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 

Recently uploaded (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

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