SlideShare a Scribd company logo
Java Fundamentals
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Architecture
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
7
Creating and Compiling Programs
• On command line
– javac file.java Source Code
Create/Modify Source Code
Compile Source Code
i.e. javac Welcome.java
Bytecode
Run Byteode
i.e. java Welcome
Result
If compilation errors
If runtime errors or incorrect result
8
Executing Applications
• On command line
– java classname
Java
Interpreter
on Windows
Java
Interpreter
on Sun Solaris
Java
Interpreter
on Linux
Bytecode
...
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
d
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Java Fundamentals.pptJava Fundamentals.ppt
Different Programming Paradigms
• Functional/procedural programming:
– program is a list of instructions to the computer
• Object-oriented programming
– program is composed of a collection objects
that communicate with each other
Main Concepts
• Object
• Class
• Inheritance
• Encapsulation
Objects
• identity – unique identification of an object
• attributes – data/state
• services – methods/operations
– supported by the object
– within objects responsibility to provide these
services to other clients
Class
• “type”
• object is an instance of class
• class groups similar objects
– same (structure of) attributes
– same services
• object holds values of its class’s attributes
Inheritance
• Class hierarchy
• Generalization and Specialization
– subclass inherits attributes and services from its
superclass
– subclass may add new attributes and services
– subclass may reuse the code in the superclass
– subclasses provide specialized behaviors (overriding
and dynamic binding)
– partially define and implement common behaviors
(abstract)
Encapsulation
• Separation between internal state of the object
and its external aspects
• How ?
– control access to members of the class
– interface “type”
What does it buy us ?
• Modularity
– source code for an object can be written and maintained
independently of the source code for other objects
– easier maintainance and reuse
• Information hiding
– other objects can ignore implementation details
– security (object has control over its internal state)
• but
– shared data need special design patterns (e.g., DB)
– performance overhead
mainly for c++ programmer
Adapted with permission from Avivit Bercovici Boden, Technion
Why Java ?
• Portable
• Easy to learn
• [ Designed to be used on the Internet ]
JVM
• JVM stands for
Java Virtual Machine
• Unlike other languages, Java “executables”
are executed on a CPU that does not exist.
OS/Hardware
machine code
C source code
myprog.c
gcc
myprog.exe
Platform Dependent
JVM
bytecode
Java source code
myprog.java
javac
myprog.class
OS/Hardware
Platform Independent
Primitive types
• int 4 bytes
• short 2 bytes
• long 8 bytes
• byte 1 byte
• float 4 bytes
• double 8 bytes
• char Unicode encoding (2 bytes)
• boolean {true,false}
Behaviors is
exactly as in
C++
Note:
Primitive type
always begin
with lower-case
• Constants
37 integer
37.2 float
42F float
0754 integer (octal)
0xfe integer (hexadecimal)
Primitive types - cont.
Wrappers
Java provides Objects which wrap
primitive types and supply methods.
Example:
Integer n = new Integer(“4”);
int m = n.intValue();
Read more about Integer in JDK Documentation
Hello World
class Hello {
public static void main(String[] args) {
System.out.println(“Hello World !!!”);
}
}
Hello.java
C:javac Hello.java
C:java Hello
( compilation creates Hello.class )
(Execution on the local JVM)
More sophisticated
class Kyle {
private boolean kennyIsAlive_;
public Kyle() { kennyIsAlive_ = true; }
public Kyle(Kyle aKyle) {
kennyIsAlive_ = aKyle.kennyIsAlive_;
}
public String theyKilledKenny() {
if (kennyIsAlive_) {
kennyIsAlive_ = false;
return “You bastards !!!”;
} else {
return “?”;
}
}
public static void main(String[] args) {
Kyle k = new Kyle();
String s = k.theyKilledKenny();
System.out.println(“Kyle: “ + s);
}
}
Default
C’tor
Copy
C’tor
Results
javac Kyle.java ( to compile )
java Kyle ( to execute )
Kyle: You bastards !!!
Arrays
• Array is an object
• Array size is fixed
Animal[] arr; // nothing yet …
arr = new Animal[4]; // only array of pointers
for(int i=0 ; i < arr.length ; i++) {
arr[i] = new Animal();
// now we have a complete array
Arrays - Multidimensional
• In C++
Animal arr[2][2]
Is:
• In Java
What is the type of
the object here ?
Animal[][] arr=
new Animal[2][2]
Static - [1/4]
• Member data - Same data is used for all the
instances (objects) of some Class.
Class A {
public int y = 0;
public static int x_ = 1;
};
A a = new A();
A b = new A();
System.out.println(b.x_);
a.x_ = 5;
System.out.println(b.x_);
A.x_ = 10;
System.out.println(b.x_);
Assignment performed
on the first access to the
Class.
Only one instance of ‘x’
exists in memory
Output:
1
5
10
a b
y y
A.x_
0 0
1
Static - [2/4]
• Member function
– Static member function can access only static members
– Static member function can be called without an
instance. Class TeaPot {
private static int numOfTP = 0;
private Color myColor_;
public TeaPot(Color c) {
myColor_ = c;
numOfTP++;
}
public static int howManyTeaPots()
{ return numOfTP; }
// error :
public static Color getColor()
{ return myColor_; }
}
Static - [2/4] cont.
Usage:
TeaPot tp1 = new TeaPot(Color.RED);
TeaPot tp2 = new TeaPot(Color.GREEN);
System.out.println(“We have “ +
TeaPot.howManyTeaPots()+ “Tea Pots”);
Static - [3/4]
• Block
– Code that is executed in the first reference to the class.
– Several static blocks can exist in the same class
( Execution order is by the appearance order in the
class definition ).
– Only static members can be accessed.
class RandomGenerator {
private static int seed_;
static {
int t = System.getTime() % 100;
seed_ = System.getTime();
while(t-- > 0)
seed_ = getNextNumber(seed_);
}
}
}
String is an Object
• Constant strings as in C, does not exist
• The function call foo(“Hello”) creates a String object,
containing “Hello”, and passes reference to it to foo.
• There is no point in writing :
• The String object is a constant. It can’t be changed using
a reference to it.
String s = new String(“Hello”);
Flow control
Basically, it is exactly like c/c++.
if/else
do/while
for
switch
If(x==4) {
// act1
} else {
// act2
}
int i=5;
do {
// act1
i--;
} while(i!=0);
int j;
for(int i=0;i<=9;i++)
{
j+=i;
}
char
c=IN.getChar();
switch(c) {
case ‘a’:
case ‘b’:
// act1
break;
default:
// act2
}
Packages
• Java code has hierarchical structure.
• The environment variable CLASSPATH contains
the directory names of the roots.
• Every Object belongs to a package ( ‘package’
keyword)
• Object full name contains the name full name of the
package containing it.
Access Control
• public member (function/data)
– Can be called/modified from outside.
• protected
– Can be called/modified from derived classes
• private
– Can be called/modified only from the current class
• default ( if no access modifier stated )
– Usually referred to as “Friendly”.
– Can be called/modified/instantiated from the same package.
Inheritance
Base
Derived
class Base {
Base(){}
Base(int i) {}
protected void foo() {…}
}
class Derived extends Base {
Derived() {}
protected void foo() {…}
Derived(int i) {
super(i);
…
super.foo();
}
}
As opposed to C++, it is possible to inherit only from ONE class.
Pros avoids many potential problems and bugs.
Cons might cause code replication
Polymorphism
• Inheritance creates an “is a” relation:
For example, if B inherits from A, than we say that
“B is also an A”.
Implications are:
– access rights (Java forbids reducing access rights) -
derived class can receive all the messages that the base
class can.
– behavior
– precondition and postcondition
Inheritance (2)
• In Java, all methods are virtual :
class Base {
void foo() {
System.out.println(“Base”);
}
}
class Derived extends Base {
void foo() {
System.out.println(“Derived”);
}
}
public class Test {
public static void main(String[] args) {
Base b = new Derived();
b.foo(); // Derived.foo() will be activated
}
}
Inheritance (3) - Optional
class classC extends classB {
classC(int arg1, int arg2){
this(arg1);
System.out.println("In classC(int arg1, int arg2)");
}
classC(int arg1){
super(arg1);
System.out.println("In classC(int arg1)");
}
}
class classB extends classA {
classB(int arg1){
super(arg1);
System.out.println("In classB(int arg1)");
}
classB(){
System.out.println("In classB()");
}
}
Inheritance (3) - Optional
class classA {
classA(int arg1){
System.out.println("In classA(int arg1)");
}
classA(){
System.out.println("In classA()");
}
}
class classB extends classA {
classB(int arg1, int arg2){
this(arg1);
System.out.println("In classB(int arg1, int arg2)");
}
classB(int arg1){
super(arg1);
System.out.println("In classB(int arg1)");
}
class B() {
System.out.println("In classB()");
}
}
Abstract
• abstract member function, means that the function does not have an implementation.
• abstract class, is class that can not be instantiated.
AbstractTest.java:6: class AbstractTest is an abstract class.
It can't be instantiated.
new AbstractTest();
^
1 error
NOTE:
An abstract class is not required to have an abstract method in it.
But any class that has an abstract method in it or that does
not provide an implementation for any abstract methods declared
in its superclasses must be declared as an abstract class.
Example
Abstract - Example
package java.lang;
public abstract class Shape {
public abstract void draw();
public void move(int x, int y) {
setColor(BackGroundColor);
draw();
setCenter(x,y);
setColor(ForeGroundColor);
draw();
}
}
package java.lang;
public class Circle extends Shape {
public void draw() {
// draw the circle ...
}
}
Interface
Interfaces are useful for the following:
 Capturing similarities among unrelated
classes without artificially forcing a class
relationship.
 Declaring methods that one or more classes
are expected to implement.
 Revealing an object's programming interface
without revealing its class.
Interface
• abstract “class”
• Helps defining a “usage contract” between classes
• All methods are public
• Java’s compensation for removing the multiple
inheritance. You can “inherit” as many interfaces
as you want.
Example
*
- The correct term is “to implement”
an interface
Interface
interface SouthParkCharacter {
void curse();
}
interface IChef {
void cook(Food food);
}
interface BabyKicker {
void kickTheBaby(Baby);
}
class Chef implements IChef, SouthParkCharacter {
// overridden methods MUST be public
// can you tell why ?
public void curse() { … }
public void cook(Food f) { … }
}
* access rights (Java forbids reducing of access rights)
When to use an interface ?
Perfect tool for encapsulating the
classes inner structure. Only the
interface will be exposed
Collections
• Collection/container
– object that groups multiple elements
– used to store, retrieve, manipulate, communicate
aggregate data
• Iterator - object used for traversing a collection
and selectively remove elements
• Generics – implementation is parametric in the
type of elements
Java Collection Framework
• Goal: Implement reusable data-structures and functionality
• Collection interfaces - manipulate collections
independently of representation details
• Collection implementations - reusable data structures
List<String> list = new ArrayList<String>(c);
• Algorithms - reusable functionality
– computations on objects that implement collection interfaces
– e.g., searching, sorting
– polymorphic: the same method can be used on many different
implementations of the appropriate collection interface
Collection Interfaces
Collection
Set List Queue
SortedSet
Map
Sorted Map
Collection Interface
• Basic Operations
– int size();
– boolean isEmpty();
– boolean contains(Object element);
– boolean add(E element);
– boolean remove(Object element);
– Iterator iterator();
• Bulk Operations
– boolean containsAll(Collection<?> c);
– boolean addAll(Collection<? extends E> c);
– boolean removeAll(Collection<?> c);
– boolean retainAll(Collection<?> c);
– void clear();
• Array Operations
– Object[] toArray(); <T> T[] toArray(T[] a); }
General Purpose Implementations
Collection
Set List Queue
SortedSet
Map
Sorted Map
HashSet HashMap
List<String> list1 = new ArrayList<String>(c);
ArrayList
TreeSet TreeMap
LinkedList
List<String> list2 = new LinkedList<String>(c);
final
• final member data
Constant member
• final member function
The method can’t be
overridden.
• final class
‘Base’ is final, thus it
can’t be extended
final class Base {
final int i=5;
final void foo() {
i=10;
//what will the compiler say
about this?
}
}
class Derived extends Base {
// Error
// another foo ...
void foo() {
}
}
(String class is final)
final
final class Base {
final int i=5;
final void foo() {
i=10;
}
}
class Derived extends Base {
// Error
// another foo ...
void foo() {
}
}
Derived.java:6: Can't subclass final classes: class Base
class class Derived extends Base {
^
1 error
IO - Introduction
• Definition
– Stream is a flow of data
• characters read from a file
• bytes written to the network
• …
• Philosophy
– All streams in the world are basically the same.
– Streams can be divided (as the name “IO” suggests) to Input and
Output streams.
• Implementation
– Incoming flow of data (characters) implements “Reader” (InputStream for
bytes)
– Outgoing flow of data (characters) implements “Writer” (OutputStream for
bytes –eg. Images, sounds etc.)
Exception - What is it and why do I care?
Definition: An exception is an event that
occurs during the execution of a program
that disrupts the normal flow of instructions.
• Exception is an Object
• Exception class must be descendent of Throwable.
Exception - What is it and why do I care?(2)
By using exceptions to manage errors, Java
programs have the following advantages over
traditional error management techniques:
1: Separating Error Handling Code from "Regular"
Code
2: Propagating Errors Up the Call Stack
3: Grouping Error Types and Error Differentiation
readFile {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
}
1: Separating Error Handling Code from "Regular" Code (1)
errorCodeType readFile {
initialize errorCode = 0;
open the file;
if (theFileIsOpen) {
determine the length of the file;
if (gotTheFileLength) {
allocate that much memory;
if (gotEnoughMemory) {
read the file into memory;
if (readFailed) {
errorCode = -1;
}
} else {
errorCode = -2;
}
} else {
errorCode = -3;
}
close the file;
if (theFileDidntClose && errorCode == 0) {
errorCode = -4;
} else {
errorCode = errorCode and -4;
}
} else {
errorCode = -5;
}
return errorCode;
}
1: Separating Error Handling Code from "Regular" Code (2)
readFile {
try {
open the file;
determine its size;
allocate that much memory;
read the file into memory;
close the file;
} catch (fileOpenFailed) {
doSomething;
} catch (sizeDeterminationFailed) {
doSomething;
} catch (memoryAllocationFailed) {
doSomething;
} catch (readFailed) {
doSomething;
} catch (fileCloseFailed) {
doSomething;
}
}
1: Separating Error Handling Code from "Regular" Code (3)
method1 {
try {
call method2;
} catch (exception) {
doErrorProcessing;
}
}
method2 throws exception {
call method3;
}
method3 throws exception {
call readFile;
}
2: Propagating Errors Up the Call Stack
Ad

Recommended

Java tutorials
Java tutorials
น้องน๊อต อยากเหยียบดวงจันทร์
 
JavaTutorials.ppt
JavaTutorials.ppt
Khizar40
 
Java tutorials
Java tutorials
saryu2011
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.
Tarunsingh198
 
java training faridabad
java training faridabad
Woxa Technologies
 
Java Tutorials
Java Tutorials
Woxa Technologies
 
Cse java
Cse java
MohammedAbdulNaseer5
 
core java
core java
Vinodh Kumar
 
Java Tutorial
Java Tutorial
Singsys Pte Ltd
 
Core_java_ppt.ppt
Core_java_ppt.ppt
SHIBDASDUTTA
 
Java PPT
Java PPT
Dilip Kr. Jangir
 
oop unit1.pptx
oop unit1.pptx
sureshkumara29
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
Kalai Selvi
 
Java Programming - UNIT - 1, Basics OOPS, Differences
Java Programming - UNIT - 1, Basics OOPS, Differences
PradeepT42
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentals
AnsgarMary
 
Java_notes.ppt
Java_notes.ppt
tuyambazejeanclaude
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
nafsigenet
 
CS8392 OOP
CS8392 OOP
DhanalakshmiVelusamy1
 
Java
Java
Prabhat gangwar
 
ppt_on_java.pptx
ppt_on_java.pptx
MAYANKKUMAR492040
 
Java
Java
s4al_com
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
java01.ppt
java01.ppt
Godwin585235
 
Java for beginners
Java for beginners
Saeid Zebardast
 
Present the syntax of Java Introduce the Java
Present the syntax of Java Introduce the Java
ssuserfd620b
 
Core java
Core java
Ganesh Chittalwar
 
Presentation to java
Presentation to java
Ganesh Chittalwar
 
java ppt for basic intro about java and its
java ppt for basic intro about java and its
kssandhu875
 
OOP_Java_Part2.pptxOOP_Java_Part1OOP_Java_Part1
OOP_Java_Part2.pptxOOP_Java_Part1OOP_Java_Part1
yatakonakiran2
 
OOP_Java_Part1OOP_Java_Part1OOP_Java_Part1.pptx
OOP_Java_Part1OOP_Java_Part1OOP_Java_Part1.pptx
yatakonakiran2
 

More Related Content

Similar to Java Fundamentals.pptJava Fundamentals.ppt (20)

Java Tutorial
Java Tutorial
Singsys Pte Ltd
 
Core_java_ppt.ppt
Core_java_ppt.ppt
SHIBDASDUTTA
 
Java PPT
Java PPT
Dilip Kr. Jangir
 
oop unit1.pptx
oop unit1.pptx
sureshkumara29
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
Kalai Selvi
 
Java Programming - UNIT - 1, Basics OOPS, Differences
Java Programming - UNIT - 1, Basics OOPS, Differences
PradeepT42
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentals
AnsgarMary
 
Java_notes.ppt
Java_notes.ppt
tuyambazejeanclaude
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
nafsigenet
 
CS8392 OOP
CS8392 OOP
DhanalakshmiVelusamy1
 
Java
Java
Prabhat gangwar
 
ppt_on_java.pptx
ppt_on_java.pptx
MAYANKKUMAR492040
 
Java
Java
s4al_com
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
java01.ppt
java01.ppt
Godwin585235
 
Java for beginners
Java for beginners
Saeid Zebardast
 
Present the syntax of Java Introduce the Java
Present the syntax of Java Introduce the Java
ssuserfd620b
 
Core java
Core java
Ganesh Chittalwar
 
Presentation to java
Presentation to java
Ganesh Chittalwar
 
java ppt for basic intro about java and its
java ppt for basic intro about java and its
kssandhu875
 
Unit3 packages &amp; interfaces
Unit3 packages &amp; interfaces
Kalai Selvi
 
Java Programming - UNIT - 1, Basics OOPS, Differences
Java Programming - UNIT - 1, Basics OOPS, Differences
PradeepT42
 
Introduction to oop and java fundamentals
Introduction to oop and java fundamentals
AnsgarMary
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
nafsigenet
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Present the syntax of Java Introduce the Java
Present the syntax of Java Introduce the Java
ssuserfd620b
 
java ppt for basic intro about java and its
java ppt for basic intro about java and its
kssandhu875
 

More from yatakonakiran2 (20)

OOP_Java_Part2.pptxOOP_Java_Part1OOP_Java_Part1
OOP_Java_Part2.pptxOOP_Java_Part1OOP_Java_Part1
yatakonakiran2
 
OOP_Java_Part1OOP_Java_Part1OOP_Java_Part1.pptx
OOP_Java_Part1OOP_Java_Part1OOP_Java_Part1.pptx
yatakonakiran2
 
Java_Arrays_Presentation-2aaaaaaaaaa.pptx
Java_Arrays_Presentation-2aaaaaaaaaa.pptx
yatakonakiran2
 
Java_Arrays_Paaaaaaaaaaresentation-1.pptx
Java_Arrays_Paaaaaaaaaaresentation-1.pptx
yatakonakiran2
 
Operating_Systems_UNIT_Concept of an Operating System1.pptx
Operating_Systems_UNIT_Concept of an Operating System1.pptx
yatakonakiran2
 
array2.pptxarrays conceptsarrays conceptsarrays concepts
array2.pptxarrays conceptsarrays conceptsarrays concepts
yatakonakiran2
 
array1.pptarrays conceptsarrays conceptsarrays concepts
array1.pptarrays conceptsarrays conceptsarrays concepts
yatakonakiran2
 
a21.pptxa24.pptxArrays122a24.pptxArrays111
a21.pptxa24.pptxArrays122a24.pptxArrays111
yatakonakiran2
 
a1.pptxArrays1Arrays1Arrays1Arrays1Arrays1
a1.pptxArrays1Arrays1Arrays1Arrays1Arrays1
yatakonakiran2
 
c2ppt.pptxslidenoteseceslidenoteseceslidenoteseceslidenoteseceslidenotesece
c2ppt.pptxslidenoteseceslidenoteseceslidenoteseceslidenoteseceslidenotesece
yatakonakiran2
 
c first pres.pptxslidenoteseceslidenoteseceslidenotesece
c first pres.pptxslidenoteseceslidenoteseceslidenotesece
yatakonakiran2
 
Arrays-from-Basics-to-Advanced final.pptx
Arrays-from-Basics-to-Advanced final.pptx
yatakonakiran2
 
CPDS1-8UNITS.docCPDS1-8UNITS.CPDS1-8UNITS.docdoc
CPDS1-8UNITS.docCPDS1-8UNITS.CPDS1-8UNITS.docdoc
yatakonakiran2
 
data structures Unit 3 notes.docxdata structures Unit 3 notes.docx
data structures Unit 3 notes.docxdata structures Unit 3 notes.docx
yatakonakiran2
 
into python.pptinto python.pptinto python.ppt
into python.pptinto python.pptinto python.ppt
yatakonakiran2
 
dataversitydatacatalogslidenotesslidenotesslidenotes
dataversitydatacatalogslidenotesslidenotesslidenotes
yatakonakiran2
 
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
Module8_DFMEA_Testing_Innovation_Creativity_v7Innovation_Creativity_v7Deliver...
Module8_DFMEA_Testing_Innovation_Creativity_v7Innovation_Creativity_v7Deliver...
yatakonakiran2
 
Design_slides Design_slides Design_slidesDesign_slides
Design_slides Design_slides Design_slidesDesign_slides
yatakonakiran2
 
Abstract classes.pptx Abstract classesAbstract classesAbstract classes
Abstract classes.pptx Abstract classesAbstract classesAbstract classes
yatakonakiran2
 
OOP_Java_Part2.pptxOOP_Java_Part1OOP_Java_Part1
OOP_Java_Part2.pptxOOP_Java_Part1OOP_Java_Part1
yatakonakiran2
 
OOP_Java_Part1OOP_Java_Part1OOP_Java_Part1.pptx
OOP_Java_Part1OOP_Java_Part1OOP_Java_Part1.pptx
yatakonakiran2
 
Java_Arrays_Presentation-2aaaaaaaaaa.pptx
Java_Arrays_Presentation-2aaaaaaaaaa.pptx
yatakonakiran2
 
Java_Arrays_Paaaaaaaaaaresentation-1.pptx
Java_Arrays_Paaaaaaaaaaresentation-1.pptx
yatakonakiran2
 
Operating_Systems_UNIT_Concept of an Operating System1.pptx
Operating_Systems_UNIT_Concept of an Operating System1.pptx
yatakonakiran2
 
array2.pptxarrays conceptsarrays conceptsarrays concepts
array2.pptxarrays conceptsarrays conceptsarrays concepts
yatakonakiran2
 
array1.pptarrays conceptsarrays conceptsarrays concepts
array1.pptarrays conceptsarrays conceptsarrays concepts
yatakonakiran2
 
a21.pptxa24.pptxArrays122a24.pptxArrays111
a21.pptxa24.pptxArrays122a24.pptxArrays111
yatakonakiran2
 
a1.pptxArrays1Arrays1Arrays1Arrays1Arrays1
a1.pptxArrays1Arrays1Arrays1Arrays1Arrays1
yatakonakiran2
 
c2ppt.pptxslidenoteseceslidenoteseceslidenoteseceslidenoteseceslidenotesece
c2ppt.pptxslidenoteseceslidenoteseceslidenoteseceslidenoteseceslidenotesece
yatakonakiran2
 
c first pres.pptxslidenoteseceslidenoteseceslidenotesece
c first pres.pptxslidenoteseceslidenoteseceslidenotesece
yatakonakiran2
 
Arrays-from-Basics-to-Advanced final.pptx
Arrays-from-Basics-to-Advanced final.pptx
yatakonakiran2
 
CPDS1-8UNITS.docCPDS1-8UNITS.CPDS1-8UNITS.docdoc
CPDS1-8UNITS.docCPDS1-8UNITS.CPDS1-8UNITS.docdoc
yatakonakiran2
 
data structures Unit 3 notes.docxdata structures Unit 3 notes.docx
data structures Unit 3 notes.docxdata structures Unit 3 notes.docx
yatakonakiran2
 
into python.pptinto python.pptinto python.ppt
into python.pptinto python.pptinto python.ppt
yatakonakiran2
 
dataversitydatacatalogslidenotesslidenotesslidenotes
dataversitydatacatalogslidenotesslidenotesslidenotes
yatakonakiran2
 
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
slidenotesece246jun2012-140803084954-phpapp01 (1).ppt
yatakonakiran2
 
Module8_DFMEA_Testing_Innovation_Creativity_v7Innovation_Creativity_v7Deliver...
Module8_DFMEA_Testing_Innovation_Creativity_v7Innovation_Creativity_v7Deliver...
yatakonakiran2
 
Design_slides Design_slides Design_slidesDesign_slides
Design_slides Design_slides Design_slidesDesign_slides
yatakonakiran2
 
Abstract classes.pptx Abstract classesAbstract classesAbstract classes
Abstract classes.pptx Abstract classesAbstract classesAbstract classes
yatakonakiran2
 
Ad

Recently uploaded (20)

2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
penafloridaarlyn
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Introduction to problem solving Techniques
Introduction to problem solving Techniques
merlinjohnsy
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Measuring, learning and applying multiplication facts.
Measuring, learning and applying multiplication facts.
cgilmore6
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 
2025 June Year 9 Presentation: Subject selection.pptx
2025 June Year 9 Presentation: Subject selection.pptx
mansk2
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Wax Moon, Richmond, VA. Terrence McPherson
Wax Moon, Richmond, VA. Terrence McPherson
TerrenceMcPherson1
 
How to Create an Event in Odoo 18 - Odoo 18 Slides
How to Create an Event in Odoo 18 - Odoo 18 Slides
Celine George
 
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
ICT-8-Module-REVISED-K-10-CURRICULUM.pdf
penafloridaarlyn
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
Introduction to problem solving Techniques
Introduction to problem solving Techniques
merlinjohnsy
 
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Battle of Bookworms 2025 - U25 Literature Quiz by Pragya
Pragya - UEM Kolkata Quiz Club
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Paper 108 | Thoreau’s Influence on Gandhi: The Evolution of Civil Disobedience
Rajdeep Bavaliya
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
Measuring, learning and applying multiplication facts.
Measuring, learning and applying multiplication facts.
cgilmore6
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Nice Dream.pdf /
Nice Dream.pdf /
ErinUsher3
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
How to Implement Least Package Removal Strategy in Odoo 18 Inventory
Celine George
 
Ad

Java Fundamentals.pptJava Fundamentals.ppt

  • 7. 7 Creating and Compiling Programs • On command line – javac file.java Source Code Create/Modify Source Code Compile Source Code i.e. javac Welcome.java Bytecode Run Byteode i.e. java Welcome Result If compilation errors If runtime errors or incorrect result
  • 8. 8 Executing Applications • On command line – java classname Java Interpreter on Windows Java Interpreter on Sun Solaris Java Interpreter on Linux Bytecode ...
  • 20. d
  • 28. Different Programming Paradigms • Functional/procedural programming: – program is a list of instructions to the computer • Object-oriented programming – program is composed of a collection objects that communicate with each other
  • 29. Main Concepts • Object • Class • Inheritance • Encapsulation
  • 30. Objects • identity – unique identification of an object • attributes – data/state • services – methods/operations – supported by the object – within objects responsibility to provide these services to other clients
  • 31. Class • “type” • object is an instance of class • class groups similar objects – same (structure of) attributes – same services • object holds values of its class’s attributes
  • 32. Inheritance • Class hierarchy • Generalization and Specialization – subclass inherits attributes and services from its superclass – subclass may add new attributes and services – subclass may reuse the code in the superclass – subclasses provide specialized behaviors (overriding and dynamic binding) – partially define and implement common behaviors (abstract)
  • 33. Encapsulation • Separation between internal state of the object and its external aspects • How ? – control access to members of the class – interface “type”
  • 34. What does it buy us ? • Modularity – source code for an object can be written and maintained independently of the source code for other objects – easier maintainance and reuse • Information hiding – other objects can ignore implementation details – security (object has control over its internal state) • but – shared data need special design patterns (e.g., DB) – performance overhead
  • 35. mainly for c++ programmer Adapted with permission from Avivit Bercovici Boden, Technion
  • 36. Why Java ? • Portable • Easy to learn • [ Designed to be used on the Internet ]
  • 37. JVM • JVM stands for Java Virtual Machine • Unlike other languages, Java “executables” are executed on a CPU that does not exist.
  • 38. OS/Hardware machine code C source code myprog.c gcc myprog.exe Platform Dependent JVM bytecode Java source code myprog.java javac myprog.class OS/Hardware Platform Independent
  • 39. Primitive types • int 4 bytes • short 2 bytes • long 8 bytes • byte 1 byte • float 4 bytes • double 8 bytes • char Unicode encoding (2 bytes) • boolean {true,false} Behaviors is exactly as in C++ Note: Primitive type always begin with lower-case
  • 40. • Constants 37 integer 37.2 float 42F float 0754 integer (octal) 0xfe integer (hexadecimal) Primitive types - cont.
  • 41. Wrappers Java provides Objects which wrap primitive types and supply methods. Example: Integer n = new Integer(“4”); int m = n.intValue(); Read more about Integer in JDK Documentation
  • 42. Hello World class Hello { public static void main(String[] args) { System.out.println(“Hello World !!!”); } } Hello.java C:javac Hello.java C:java Hello ( compilation creates Hello.class ) (Execution on the local JVM)
  • 43. More sophisticated class Kyle { private boolean kennyIsAlive_; public Kyle() { kennyIsAlive_ = true; } public Kyle(Kyle aKyle) { kennyIsAlive_ = aKyle.kennyIsAlive_; } public String theyKilledKenny() { if (kennyIsAlive_) { kennyIsAlive_ = false; return “You bastards !!!”; } else { return “?”; } } public static void main(String[] args) { Kyle k = new Kyle(); String s = k.theyKilledKenny(); System.out.println(“Kyle: “ + s); } } Default C’tor Copy C’tor
  • 44. Results javac Kyle.java ( to compile ) java Kyle ( to execute ) Kyle: You bastards !!!
  • 45. Arrays • Array is an object • Array size is fixed Animal[] arr; // nothing yet … arr = new Animal[4]; // only array of pointers for(int i=0 ; i < arr.length ; i++) { arr[i] = new Animal(); // now we have a complete array
  • 46. Arrays - Multidimensional • In C++ Animal arr[2][2] Is: • In Java What is the type of the object here ? Animal[][] arr= new Animal[2][2]
  • 47. Static - [1/4] • Member data - Same data is used for all the instances (objects) of some Class. Class A { public int y = 0; public static int x_ = 1; }; A a = new A(); A b = new A(); System.out.println(b.x_); a.x_ = 5; System.out.println(b.x_); A.x_ = 10; System.out.println(b.x_); Assignment performed on the first access to the Class. Only one instance of ‘x’ exists in memory Output: 1 5 10 a b y y A.x_ 0 0 1
  • 48. Static - [2/4] • Member function – Static member function can access only static members – Static member function can be called without an instance. Class TeaPot { private static int numOfTP = 0; private Color myColor_; public TeaPot(Color c) { myColor_ = c; numOfTP++; } public static int howManyTeaPots() { return numOfTP; } // error : public static Color getColor() { return myColor_; } }
  • 49. Static - [2/4] cont. Usage: TeaPot tp1 = new TeaPot(Color.RED); TeaPot tp2 = new TeaPot(Color.GREEN); System.out.println(“We have “ + TeaPot.howManyTeaPots()+ “Tea Pots”);
  • 50. Static - [3/4] • Block – Code that is executed in the first reference to the class. – Several static blocks can exist in the same class ( Execution order is by the appearance order in the class definition ). – Only static members can be accessed. class RandomGenerator { private static int seed_; static { int t = System.getTime() % 100; seed_ = System.getTime(); while(t-- > 0) seed_ = getNextNumber(seed_); } } }
  • 51. String is an Object • Constant strings as in C, does not exist • The function call foo(“Hello”) creates a String object, containing “Hello”, and passes reference to it to foo. • There is no point in writing : • The String object is a constant. It can’t be changed using a reference to it. String s = new String(“Hello”);
  • 52. Flow control Basically, it is exactly like c/c++. if/else do/while for switch If(x==4) { // act1 } else { // act2 } int i=5; do { // act1 i--; } while(i!=0); int j; for(int i=0;i<=9;i++) { j+=i; } char c=IN.getChar(); switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2 }
  • 53. Packages • Java code has hierarchical structure. • The environment variable CLASSPATH contains the directory names of the roots. • Every Object belongs to a package ( ‘package’ keyword) • Object full name contains the name full name of the package containing it.
  • 54. Access Control • public member (function/data) – Can be called/modified from outside. • protected – Can be called/modified from derived classes • private – Can be called/modified only from the current class • default ( if no access modifier stated ) – Usually referred to as “Friendly”. – Can be called/modified/instantiated from the same package.
  • 55. Inheritance Base Derived class Base { Base(){} Base(int i) {} protected void foo() {…} } class Derived extends Base { Derived() {} protected void foo() {…} Derived(int i) { super(i); … super.foo(); } } As opposed to C++, it is possible to inherit only from ONE class. Pros avoids many potential problems and bugs. Cons might cause code replication
  • 56. Polymorphism • Inheritance creates an “is a” relation: For example, if B inherits from A, than we say that “B is also an A”. Implications are: – access rights (Java forbids reducing access rights) - derived class can receive all the messages that the base class can. – behavior – precondition and postcondition
  • 57. Inheritance (2) • In Java, all methods are virtual : class Base { void foo() { System.out.println(“Base”); } } class Derived extends Base { void foo() { System.out.println(“Derived”); } } public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Derived.foo() will be activated } }
  • 58. Inheritance (3) - Optional class classC extends classB { classC(int arg1, int arg2){ this(arg1); System.out.println("In classC(int arg1, int arg2)"); } classC(int arg1){ super(arg1); System.out.println("In classC(int arg1)"); } } class classB extends classA { classB(int arg1){ super(arg1); System.out.println("In classB(int arg1)"); } classB(){ System.out.println("In classB()"); } }
  • 59. Inheritance (3) - Optional class classA { classA(int arg1){ System.out.println("In classA(int arg1)"); } classA(){ System.out.println("In classA()"); } } class classB extends classA { classB(int arg1, int arg2){ this(arg1); System.out.println("In classB(int arg1, int arg2)"); } classB(int arg1){ super(arg1); System.out.println("In classB(int arg1)"); } class B() { System.out.println("In classB()"); } }
  • 60. Abstract • abstract member function, means that the function does not have an implementation. • abstract class, is class that can not be instantiated. AbstractTest.java:6: class AbstractTest is an abstract class. It can't be instantiated. new AbstractTest(); ^ 1 error NOTE: An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or that does not provide an implementation for any abstract methods declared in its superclasses must be declared as an abstract class. Example
  • 61. Abstract - Example package java.lang; public abstract class Shape { public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor); draw(); setCenter(x,y); setColor(ForeGroundColor); draw(); } } package java.lang; public class Circle extends Shape { public void draw() { // draw the circle ... } }
  • 62. Interface Interfaces are useful for the following:  Capturing similarities among unrelated classes without artificially forcing a class relationship.  Declaring methods that one or more classes are expected to implement.  Revealing an object's programming interface without revealing its class.
  • 63. Interface • abstract “class” • Helps defining a “usage contract” between classes • All methods are public • Java’s compensation for removing the multiple inheritance. You can “inherit” as many interfaces as you want. Example * - The correct term is “to implement” an interface
  • 64. Interface interface SouthParkCharacter { void curse(); } interface IChef { void cook(Food food); } interface BabyKicker { void kickTheBaby(Baby); } class Chef implements IChef, SouthParkCharacter { // overridden methods MUST be public // can you tell why ? public void curse() { … } public void cook(Food f) { … } } * access rights (Java forbids reducing of access rights)
  • 65. When to use an interface ? Perfect tool for encapsulating the classes inner structure. Only the interface will be exposed
  • 66. Collections • Collection/container – object that groups multiple elements – used to store, retrieve, manipulate, communicate aggregate data • Iterator - object used for traversing a collection and selectively remove elements • Generics – implementation is parametric in the type of elements
  • 67. Java Collection Framework • Goal: Implement reusable data-structures and functionality • Collection interfaces - manipulate collections independently of representation details • Collection implementations - reusable data structures List<String> list = new ArrayList<String>(c); • Algorithms - reusable functionality – computations on objects that implement collection interfaces – e.g., searching, sorting – polymorphic: the same method can be used on many different implementations of the appropriate collection interface
  • 68. Collection Interfaces Collection Set List Queue SortedSet Map Sorted Map
  • 69. Collection Interface • Basic Operations – int size(); – boolean isEmpty(); – boolean contains(Object element); – boolean add(E element); – boolean remove(Object element); – Iterator iterator(); • Bulk Operations – boolean containsAll(Collection<?> c); – boolean addAll(Collection<? extends E> c); – boolean removeAll(Collection<?> c); – boolean retainAll(Collection<?> c); – void clear(); • Array Operations – Object[] toArray(); <T> T[] toArray(T[] a); }
  • 70. General Purpose Implementations Collection Set List Queue SortedSet Map Sorted Map HashSet HashMap List<String> list1 = new ArrayList<String>(c); ArrayList TreeSet TreeMap LinkedList List<String> list2 = new LinkedList<String>(c);
  • 71. final • final member data Constant member • final member function The method can’t be overridden. • final class ‘Base’ is final, thus it can’t be extended final class Base { final int i=5; final void foo() { i=10; //what will the compiler say about this? } } class Derived extends Base { // Error // another foo ... void foo() { } } (String class is final)
  • 72. final final class Base { final int i=5; final void foo() { i=10; } } class Derived extends Base { // Error // another foo ... void foo() { } } Derived.java:6: Can't subclass final classes: class Base class class Derived extends Base { ^ 1 error
  • 73. IO - Introduction • Definition – Stream is a flow of data • characters read from a file • bytes written to the network • … • Philosophy – All streams in the world are basically the same. – Streams can be divided (as the name “IO” suggests) to Input and Output streams. • Implementation – Incoming flow of data (characters) implements “Reader” (InputStream for bytes) – Outgoing flow of data (characters) implements “Writer” (OutputStream for bytes –eg. Images, sounds etc.)
  • 74. Exception - What is it and why do I care? Definition: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. • Exception is an Object • Exception class must be descendent of Throwable.
  • 75. Exception - What is it and why do I care?(2) By using exceptions to manage errors, Java programs have the following advantages over traditional error management techniques: 1: Separating Error Handling Code from "Regular" Code 2: Propagating Errors Up the Call Stack 3: Grouping Error Types and Error Differentiation
  • 76. readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } 1: Separating Error Handling Code from "Regular" Code (1)
  • 77. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } } else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; } 1: Separating Error Handling Code from "Regular" Code (2)
  • 78. readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } 1: Separating Error Handling Code from "Regular" Code (3)
  • 79. method1 { try { call method2; } catch (exception) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } 2: Propagating Errors Up the Call Stack

Editor's Notes

  • #28: flexibility, easing changes to programs easier to learn simpler to develop, maintain and analysize