+ All Categories
Home > Software > DITEC - Programming with Java

DITEC - Programming with Java

Date post: 19-Feb-2017
Category:
Upload: rasan-samarasinghe
View: 99 times
Download: 0 times
Share this document with a friend
73
Diploma in Information Technology Module VIII: Programming with Java Rasan Samarasinghe ESOFT Computer Studies (pvt) Ltd. No 68/1, Main Street, Pallegama, Embilipitiya.
Transcript
Page 1: DITEC - Programming with Java

Diploma in Information Technology

Module VIII: Programming with Java

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

Page 2: DITEC - Programming with Java

Contents1. Introduction to Java2. Features of Java3. What you can create by Java?4. Start Java Programming5. Creating First Java Program6. Java Virtual Machine7. Basic Rules to Remember8. Keywords in Java9. Comments in Java Programs10. Printing Statements11. Primitive Data Types in Java12. Arithmetic Operators13. Assignment Operators14. Comparison Operators15. Logical Operators16. If Statement17. If… Else Statement18. If… Else if… Else Statement19. Nested If Statement

20. While Loop21. Do While Loop22. For Loop23. Reading User Input24. Arrays25. Two Dimensional Arrays26. Objects and Classes27. Java Classes28. Java Objects29. Methods with Return Value30. Methods without Return Value31. Method Overloading32. Variable Types33. Inheritance34. Method Overriding35. Access Modifiers36. Packages37. GUI Applications in Java38. Java Applets

Page 3: DITEC - Programming with 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

Page 4: DITEC - Programming with Java

Features of Java

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

Page 5: DITEC - Programming with Java

What you can create by Java?

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

Page 6: DITEC - Programming with Java

Start Java Programming

What you need to program in Java?

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

Page 7: DITEC - Programming with Java

Creating First Java Program

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

MyFirstApp.java

Page 8: DITEC - Programming with Java

Java Virtual Machine (JVM)

Page 9: DITEC - Programming with Java

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.

Page 10: DITEC - Programming with Java

Basic Rules to Remember

Java is case sensitive…

Hello not equals to hello

Page 11: DITEC - Programming with Java

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

Page 12: DITEC - Programming with Java

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

Page 13: DITEC - Programming with 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");}}

Page 14: DITEC - Programming with Java

Basic Rules to Remember

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

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

Page 15: DITEC - Programming with Java

Keywords in Java

Page 16: DITEC - Programming with Java

Comments in Java Programs

Comments for single line

// this is a single line comment

For multiline

/* this is a multilinecomment*/

Page 17: DITEC - Programming with Java

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

Page 18: DITEC - Programming with Java

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

Page 19: DITEC - Programming with Java

Variable Declaration in Java

Variable declarationtype variable_list;

Variable declaration and initializationtype variable_name = value;

Page 20: DITEC - Programming with Java

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'.

Page 21: DITEC - Programming with Java

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

Page 22: DITEC - Programming with Java

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

Page 23: DITEC - Programming with Java

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

Page 24: DITEC - Programming with Java

Logical Operators

Operator Name Example

&& AND (A && B) is False

|| OR (A || B) is True

! NOT !(A && B) is True

A = True, B = False

Page 25: DITEC - Programming with Java

If Statement

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

expression is true}

Page 26: DITEC - Programming with Java

If Statement

Boolean Expression

Statements

True

False

Page 27: DITEC - Programming with Java

If… Else Statement

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

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

false}

Page 28: DITEC - Programming with Java

If… Else Statement

Boolean Expression

Statements

True

False

Statements

Page 29: DITEC - Programming with Java

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.}

Page 30: DITEC - Programming with Java

If… Else if… Else Statement

Boolean expression 1

False

Statements

Boolean expression 2

Boolean expression 3

Statements

Statements

False

False

Statements

True

True

True

Page 31: DITEC - Programming with Java

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 }}

Page 32: DITEC - Programming with Java

Nested If Statement

Boolean Expression 1

True

False

StatementsBoolean Expression 2

True

False

Page 33: DITEC - Programming with Java

While Loop

while(Boolean_expression){ //Statements}

Page 34: DITEC - Programming with Java

While Loop

Boolean Expression

Statements

True

False

Page 35: DITEC - Programming with Java

Do While Loop

do{ //Statements}while(Boolean_expression);

Page 36: DITEC - Programming with Java

Do While Loop

Boolean Expression

Statements

True

False

Page 37: DITEC - Programming with Java

For Loop

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

Page 38: DITEC - Programming with Java

For Loop

Boolean Expression

Statements

True

False

Update

Initialization

Page 39: DITEC - Programming with Java

Nested Loop

Boolean Expression

True

False

Boolean Expression

Statements

True

False

Page 40: DITEC - Programming with Java

Reading User Input by the Keyboardimport java.io.*;

public class DemoApp{public static void main(String [] args) throws IOException{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.print(“Enter your text: “);String txt = br.readLine();System.out.println(“You have entered:” + txt);}}

Page 41: DITEC - Programming with Java

Arrays

10 30 20 50 15 35

0 1 2 3 4 5

Size = 6

Element Index No

An Array can hold many values in a same data type under a single name

A single dimensional array

Page 42: DITEC - Programming with Java

Building a Single Dimensional Array

// Creating an ArrayDataType[] ArrayName = new DataType[size];

// Assigning valuesArrayName[index] = value;ArrayName[index] = value;……..

Page 43: DITEC - Programming with Java

Building a Single Dimensional Array

char[] letters = new char[4];

letters[0] = ‘a’;letters[1] = ‘b’;letters[2] = ‘c’;letters[3] = ‘d’;

0 1 2 3

a b c d

0 1 2 3

letters

letters

Values in an Array can access by referring index number

Page 44: DITEC - Programming with Java

Building a Single Dimensional Array

//using an array initializerDataType[] ArrayName = {element 1, element 2,

element 3, … element n}

int[] points = {10, 20, 30, 40, 50}; 10 20 30 40

0 1 2 3

points

50

4

Page 45: DITEC - Programming with Java

Manipulating Arrays

Finding the largest value of an Array

Sorting an Array

15

50

35

25

10

2

1

5

4

3

1

2

3

4

5

Page 46: DITEC - Programming with Java

Two Dimensional Arrays

10 20 30

100 200 300

0 1 2

0

1

int[][] abc = new int[2][3];

abc[0][0] = 10;abc[0][1] = 20;abc[0][2] = 30;abc[1][0] = 100;abc[1][1] = 200;abc[1][2] = 300;

Rows Columns

Column Index

Row Index

Page 47: DITEC - Programming with Java

Java Objects and Classes

Page 48: DITEC - Programming with Java

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

Page 49: DITEC - Programming with Java

Java Objects

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

//calling methodmyPet.bark();

Page 50: DITEC - Programming with Java

Methods

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

• Methods with Return Value• Methods without Return Value

Page 51: DITEC - Programming with Java

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

Page 52: DITEC - Programming with Java

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

Page 53: DITEC - Programming with Java

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”);}

}

Page 54: DITEC - Programming with Java

Variable Types

Variables in a Class can be categorize into three types

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

Page 55: DITEC - Programming with Java

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”);}

}

Page 56: DITEC - Programming with Java

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”);}

}

Page 57: DITEC - Programming with Java

Static/Class Variables

• 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.

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

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

}

Page 58: DITEC - Programming with Java

Inheritance

class Vehicle{//attributes and methods}

class Car extends Vehicle{//attributes and methods}

class Van extends Vehicle{//attributes and methods}

Vehicle

Car Van

Page 59: DITEC - Programming with Java

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”);}}

Page 60: DITEC - Programming with Java

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

Page 61: DITEC - Programming with Java

Packages

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and annotations) providing access protection and namespace management.

//At the top of your source codeimport <package name>.*;import <package name>.<class name>;

Page 62: DITEC - Programming with Java

GUI Applications in Java

• Abstract Window Toolkit• Frame Class• Layouts• Label Class• TextField Class• Button Class• Events

Page 63: DITEC - Programming with Java

Abstract Window Toolkit

The Abstract Window Toolkit (AWT) is a package of JDK classes for creating GUI components such as buttons, menus, and scrollbars for applets and standalone applications.

import java.awt.*;

Page 64: DITEC - Programming with Java

Frame Class

Frame myFrame = new Frame(“My Frame”);myFrame.setSize(300,200);myFrame.setVisible(true);

Page 65: DITEC - Programming with Java

LayoutsmyFrame.setLayout(new FlowLayout()); myFrame.setLayout(new GridLayout(2,3));

myFrame.setLayout(null);

Page 66: DITEC - Programming with Java

Label Class

Label lbl = new Label("Hello World");lbl.setBounds(120,40,120,25);myFrame.add(lbl);

Page 67: DITEC - Programming with Java

TextField Class

TextField txt = new TextField();txt.setBounds(100,90,120,25);myFrame.add(txt);

Page 68: DITEC - Programming with Java

Button Class

Button btn = new Button("OK");btn.setBounds(120,150,60,25);myFrame.add(btn);

Page 69: DITEC - Programming with Java

Events

An event is when something special happens within a Graphical User Interface.

Things like buttons being clicked, the mouse moving, text being entered into text fields, the program closing, etc.. then an event will trigger.

Page 70: DITEC - Programming with Java

How Events Handling Work?

Page 71: DITEC - Programming with Java

Java Applets

An applet is a Java program that runs in a Web browser.

Page 72: DITEC - Programming with Java

Creating a Java Applet

import java.applet.*;import java.awt.*;

public class HelloWorldApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello World", 25, 50); } }

<applet code="HelloWorldApplet.class" width="320" height="120"></applet>

Write a Java Applet and compile it

Embed it in a HTML file

Page 73: DITEC - Programming with Java

The End

http://twitter.com/rasansmn


Recommended