SlideShare uma empresa Scribd logo
1 de 107
Certificate in Java Basics
Rasan Samarasinghe
ESOFT Computer Studies (pvt) Ltd.
No 68/1, Main Street, Pallegama, Embilipitiya.
Programme Structure
Module 1
1.1 Introduction to Java
Module 2
2.1 Getting Start Java
Programming Language
2.2 Java Variables Java Objects
Java Methods
Module 3
3.1 Operators
3.2 Flow Control
Module 4
4.1 Access Modifiers
4.2 Non Access Modifiers
4.3 Interfaces
Module 5
5.1 Object Orientation
Module 6
6.1 String
6.2 String Buffer and String
Builder Classes
6.3 Scanner
Module 7
7.1 Wrapper classes
7.2 Auto boxing
Module 8
8.1 Basic Collection Framework
Module 9
9.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 editor
Command 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 Whitespaces
Except ( ) ; { } . [ ] + - * / =
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 multiline
comment
*/
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 onen 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 declaration
type variable_list;
Variable declaration and initialization
type 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
name
color
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 Attributes
myPet.name = “Scooby”;
myPet.color = “Brown”;
//calling method
myPet.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 num1, int num2){
int result;
if (num1 > num2){
result = num1;
}else{
result = num2;
}
return result;
}
Access modifier
Return type
Method name
parameters
Return value
Method body
Methods without Return Value
public void {
System.out.println(“your text: “ + txt)
}
Access modifier
Void represents no return value
Method 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 class
Dog 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 Variables
2. Instance Variables
3. 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
Statements
Boolean
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”);
}
}
Polymorphism
class 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();
Encapsulation
class student{
private int age;
public int getAge(){
return age;
}
public void setAge(int n){
age = n;
}
}
Data
Input Output
Method 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>”);
or
String <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 Methods
public 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 Methods
StringBuilder 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 Methods
String 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 Methods
Method 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; //autoboxing
int x = intObject; //unboxing
int x = intObject + 7; //unboxing
AutoBoxing in Method Invocation
public static Integer show(Integer iParam){
System.out.println(iParam);
return iParam;
}
//method invocation
show(3); //autoboxing
int result = show(3); //unboxing
Comparing Objects with equality Operator
Integer num1 = 1; // autoboxing
int 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 autoboxing
Integer 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 Framework
The Collection Interface
This enables you to work with groups of objects; it is at the top of the collections hierarchy.
The List Interface
This extends Collection and an instance of List stores an ordered collection of elements.
The Set
This extends Collection to handle sets, which must contain unique elements
The SortedSet
This extends Set to handle sorted sets
The Map
This maps unique keys to values.
The Map.Entry
This describes an element (a key/value pair) in a map. This is an inner class of Map.
The SortedMap
This extends Map so that the keys are maintained in ascending order.
The Enumeration
This 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 Framework
AbstractCollection
Implements most of the Collection interface.
AbstractList
Extends AbstractCollection and implements most of the List interface.
AbstractSequentialList
Extends AbstractList for use by a collection that uses sequential rather than random access of its
elements.
LinkedList
Implements a linked list by extending AbstractSequentialList.
ArrayList
Implements a dynamic array by extending AbstractList.
AbstractSet
Extends AbstractCollection and implements most of the Set interface.
HashSet
Extends AbstractSet for use with a hash table.
LinkedHashSet
Extends HashSet to allow insertion-order iterations.
Implementations on Collection Framework
TreeSet
Implements a set stored in a tree. Extends AbstractSet.
AbstractMap
Implements most of the Map interface.
HashMap
Extends AbstractMap to use a hash table.
TreeMap
Extends AbstractMap to use a tree.
WeakHashMap
Extends AbstractMap to use a hash table with weak keys.
LinkedHashMap
Extends HashMap to allow insertion-order iterations.
IdentityHashMap
Extends AbstractMap and uses reference equality when comparing documents.
Implementations on Collection Framework
Vector
This implements a dynamic array. It is similar to ArrayList, but with some differences.
Stack
Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Dictionary
Dictionary is an abstract class that represents a key/value storage repository and operates much like
Map.
Hashtable
Hashtable was part of the original java.util and is a concrete implementation of a Dictionary.
Properties
Properties 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.
BitSet
A 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
Exceptions
by 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

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
DIWE - Working with MySQL Databases
DIWE - Working with MySQL DatabasesDIWE - Working with MySQL Databases
DIWE - Working with MySQL Databases
 
Oops presentation
Oops presentationOops presentation
Oops presentation
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
C++ oop
C++ oopC++ oop
C++ oop
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Clean code slide
Clean code slideClean code slide
Clean code slide
 
Clean code
Clean codeClean code
Clean code
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 
Clean code
Clean codeClean code
Clean code
 
C Theory
C TheoryC Theory
C Theory
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
C++ theory
C++ theoryC++ theory
C++ theory
 

Destaque

DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementRasan Samarasinghe
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project ManagementRasan Samarasinghe
 
X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009Frank
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) Rasan Samarasinghe
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scannerArif Ullah
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Harmeet Singh(Taara)
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructorShivam Singhal
 
DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)Rasan Samarasinghe
 
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)VLSI SYSTEM Design
 
DITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mailDITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mailRasan Samarasinghe
 
1 java - data type
1  java - data type1  java - data type
1 java - data typevinay arora
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringRasan Samarasinghe
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classesyoavwix
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in javaMahmoud Ali
 

Destaque (20)

DISE - Software Testing and Quality Management
DISE - Software Testing and Quality ManagementDISE - Software Testing and Quality Management
DISE - Software Testing and Quality Management
 
DISE - Introduction to Project Management
DISE - Introduction to Project ManagementDISE - Introduction to Project Management
DISE - Introduction to Project Management
 
X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009X$Tables And Sga Scanner, DOAG2009
X$Tables And Sga Scanner, DOAG2009
 
Oops concepts
Oops conceptsOops concepts
Oops concepts
 
DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update) DITEC - Expose yourself to Internet & E-mail (second update)
DITEC - Expose yourself to Internet & E-mail (second update)
 
Buffer and scanner
Buffer and scannerBuffer and scanner
Buffer and scanner
 
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)Java 8 Streams And Common Operations By Harmeet Singh(Taara)
Java 8 Streams And Common Operations By Harmeet Singh(Taara)
 
java: basics, user input, data type, constructor
java:  basics, user input, data type, constructorjava:  basics, user input, data type, constructor
java: basics, user input, data type, constructor
 
DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)DITEC - Expose yourself to Internet & E-mail (updated)
DITEC - Expose yourself to Internet & E-mail (updated)
 
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
Define location of Preplaced cells(http://www.vlsisystemdesign.com/PD-Flow.php)
 
DITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mailDITEC - Expose yourself to Internet & E-mail
DITEC - Expose yourself to Internet & E-mail
 
DITEC - Software Engineering
DITEC - Software EngineeringDITEC - Software Engineering
DITEC - Software Engineering
 
1 java - data type
1  java - data type1  java - data type
1 java - data type
 
DISE - Introduction to Software Engineering
DISE - Introduction to Software EngineeringDISE - Introduction to Software Engineering
DISE - Introduction to Software Engineering
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
DISE - Programming Concepts
DISE - Programming ConceptsDISE - Programming Concepts
DISE - Programming Concepts
 
DITEC - E-Commerce & ASP.NET
DITEC - E-Commerce & ASP.NETDITEC - E-Commerce & ASP.NET
DITEC - E-Commerce & ASP.NET
 
Jnp
JnpJnp
Jnp
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
DISE - OOAD Using UML
DISE - OOAD Using UMLDISE - OOAD Using UML
DISE - OOAD Using UML
 

Semelhante a Esoft Metro Campus - Certificate in java basics (20)

Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Core java
Core javaCore java
Core java
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Pi j1.3 operators
Pi j1.3 operatorsPi j1.3 operators
Pi j1.3 operators
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Java Intro
Java IntroJava Intro
Java Intro
 
Java
JavaJava
Java
 
Java session4
Java session4Java session4
Java session4
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
JavaTutorials.ppt
JavaTutorials.pptJavaTutorials.ppt
JavaTutorials.ppt
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 

Mais de Rasan Samarasinghe

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptxRasan Samarasinghe
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrumRasan Samarasinghe
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling LanguageRasan Samarasinghe
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIRasan Samarasinghe
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Rasan Samarasinghe
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitRasan Samarasinghe
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationRasan Samarasinghe
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningRasan Samarasinghe
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesRasan Samarasinghe
 

Mais de Rasan Samarasinghe (13)

Managing the under performance in projects.pptx
Managing the under performance in projects.pptxManaging the under performance in projects.pptx
Managing the under performance in projects.pptx
 
Agile project management with scrum
Agile project management with scrumAgile project management with scrum
Agile project management with scrum
 
Introduction to Agile
Introduction to AgileIntroduction to Agile
Introduction to Agile
 
IT Introduction (en)
IT Introduction (en)IT Introduction (en)
IT Introduction (en)
 
Application of Unified Modelling Language
Application of Unified Modelling LanguageApplication of Unified Modelling Language
Application of Unified Modelling Language
 
Advanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST APIAdvanced Web Development in PHP - Understanding REST API
Advanced Web Development in PHP - Understanding REST API
 
Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...Advanced Web Development in PHP - Understanding Project Development Methodolo...
Advanced Web Development in PHP - Understanding Project Development Methodolo...
 
Advanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with GitAdvanced Web Development in PHP - Code Versioning and Branching with Git
Advanced Web Development in PHP - Code Versioning and Branching with Git
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
 
DIWE - File handling with PHP
DIWE - File handling with PHPDIWE - File handling with PHP
DIWE - File handling with PHP
 
DIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web DesigningDIWE - Coding HTML for Basic Web Designing
DIWE - Coding HTML for Basic Web Designing
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
 
DISE - Database Concepts
DISE - Database ConceptsDISE - Database Concepts
DISE - Database Concepts
 

Último

MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 

Último (20)

2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 

Esoft Metro Campus - Certificate in java basics

  • 1. Certificate in Java Basics Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
  • 2. Programme Structure Module 1 1.1 Introduction to Java Module 2 2.1 Getting Start Java Programming Language 2.2 Java Variables Java Objects Java Methods Module 3 3.1 Operators 3.2 Flow Control Module 4 4.1 Access Modifiers 4.2 Non Access Modifiers 4.3 Interfaces Module 5 5.1 Object Orientation Module 6 6.1 String 6.2 String Buffer and String Builder Classes 6.3 Scanner Module 7 7.1 Wrapper classes 7.2 Auto boxing Module 8 8.1 Basic Collection Framework Module 9 9.1 Java Exception
  • 4. 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
  • 5. Features of Java  Object Oriented  Platform independent  Simple  Secure  Portable  Robust  Multi-threaded  Interpreted  High Performance
  • 6. What you can create by Java? • Desktop (GUI) applications • Enterprise level applications • Web applications • Web services • Java Applets • Mobile applications
  • 7. 2.1 Getting Start Java Programming Language
  • 8. Start Java Programming What you need to program in Java? Java Development Kit (JDK) Microsoft Notepad or any other text editor Command Prompt
  • 9. Creating First Java Program public class MyFirstApp{ public static void main(String[] args){ System.out.println("Hello World"); } } MyFirstApp.java
  • 11. 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.
  • 12. Basic Rules to Remember Java is case sensitive… Hello not equals to hello
  • 13. 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
  • 14. 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
  • 15. 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"); } }
  • 16. Basic Rules to Remember Tokens must be separated by Whitespaces Except ( ) ; { } . [ ] + - * / = public class MyFirstApp{ public static void main(String[] args){ System.out.println("Hello World"); } }
  • 18. Comments in Java Programs Comments for single line // this is a single line comment For multiline /* this is a multiline comment */
  • 19. 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 onen line two”);//prints text in two lines
  • 20. 2.2 Java Variables Java Objects Java Methods
  • 21. 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
  • 22. Variable Declaration in Java Variable declaration type variable_list; Variable declaration and initialization type variable_name = value;
  • 23. 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'.
  • 24. Java Objects and Classes
  • 25. Java Classes Method Dog name color bark() class Dog{ String name; String color; public Dog(){ } public void bark(){ System.out.println(“dog is barking!”); } } Attributes Constructor
  • 26. Java Objects Dog myPet = new Dog(); //creating an object //Assigning values to Attributes myPet.name = “Scooby”; myPet.color = “Brown”; //calling method myPet.bark();
  • 27. Methods Method is a group of statements to perform a specific task. • Methods with Return Value • Methods without Return Value
  • 28. Methods with Return Value public int num1, int num2){ int result; if (num1 > num2){ result = num1; }else{ result = num2; } return result; } Access modifier Return type Method name parameters Return value Method body
  • 29. Methods without Return Value public void { System.out.println(“your text: “ + txt) } Access modifier Void represents no return value Method name parameter Method body
  • 30. 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 class Dog myDog = new Dog(“brown”); Constructor String Parameter String Argument
  • 31. Variables in a Class Variables in a Class can be categorize into three types 1. Local Variables 2. Instance Variables 3. Static/Class Variables
  • 32. 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”); } }
  • 33. 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”); } }
  • 34. 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.
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. Logical Operators Operator Name Example && AND (A && B) is False || OR (A || B) is True ! NOT !(A && B) is True A = True, B = False
  • 41. If Statement if(Boolean_expression) { //Statements will execute if the Boolean expression is true }
  • 43. If… Else Statement if(Boolean_expression){ //Executes when the Boolean expression is true }else{ //Executes when the Boolean expression is false }
  • 45. 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. }
  • 46. If… Else if… Else Statement Boolean expression 1 False Statements Boolean expression 2 Boolean expression 3 Statements Statements False False Statements True True True
  • 47. 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 } }
  • 48. Nested If Statement Boolean Expression 1 True False Statements Boolean Expression 2 True False
  • 49. Switch Statement switch (value) { case constant: //statements break; case constant: //statements break; default: //statements }
  • 60. 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
  • 61. 4.2 Non Access Modifiers
  • 62. 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.
  • 64. 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!”); } }
  • 66. Inheritance class Vehicle{ //attributes and methods } class Car extends Vehicle{ //attributes and methods } class Van extends Vehicle{ //attributes and methods } Vehicle Car Van
  • 67. 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”); } }
  • 68. 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”); } }
  • 69. Polymorphism class 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();
  • 70. Encapsulation class student{ private int age; public int getAge(){ return age; } public void setAge(int n){ age = n; } } Data Input Output Method Method Method
  • 72. 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>”); or String <variable name> = “<value>”;
  • 73. Useful Operations with Strings • Concatenating Strings • length() • charAt(<index>) • substring(int <begin index>, int <end index>) • trim() • toLowerCase() • toUpperCase()
  • 74. 6.2 String Buffer and String Builder Classes
  • 75. StringBuffer Class The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. StringBuffer <variable name> = new StringBuffer(" <value> ");
  • 76. StringBuffer Class Methods public 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.
  • 77. 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> ");
  • 78. StringBuilder Class Methods StringBuilder 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.
  • 79. 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
  • 81. 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>”));
  • 82. Scanner Class Methods String 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.
  • 84. 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.
  • 86. 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
  • 87. Wrapper Class Methods Method 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
  • 89. AutoBoxing Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.
  • 90. AutoBoxing Integer intObject = 34; //autoboxing int x = intObject; //unboxing int x = intObject + 7; //unboxing
  • 91. AutoBoxing in Method Invocation public static Integer show(Integer iParam){ System.out.println(iParam); return iParam; } //method invocation show(3); //autoboxing int result = show(3); //unboxing
  • 92. Comparing Objects with equality Operator Integer num1 = 1; // autoboxing int 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 autoboxing Integer anotherOne = new Integer(1); System.out.println("one == anotherOne); // false
  • 93. 8.1 Basic Collection Framework
  • 94. 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).
  • 95. 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.
  • 96. Interfaces on Collection Framework The Collection Interface This enables you to work with groups of objects; it is at the top of the collections hierarchy. The List Interface This extends Collection and an instance of List stores an ordered collection of elements. The Set This extends Collection to handle sets, which must contain unique elements The SortedSet This extends Set to handle sorted sets The Map This maps unique keys to values. The Map.Entry This describes an element (a key/value pair) in a map. This is an inner class of Map. The SortedMap This extends Map so that the keys are maintained in ascending order. The Enumeration This is legacy interface and defines the methods by which you can enumerate (obtain one at a time) the elements in a collection of objects.
  • 97. Implementations on Collection Framework AbstractCollection Implements most of the Collection interface. AbstractList Extends AbstractCollection and implements most of the List interface. AbstractSequentialList Extends AbstractList for use by a collection that uses sequential rather than random access of its elements. LinkedList Implements a linked list by extending AbstractSequentialList. ArrayList Implements a dynamic array by extending AbstractList. AbstractSet Extends AbstractCollection and implements most of the Set interface. HashSet Extends AbstractSet for use with a hash table. LinkedHashSet Extends HashSet to allow insertion-order iterations.
  • 98. Implementations on Collection Framework TreeSet Implements a set stored in a tree. Extends AbstractSet. AbstractMap Implements most of the Map interface. HashMap Extends AbstractMap to use a hash table. TreeMap Extends AbstractMap to use a tree. WeakHashMap Extends AbstractMap to use a hash table with weak keys. LinkedHashMap Extends HashMap to allow insertion-order iterations. IdentityHashMap Extends AbstractMap and uses reference equality when comparing documents.
  • 99. Implementations on Collection Framework Vector This implements a dynamic array. It is similar to ArrayList, but with some differences. Stack Stack is a subclass of Vector that implements a standard last-in, first-out stack. Dictionary Dictionary is an abstract class that represents a key/value storage repository and operates much like Map. Hashtable Hashtable was part of the original java.util and is a concrete implementation of a Dictionary. Properties Properties 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. BitSet A BitSet class creates a special type of array that holds bit values. This array can increase in size as needed.
  • 100. 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.
  • 102. 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
  • 103. Exception Hierarchy Throwable Exception Error IOException RuntimeException ThreadDeath ArithmeticException NullPointerException ClassCastException ******
  • 104. 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.
  • 105. 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 Exceptions by using try catch blocks or throw Exceptions
  • 106. 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.

Notas do Editor

  1. double avg = 45.6567; System.out.println(String.format("%.2f", avg)); // rounds and limit 2 decimal places
  2. There are no any static outer classes in java but “Static inner Classes” public class A { public static void main(String[] args) { B b = new B(); } public static class B { } } Because class B is declared static you can explicitly instantiate as: B b = new B(); Note if class B wasn't declared static to make it stand alone, an instance object call would've looked like this: A a= new A(); B b = a.new B(); Static methods can be called without instantiating an object / Static methods can be called outside of the class directly with the class name ----------------------------------------------------------------------------- Final classes can not be extended ----------------------------------------------------------------------------- Synchronized methods demo program class show{ public synchronized void display(int n){ try{ for(int i=1; i<=5; i++){ System.out.println(i*n); Thread.sleep(1000); } }catch(Exception e){ } } } class rasan implements Runnable{ int n; show s; public rasan(int n, show s){ this.n = n; this.s = s; } public void run(){ s.display(n); } } public class MySync { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here show sh = new show(); Thread x = new Thread(new rasan(10,sh)); Thread y = new Thread(new rasan(100,sh)); x.start(); y.start(); } }
  3. Void welcome() ///Hello world ///Void welcome(“saman”) ////Hello Saman
  4. package scanxan; import java.io.*; import java.util.Scanner; /** * * @author Rasan Samarasinghe */ public class ScanXan { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException{ // TODO code application logic here Scanner s = null; try{ s = new Scanner(new FileReader("xox.txt")); //s.useDelimiter(","); while(s.hasNext()){ System.out.println(s.next()); } }finally{ if(s != null){ s.close(); } } } } //------------------------------------------------------------------- package scansum; import java.io.*; import java.util.Locale; import java.util.Scanner; /** * * @author Rasan Samarasinghe */ public class ScanSum{ /** * @param args the command line arguments */ public static void main(String[] args) throws IOException{ // TODO code application logic here Scanner s= null; double sum = 0; try{ s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt"))); s.useLocale(Locale.US); while(s.hasNext()){ if(s.hasNextDouble()){ sum += s.nextDouble(); }else{ s.next(); } } }finally{ s.close(); } System.out.println(sum); } }
  5. In first example both argument of == operator is primitive int type so no autoboxing occurs and since 1==1 it prints true While in second example during assignment to num1, autoboxing occurs which converts primitive 1 into Integer(1) and when we compare num1==num2 unboxing occurs and Integer(1) is converted back to 1 by calling Integer.intValue() method and since 1==1 result is true. In Third example which is a corner case in autoboxing, both Integer object are initialized automatically due to autoboxing and since Integer.valueOf() method is used to convert int to Integer and it caches object ranges from -128 to 127, it returns same object both time. In short obj1 and obj2 are pointing to same object and when we compare two object with == operator it returns true without any autoboxing. In last example object are explicitly initialized and compared using equality operator , this time == return false because both one and anotherOne reference variables are pointing to different object.
  6. //Collections Interface package collectionsdemo; import java.util.*; /** * * @author Rasan Samarasinghe */ public class CollectionsDemo { public static void main(String[] args) { // TODO code application logic here List a1 = new ArrayList(); a1.add("rasan"); a1.add("indunil"); a1.add("Samarasinghe"); System.out.print("Arraylist elements:"); System.out.println(a1); List l1 = new LinkedList(); l1.add("rasan"); l1.add("indunil"); l1.add("samarasinghe"); System.out.println("linkedlist elements: " + l1); Set s1 = new HashSet(); s1.add("rasan"); s1.add("indunil"); s1.add("samarasinghe"); System.out.println("hashlist elements: "+s1); Map m1 = new HashMap(); m1.put("rasan","3"); m1.put("indunil", "5"); m1.put("samarasinghe", "4"); System.out.println("Map elements: " + m1); } } /* Arraylist vs Linkedlist 1. remove operations give good performance in LinkedList compared to ArrayList. if there is a requirement of frequent addition and deletion in application then LinkedList is a best choice. 2. Search (get method) operations are fast in Arraylist but not in LinkedList If there are less add and remove operations and more search operations requirement, ArrayList would be your best bet. Hashset vs Hashmap HashSet is a set, e.g. {1,2,3,4,5} In the HashSet, there must be no duplicate elements. 2. HashMap is a key -> value (key to value) map, e.g. {a -> 1, b -> 2, c -> 2, d -> 1} In the HashMap there must not be duplicate keys, but it may have duplicate values. */
  7. //Linked List package linkedlistdemo; import java.util.*; public class LinkedListDemo { public static void main(String[] args) { // TODO code application logic here LinkedList ll = new LinkedList(); ll.add("G"); ll.add("C"); ll.add("D"); ll.add("B"); ll.add("E"); ll.addFirst("A"); ll.addLast("Z"); ll.add(1, "A1"); System.out.println("original contents of ll: "+ll); ll.remove("B"); ll.remove(4); System.out.println("contents after deletion: "+ll); ll.removeFirst(); ll.removeLast(); System.out.println("ll after removing first and last: "+ll); Object val = ll.get(2); ll.set(2, val.toString()+val.toString()); System.out.println("ll after change: "+ ll); } } /* void add(int index, Object element) Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index > size()). boolean add(Object o) Appends the specified element to the end of this list. boolean addAll(Collection c) Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator. Throws NullPointerException if the specified collection is null. boolean addAll(int index, Collection c) Inserts all of the elements in the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null. void addFirst(Object o) Inserts the given element at the beginning of this list. void addLast(Object o) Appends the given element to the end of this list. void clear() Removes all of the elements from this list. Object clone() Returns a shallow copy of this LinkedList. boolean contains(Object o) Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)). Object get(int index) Returns the element at the specified position in this list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()). Object getFirst() Returns the first element in this list. Throws NoSuchElementException if this list is empty. Object getLast() Returns the last element in this list. Throws NoSuchElementException if this list is empty. int indexOf(Object o) Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element. int lastIndexOf(Object o) Returns the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element. ListIterator listIterator(int index) Returns a list-iterator of the elements in this list (in proper sequence), starting at the specified position in the list. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()). Object remove(int index) Removes the element at the specified position in this list. Throws NoSuchElementException if this list is empty. boolean remove(Object o) Removes the first occurrence of the specified element in this list. Throws NoSuchElementException if this list is empty. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()). Object removeFirst() Removes and returns the first element from this list. Throws NoSuchElementException if this list is empty. Object removeLast() Removes and returns the last element from this list. Throws NoSuchElementException if this list is empty. Object set(int index, Object element) Replaces the element at the specified position in this list with the specified element. Throws IndexOutOfBoundsException if the specified index is is out of range (index < 0 || index >= size()). int size() Returns the number of elements in this list. Object[] toArray() Returns an array containing all of the elements in this list in the correct order. Throws NullPointerException if the specified array is null. Object[] toArray(Object[] a) Returns an array containing all of the elements in this list in the correct order; the runtime type of the returned array is that of the specified array. */
  8. //Stack package stackdemo; import java.util.*; public class StackDemo { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Stack st = new Stack(); System.out.println(st); st.push(new Integer(10)); System.out.println(st); st.push(new Integer(40)); st.push(new Integer(60)); System.out.println(st); System.out.println(st.peek()); System.out.println(st.pop()); System.out.println(st); System.out.println(st.search(new Integer(70))); } } /* boolean empty() Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements. Object peek( ) Returns the element on the top of the stack, but does not remove it. Object pop( ) Returns the element on the top of the stack, removing it in the process. Object push(Object element) Pushes element onto the stack. element is also returned. int search(Object element) Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned. */
  9. //Algorithms package algorithmsdemo; import java.util.*; public class AlgorithmsDemo { public static void main(String[] args) { // TODO code application logic here LinkedList ll = new LinkedList(); ll.add(new Integer(-8)); ll.add(new Integer(20)); ll.add(new Integer(-20)); ll.add(new Integer(8)); Comparator r = Collections.reverseOrder(); Collections.sort(ll,r); Iterator li = ll.iterator(); System.out.print("list ordered in reverse: "); while(li.hasNext()){ System.out.print(li.next()+" "); } System.out.println(); Collections.shuffle(ll); li = ll.iterator(); System.out.print("list shuffled: "); while(li.hasNext()){ System.out.print(li.next()+" "); } System.out.println(); System.out.println("maximum value: " + Collections.max(ll)); System.out.println("minimum value: " + Collections.min(ll)); } }