Java Session1

48
  Session

Transcript of Java Session1

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 1/48

Session

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 2/48

Objectives:

Object & Class. Abstract Class & Interface.

Package. String. Exception Handling. Wrapper Class. Collection Frame work.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 3/48

Object

Shapes

Mammals

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 4/48

A Dog has name ,It has some color ,

It belongs to a breed ,It may be hungry . name , color, breed, hungry are the attributes of Dog

object.Dog can bark , search , eat ……..Bark, search, eat define some behaviour of Dog object.

Behavior (Doing Responsibility) is how an objectreacts, in terms of its state changes, in response tooperations performed upon it.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 5/48

ClassClass Defines the attributes and behaviour of the

objects.Class is the blueprint of the objects. Objects are physical entity and class is the logical

construct of the objects. An object has some states .

• State( Knowing Responsibility ) is a set of propertieswhich can take different values at different times inthe object’s life.

• Every object has an unique identity number.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 6/48

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 7/48

Java Objects & ClassContd.

• Example: • Mr. White is married. He teaches OO Software

Engineering classes on Fridays. He is a part-timemember of the faculty at the CS Department of the

All-Smart Institute. John is enrolled in the OOSEclass that Mr. White teaches. Mrs. White uses aNano for transportation to and from the campus(she teaches Philosophy at the same institute).Class size is limited at the institute to 14 students.Janet, the sister of John is enrolled for violincourse in the same institute.

Identify all the objects & Similar

Objects / Class or Type that defines the objects …

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 8/48

Java Objects & ClassContd.

• OBJECTS are:

Mr. WhiteFaculty

Mrs. WhiteFaculty

JohnStudent

Janet Student

NanoCar

PhilosophyDepartment

CSDepartment

All-SmartInstitute

OOSECourse ViolinCourse

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 9/48

Properties of Object OrientatedProgramming (OOP)

Common properties of OOP is given below-

• Abstraction

• Encapsulation.• Inheritance.

• Polymorphism.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 10/48

Java as Object OrientatedProgramming

IETE

Java SourceCode(.java file)

Java Compiler(javac)

Bytecode(.class file)

JVM

Interpreter

JVM

Interpreter

JVM

Interpreter

Windows Unix Mac

Executable file(Output)

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 11/48

• Example Java program to print “HELLO WORLD”

class exampleHW{

public static void main (String args[]){

System.out.println (“HELLO WORLD” );

}}

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 12/48

Java Programming ElementsContd.

Datatype Size

byte 8 bitsshort 16 bits

int 32 bitslong 64 bitsfloat 32 bits

double 64 bits

Character takes 16 bits(Unicode), and size of theBoolean data type is machine dependent.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 13/48

Java Programming ElementsContd.

Arrays•An Array is a Container object that holds a fixed number ofvalues of a single type.

•Array can contain both primitive and reference data types.

•Each item in an array is called an element , and each element isaccessed by its numerical index.

• Array Declaration – int myIntegers[ ]; – int[ ] myIntegers;

• Array memory allocation: – int myIntegers[] = new int[10];

• Array Initialization: – int myIntegers[] = {1,2,3,4,5};

Indicates the same

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 14/48

Method Overloading

The Java programming supports language overloading methods,and Java can distinguish between methods with different method

signatures . This means that methods within a class can have the

same name if they have different parameter lists.

• Method Overloading (Compile time Polymorphism)•Two or more methods with dif ferent signatur es .

•The functions which differ only in their return types cannot be overloaded.•The compiler will select the right function depending on thetype of parameters passed.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 15/48

Method OverloadingContd. ExampleClass ExampleMO{

int method1 (int a)

{… }

int method1 (int a, int b) // overloaded method method1{

}

} IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 16/48

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 17/48

Method Overriding• Method Overriding (Runtime Polymorphism)

• A method in the subclass to ‘override’ the method in super classthat has the same signature .

• Which method to be called, is determined at runtime, not at thecompile time.

• We used method overriding to achieve polymorphism.Example:

public class Animal {public static void testClassMethod() {

System.out.println("The class method in Animal.");}public void testInstanceMethod() {

System.out.println("The instance method in Animal.");}

} IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 18/48

The second class, a subclass of Animal, is called Cat: public class Cat extends Animal {

public void testClassMethod() {System.out.println("The class method in Cat.");

} public void testInstanceMethod() {

System.out.println("The instance method in Cat.");}

public static void main(String [] args) {Cat myCat = new Cat();Animal myAnimal = myCat;Animal.testClassMethod();

myAnimal.testInstanceMethod();}

}The output from this program is as follows:The class method in Animal.The instance method in Cat. IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 19/48

Abstract Classes

• An Abstract class is a conceptual class.• An Abstract class cannot be instantiated –

objects cannot be created.Abstract classes

provides a common root for a group ofclasses, nicely tied together in a package.• When a class contains one or more abstract

methods, it should be declared as abstract

class.• The abstract methods of an abstract classmust be defined in its subclass.

• We cannot declare abstract constructors orabstract static methods. IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 20/48

Abstract Class -Example

20

• Shape is a abstract class.

Shape

Circle Rectangle

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 21/48

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 22/48

Abstract Class – ExampleContd .

public Circle extends Shape { protected double r; protected static final double PI =3.1415926535;

public Circle() { r = 1.0; ) public double area() { return PI * r * r; }… }

public Rectangle extends Shape { protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; }

}IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 23/48

Interfaces

• Interface is a conceptual entity similar to a Abstractclass.

• Can contain only constants (final variables) and

abstract method (no implementation) - Differentfrom Abstract classes.

• Use when a number of classes share a commoninterface.

• Each class should implement the interface.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 24/48

Interface - Example<<Interface>>

Speaker

Politician

speak()

speak()

Priest

speak()

Lecturer

speak()

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 25/48

Interfaces Definition

interface InterfaceName {// Constant/Final Variable Declaration// Abstract Methods

}

Example:-interface Speaker {

public void speak( );}

I mplementing Interface:-class ClassName implements InterfaceName [, InterfaceName2, …]{

// Body of Class}

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 26/48

Implementing InterfacesExampleclass Politician implements Speaker {

public void speak(){System.out.println( “Talk politics ”);

}}

class Priest implements Speaker {

public void speak(){System.out.println( “Religious Talks ”);

}}

class Lecturer implements Speaker { public void speak(){

System.out.println( “Talks Object Oriented Design and Programming! ”);}

}

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 27/48

Java Packages

• A package is a grouping of related types providingaccess protection and name space management.

• The types that are part of the Java platform aremembers of various packages that bundle classes byfunction: fundamental classes are in java.lang, classesfor reading and writing (input and output) arein java.io, and so on. You can put your types in

packages too.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 28/48

Java Packages Contd.Example:package points;import java.util.*;class Point {

int x, y; // coordinatesPointColor color; // color of this point

Point next; // next point with this colorstatic int nPoints;

}class PointColor {

Point first; // first point with this colorPointColor(int color) {

this.color = color;}private int color; // color components

} IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 29/48

String• Sequence of character.Example:

“Java”, “Smith”……..

• In Java Strings are objects of String class.

• String objects can be created in ways:

String name= new String(“Smith”);

String name= “Smith”;

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 30/48

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 31/48

String Contd.

IETE

String name=―Smith ; name=name+― Ray ;

Stack

name

Heap

Smith

Smith Ray

• String objects are immutable.

??

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 32/48

Empty Strings

• An empty String has no characters. It’s lengthis 0.

• Not the same as an uninitialized String.

IETE

String word1 = "";String word2 = new String();

Empty strings

private String errorMsg; errorMsg is null

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 33/48

Important Methods of String Class charAt() Returns the character located at the specified index.

concat() Appends one String to the end of another ( "+" also works). equalsIgnoreCase() Determines the equality of two Strings, ignoringcase. length() Returns the number of characters in a String.

replace() Replaces occurrences of a character with a new character. substring() Returns a part of a String. toLowerCase() Returns a String with uppercase characters converted. toString() Returns the value of a String.

toUpperCase() Returns a String with lowercase characters converted. trim() Removes whitespace from the ends of a String.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 34/48

Methods — Equalityboolean b = word1. equals (word2);

returns true if the string word1 is equal to word2

boolean b = word1. equalsIgnoreCase (word2);returns true if the string word1 matches word2 ,case-blind

IETE

b = “Raiders”.equals “Raiders”);//true b = “Raiders”.equals “raiders”);//false

b = “Raiders”.equalsIgnoreCase “raiders”);//true

if team.equalsIgnoreCase “raiders”)) System.out.println “Go You “ + team);

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 35/48

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 36/48

Exceptions – Handling exceptions

IETE

• What do you do when an Exceptionoccurs?

Handle the exception using try/catch/finallyThrow the Exception back to the calling method.

•Try/catch/finally

public class MyClass {public void exceptionMethod() {

try {// exception-block

} catch (Exception ex) {// handle exception

} finally {//clean-up

}}

}

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 37/48

Exceptions – Handling exceptions Cont

• Try/catch/finally - 2 public class MyClass {

public void exceptionMethod() {try {

// exception-block} catch (FileNotFoundException ex) {

// handle exception} catch (Exception ex) {

// handle exception} finally { //clean-up }

}}

• Using throwspublic class MyClass {

public void exceptionMethod() throws Exception {// exception-block

}}

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 38/48

Exceptions – Handling exceptionsContd.• Using throw

IETE

class MyException extends Exception { }

class TestEx {void doStuff() {throw new MyException(); // Throw a checkedexception

}}

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 39/48

Wrapper Class

• Wrapper classes encapsulate, or wrap, the primitivetypes within a class. Thus, they are commonlyreferred to as type wrappers .

• Wrapper objects are immutable.

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 40/48

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 41/48

Collections - Introduction

String student1 = “a”; String student2 = “b”; String student3 = “c”; String student4 = “d”; String student5 = “e”; String student6 = “f”;

• Difficult to maintain multiple items of same type asdifferent variables

• Data-manipulation issues

• Unnecessary code

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 42/48

Collections – Arrays v/s Collections

abc def jklghi

abc 123 defnew Person()

Arrays

Collections

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 43/48

Collections - Overview

LinkedHashSet

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 44/48

Collections – Collection types

• Three basic flavors of collections:Lists - Lists of things (classes that implement List)Sets - Unique things (classes that implement Set)Maps - Things with a unique ID (classes that implement Map)

• The sub-flavors:Ordered - You can iterate through the collection in a specific order.Sorted - Collection is sorted in the natural order (alphabetical for

Strings).UnorderedUnsorted

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 45/48

Collections – Lists

• ArrayList

Ordered collectionTo be considered when thread safety is a concern.Often used methods – add(), remove(), set(), get(), size()

• Vector

Resizable-array implementation of the List interface.Ordered collection.Should be considered when there is more of data retrieval than add/delete.Often used methods – add(), get(), remove(), set(), size()

• Linked ListOrdered collection.Faster insertion/deletion and slower retrieval when compared to ArrayList

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 46/48

Collections – Set

• HashSet

Not SortedNot OrderedShould be used if only requirement is uniquenessOften used methods – add(), contains(), remove(), size()

LinkedHashSetNot SortedOrderedSubclass of HashSetShould be used if the order of elements is important

• TreeSetSortedOrderedShould be used if you want to store objects in a sorted fashionOften used methods – first(), last(), add(), addAll(), subset()

• HashSet

Not SortedNot OrderedShould be used if only requirement is uniquenessOften used methods – add(), contains(), remove(), size()

LinkedHashSetNot SortedOrderedSubclass of HashSetShould be used if the order of elements is important

• HashSet

Not SortedNot OrderedShould be used if only requirement is uniquenessOften used methods – add(), contains(), remove(), size()

LinkedHashSet

SortedOrderedShould be used if you want to store objects in a sorted fashionOften used methods – first(), last(), add(), addAll(), subset()

Not SortedOrderedSubclass of HashSetShould be used if the order of elements is important

• HashSet

Not SortedNot OrderedShould be used if only requirement is uniquenessOften used methods – add(), contains(), remove(), size()

LinkedHashSet

• TreeSet

Not SortedOrderedSubclass of HashSetShould be used if the order of elements is important

• HashSet

Not SortedNot OrderedShould be used if only requirement is uniquenessOften used methods – add(), contains(), remove(), size()

LinkedHashSet

SortedOrderedShould be used if you want to store objects in a sorted fashionOften used methods – first(), last(), add(), addAll(), subset()

• TreeSet

Not SortedOrderedSubclass of HashSetShould be used if the order of elements is important

• HashSet

Not SortedNot OrderedShould be used if only requirement is uniquenessOften used methods – add(), contains(), remove(), size()

LinkedHashSet

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 47/48

Collections – Map

Not sorted, but ordered

• LinkedHashMap

Not Sorted, not orderedCannot have null keys or valuesThread-safe

• HashMap

Not Sorted, not orderedCan have one null key and any number of null valuesNot thread-safeOften used methods – get(), put(), containsKey(), keySet()

Hashtable

Sorted, ordered

• TreeMap

IETE

8/12/2019 Java Session1

http://slidepdf.com/reader/full/java-session1 48/48