SlideShare a Scribd company logo
Introduction to Sun Microsystems java
 High level OOPL
 Platform Independent
 Case Sensitive
2
Can you make coffee with it?
3
It was meant to!!
A programming language for appliances!
4
Java Virtual Machine
Must Run on Any Architecture
Program
in Java
Java
Compiler
Java
Bytecode
Java Virtual Machine
“WRITE ONCE, RUN ANYWHERE!”
debug
pretty portable
5
Doesn’t Make Coffee Yet
6
So What’s Java Good For?
Web applications!
Java Applet
Server
Java Applet
7
Java on the Web: Java Applets
 Clients download applets via Web browser
 Browser runs applet in a Java Virtual Machine
(JVM)
Interactive web, security, and client consistency
Slow to download, inconsistent VMs (besides,
flash won this war)
Applet
Client
Server
8
Java on the Web: J2EE
 Thin clients (minimize download)
 Java all “server side”
THIS IS WHAT YOU’LL BE DOING!!
Client
Server
JSPs
Servlets
EJB
JDBC
9
The Java programming environment
 Compared to C++:
 no header files, macros, pointers and references, unions,
operator overloading, templates, etc.
 Object-orientation: Classes + Inheritance
 Distributed: RMI, Servlet, Distributed object programming.
 Robust: Strong typing + no pointer + garbage collection
 Secure: Type-safety + access control
 Architecture neutral: architecture neutral representation
 Portable
 Interpreted
 High performance through Just in time compilation
(compiler converts byte code to native code) + runtime
modification of code
 Multi-threaded
10
Java Features
 Well defined primitive data types: int, float, double, char, etc.
 int 4 bytes [–2,147,648, 2,147,483,647]
 Control statements similar to C++: if-then-else, switch, while, for
 Interfaces
 Exceptions
 Concurrency (Multi-Threading)
 Packages
 Reflection (makes it possible to inspect classes, interfaces, fields
and methods at runtime, without knowing the names of the
classes, methods etc. at compile time. It is also possible to
instantiate new objects, invoke methods and get/set field values
using reflection. )
 Applet model
11
The Java programming environment
 Java programming language specification
 Syntax of Java programs
 Defines different constructs
 Java byte code: Intermediate representation for Java
programs
 Java compiler: Program that Transform Java programs
into Java byte code
 Java interpreter: Read programs written in Java byte code
and execute them (converts byte into native code. i.e
Codes other than java).
 Java virtual machine: The whole technology is based on
the concept of JVM. Translator of byte code into platform
specific machine language. It is the Runtime system that
provides various services to running programs (Logical
representation of JRE)
12
JVM
13
JIT (Just-in-Time) Compilation
14
JVM
 JVM stands for Java Virtual Machine. It’s an abstract
computer or virtual computer which runs the compiled
java programs. Actually JVM is a software implementation
which stands on the top of the real hardware platform and
operating system. It provides abstraction between the
compiled java program and the hardware and operating
system.
 JIT: This Compiler converts byte code to native code.
 Old Interpreter was replaced with JIT to increase the
performance of java applications.
 When JVM compiles the class file it does not compile the
full class file in one shot. Compilation is done on function
basis or file basis. Depending on need basis the
compilation is done. This type of compilation is termed as
JIT or Just-in- Time compilation.
15
General ( java1.5 –Tiger & java1.6 – Mustang (wild horse))
 can run your compiled code on any operating system
without recompiling your source code
 JVM and Java Application Programming Interface (API) that
are kinds of readymade software components
 Java programming environment: Set of libraries that
provide services such as GUI, data structures,etc.
 Java enabled browsers: Browsers that include a JVM +
ability to load programs from remote hosts
 Platform Dependent – JVM, Java Compiler, Java Interpreter,
C program, JDK.
 Platform Independent – Java program.
 JDK (Java Development Kit) – Collection of various tools,
required to develop and run program
 Tools ( JRE, Java Compiler, Java Interpreter)
16
Path & classpath
 To run the program , Set the properties, then only MS-DOS
knows about java commands. (Temporary)
 set path=%path%; (jdk - bin) (Binary files will be accessible
in all the folders & driver of OS)
 set classpath=%classpath%.; (jdk - lib) (The class will be
available in all the folder of OS)
 The other way of setting up the path
 My Computer – Advanced – Environment variables –
proceed. (Permanent)
 JAVA_HOME – jdk
 Importance of path: Binary will be accessible in all the
folders and driver of O.S
 Importance of classpath: .class files will be available in all
the folders of O.S
17
OOPs Concepts- PIE
 Abstraction: Providing essential properties and
operation of an object by hiding internal things.
 Encapsulation: Placing all the properties and
operations of an object in one place.
 The place is called as class, Properties are called
as variables, Operations are called as methods.
 Polymorphism : Remote control application -
one button is used for switch on/ off.
18
Java: A tiny intro
 How are Java programs written?
 How are variables declared?
 How are expressions specified?
 How are control structures defined?
 How to define simple methods?
 What are classes and objects?
 What about exceptions?
19
How are Java programs written?
 Define a class HelloWorld and store it into a file:
HelloWorld.java:
public class HelloWorld {
public static void main (String[] args) {
System.out.println(“Hello, World”);
}
}
 Compile HelloWorld.java
javac HelloWorld.java
Output: HelloWorld.class
 Run
java HelloWorld
Output: Hello, World
20
How are variables declared?
Fibonacci:
class Fibonacci {
public static void main(String[] arg) {
int lo = 1;
int hi = 1;
System.out.println(lo);
while (hi < 50) {
System.out.println(hi);
hi = hi + lo;
lo = hi – lo;
}
}
}
21
How to define expressions?
 Arithmetic: +, -, *,/, %, =
8 + 3 * 2 /4
Use standard precedence and associativity rules
 Predicates: ==, !=, >, <, >=, <=
public class Demo {
public static void main (String[] argv) {
boolean b;
b = (2 + 2 == 4);
System.out.println(b);
}
}
22
How are simple methods defined?
Every method is defined inside a Java class definition
public class Movie {
public static int movieRating(int s, int a, int d) {
return s+a+d;
}
}
public class Demo {
public static void main (String argv[]) {
int script = 6, acting = 9, directing = 8;
displayRating(script, acting, directing);
}
public static void displayRating(int s, int a, int d){
System.out.print(“The rating of this movie is”);
System.out.println(Movie.movieRating(s, a, d));
}
}
23
How are control structures specified?
Typical flow of control statements: if-then-else, while, switch,
do-while, and blocks
class ImprovedFibo {
static final int MAX_INDEX = 10;
public static void main (String[] args) {
int lo = 1;
int hi = 1;
String mark = null;
for (int i = 2; i < MAX_INDEX; i++) {
if ((i % 2) == 0)
mark = " *";
else mark = "";
System.out.println(i+ ": " + hi + mark);
hi = lo + hi;
lo = hi - lo;
}}}
24
What are classes and objects?
Classes: templates for constructing instances
 Fields
 Instance variables
 Static variables
 Methods
 Instance
 Static
class Point {
public double x, y;
}
Point lowerleft = new Point();
Point upperRight = new Point();
Point middlePoint = new Point();
lowerLeft.x = 0.0; lowerLeft.y = 0.0;
upperRight.x = 1280.0; upperRight.y = 1024.0
middlePoint.x = 640.0; middlePoint.y = 512.0
25
How are instance methods defined?
Instance methods take an implicit parameter:
instance on which method is invoked
public class Movie {
public int script, acting, directing;
public int rating() {
return script + acting + directing;
}
}
public class Demo {
public static void main (String argv[]) {
Movie m = new Movie();
m.script = 6; m.acting = 9; m.directing = 8;
System.out.print(“The rating of this movie is”);
System.out.println(m.rating());
}
}
26
How to extend classes?
 Inheritance: mechanism for extending behavior
of classes; leads to construction of hierarchy of
classes [Note: no multiple inheritance]
 What happens when class C extends class D:
 Inherits instance variables
 Inherits static variables
 Inherits instance methods
 Inherits static methods
 C can:
 Add new instance variables
 Add new methods (static and dynamic)
 Modify methods (only implementation)
 Cannot delete anything
27
How to extend classes?
public class Attraction {
public int minutes;
public Attraction() {minutes = 75;}
public int getMinutes() {return minutes;}
public void setMinutes(int d) {minutes = d;}
}
public class Movie extends Attraction {
public int script, acting, directing;
public Movie() {script = 5; acting = 5; directing = 5;}
public Movie(int s, int a, int d) {
script = s; acting = a; directing = d;
}
public int rating() {return script + acting + directing;}
}
public class Symphony extends Attraction {
public int playing, music, conducting;
public Symphony() {playing = music = conducting = 5;}
public Symphony(int p, int m, int c) {
playing = p; music = m; conducting = c;
}
public int rating() {return playing + music + conducting;}
}
28
What are abstract classes?
 Abstract class: Merely a place holder for class
definitions; cannot be used to create instances.;
public abstract class Attraction {
public int minutes;
public Attraction() {minutes = 75;}
public int getMinutes() {return minutes;}
public void setMinutes(int d) {minutes = d;}
public abstract void m();
}
 Following is an error:
Attraction x;
x = new Attraction();
 Following is not an error:
public class Movie extends Attraction { … }
public class Symphony extends Attraction { … }
Attraction x;
x = new Movie ();
x = new Symphony();
29
Packages
Object
Attraction Auxiliaries Demonstration
Movie Symphony
extends
extends
• How do we organize above classes into a single unit? Put them in file?
However, only one public class per file (whose name is same as file’s)
• Solution: Place several files (compilation units) into a package
30
Packages – cont’d.
 units of organizing related Classes, Interfaces,
Sub packages
 Why?
 Reduce name clashing
 Limit visibility of names
 Java programs typically organized in terms of
packages and subpackages
 Each package may then be divided into several
packages, subpackages, and classes
 Each class can then be stored in a separate file
 Each source file starts with something like:
package mypackage;
 Code in source file is now part of mypackage
31
Packages – cont’d.
package onto.java.entertainment;
public class Movie extends class Attraction {…}
package onto.java.entertainment;
import java.io.*;
import java.util.*;
public class Auxiliaries { … }
package onto.java.entertainment;
public abstract class Attraction { … }
•Where to store packages?
•How does Java find packages?
•Export and Import
•Access control
32
Exceptions
public class A {
public void foo() throws MyException {
if(aBadThingHappened()) {
throw new MyException();
}
}
public void bar() {
try {
this.foo();
} catch (MyException e) {
e.printStackTrace();
}
}
}
public class MyException extends Exception {
public MyException() {}
public MyException(String message) {
super(String message);
}
}
33
Finally
public class A {
public void foo() throws MyException {
throw new MyException();
}
}
public void bar() {
try {
this.foo();
} catch (MyException e) {
e.printStackTrace();
} catch (YourException e) {
e.printStackTrace();
} finally {
... // always executed before leaving the try/catch
}
}
}
34
Resources
 http://java.sun.com/
 Java[tm] 2 Platform, Standard Edition v1.4.1
 java, javac, jar, jre, etc.
 Any platform... FREE!
 Online documentation and tutorials
 http://www.eclipse.org/
 Integrated development environment (IDE) for nothing in
particular
 Java[tm] development tools (JDT) (comes with Eclips)
 Project management
 Editor
 Incremental compiler
 CVS support
 C/C++ extension in progress
 AspectJ support
 Windows, Linux, and Mac.... FREE!
35
Qualifiers
 public – any class* may access
 (no qualifier) “package protected” – only the
class* and classes* in the same package may
access
 protected – only the class* and decendent
classes* may access
 private – only the class* may access
 The class or instances of the class (an object of the
class)
36
Package Protected
package edu.ucdavis;
public class A {
int x;
}
package edu.ucdavis;
public class B {
void foo(A a) { a.x; } // OK, same package
}
package edu.ucdavis.cs;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package edu;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package edu.ucdavis.cs;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
package org.omg;
public class B {
void foo(A a) { a.x; } // Not OK, different package
}
37
Protected
public class A {
protected int x;
}
public class B extends A {
void foo(A a) { this.x; a.x; } // OK, B is a decendent of A
}
public class C extends B {
void foo(A a) { this.x; a.x; } // OK, C is a decendent of A through
B
}package edu; // Uh oh!
public class D extends C {
void foo(A a) { this.x; a.x; } // OK, D is a decendent of A
}
public class E {
void foo(A a) { this.x; a.x; } // NOT OK, E is NOT a decendent of A
}
38
Threads
 Multiple “threads” of execution within the same
program, share the same memory space ->
“lightweight”.
 Perform multiple tasks at the same time.
 Work on the same task in parallel.
 Heavily used in user interfaces.
 Web browsers: load web pages while the user can still
scroll, go back, open a new window, etc.
 Web servers: serve multiple requests in parallel.
 Can take advantage of multiple processors.
 Threads in Java
 Java manages and schedules threads
 Java provides “synchronize” to help coordinate multiple
threads
39
Creating a Thread in Java
public class MyThread extends Thread {
public MyThread(String threadName) {
super(threadName);
}
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(i + “ “ + getName());
try {
sleep((long)(Math.random() * 1000));
} catch(InterruptedException e) {}
}
}
}
40
Creating a Thread in Java
public class ThreadTest {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
MyThread t = new MyThread(args[i]);
t.start();
}
}
}
> java ThreadTest Bob Frank
0 Bob
0 Frank
1 Bob
2 Bob
1 Frank
3 Bob
2 Frank
3 Frank
4 Frank
...
41
Creating a Thread in Java via Interface
public class MyRunnable implements Runnable {
String name;
public MyRunnable(String name) {
this.name = name;
}
public void run() {
for(int i; i < 10; i++) {
System.out.println(i + “ “ + name());
try {
sleep((long)(Math.random() * 1000));
} catch(InterruptedException e) {}
}
}
}
public class ThreadTest {
public static void main(String[] args) {
for(int i = 0; i < args.length; i++) {
Thread t = new Thread(new MyRunnable(args[i]), args[i]);
t.start();
}
}
}
42
Producer Consumer Problem
public class Producer
extends Thread {
private Share shared;
public Producer(Share s) {
shared = s;
}
public void run() {
for(int i = 0; i < 10; i++){
shared.put(i);
}
}
}
shared.put(0)
shared.get() // 0 gotten
shared.get() // 0 gotten again!!
shared.put(0)
shared.put(1)
shared.get() // 0 never gotten!!
public class Consumer
extends Thread {
private Share shared;
public Consumer(Share s) {
shared = s;
}
public void run() {
int value;
for(int i = 0; i < 10; i++) {
value = shared.get();
}
}
}
// what about simultaneous
// access?!
shared.put(0) shared.get()
RACE CONDITIONS!
43
public class Share {
private int s;
public synchronized int get() { ... }
public synchronized void put(int s) { ... }
}
Synchronized
 Synchronized provides mutual exclusion on an
object
 For any object, only one thread may execute
inside any of that object’s synchronized
methods
Share s1 = new Share();
Share s2 = new Share();
Thread t1 = ...;
Thread t2 = ...;
t1 -> s1.get() // gets in
t2 -> s1.put(32) // blocks
t1 -> s1.get() // gets in
t2 -> s2.put(4) // gets in
44
public class Share {
private int s;
private boolean empty = true;
public synchronized int get() {
while (empty == true) {
try {
wait(); // nothing to get, wait
} catch (InterruptedException e) {}
}
empty = true;
notifyAll(); // wakeup waiting Consumers/Producers
return s;
}
public synchronized void put(int s) {
while (empty == false) {
try {
wait(); // no room
} catch (InterruptedException e) {}
}
this.s = s;
empty = false;
notifyAll(); // wakeup waiting Consumers/Producers
}
}
Producer Consumer Coordination

More Related Content

What's hot

New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Deniz Oguz
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
Partnered Health
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
Sandeep Rawat
 
Java Basics
Java BasicsJava Basics
Java Basics
Brandon Black
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
Singsys Pte Ltd
 
Java basic
Java basicJava basic
Java basic
Arati Gadgil
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
Akash Pandey
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
Ahmed Ayman
 
Java features
Java featuresJava features
Java features
Prashant Gajendra
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
Java2Blog
 
Core java online training
Core java online trainingCore java online training
Core java online training
Glory IT Technologies Pvt. Ltd.
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
RAMU KOLLI
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
Edureka!
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Edureka!
 
Core java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsCore java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsQUONTRASOLUTIONS
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
Nithin Kumar,VVCE, Mysuru
 
Java introduction
Java introductionJava introduction
Java introduction
The icfai university jaipur
 

What's hot (20)

New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Java For beginners and CSIT and IT students
Java  For beginners and CSIT and IT studentsJava  For beginners and CSIT and IT students
Java For beginners and CSIT and IT students
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java basic
Java basicJava basic
Java basic
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Introduction to java Programming
Introduction to java ProgrammingIntroduction to java Programming
Introduction to java Programming
 
Java features
Java featuresJava features
Java features
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Core java online training
Core java online trainingCore java online training
Core java online training
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Introduction to Java Programming
Introduction to Java ProgrammingIntroduction to Java Programming
Introduction to Java Programming
 
Core java Basics
Core java BasicsCore java Basics
Core java Basics
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
 
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | EdurekaJava Programming | Java Tutorial For Beginners | Java Training | Edureka
Java Programming | Java Tutorial For Beginners | Java Training | Edureka
 
Core java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutionsCore java over view basics introduction by quontra solutions
Core java over view basics introduction by quontra solutions
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Java introduction
Java introductionJava introduction
Java introduction
 

Viewers also liked

Code Crime Scene pawel klimczyk
Code Crime Scene   pawel klimczykCode Crime Scene   pawel klimczyk
Code Crime Scene pawel klimczyk
Pawel Klimczyk
 
Software testing strategies
Software testing strategiesSoftware testing strategies
Software testing strategiesKrishna Sujeer
 
Lista de Chequeo Scrum
Lista de Chequeo ScrumLista de Chequeo Scrum
Lista de Chequeo Scrum
Sergio Gomez Florez
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_FrameworkKrishna Sujeer
 
VIEW26 - for software quality professionals
VIEW26 - for software quality professionalsVIEW26 - for software quality professionals
VIEW26 - for software quality professionals
Ajay Emmanuel
 
LSI - PMP - Training material
LSI - PMP - Training materialLSI - PMP - Training material
LSI - PMP - Training materialKrishna Sujeer
 
Recruitment_Process[1]
Recruitment_Process[1]Recruitment_Process[1]
Recruitment_Process[1]Krishna Sujeer
 
Blue Green Deployment com Docker
Blue Green Deployment com DockerBlue Green Deployment com Docker
Blue Green Deployment com Docker
Pedro Cavalheiro
 
Solid as OOP abstraction
Solid as OOP abstractionSolid as OOP abstraction
Solid as OOP abstraction
Pawel Klimczyk
 
Calidad de software septimo semestre
Calidad de software septimo semestreCalidad de software septimo semestre
Calidad de software septimo semestre
rodrigoarriagasalinas
 
SOLID for Adults
SOLID for AdultsSOLID for Adults
SOLID for Adults
Pawel Klimczyk
 
Software quality
Software qualitySoftware quality
Software quality
Pedro Cavalheiro
 
JSON API: Não reinvente a roda
JSON API: Não reinvente a rodaJSON API: Não reinvente a roda
JSON API: Não reinvente a roda
Pedro Cavalheiro
 
Software testing career
Software testing careerSoftware testing career
Software testing career
Ahmed Ahmed Mokhtar
 
MODELO DE PROCESOS DEL SOFTWARE
MODELO DE PROCESOS DEL SOFTWAREMODELO DE PROCESOS DEL SOFTWARE
MODELO DE PROCESOS DEL SOFTWARE
Micky Jerzy
 
API Testing – Keeping a Check on Agile Software Development
API Testing – Keeping a Check on Agile Software DevelopmentAPI Testing – Keeping a Check on Agile Software Development
API Testing – Keeping a Check on Agile Software Development
Software Testing Solution
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality Assurance
Saqib Raza
 

Viewers also liked (20)

Code Crime Scene pawel klimczyk
Code Crime Scene   pawel klimczykCode Crime Scene   pawel klimczyk
Code Crime Scene pawel klimczyk
 
Software testing strategies
Software testing strategiesSoftware testing strategies
Software testing strategies
 
Software Processes
Software ProcessesSoftware Processes
Software Processes
 
2 - OOPS
2 - OOPS2 - OOPS
2 - OOPS
 
Lista de Chequeo Scrum
Lista de Chequeo ScrumLista de Chequeo Scrum
Lista de Chequeo Scrum
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
VIEW26 - for software quality professionals
VIEW26 - for software quality professionalsVIEW26 - for software quality professionals
VIEW26 - for software quality professionals
 
LSI - PMP - Training material
LSI - PMP - Training materialLSI - PMP - Training material
LSI - PMP - Training material
 
Recruitment_Process[1]
Recruitment_Process[1]Recruitment_Process[1]
Recruitment_Process[1]
 
Blue Green Deployment com Docker
Blue Green Deployment com DockerBlue Green Deployment com Docker
Blue Green Deployment com Docker
 
Solid as OOP abstraction
Solid as OOP abstractionSolid as OOP abstraction
Solid as OOP abstraction
 
Calidad de software septimo semestre
Calidad de software septimo semestreCalidad de software septimo semestre
Calidad de software septimo semestre
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
SOLID for Adults
SOLID for AdultsSOLID for Adults
SOLID for Adults
 
Software quality
Software qualitySoftware quality
Software quality
 
JSON API: Não reinvente a roda
JSON API: Não reinvente a rodaJSON API: Não reinvente a roda
JSON API: Não reinvente a roda
 
Software testing career
Software testing careerSoftware testing career
Software testing career
 
MODELO DE PROCESOS DEL SOFTWARE
MODELO DE PROCESOS DEL SOFTWAREMODELO DE PROCESOS DEL SOFTWARE
MODELO DE PROCESOS DEL SOFTWARE
 
API Testing – Keeping a Check on Agile Software Development
API Testing – Keeping a Check on Agile Software DevelopmentAPI Testing – Keeping a Check on Agile Software Development
API Testing – Keeping a Check on Agile Software Development
 
Software Quality Assurance
Software Quality AssuranceSoftware Quality Assurance
Software Quality Assurance
 

Similar to 1- java

Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
Zeeshan MIrza
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
R. Sosa
 
Introduction to java programming part 1
Introduction to java programming   part 1Introduction to java programming   part 1
Introduction to java programming part 1
university of education,Lahore
 
Csharp dot net
Csharp dot netCsharp dot net
Csharp dot net
Revanth Mca
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
Shaharyar khan
 
basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
sujatha629799
 
Ppt chapter02
Ppt chapter02Ppt chapter02
Ppt chapter02
Richard Styner
 
Java introduction
Java introductionJava introduction
Java introduction
Migrant Systems
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
Nicola Pedot
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basicstosine
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
Jay Palit
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
Mohit Belwal
 
Curso de Programación Java Básico
Curso de Programación Java BásicoCurso de Programación Java Básico
Curso de Programación Java Básico
Universidad de Occidente
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
Java Notes
Java Notes Java Notes
Java Notes
Sreedhar Chowdam
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
Madhura Bhalerao
 

Similar to 1- java (20)

Introduction to-java
Introduction to-javaIntroduction to-java
Introduction to-java
 
Javalecture 1
Javalecture 1Javalecture 1
Javalecture 1
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
Java Programming for Designers
Java Programming for DesignersJava Programming for Designers
Java Programming for Designers
 
Introduction to java programming part 1
Introduction to java programming   part 1Introduction to java programming   part 1
Introduction to java programming part 1
 
Csharp dot net
Csharp dot netCsharp dot net
Csharp dot net
 
What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)What is Java Technology (An introduction with comparision of .net coding)
What is Java Technology (An introduction with comparision of .net coding)
 
Proyect of english
Proyect of englishProyect of english
Proyect of english
 
basic_java.ppt
basic_java.pptbasic_java.ppt
basic_java.ppt
 
Ppt chapter02
Ppt chapter02Ppt chapter02
Ppt chapter02
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
 
J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01J2ee strutswithhibernate-140121221332-phpapp01
J2ee strutswithhibernate-140121221332-phpapp01
 
Java & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
 
Curso de Programación Java Básico
Curso de Programación Java BásicoCurso de Programación Java Básico
Curso de Programación Java Básico
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
OOPS JAVA.pdf
OOPS JAVA.pdfOOPS JAVA.pdf
OOPS JAVA.pdf
 

More from Krishna Sujeer

1-informatica-training
1-informatica-training1-informatica-training
1-informatica-trainingKrishna Sujeer
 
SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03Krishna Sujeer
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,Krishna Sujeer
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,Krishna Sujeer
 
KEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 NotesKEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 NotesKrishna Sujeer
 
ETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_SujeerETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_SujeerKrishna Sujeer
 
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)Krishna Sujeer
 
Software Quality Management
Software Quality ManagementSoftware Quality Management
Software Quality ManagementKrishna Sujeer
 
Basic adminstration and configuration techniques
Basic adminstration and configuration techniquesBasic adminstration and configuration techniques
Basic adminstration and configuration techniquesKrishna Sujeer
 
SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0Krishna Sujeer
 
MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2Krishna Sujeer
 
SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03Krishna Sujeer
 
INTRODUCTION TO BIG DATA HADOOP
INTRODUCTION TO BIG DATA HADOOPINTRODUCTION TO BIG DATA HADOOP
INTRODUCTION TO BIG DATA HADOOPKrishna Sujeer
 

More from Krishna Sujeer (18)

1-informatica-training
1-informatica-training1-informatica-training
1-informatica-training
 
SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
 
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
KRISHNA NAYAKSujeer B.E(IT), MS(QM) , PGDCA,ITIL PMP,
 
KEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 NotesKEYTAKEAWAYAS Krishna Nayak v2.0 Notes
KEYTAKEAWAYAS Krishna Nayak v2.0 Notes
 
Selenium.PDF
Selenium.PDFSelenium.PDF
Selenium.PDF
 
ETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_SujeerETI_Krishna_Nayak_Sujeer
ETI_Krishna_Nayak_Sujeer
 
KRISHNA_NAYAK_Sujeer
KRISHNA_NAYAK_SujeerKRISHNA_NAYAK_Sujeer
KRISHNA_NAYAK_Sujeer
 
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
itil2011foundation-allvolumes-signed-131020235516-phpapp01 (1)
 
Software Quality Management
Software Quality ManagementSoftware Quality Management
Software Quality Management
 
Basic adminstration and configuration techniques
Basic adminstration and configuration techniquesBasic adminstration and configuration techniques
Basic adminstration and configuration techniques
 
SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0SAP HCM CORE MODULES V1.0
SAP HCM CORE MODULES V1.0
 
20410B_01
20410B_0120410B_01
20410B_01
 
MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2MASTER_Trainer Notes_V5.2
MASTER_Trainer Notes_V5.2
 
7_-_Inheritance
7_-_Inheritance7_-_Inheritance
7_-_Inheritance
 
SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03SAP REQRUITMENT NOTES03
SAP REQRUITMENT NOTES03
 
Big Data & Hadoop
Big Data & HadoopBig Data & Hadoop
Big Data & Hadoop
 
INTRODUCTION TO BIG DATA HADOOP
INTRODUCTION TO BIG DATA HADOOPINTRODUCTION TO BIG DATA HADOOP
INTRODUCTION TO BIG DATA HADOOP
 

1- java

  • 1. Introduction to Sun Microsystems java  High level OOPL  Platform Independent  Case Sensitive
  • 2. 2 Can you make coffee with it?
  • 3. 3 It was meant to!! A programming language for appliances!
  • 4. 4 Java Virtual Machine Must Run on Any Architecture Program in Java Java Compiler Java Bytecode Java Virtual Machine “WRITE ONCE, RUN ANYWHERE!” debug pretty portable
  • 6. 6 So What’s Java Good For? Web applications! Java Applet Server Java Applet
  • 7. 7 Java on the Web: Java Applets  Clients download applets via Web browser  Browser runs applet in a Java Virtual Machine (JVM) Interactive web, security, and client consistency Slow to download, inconsistent VMs (besides, flash won this war) Applet Client Server
  • 8. 8 Java on the Web: J2EE  Thin clients (minimize download)  Java all “server side” THIS IS WHAT YOU’LL BE DOING!! Client Server JSPs Servlets EJB JDBC
  • 9. 9 The Java programming environment  Compared to C++:  no header files, macros, pointers and references, unions, operator overloading, templates, etc.  Object-orientation: Classes + Inheritance  Distributed: RMI, Servlet, Distributed object programming.  Robust: Strong typing + no pointer + garbage collection  Secure: Type-safety + access control  Architecture neutral: architecture neutral representation  Portable  Interpreted  High performance through Just in time compilation (compiler converts byte code to native code) + runtime modification of code  Multi-threaded
  • 10. 10 Java Features  Well defined primitive data types: int, float, double, char, etc.  int 4 bytes [–2,147,648, 2,147,483,647]  Control statements similar to C++: if-then-else, switch, while, for  Interfaces  Exceptions  Concurrency (Multi-Threading)  Packages  Reflection (makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection. )  Applet model
  • 11. 11 The Java programming environment  Java programming language specification  Syntax of Java programs  Defines different constructs  Java byte code: Intermediate representation for Java programs  Java compiler: Program that Transform Java programs into Java byte code  Java interpreter: Read programs written in Java byte code and execute them (converts byte into native code. i.e Codes other than java).  Java virtual machine: The whole technology is based on the concept of JVM. Translator of byte code into platform specific machine language. It is the Runtime system that provides various services to running programs (Logical representation of JRE)
  • 14. 14 JVM  JVM stands for Java Virtual Machine. It’s an abstract computer or virtual computer which runs the compiled java programs. Actually JVM is a software implementation which stands on the top of the real hardware platform and operating system. It provides abstraction between the compiled java program and the hardware and operating system.  JIT: This Compiler converts byte code to native code.  Old Interpreter was replaced with JIT to increase the performance of java applications.  When JVM compiles the class file it does not compile the full class file in one shot. Compilation is done on function basis or file basis. Depending on need basis the compilation is done. This type of compilation is termed as JIT or Just-in- Time compilation.
  • 15. 15 General ( java1.5 –Tiger & java1.6 – Mustang (wild horse))  can run your compiled code on any operating system without recompiling your source code  JVM and Java Application Programming Interface (API) that are kinds of readymade software components  Java programming environment: Set of libraries that provide services such as GUI, data structures,etc.  Java enabled browsers: Browsers that include a JVM + ability to load programs from remote hosts  Platform Dependent – JVM, Java Compiler, Java Interpreter, C program, JDK.  Platform Independent – Java program.  JDK (Java Development Kit) – Collection of various tools, required to develop and run program  Tools ( JRE, Java Compiler, Java Interpreter)
  • 16. 16 Path & classpath  To run the program , Set the properties, then only MS-DOS knows about java commands. (Temporary)  set path=%path%; (jdk - bin) (Binary files will be accessible in all the folders & driver of OS)  set classpath=%classpath%.; (jdk - lib) (The class will be available in all the folder of OS)  The other way of setting up the path  My Computer – Advanced – Environment variables – proceed. (Permanent)  JAVA_HOME – jdk  Importance of path: Binary will be accessible in all the folders and driver of O.S  Importance of classpath: .class files will be available in all the folders of O.S
  • 17. 17 OOPs Concepts- PIE  Abstraction: Providing essential properties and operation of an object by hiding internal things.  Encapsulation: Placing all the properties and operations of an object in one place.  The place is called as class, Properties are called as variables, Operations are called as methods.  Polymorphism : Remote control application - one button is used for switch on/ off.
  • 18. 18 Java: A tiny intro  How are Java programs written?  How are variables declared?  How are expressions specified?  How are control structures defined?  How to define simple methods?  What are classes and objects?  What about exceptions?
  • 19. 19 How are Java programs written?  Define a class HelloWorld and store it into a file: HelloWorld.java: public class HelloWorld { public static void main (String[] args) { System.out.println(“Hello, World”); } }  Compile HelloWorld.java javac HelloWorld.java Output: HelloWorld.class  Run java HelloWorld Output: Hello, World
  • 20. 20 How are variables declared? Fibonacci: class Fibonacci { public static void main(String[] arg) { int lo = 1; int hi = 1; System.out.println(lo); while (hi < 50) { System.out.println(hi); hi = hi + lo; lo = hi – lo; } } }
  • 21. 21 How to define expressions?  Arithmetic: +, -, *,/, %, = 8 + 3 * 2 /4 Use standard precedence and associativity rules  Predicates: ==, !=, >, <, >=, <= public class Demo { public static void main (String[] argv) { boolean b; b = (2 + 2 == 4); System.out.println(b); } }
  • 22. 22 How are simple methods defined? Every method is defined inside a Java class definition public class Movie { public static int movieRating(int s, int a, int d) { return s+a+d; } } public class Demo { public static void main (String argv[]) { int script = 6, acting = 9, directing = 8; displayRating(script, acting, directing); } public static void displayRating(int s, int a, int d){ System.out.print(“The rating of this movie is”); System.out.println(Movie.movieRating(s, a, d)); } }
  • 23. 23 How are control structures specified? Typical flow of control statements: if-then-else, while, switch, do-while, and blocks class ImprovedFibo { static final int MAX_INDEX = 10; public static void main (String[] args) { int lo = 1; int hi = 1; String mark = null; for (int i = 2; i < MAX_INDEX; i++) { if ((i % 2) == 0) mark = " *"; else mark = ""; System.out.println(i+ ": " + hi + mark); hi = lo + hi; lo = hi - lo; }}}
  • 24. 24 What are classes and objects? Classes: templates for constructing instances  Fields  Instance variables  Static variables  Methods  Instance  Static class Point { public double x, y; } Point lowerleft = new Point(); Point upperRight = new Point(); Point middlePoint = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 1280.0; upperRight.y = 1024.0 middlePoint.x = 640.0; middlePoint.y = 512.0
  • 25. 25 How are instance methods defined? Instance methods take an implicit parameter: instance on which method is invoked public class Movie { public int script, acting, directing; public int rating() { return script + acting + directing; } } public class Demo { public static void main (String argv[]) { Movie m = new Movie(); m.script = 6; m.acting = 9; m.directing = 8; System.out.print(“The rating of this movie is”); System.out.println(m.rating()); } }
  • 26. 26 How to extend classes?  Inheritance: mechanism for extending behavior of classes; leads to construction of hierarchy of classes [Note: no multiple inheritance]  What happens when class C extends class D:  Inherits instance variables  Inherits static variables  Inherits instance methods  Inherits static methods  C can:  Add new instance variables  Add new methods (static and dynamic)  Modify methods (only implementation)  Cannot delete anything
  • 27. 27 How to extend classes? public class Attraction { public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes(int d) {minutes = d;} } public class Movie extends Attraction { public int script, acting, directing; public Movie() {script = 5; acting = 5; directing = 5;} public Movie(int s, int a, int d) { script = s; acting = a; directing = d; } public int rating() {return script + acting + directing;} } public class Symphony extends Attraction { public int playing, music, conducting; public Symphony() {playing = music = conducting = 5;} public Symphony(int p, int m, int c) { playing = p; music = m; conducting = c; } public int rating() {return playing + music + conducting;} }
  • 28. 28 What are abstract classes?  Abstract class: Merely a place holder for class definitions; cannot be used to create instances.; public abstract class Attraction { public int minutes; public Attraction() {minutes = 75;} public int getMinutes() {return minutes;} public void setMinutes(int d) {minutes = d;} public abstract void m(); }  Following is an error: Attraction x; x = new Attraction();  Following is not an error: public class Movie extends Attraction { … } public class Symphony extends Attraction { … } Attraction x; x = new Movie (); x = new Symphony();
  • 29. 29 Packages Object Attraction Auxiliaries Demonstration Movie Symphony extends extends • How do we organize above classes into a single unit? Put them in file? However, only one public class per file (whose name is same as file’s) • Solution: Place several files (compilation units) into a package
  • 30. 30 Packages – cont’d.  units of organizing related Classes, Interfaces, Sub packages  Why?  Reduce name clashing  Limit visibility of names  Java programs typically organized in terms of packages and subpackages  Each package may then be divided into several packages, subpackages, and classes  Each class can then be stored in a separate file  Each source file starts with something like: package mypackage;  Code in source file is now part of mypackage
  • 31. 31 Packages – cont’d. package onto.java.entertainment; public class Movie extends class Attraction {…} package onto.java.entertainment; import java.io.*; import java.util.*; public class Auxiliaries { … } package onto.java.entertainment; public abstract class Attraction { … } •Where to store packages? •How does Java find packages? •Export and Import •Access control
  • 32. 32 Exceptions public class A { public void foo() throws MyException { if(aBadThingHappened()) { throw new MyException(); } } public void bar() { try { this.foo(); } catch (MyException e) { e.printStackTrace(); } } } public class MyException extends Exception { public MyException() {} public MyException(String message) { super(String message); } }
  • 33. 33 Finally public class A { public void foo() throws MyException { throw new MyException(); } } public void bar() { try { this.foo(); } catch (MyException e) { e.printStackTrace(); } catch (YourException e) { e.printStackTrace(); } finally { ... // always executed before leaving the try/catch } } }
  • 34. 34 Resources  http://java.sun.com/  Java[tm] 2 Platform, Standard Edition v1.4.1  java, javac, jar, jre, etc.  Any platform... FREE!  Online documentation and tutorials  http://www.eclipse.org/  Integrated development environment (IDE) for nothing in particular  Java[tm] development tools (JDT) (comes with Eclips)  Project management  Editor  Incremental compiler  CVS support  C/C++ extension in progress  AspectJ support  Windows, Linux, and Mac.... FREE!
  • 35. 35 Qualifiers  public – any class* may access  (no qualifier) “package protected” – only the class* and classes* in the same package may access  protected – only the class* and decendent classes* may access  private – only the class* may access  The class or instances of the class (an object of the class)
  • 36. 36 Package Protected package edu.ucdavis; public class A { int x; } package edu.ucdavis; public class B { void foo(A a) { a.x; } // OK, same package } package edu.ucdavis.cs; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu; public class B { void foo(A a) { a.x; } // Not OK, different package } package edu.ucdavis.cs; public class B { void foo(A a) { a.x; } // Not OK, different package } package org.omg; public class B { void foo(A a) { a.x; } // Not OK, different package }
  • 37. 37 Protected public class A { protected int x; } public class B extends A { void foo(A a) { this.x; a.x; } // OK, B is a decendent of A } public class C extends B { void foo(A a) { this.x; a.x; } // OK, C is a decendent of A through B }package edu; // Uh oh! public class D extends C { void foo(A a) { this.x; a.x; } // OK, D is a decendent of A } public class E { void foo(A a) { this.x; a.x; } // NOT OK, E is NOT a decendent of A }
  • 38. 38 Threads  Multiple “threads” of execution within the same program, share the same memory space -> “lightweight”.  Perform multiple tasks at the same time.  Work on the same task in parallel.  Heavily used in user interfaces.  Web browsers: load web pages while the user can still scroll, go back, open a new window, etc.  Web servers: serve multiple requests in parallel.  Can take advantage of multiple processors.  Threads in Java  Java manages and schedules threads  Java provides “synchronize” to help coordinate multiple threads
  • 39. 39 Creating a Thread in Java public class MyThread extends Thread { public MyThread(String threadName) { super(threadName); } public void run() { for(int i = 0; i < 10; i++) { System.out.println(i + “ “ + getName()); try { sleep((long)(Math.random() * 1000)); } catch(InterruptedException e) {} } } }
  • 40. 40 Creating a Thread in Java public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { MyThread t = new MyThread(args[i]); t.start(); } } } > java ThreadTest Bob Frank 0 Bob 0 Frank 1 Bob 2 Bob 1 Frank 3 Bob 2 Frank 3 Frank 4 Frank ...
  • 41. 41 Creating a Thread in Java via Interface public class MyRunnable implements Runnable { String name; public MyRunnable(String name) { this.name = name; } public void run() { for(int i; i < 10; i++) { System.out.println(i + “ “ + name()); try { sleep((long)(Math.random() * 1000)); } catch(InterruptedException e) {} } } } public class ThreadTest { public static void main(String[] args) { for(int i = 0; i < args.length; i++) { Thread t = new Thread(new MyRunnable(args[i]), args[i]); t.start(); } } }
  • 42. 42 Producer Consumer Problem public class Producer extends Thread { private Share shared; public Producer(Share s) { shared = s; } public void run() { for(int i = 0; i < 10; i++){ shared.put(i); } } } shared.put(0) shared.get() // 0 gotten shared.get() // 0 gotten again!! shared.put(0) shared.put(1) shared.get() // 0 never gotten!! public class Consumer extends Thread { private Share shared; public Consumer(Share s) { shared = s; } public void run() { int value; for(int i = 0; i < 10; i++) { value = shared.get(); } } } // what about simultaneous // access?! shared.put(0) shared.get() RACE CONDITIONS!
  • 43. 43 public class Share { private int s; public synchronized int get() { ... } public synchronized void put(int s) { ... } } Synchronized  Synchronized provides mutual exclusion on an object  For any object, only one thread may execute inside any of that object’s synchronized methods Share s1 = new Share(); Share s2 = new Share(); Thread t1 = ...; Thread t2 = ...; t1 -> s1.get() // gets in t2 -> s1.put(32) // blocks t1 -> s1.get() // gets in t2 -> s2.put(4) // gets in
  • 44. 44 public class Share { private int s; private boolean empty = true; public synchronized int get() { while (empty == true) { try { wait(); // nothing to get, wait } catch (InterruptedException e) {} } empty = true; notifyAll(); // wakeup waiting Consumers/Producers return s; } public synchronized void put(int s) { while (empty == false) { try { wait(); // no room } catch (InterruptedException e) {} } this.s = s; empty = false; notifyAll(); // wakeup waiting Consumers/Producers } } Producer Consumer Coordination