KEMBAR78
Cse java | PPT
• Java is a programming language and a platform developed by
James Gosling at Sun Microsystems and released in 1995.
• There are many versions of java, the current version is Java SE
10.
• The features of Java are i) Simple ,ii) Object-Oriented ,iii)
Portable ,iv) Platform Independent ,v) Secured ,vi) Robust ,vii)
Architectural Neutral ,viii) Interpreted ,ix) High Performance ,x)
Multithreaded ,xi) Distributed and Dynamic
Why Java ? And Its Applications
• Portable
• Easy to learn
Applications:
 Desktop and Web Applications
 Business Applications
 Mobiles and Games
 Embedded System
 Smart Card
 Robotics etc.
JVM, JRE and JDK
• JVM stands for Java Virtual Machine
• Unlike other languages, Java “executables” are executed on a CPU that
does not exist.
• JRE stands for Java Runtime Environment
• JRE is a set of software tools which are used for developing java
applications.
• JDK stands for Java Development Kit
• It contains JRE+development tools (compiler, interpreter/loader ,etc.)
OS/Hardware
machine codeC 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();
Example program
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)
Arrays
• Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of
elements in a java array.
• Array in java is index based, first element of the array is stored at 0 index.
Arrays(cont..)
Advantage of Java Array
• Code Optimization: It makes the code optimized, we can retrieve or sort the
data easily.
• Random access: We can get any data located at any index position.
Disadvantage of Java Array
• Size Limit: We can store only fixed size of elements in the array. It doesn't
grow its size at runtime. To solve this problem, collection framework is used in
java.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Single-Dimension Array
Single-Dimension array in java
Syntax to Declare an Single-Dimension Array in java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Output: 33
3
4
5
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initializ
ation
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Multi-Dimension Array
Multidimensional array in java
In such case, data is stored in row and column based index (also known as
matrix form).
Syntax to Declare
Multidimensional Array in Java.
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Output: 1 2 3
2 4 5
4 4 5
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
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.
• A java package is a group of similar types of classes, interfaces and sub-
packages .
• Advantages of Packages are
• Easily maintained
• Provides access protection and
• Removes named conflicts
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”.
• Polymorphism is a concept by which we can perform a single
action by different ways. Polymorphism is derived from 2 Greek
words: poly and morphs. The word "poly" means many and "morphs"
means forms. So polymorphism means many forms.
• There are two types of polymorphism in java: compile time
polymorphism and runtime polymorphism. We can perform
polymorphism in java by method overloading and method overriding.
perform
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
}
}
Abstract keyword
• abstract member function, means that the function does not have an
implementation.
• abstract class, is class that can not be instantiated.
AbstractTest.java:6: class AbstractTest is an abstract
class.
It can't be instantiated.
new AbstractTest();
^
1 error
NOTE:
An abstract class is not required to have an abstract method in it.
But any class that has an abstract method in it or that does
not provide an implementation for any abstract methods declared
in its superclasses must be declared as an abstract class.
Abstract - Example
package java.lang;
public abstract class Shape {
public abstract void draw();
public void move(int x, int y) {
setColor(BackGroundColor);
draw();
setCenter(x,y);
setColor(ForeGroundColor);
draw();
}
}
package java.lang;
public class Circle extends Shape {
public void draw() {
// draw the circle ...
}
}
Interface
• An interface in java is a blueprint of a class. It has static constants and
abstract methods.
• The interface in java is a mechanism to achieve abstraction.
The main uses of an Interfaces are as follows
• It is used to achieve abstraction.
• By interface, we can support the functionality of multiple inheritance.
• It can be used to achieve loose coupling.
Interface Example
interface printable{
void print();
}
class A6 implements printable{
public void print(){System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output: Hello
Interface v/s Abstract Class
Collection Framework
• 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
• Goal: Implement reusable data-structures and functionality
• Collection framework represents a unified architecture for storing and
manipulating group of objects. It has:
1)Interfaces and its implementations i.e. classes
2)Algorithm
• Collection interfaces - manipulate collections independently of representation
details
• Collection implementations - reusable data structures
List<String> list = new ArrayList<String>(c);
Collection Interfaces
Collection
Set List Queue
SortedSet
Map
Sorted Map
Hierarchies
Collection Interface
• Basic Operations
– int size();
– boolean isEmpty();
– boolean contains(Object element);
– boolean add(E element);
– boolean remove(Object element);
– Iterator iterator();
• Bulk Operations
– boolean containsAll(Collection<?> c);
– boolean addAll(Collection<? extends E> c);
– boolean removeAll(Collection<?> c);
– boolean retainAll(Collection<?> c);
– void clear();
• Array Operations
– Object[] toArray(); <T> T[] toArray(T[] a); }
General Purpose Implementations
Collection
Set List Queue
SortedSet
Map
Sorted Map
HashSet HashMap
List<String> list1 = new ArrayList<String>(c);
ArrayListTreeSet TreeMapLinkedList
List<String> list2 = new LinkedList<String>(c);
Final keyword
• 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 keyword (cont..)
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.)
Cse java

Cse java

  • 1.
    • Java isa programming language and a platform developed by James Gosling at Sun Microsystems and released in 1995. • There are many versions of java, the current version is Java SE 10. • The features of Java are i) Simple ,ii) Object-Oriented ,iii) Portable ,iv) Platform Independent ,v) Secured ,vi) Robust ,vii) Architectural Neutral ,viii) Interpreted ,ix) High Performance ,x) Multithreaded ,xi) Distributed and Dynamic
  • 2.
    Why Java ?And Its Applications • Portable • Easy to learn Applications:  Desktop and Web Applications  Business Applications  Mobiles and Games  Embedded System  Smart Card  Robotics etc.
  • 3.
    JVM, JRE andJDK • JVM stands for Java Virtual Machine • Unlike other languages, Java “executables” are executed on a CPU that does not exist. • JRE stands for Java Runtime Environment • JRE is a set of software tools which are used for developing java applications. • JDK stands for Java Development Kit • It contains JRE+development tools (compiler, interpreter/loader ,etc.)
  • 4.
    OS/Hardware machine codeC sourcecode myprog.c gcc myprog.exe Platform Dependent JVM bytecode Java source code myprog.java javac myprog.class OS/Hardware Platform Independent
  • 5.
    Primitive types • int4 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
  • 6.
    • Constants 37 integer 37.2float 42F float 0754 integer (octal) 0xfe integer (hexadecimal) Primitive types - cont.
  • 7.
    Wrappers Java provides Objectswhich wrap primitive types and supply methods. Example: Integer n = new Integer(“4”); int m = n.intValue();
  • 8.
    Example program 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)
  • 9.
    Arrays • Java arrayis an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. • Array in java is index based, first element of the array is stored at 0 index.
  • 10.
    Arrays(cont..) Advantage of JavaArray • Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. • Random access: We can get any data located at any index position. Disadvantage of Java Array • Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java. Types of Array in java There are two types of array. • Single Dimensional Array • Multidimensional Array
  • 11.
    Single-Dimension Array Single-Dimension arrayin java Syntax to Declare an Single-Dimension Array in java dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Output: 33 3 4 5 class Testarray1{ public static void main(String args[]){ int a[]={33,3,4,5};//declaration, instantiation and initializ ation //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
  • 12.
    Multi-Dimension Array Multidimensional arrayin java In such case, data is stored in row and column based index (also known as matrix form). Syntax to Declare Multidimensional Array in Java. dataType[][] arrayRefVar; (or) dataType [][]arrayRefVar; (or) dataType arrayRefVar[][]; (or) dataType []arrayRefVar[]; Output: 1 2 3 2 4 5 4 4 5 class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }}
  • 13.
    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
  • 14.
    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_; } }
  • 15.
    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”);
  • 16.
    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_); } } }
  • 17.
    String is anObject • 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”);
  • 18.
    Flow control Basically, itis 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 }
  • 19.
    Packages • Java codehas 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. • A java package is a group of similar types of classes, interfaces and sub- packages . • Advantages of Packages are • Easily maintained • Provides access protection and • Removes named conflicts
  • 20.
    Access Control • publicmember (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.
  • 21.
    Inheritance Base Derived class Base { Base(){} Base(inti) {} 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
  • 22.
    Polymorphism • Inheritance createsan “is a” relation: For example, if B inherits from A, than we say that “B is also an A”. • Polymorphism is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms. • There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding. perform
  • 23.
    Inheritance (2) • InJava, 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 } }
  • 24.
    Abstract keyword • abstractmember 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.
  • 25.
    Abstract - Example packagejava.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 ... } }
  • 26.
    Interface • An interfacein java is a blueprint of a class. It has static constants and abstract methods. • The interface in java is a mechanism to achieve abstraction. The main uses of an Interfaces are as follows • It is used to achieve abstraction. • By interface, we can support the functionality of multiple inheritance. • It can be used to achieve loose coupling.
  • 27.
    Interface Example interface printable{ voidprint(); } class A6 implements printable{ public void print(){System.out.println("Hello"); } public static void main(String args[]){ A6 obj = new A6(); obj.print(); } } Output: Hello
  • 28.
  • 29.
    Collection Framework • 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 • Goal: Implement reusable data-structures and functionality • Collection framework represents a unified architecture for storing and manipulating group of objects. It has: 1)Interfaces and its implementations i.e. classes 2)Algorithm • Collection interfaces - manipulate collections independently of representation details • Collection implementations - reusable data structures List<String> list = new ArrayList<String>(c);
  • 30.
    Collection Interfaces Collection Set ListQueue SortedSet Map Sorted Map Hierarchies
  • 31.
    Collection Interface • BasicOperations – 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); }
  • 32.
    General Purpose Implementations Collection SetList Queue SortedSet Map Sorted Map HashSet HashMap List<String> list1 = new ArrayList<String>(c); ArrayListTreeSet TreeMapLinkedList List<String> list2 = new LinkedList<String>(c);
  • 33.
    Final keyword • finalmember 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)
  • 34.
    Final keyword (cont..) finalclass 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
  • 35.
    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.)