Esoft Metro Campus - Certificate in java basics

Post on 19-Feb-2017

34 views 1 download

Transcript of Esoft Metro Campus - Certificate in java basics

Certificate in Java Basics

Rasan SamarasingheESOFT Computer Studies (pvt) Ltd.No 68/1, Main Street, Pallegama, Embilipitiya.

Programme Structure

Module 11.1 Introduction to Java

Module 22.1 Getting Start Java Programming Language2.2 Java Variables Java Objects Java Methods

Module 33.1 Operators3.2 Flow Control

Module 44.1 Access Modifiers4.2 Non Access Modifiers4.3 Interfaces

Module 55.1 Object Orientation

Module 66.1 String6.2 String Buffer and String Builder Classes6.3 Scanner

Module 77.1 Wrapper classes7.2 Auto boxing

Module 88.1 Basic Collection Framework

Module 99.1 Java Exception

1.1 Introduction to Java

Introduction to Java

• Developed by Sun Microsystems (has merged into Oracle Corporation later)

• Initiated by James Gosling• Released in 1995• Java has 3 main versions as Java SE, Java EE

and Java ME

Features of Java

Object Oriented Platform independent Simple Secure Portable Robust Multi-threaded Interpreted High Performance

What you can create by Java?

• Desktop (GUI) applications• Enterprise level applications• Web applications• Web services• Java Applets• Mobile applications

2.1 Getting Start Java Programming Language

Start Java Programming

What you need to program in Java?

Java Development Kit (JDK)Microsoft Notepad or any other text editorCommand Prompt

Creating First Java Program

public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}

MyFirstApp.java

Java Virtual Machine (JVM)

Java Virtual Machine (JVM)

1. When Java source code (.java files) is compiled, it is translated into Java bytecodes and then placed into (.class) files.

2. The JVM executes Java bytecodes and run the program.

Java was designed with a concept of write once and run anywhere. Java Virtual Machine plays the

central role in this concept.

Basic Rules to Remember

Java is case sensitive…

Hello not equals to hello

Basic Rules to Remember

Class name should be a single word and it cannot contain symbols and should be started

with a character…

Wrong class name Correct way

Hello World HelloWorld

Java Window Java_Window

3DUnit Unit3D

“FillForm” FillForm

public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}

Basic Rules to Remember

Name of the program file should exactly match the class name...

Save as MyFirstApp.java

Basic Rules to Remember

Main method which is a mandatory part of every java program…

public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}

Basic Rules to Remember

Tokens must be separated by WhitespacesExcept ( ) ; { } . [ ] + - * / =

public class MyFirstApp{public static void main(String[] args){System.out.println("Hello World");}}

Keywords in Java

Comments in Java Programs

Comments for single line

// this is a single line comment

For multiline

/* this is a multilinecomment*/

Printing Statements

System.out.print(“your text”); //prints text

System.out.println(“your text”); //prints text and create a new line

System.out.print(“line one\n line two”);//prints text in two lines

2.2 Java Variables Java Objects Java Methods

Primitive Data Types in Java

Keyword Type of data the variable will store Size in memory

boolean true/false value 1 bit

byte byte size integer 8 bits

char a single character 16 bits

double double precision floating point decimal number 64 bits

float single precision floating point decimal number 32 bits

int a whole number 32 bits

long a whole number (used for long numbers) 64 bits

short a whole number (used for short numbers) 16 bits

Variable Declaration in Java

Variable declarationtype variable_list;

Variable declaration and initializationtype variable_name = value;

Variable Declaration in Java

int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing d and f.

byte z = 22; // initializes z.

double pi = 3.14159; // declares an approximation of pi.

char x = 'x'; // the variable x has the value 'x'.

Java Objects and Classes

Java Classes

Method

Dog

namecolor

bark()

class Dog{

String name;String color;

public Dog(){}

public void bark(){System.out.println(“dog is barking!”);}

}

Attributes

Constructor

Java Objects

Dog myPet = new Dog(); //creating an object //Assigning values to AttributesmyPet.name = “Scooby”; myPet.color = “Brown”;

//calling methodmyPet.bark();

Methods

Method is a group of statements to perform a specific task.

• Methods with Return Value• Methods without Return Value

Methods with Return Value

public int max(int num1, int num2){int result;if (num1 > num2){result = num1;}else{result = num2;}return result;}

Access modifierReturn typeMethod name

parameters

Return valueMethod body

Methods without Return Value

public void print(String txt){System.out.println(“your text: “ + txt)}

Access modifierVoid represents no return valueMethod name

parameter

Method body

Constructors

• Each time a new object is created the constructor will be invoked

• Constructor are created with class name

• There can be more constructors distinguished by their parameters

class Dog{String name;

public Dog(String name){this.name = name;}

}

//creating an object from Dog classDog myDog = new Dog(“brown”);

Constructor

String Parameter

String Argument

Variables in a Class

Variables in a Class can be categorize into three types

1. Local Variables2. Instance Variables3. Static/Class Variables

Local Variables

• Declared in methods, constructors, or blocks.

• Access modifiers cannot be used.

• Visible only within the declared method, constructor or block.

• Should be declared with an initial value.

public class Vehicle{int number;String color;static String model;

void Drive(){int speed = 100;System.out.print(“vehicle is driving in “ + speed + “kmph”);}

}

Instance Variables

• Declared in a class, but outside a method, constructor or any block.

• Access modifiers can be given.• Can be accessed directly

anywhere in the class. • Have default values. • Should be called using an

object reference to access within static methods and outside of the class.

public class Vehicle{int number;String color;static String model;

void Drive(){int speed = 100;System.out.print(“vehicle is driving in “ + speed + “kmph”);}

}

Static/Class Variables

public class Vehicle{int number;String color;static String model;

void Drive(){int speed = 100;System.out.print(“vehicle is driving in “ + speed + “kmph”);}

}

• Declared with the static keyword in a class, but outside a method, constructor or a block.

• Only one copy for each class regardless how many objects created.

• Have default values. • Can be accessed by calling

with the class name.

3.1 Operators

Arithmetic Operators

Operator Description Example+ Addition A + B will give 30

- Subtraction A - B will give -10

* Multiplication A * B will give 200

/ Division B / A will give 2

% Modulus B % A will give 0

++ Increment B++ gives 21

-- Decrement B-- gives 19

A = 10, B = 20

Assignment Operators

Operator Example

= C = A + B will assign value of A + B into C

+= C += A is equivalent to C = C + A

-= C -= A is equivalent to C = C - A

*= C *= A is equivalent to C = C * A

/= C /= A is equivalent to C = C / A

%= C %= A is equivalent to C = C % A

Comparison Operators

Operator Example

== (A == B) is false.

!= (A != B) is true.

> (A > B) is false.

< (A < B) is true.

>= (A >= B) is false.

<= (A <= B) is true.

A = 10, B = 20

Logical Operators

Operator Name Example

&& AND (A && B) is False

|| OR (A || B) is True

! NOT !(A && B) is True

A = True, B = False

3.2 Flow Control

If Statement

if(Boolean_expression){ //Statements will execute if the Boolean

expression is true}

If Statement

Boolean Expression

Statements

True

False

If… Else Statement

if(Boolean_expression){ //Executes when the Boolean expression is

true}else{ //Executes when the Boolean expression is

false}

If… Else Statement

Boolean Expression

Statements

True

False

Statements

If… Else if… Else Statement

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is true}else if(Boolean_expression 2){ //Executes when the Boolean expression 2 is true}else if(Boolean_expression 3){ //Executes when the Boolean expression 3 is true}else { //Executes when the none of the above condition is true.}

If… Else if… Else Statement

Boolean expression 1

False

Statements

Boolean expression 2

Boolean expression 3

Statements

Statements

False

False

Statements

True

True

True

Nested If Statement

if(Boolean_expression 1){ //Executes when the Boolean expression 1 is

true if(Boolean_expression 2){ //Executes when the Boolean expression 2 is

true }}

Nested If Statement

Boolean Expression 1

True

False

StatementsBoolean Expression 2

True

False

Switch Statement

switch (value) { case constant: //statements break; case constant: //statements break; default: //statements}

While Loop

while(Boolean_expression){ //Statements}

While Loop

Boolean Expression

Statements

True

False

Do While Loop

do{ //Statements}while(Boolean_expression);

Do While Loop

Boolean Expression

Statements

True

False

For Loop

for(initialization; Boolean_expression; update){ //Statements}

For Loop

Boolean Expression

Statements

True

False

Update

Initialization

break Statement

Boolean Expression

Statements

True

False

break

continue Statement

Boolean Expression

Statements

True

False

continue

Nested Loop

Boolean Expression

True

False

Boolean Expression

Statements

True

False

4.1 Access Modifiers

Access Modifiers

Access Modifiers

Same class

Same package Sub class Other

packages

public Y Y Y Y

protected Y Y Y N

No access modifier Y Y N N

private Y N N N

4.2 Non Access Modifiers

Non Access Modifiers

• The static modifier for creating class methods and variables.

• The final modifier for finalizing the implementations of classes, methods, and variables.

• The abstract modifier for creating abstract classes and methods.

• The synchronized and volatile modifiers, which are used for threads.

4.3 Interfaces

Interfaces

• An interface contains a collection of abstract methods that a class implements.

• Interfaces states the names of methods, their return types and arguments.

• There is no body for any method in interfaces.

• A class can implement more than one interface at a time.

interface Vehicle{public void Drive(int speed);public void Stop();}

public class Car implements Vehicle{

public void Drive(int kmph){System.out.print(“Vehicle is driving in ” + kmph + “kmph speed”);}

public void Stop(){System.out.print(“Car stopped!”);}

}

5.1 Object Orientation

Inheritance

class Vehicle{//attributes and methods}

class Car extends Vehicle{//attributes and methods}

class Van extends Vehicle{//attributes and methods}

Vehicle

Car Van

Method Overloading

public class Car{

public void Drive(){System.out.println(“Car is driving”);}

public void Drive(int speed){System.out.println(“Car is driving in ” + speed + “kmph”);}

}

Method Overriding

class Vehicle{public void drive(){System.out.println(“Vehicle is driving”);}}

class Car extends Vehicle{public void drive(){System.out.println(“Car is driving”);}}

Polymorphismclass Animal{public void Speak(){}}

class Cat extends Animal{public void Speak(){System.out.println(“Meow");}}

class Dog extends Animal{public void Speak(){System.out.println(“Woof");}}

class Duck extends Animal{public void Speak(){System.out.println(“Quack");}}

Animal d = new Dog();Animal c = new Cat();Animal du = new Duck();

d.Speak();c.Speak();du.Speak();

Encapsulationclass student{

private int age;

public int getAge(){return age;}

public void setAge(int n){age = n;}

}

Data

Input OutputMethod Method

Method

6.1 String

Strings

• String is a sequence of characters• In java, Strings are objects.• Strings have been given some features to be

looked similar to primitive type.

String <variable name> = new String(“<value>”);orString <variable name> = “<value>”;

Useful Operations with Strings

• Concatenating Strings• length()• charAt(<index>)• substring(int <begin index>, int <end index>)• trim()• toLowerCase() • toUpperCase()

6.2 String Buffer and String Builder Classes

StringBuffer Class

The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters.

StringBuffer <variable name> = new StringBuffer(" <value> ");

StringBuffer Class Methodspublic StringBuffer append(String s)Updates the value of the object that invoked the method. The method takes boolean, char, int, long, Strings etc.

public StringBuffer reverse()The method reverses the value of the StringBuffer object that invoked the method.

public delete(int start, int end)Deletes the string starting from start index until end index.

public insert(int offset, int i)This method inserts an string s at the position mentioned by offset.

replace(int start, int end, String str)This method replaces the characters in a substring of this StringBuffer with characters in the specified String.

StringBuilder Class

The java.lang.StringBuilder class is mutable sequence of characters. This provides an API compatible with StringBuffer, but with no guarantee of synchronization.

StringBuilder <variable name> = new StringBuilder(" <value> ");

StringBuilder Class MethodsStringBuilder append(String str)This method appends the specified string to this character sequence.

StringBuilder reverse()This method causes this character sequence to be replaced by the reverse of the sequence.

StringBuilder delete(int start, int end)This method removes the characters in a substring of this sequence.

StringBuilder insert(int offset, String str)This method inserts the string into this character sequence.

StringBuilder replace(int start, int end, String str)This method replaces the characters in a substring of this sequence with characters in the specified String.

Comparison

String Class StringBuffer Class StringBuilder Class

Immutable Mutable Mutable

Not thread safe Thread safe Not thread safe

Not synchronized Synchronized Not synchronized

Fast Slow Fast

6.3 Scanner

Scanner Class

• The java.util.Scanner is useful for breaking down formatter input into tokens and translating individual tokens to their data type.

• A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Scanner <variable name> = new Scanner(“<value>”);

Scanner <variable name> = new Scanner(new BufferedReader(new FileReader(“<filename.ext>”));

Scanner Class MethodsString next()This method finds and returns the next complete token from this scanner.

String next(String pattern)This method returns the next token if it matches the pattern constructed from the specified string.

boolean hasNext()This method returns true if this scanner has another token in its input.

String nextLine()This method advances this scanner past the current line and returns the input that was skipped.

Scanner useDelimiter(String pattern)This method sets this scanner's delimiting pattern to a pattern constructed from the specified String.

int nextInt()This method scans the next token of the input as an int.

7.1 Wrapper Classes

Wrapper Classes

• Each of Java's eight primitive data types has a class dedicated to it known as wrapper classes.

• A wrapper class wraps around a data type and gives it an object appearance.

• Wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

Wrapper Classes

Wrapper Classes

Primitive Wrapper Class Constructor Argument

boolean Boolean boolean or String

byte Byte byte or String

char Character char

int Integer int or String

float Float float, double or String

double Double double or String

long Long long or String

short Short short or String

Wrapper Class MethodsMethod Purpose

parseInt(s) Returns a signed decimal integer value equivalent to string s

toString(i) Returns a new String object representing the integer i

byteValue() Returns the value of this Integer as a byte

doubleValue() Returns the value of this Integer as an double

floatValue() Returns the value of this Integer as a float

intValue() Returns the value of this Integer as an int

shortValue() Returns the value of this Integer as a short

longValue() Returns the value of this Integer as a long

int compareTo(int i) Compares the numerical value of the invoking object with that of i. Returns 0, minus value or positive value

static int compare(int num1, int num2)

Compares the values of num1 and num2. Returns 0, minus value or positive value

boolean equals(Object intObj)

Returns true if the invoking Integer object is equivalent to intObj. Otherwise, it returns false

7.2 Auto Boxing

AutoBoxing

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

AutoBoxing

Integer intObject = 34; //autoboxingint x = intObject; //unboxingint x = intObject + 7; //unboxing

AutoBoxing in Method Invocation

public static Integer show(Integer iParam){ System.out.println(iParam); return iParam;}

//method invocation

show(3); //autoboxingint result = show(3); //unboxing

Comparing Objects with equality Operator

Integer num1 = 1; // autoboxingint num2 = 1;System.out.println(num1 == num2); // true

Integer obj1 = 1; // autoboxing will call Integer.valueOf()Integer obj2 = 1; // same call to Integer.valueOf() will return same cached Object (values less than 255)System.out.println(obj1 == obj2); // true

Integer one = new Integer(1); // no autoboxingInteger anotherOne = new Integer(1);System.out.println("one == anotherOne); // false

8.1 Basic Collection Framework

What is a Collection?

• An object that groups multiple elements into a single unit.

• Used to store, retrieve, manipulate, and communicate aggregate data.

• They represent data items that form a natural group, such as a mail folder (collection of letters), or a telephone directory (a mapping of names to phone numbers).

Java Collection Framework

Java Collection Framework is a unified architecture for representing and manipulating collections.

It contain the following:

• Interfaces: Abstract data types that represent collections.

• Implementations: Concrete implementations of the collection interfaces.

• Algorithms: Methods that perform useful computations.

Interfaces on Collection FrameworkThe Collection InterfaceThis enables you to work with groups of objects; it is at the top of the collections hierarchy.

The List InterfaceThis extends Collection and an instance of List stores an ordered collection of elements.

The SetThis extends Collection to handle sets, which must contain unique elements

The SortedSetThis extends Set to handle sorted sets

The MapThis maps unique keys to values.

The Map.EntryThis describes an element (a key/value pair) in a map. This is an inner class of Map.

The SortedMapThis extends Map so that the keys are maintained in ascending order.

The EnumerationThis is legacy interface and defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.

Implementations on Collection FrameworkAbstractCollectionImplements most of the Collection interface.

AbstractListExtends AbstractCollection and implements most of the List interface.

AbstractSequentialListExtends AbstractList for use by a collection that uses sequential rather than random access of its elements.

LinkedListImplements a linked list by extending AbstractSequentialList.

ArrayListImplements a dynamic array by extending AbstractList.

AbstractSetExtends AbstractCollection and implements most of the Set interface.

HashSetExtends AbstractSet for use with a hash table.

LinkedHashSetExtends HashSet to allow insertion-order iterations.

Implementations on Collection FrameworkTreeSetImplements a set stored in a tree. Extends AbstractSet.

AbstractMapImplements most of the Map interface.

HashMapExtends AbstractMap to use a hash table.

TreeMapExtends AbstractMap to use a tree.

WeakHashMapExtends AbstractMap to use a hash table with weak keys.

LinkedHashMapExtends HashMap to allow insertion-order iterations.

IdentityHashMapExtends AbstractMap and uses reference equality when comparing documents.

Implementations on Collection Framework

VectorThis implements a dynamic array. It is similar to ArrayList, but with some differences.

StackStack is a subclass of Vector that implements a standard last-in, first-out stack.

DictionaryDictionary is an abstract class that represents a key/value storage repository and operates much like Map.

HashtableHashtable was part of the original java.util and is a concrete implementation of a Dictionary.

PropertiesProperties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String.

BitSetA BitSet class creates a special type of array that holds bit values. This array can increase in size as needed.

Algorithms on Collection Framework

static int binarySearch(List list, Object value)Searches for value in list. The list must be sorted. Returns the position of value in list, or -1 if value is not found.

static Object max(Collection c)Returns the maximum element in c as determined by natural ordering. The collection need not be sorted.

static Object min(Collection c)Returns the minimum element in c as determined by natural ordering.

static void sort(List list, Comparator comp)Sorts the elements of list as determined by comp.

static void shuffle(List list)Shuffles the elements in list.

9.1 Java Exception

Exceptions

An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, like:

• A user has entered invalid data.• A file that needs to be opened cannot be found.• A network connection has been lost in the

middle of communications

Exception Hierarchy

Throwable

Exception Error

IOException RuntimeException ThreadDeath

ArithmeticException NullPointerException ClassCastException

******

Exception Categories

• Checked exceptions: Cannot simply be ignored at the time of compilation.

• Runtime exceptions: Ignored at the time of compilation.

• Errors: Problems that arise beyond the control of the user or the programmer.

Handling and Throwing Exceptions

try { //Protected code } catch(ExceptionName var) { //Catch block } finally { //The finally block always executes}

public void Show() throws <ExceptionName> {throw new <ExceptionName>;}

You can…

handle Exceptionsby using try catch blocks

or

throw Exceptions

Declaring you own Exception

• All exceptions must be a child of Throwable.

• If you want to write a checked exception, you need to extend the Exception class.

• If you want to write a runtime exception, you need to extend the RuntimeException class.

The End

http://twitter.com/rasansmn