61
Java Introduction Prepared by: Ragab Mustafa

Java introduction

Embed Size (px)

DESCRIPTION

Presentation about Java Programming

Citation preview

Page 1: Java introduction

Java Introduction

Prepared by: Ragab Mustafa

Page 2: Java introduction

Agenda

• Overview of Programming Languages.• What’s and why Java.• What’s Eclipse .• Writing first program in Java.• Basics of java programming Language.• Variables, Operators and Types.• Methods, Conditionals and Loops.

Page 3: Java introduction

Agenda cont.

• Classes, Arrays and objects.• Solving a problems in Java.• Object-oriented Programming(OOP).• Inheritance.

Page 4: Java introduction

Overview of Programming Languages.

• There are three types of programming languages:

Machine Languages that encoded in 1’s and 0’s, that’s hard to write program in these languages.

Low Level Languages(e.g. Assembly)it’s close to the machine code but not the same also it’s easer to write and read(understand).

High Level Languages (e.g. C,C++,Java and C#)these Languages needs a compiler to translate the program into machine code.

Page 5: Java introduction

What’s Java

• Java is an OOP language developed at Sun Microsystems Labs by James Gosling at 1991.

• The first version called “OAK” but at 1995 “Netscape” announced that Java would be incorporated into Netscape Navigator.

• Sun formally announced Java at a major conference in May 1995.

• it is also a good not only in “object-oriented programming “but also in “general programming language”.

Page 6: Java introduction

Why Java

• Java has some advantages make it differ from the other languages as:

o That it is platform independent(mean work well in the internet). It achieves this by using something called the ‘Java Virtual Machine’ (JVM).

o It’s a free source language.

Page 7: Java introduction

Why Java cont.

• Also it’s 1. Simple Architecture neutral .2. Object oriented Portable .3. Distributed High performance .4. Multithreaded Robust .5. Dynamic Secure.

Page 8: Java introduction

What’s Eclipse

• Eclipse is a portable IDE for java it’s easy and powerful.

• There are more than one IDE for java as NetBeans, JBuilder and JDeveloper.

Page 9: Java introduction

Prepare your PC and yourself!

• First you must download JDK from sun or go to here.

• Then run the IDE that you will treat with it here we will work by Eclipse.

• To download Eclipse IDE go to here or go to the home page of Eclipse .

• Just you download the IDE (hint: Eclipse is portable not installed) run it that will Explained by video.

Page 10: Java introduction

The first program in java

• Write the program:public class FirstProgram

{public static void main (String[] args)

{System.out.print("Hello, 2 + 3 = ");System.out.println(5);System.out.println("Good Bye");}

}

Page 11: Java introduction

Basics of Java

• Program Structureclass CLASSNAME {public static void main(String[] args)

{STATEMENTS

}}

Page 12: Java introduction

Variables• Named location that stores a value• Form:

TYPE NAME;• Example:

String fName;class Hello {public static void main(String[] arguments)

{String fName = “ragab”;System.out.println(fName);fName = "Something else";System.out.println(fName);}

}

Page 13: Java introduction

Types

• Limits a variable to kinds of valuesString: plain text (“hello”)double: Floating-point, “real” valued number(3.14, -7.0) int: integer (5, -18)

String fName = “hello”;double Pi = 3.14;

Page 14: Java introduction

Types

• Order of Operations :Precedence like math, left to right.Right hand side of = evaluated first.

double x= 20double x =3 / 2+ 1; // x= 2.0

• Conversion by casting Int a = 2; // a = 2double a = (double)2; // a = 2.0 double a = 2/3; // a = 0.0double a = (double)2/3; // a = 0.6666… int a = (int)18.7; // a=18

Page 15: Java introduction

Types

• Conversion by method:o Int to String:

String five = Integer.toString(5);String five = “” + 5; // five = “5”

o String to int:Int a=Integer.parseInt(“18”);

• Mathematical Functions:o Math.sin(x) o Math.cos(Math.PI / 2)o Math.log(Math.log(x + y))

Page 16: Java introduction

Operators

• Symbols that perform simple computations• Assignment: =• Addition: +• Subtraction: -• Multiplication: *• Division: /

Page 17: Java introduction

Example

class Math {public static void main(String[] arguments){int score;score = 1 + 2 * 3;System.out.println(score);double copy = score;copy = copy / 2;System.out.println(copy);score = (int) copy;System.out.println(score);}

}

Page 18: Java introduction

Methods

• Adding Methods public static void NAME() { STATEMENTS }

• To call a method:NAME();

• Parameters public static void NAME(TYPE NAME) { STATEMENTS }

• To call: NAME(EXPRESSION);

Page 19: Java introduction

Methods

• Example:class Square {

Public static void printSquare(int x){System.out.println(x*x);}

public static void main(String[] arguments){ int value = 2;printSquare(value);printSquare(3);printSquare(value*22); }

}

Page 20: Java introduction

Methods

• Multiple Parameters[…] NAME(TYPE NAME, TYPE NAME) {STATEMENTS } NAME(arg1, arg2);

• Return Values public static TYPE NAME() { STATEMENTS return EXPRESSION; }

void means “no type”

Page 21: Java introduction

Conditionals

• if statement if (COMPARISON) {STATEMENTS }

• Example:class If {

public static void test((int x)) { if (x > 5){

System.out.println((x + " is > 5");}

} public static void main(String[] arguments){

test(6); test(5); test(4); }

}

Page 22: Java introduction

Conditionals

• Comparison operators x > y: x is greater than y x< y: x is less than yx >= y: x is greater than or equal to y x <= y: x is less than or equal to y x == y: x equals y (assignment: =)

Page 23: Java introduction

Conditionals

• else if (COMPARISON) {STATEMENTS } else { STATEMENTS }

• else if if (COMPARISON) {STATEMENTS} else if (COMPARISON) { STATEMENTS } else if (COMPARISON) { STATEMENTS } else { STATEMENTS }

Page 24: Java introduction

Conditionals• Example

public static void test(int x){ if (x > 5){System.out.println(x + " is > 5");} else if (x == 5){System.out.println(x + " equals 5");} else {System.out.println(x +”is < 5"); } } public static void main(String[] arguments){ test(6); test(5); test(4); }

Page 25: Java introduction

Loopsstatic void main (String[] arguments) {System.out.println(“This is line 1”);System.out.println(“This is line 2”);System.out.println(“This is line 3”);}

• What if you want to do it for 200 lines?• Loop operators allow to loop through a block

of code. • There are several loop operators in Java.

Page 26: Java introduction

Loops

• The while operator:while (condition) {statement}

• Example:int i = 0;while (i < 3) {System.out.println(“This is line “ + i);i = i+1;}

• Count carefully • Make sure that your loop has a chance to finish.

Page 27: Java introduction

Loops

• The for operator:for (initialization;condition;update){statement}

• Example:int i;for (i = 0; i < 3; i=i++) {System.out.println (“This is line “ + i);}

• Embedded loops:for (int i = 0; i < 3; i++) {for (int j = 2; j < 4; j++){System.out.println (i + “ “ + j);} }

• Scope of the variable defined in the initialization: respective for block

Page 28: Java introduction

Loops

• Branching Statements :• break terminates a for or while loop

for (int i=0; i<100; i++) {if(i ==terminationValue)break;else {...}}

• continue skips the current iteration of a for or while loop and proceeds directly to the next iteration

for (int i=0; i<100; i++) {if(i == skipValue)continue;else {...}}

Page 29: Java introduction

Arrays

• An array is an indexed list of values.• You can make an array of int, of double, of

String,etc.All elements of an array must have the same type.

• This array contain n elements.

0 1 2 3 n-1

Page 30: Java introduction

Arrays

• An array is noted using [] and is declared in the usual way:

int values[]; // empty array int[] values; // equivalent declaration

• To create an array of a given size, use the operator new :

int values[] = new int[5];

• or you may use a variable to specify the size: int size = 12;int values[] = new int[size];

Page 31: Java introduction

Arrays

• Array Initialization:• Curly braces can be used to initialize an array in

the array declaration statement (and only there).int values[] = { 12, 24, -23, 47 };

• To access the elements of an array, use the [] operator: values[index]

• Example: int values[] = { 12, 24, -23, 47 };values[3] = 18; // writeint x = values[1] + 3; // read

Page 32: Java introduction

Arrays• Each array has a length variable built-in that contains the length of the array.

int values[] = new int[12];int size = values.length; // 12

• Looping through an array• Example :

int values[] = new int[5];for (int i=0; i<values.length; i++) {values[i] = i;int y = values[i] *values[i];System.out.println(y);}

• Another one:double values[] = new double[25];int j=0;while (j<values.length) {...j++;}

Page 33: Java introduction

• Objects are a collection of related data and methods.

• Example: • Strings A string is a collection of characters

(letters) and has a set of methods built in. String nextTrip = “Mexico”; int size = nextTrip.length(); // 6

Objects

Page 34: Java introduction

Objects

• To create a new object, use the new operator. If you do not use new, you are making a reference to an object (i.e. a pointer to the same object).

Point p; p.x = 23; p.y = -12; public static Point middlePoint (Point p1, Point p2) { Point q = new Point ((p1.x+p2.x)/2, (p1.y+p2.y)/2); return q; }

Page 35: Java introduction

Classes

• A class is a prototype to design objects.• It is a set of variables and methods that

encapsulates the properties of the class of objects.

• In Java, you can (will) create several classes in project.

• A class constructor is called each time an object of the class is instantiated (created).

Page 36: Java introduction

Packages

• A package is a set of classes that relate to a same purpose.

• Example: math, graphics, input/output... • In order to use a package, you have to import

it. package

class class class

object

Page 37: Java introduction

Object Oriented Programming

• Objects are a collection of related data and methods.

• To create a new object, use the new operator. If you do not use new, you are making a reference to an object (i.e a pointer to the same object).

Page 38: Java introduction

Objects and references

Point p1 = new Point (12,34);Point p2 = p1;System.out.println(“x = “ + p2.x); // 12p1.x = 24;System.out.println(“x = “ + p2.x); // 24!

Page 39: Java introduction

The null object

• null simply represents no object. It is convenient

• as a return value to mean that a method failed for example. It may also be used to “remove” an element from an array. String values[] = { “ragab”, “ahmed”, “zidan” };values[1] = null;

Page 40: Java introduction

Object methods v.s. class methodsclass Bicycle {static int gear, speed;public static void speedUp (Bicycle b) {b.speed += 10;}public static void main (String[] arguments) {Bicycle bike1 = new Bicycle();speedUp (bike1); }}

• static means that the variable is going to be same for all objects of the class.

• Class methods are declared static.• static = the same for all objects• nonstatic = different for each object

Page 41: Java introduction

Abstraction

• Objects are tools for abstraction. • Abstraction is a fundamental concept in

computer science. • In Java, objects are instances of a class. • A class contains variables and methods that

capture the essence of the object. • An object is instantiated using new

Page 42: Java introduction

Why is abstraction important?

• Modularity (allows to subdivide a big problem into smaller sub-problems)

• Powerful representation of real-world problems

Page 43: Java introduction

Inheritance

• In the world, people inherit characteristics from their parents.

• In computer science, objects inherit variables and methods from their parents.

• When you define a class in Java, you may define it as a subclass of another class (its parent).

Page 44: Java introduction

Why inheritance and it’s rules?

• Avoid duplicate code • Improve modularity

Inheritance rules• The subclass inherits all variables and methods • Use the extends keyword to indicate that one

class inherits from another • Use the super keyword in the subclass

constructor to call the parent constructor

Page 45: Java introduction

Modularity

Page 46: Java introduction

Examplepublic class Vehicle {public int nWheels; // number of wheelspublic Vehicle (int n) {nWheels = n;}int getNWheels () {return nWheels;}}

• ----------------------------------------public class Car extends Vehicle {public Car (int n) {super (n);}public void openWindow() {}}

Page 47: Java introduction

Examplepublic class Bicycle extends Vehicle {public Bicycle (int n) {super (n);}public void freeStyle() {}}

• -------------------------------------public class World {public static void main (String[] args) {Bicycle bike = new Bike (2);Car car = new Car (4);System.out.println (“Car has “ +car.getNWheels() + “ wheels”);System.out.println (“Bike has “ +bike.getNWheels() + “ wheels”);}}

Page 48: Java introduction

OOP: Scope & Visibility

• Scope: – A variable cannot be used outside of the curly braces (“{...}”) in which it is declared. – E.g., Class-level variables (fields) are usable

everywhere in the class; loop variables are only usable in the scope of the loop

Page 49: Java introduction

OOP: Scope & Visibility

• Visibility: – public fields, methods, & constructors can be “seen” or

used directly by all classes & subclasses – protected fields, methods, & constructors can only be

seen or used from within their class or subclasses – private fields, methods, & constructors can only be seen

or used from within their exact class (in general, most or all of a class’s fields should be private)

– Fields, methods, and constructors with unspecified (“default” or “package”) visibility can be seen by some classes – more on this later

Page 50: Java introduction

OOP: Getter & Setter Methods

• Another way to access or modify fields • Good programming practice • Widely-used convention in Java • Also called accessors and mutators • Don’t come for free, but very useful when

dealing with private or protected fields

Page 51: Java introduction

OOP: Ecapsulation

• The Principle of Encapsulation • Allows one to access and change the internals

of a class, without having “direct access” • Visibility, Accessors, & Mutators are vital tools

for this OOP principle

Page 52: Java introduction

OOP: this

• A way for an instance of class to refer to itself– E.g.: say Engineer has a field called trafficHours and a setter

method with this signature: – public void setTrafficHours(int trafficHours);– How to resolve scope? – Solution: use this.trafficHours = trafficHours; – this does not work inside static methods

• Good programming practice • Standard Java convention • Does come for free, has many uses

Page 53: Java introduction

Inheritance & Abstraction

• A class can extend another (single) class• Subclasses inherit methods and variables from

their parents • This allows us to use objects to form an

hierarchy of representations • Classifications of objects and relationships

between them can now be modeled!

Page 54: Java introduction

Inheritance & Abstraction:The Object class

• Every class implicitly extends Object• So, in Java, every object is an Object… • “Class Object is the root of the class hierarchy.

Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.” – from the Java API

• Core and backbone of OOP in Java • Methods of note are equals(Object) and

toString() – more on these later

Page 55: Java introduction

Inheritance & Abstraction:Overriding & Overloading

• What if we want a subclass’s inherited method to do something different than that of its parent? – Override it!

• What if we want multiple constructors for a class, or methods with the same name but different arguments? – Overload them!

Page 56: Java introduction

Inheritance & Abstraction:Overriding & Overloading

• Overriding: re-defining an inherited method • E.g., Say every Manager gets a weekly bonus

of amount weeklyBonus (which would be defined somewhere in the class)

• To reflect this, we can override the weeklyPay() method simply by explicitly defining it again in Manager, with the desired changes

Page 57: Java introduction

Inheritance & Abstraction:Overriding & Overloading

• Overloading: method or constructor with same name and type as another, but with a different signature (i.e., takes different number, ordering, or types of arguments)

• Cannot have methods with same name and arguments and different return type

Page 58: Java introduction

Method Overriding

• Method overriding occurs when a subclass implements a method that is already implemented in a superclass. The method name must be the same, and the parameter and return types of the subclass's implementation must be subtypes of the superclass's implementation. You cannot allow less access than the access level of the superclass's method.

eg, class Timer { public Date getDate(Country c) { ... } } class USATimer { public Date getDate(USA usa) { ... } }

Page 59: Java introduction

Method Overloading

• Method overloading is when two methods

share the same name but have a different number or type of parameters.

eg, public void print(String str) { ... } public void print(Date date) { ... }

Page 60: Java introduction

References

• Java how to program, book.• Essential Java for scientists and Engineering,

book.• MIT Lectures.• Tutorial from sun.

Page 61: Java introduction

THANK YOU FOR ATTENTION