SlideShare a Scribd company logo
1 of 36
The Global Open University
Nagaland
JAVA
Special Tips & Tricks
2
Java Virtual Machine
Program
in Java
Java
Compiler
Java
Bytecode
Java Virtual Machine
“WRITE ONCE, RUN ANYWHERE!”
debug
pretty portable
Web applciations!
3
Java Applet
Server
Java Applet
 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)
4
Applet
Client
Server
 Thin clients (minimize download)
 Java all “server side”
THIS IS WHAT YOU’LL BE DOING!!
5
Client
Server
JSPs
Servlets
EJB
JDBC
 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 + runtime
modification of code
 Multi-threaded
6
 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
 Packages
 Name spaces
 Reflection
 Applet model
7
 Java programming language specification
 Syntax of Java programs
 Defines different constructs and their semantics
 Java byte code: Intermediate representation for Java programs
 Java compiler: Transform Java programs into Java byte code
 Java interpreter: Read programs written in Java byte code and execute
them
 Java virtual machine: Runtime system that provides various services to
running programs
 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
8
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?
9
 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
10
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 = lo + hi;
lo = hi – lo;
}
}
}
11
 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);
}
}
12
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));
}
}
13
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;
}}}
14
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
15
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());
}
}
16
 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
17
18
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;}
}
19
 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();
20
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
 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
21
package onto.java.entertainment;
public class Movie extends class Attraction {…}
22
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
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);
}
}
23
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
}
}
}
24
 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!
25
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)
26
27
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
}
28
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
}
 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
29
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) {}
}
}
}
30
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
...
31
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();
}
}
}
32
33
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!
public class Share {
private int s;
public synchronized int get() { ... }
public synchronized void put(int s) { ... }
}
34
 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
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
}
}
35
This material has been taken from Online
Certificate course on JAVA from Global Open
University Online certification programme. For
complete course material visit:
http://tgouwp.eduhttp://tgouwp.edu
About Global Open University :
The global open university is now offering certification courses in
various fields. Even you can study, give exam from comfort of your
home. These are short term and totally online courses. For more
details you can visit:
Email id: info@tgouwp.edu

More Related Content

What's hot

Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfacesKalai Selvi
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiersSrinivas Reddy
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to AgileAnton Keks
 
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 studentsPartnered Health
 
Introduction to java
Introduction to  javaIntroduction to  java
Introduction to javaKalai Selvi
 
Java session13
Java session13Java session13
Java session13Niit Care
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
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 | EdurekaEdureka!
 
Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course Kernel Training
 

What's hot (20)

Chapter iii(oop)
Chapter iii(oop)Chapter iii(oop)
Chapter iii(oop)
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfacesUnit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Java non access modifiers
Java non access modifiersJava non access modifiers
Java non access modifiers
 
Java Course 6: Introduction to Agile
Java Course 6: Introduction to AgileJava Course 6: Introduction to Agile
Java Course 6: Introduction to Agile
 
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  javaIntroduction to  java
Introduction to java
 
Java session13
Java session13Java session13
Java session13
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Core java
Core java Core java
Core java
 
Basic java for Android Developer
Basic java for Android DeveloperBasic java for Android Developer
Basic java for Android Developer
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Presentation to java
Presentation  to  javaPresentation  to  java
Presentation to java
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
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 introduction | Basics | free course
Core Java introduction | Basics | free course Core Java introduction | Basics | free course
Core Java introduction | Basics | free course
 

Viewers also liked

An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeOmar Bashir
 
Mobile cloud Computing
Mobile cloud ComputingMobile cloud Computing
Mobile cloud ComputingPooja Sharma
 
Mobile cloud computing; Future of Cloud Computing
Mobile cloud computing; Future of Cloud ComputingMobile cloud computing; Future of Cloud Computing
Mobile cloud computing; Future of Cloud ComputingVineet Garg
 
Mobile Cloud Computing: Big Picture
Mobile Cloud Computing: Big PictureMobile Cloud Computing: Big Picture
Mobile Cloud Computing: Big PictureReza Rahimi
 
Mobile Cloud Computing
Mobile Cloud ComputingMobile Cloud Computing
Mobile Cloud ComputingVikas Kottari
 

Viewers also liked (7)

An Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and RuntimeAn Introduction to Java Compiler and Runtime
An Introduction to Java Compiler and Runtime
 
Mobile cloud Computing
Mobile cloud ComputingMobile cloud Computing
Mobile cloud Computing
 
Mobile cloud computing; Future of Cloud Computing
Mobile cloud computing; Future of Cloud ComputingMobile cloud computing; Future of Cloud Computing
Mobile cloud computing; Future of Cloud Computing
 
Mobile Cloud Computing: Big Picture
Mobile Cloud Computing: Big PictureMobile Cloud Computing: Big Picture
Mobile Cloud Computing: Big Picture
 
Mobile Cloud Computing
Mobile Cloud ComputingMobile Cloud Computing
Mobile Cloud Computing
 
Presentation on java
Presentation  on  javaPresentation  on  java
Presentation on java
 
Performance appraisal ppt
Performance appraisal pptPerformance appraisal ppt
Performance appraisal ppt
 

Similar to Core Java- An advanced review of features

Introduction to java
Introduction to javaIntroduction to java
Introduction to javaAjay Sharma
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2miiro30
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUCDevelopment of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUCInfinIT - Innovationsnetværket for it
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.Tarunsingh198
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...yazad dumasia
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
Java peresentation new soft
Java peresentation new softJava peresentation new soft
Java peresentation new softMohamed Refaat
 

Similar to Core Java- An advanced review of features (20)

Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Fundamentals of oop lecture 2
Fundamentals of oop lecture 2Fundamentals of oop lecture 2
Fundamentals of oop lecture 2
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Packages and interfaces
Packages and interfacesPackages and interfaces
Packages and interfaces
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Packaes & interfaces
Packaes & interfacesPackaes & interfaces
Packaes & interfaces
 
1- java
1- java1- java
1- java
 
L04 Software Design 2
L04 Software Design 2L04 Software Design 2
L04 Software Design 2
 
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUCDevelopment of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
Development of Java tools using SWT and WALA af Hans Søndergaard, ViaUC
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
C# .NET: Language Features and Creating .NET Projects, Namespaces Classes and...
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Java Tutorial 1
Java Tutorial 1Java Tutorial 1
Java Tutorial 1
 
Inheritance
InheritanceInheritance
Inheritance
 
Cse java
Cse javaCse java
Cse java
 
Java peresentation new soft
Java peresentation new softJava peresentation new soft
Java peresentation new soft
 

Recently uploaded

EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 

Recently uploaded (20)

OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 

Core Java- An advanced review of features

  • 1. The Global Open University Nagaland JAVA Special Tips & Tricks
  • 2. 2 Java Virtual Machine Program in Java Java Compiler Java Bytecode Java Virtual Machine “WRITE ONCE, RUN ANYWHERE!” debug pretty portable
  • 4.  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) 4 Applet Client Server
  • 5.  Thin clients (minimize download)  Java all “server side” THIS IS WHAT YOU’LL BE DOING!! 5 Client Server JSPs Servlets EJB JDBC
  • 6.  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 + runtime modification of code  Multi-threaded 6
  • 7.  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  Packages  Name spaces  Reflection  Applet model 7
  • 8.  Java programming language specification  Syntax of Java programs  Defines different constructs and their semantics  Java byte code: Intermediate representation for Java programs  Java compiler: Transform Java programs into Java byte code  Java interpreter: Read programs written in Java byte code and execute them  Java virtual machine: Runtime system that provides various services to running programs  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 8
  • 9. 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? 9
  • 10.  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 10
  • 11. 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 = lo + hi; lo = hi – lo; } } } 11
  • 12.  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); } } 12
  • 13. 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)); } } 13
  • 14. 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; }}} 14
  • 15. 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 15
  • 16. 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()); } } 16
  • 17.  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 17
  • 18. 18 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;} }
  • 19. 19  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();
  • 20. 20 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
  • 21.  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 21
  • 22. package onto.java.entertainment; public class Movie extends class Attraction {…} 22 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
  • 23. 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); } } 23
  • 24. 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 } } } 24
  • 25.  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! 25
  • 26. 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) 26
  • 27. 27 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 }
  • 28. 28 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 }
  • 29.  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 29
  • 30. 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) {} } } } 30
  • 31. 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 ... 31
  • 32. 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(); } } } 32
  • 33. 33 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!
  • 34. public class Share { private int s; public synchronized int get() { ... } public synchronized void put(int s) { ... } } 34  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
  • 35. 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 } } 35
  • 36. This material has been taken from Online Certificate course on JAVA from Global Open University Online certification programme. For complete course material visit: http://tgouwp.eduhttp://tgouwp.edu About Global Open University : The global open university is now offering certification courses in various fields. Even you can study, give exam from comfort of your home. These are short term and totally online courses. For more details you can visit: Email id: info@tgouwp.edu