30
JAVA Programming Basic Chapter 2

JAVA P rogramming B asic

  • Upload
    jersey

  • View
    32

  • Download
    0

Embed Size (px)

DESCRIPTION

JAVA P rogramming B asic. Chapter 2. Chapter 2. 2.0 Java Programming Basic 2.1 Structured language vs OOP language 2.2 Introduction to JAVA Application 2.3 Data Types 2.4 Control Structures 2.5 Array 2.6 Packages. Structured language vs OOP language. Structured language. - PowerPoint PPT Presentation

Citation preview

Page 1: JAVA P rogramming  B asic

JAVA Programming Basic

Chapter 2

Page 2: JAVA P rogramming  B asic

Chapter 2

2.0 Java Programming Basic 2.1 Structured language vs OOP language 2.2 Introduction to JAVA Application 2.3 Data Types 2.4 Control Structures 2.5 Array 2.6 Packages

Page 3: JAVA P rogramming  B asic

Structured language vs OOP language

A programming language where the program may be broken down into blocks or procedures which can be written without detailed knowledge of the inner workings of other blocks, thus allowing a top-down design approach.

The use of a class of programming languages and techniques based on the concept of an “object” which is a data structure (abstract data type) encapsulated with a set of routines, called “methods”, which operate on the data. Operations on the data can only be performed via these methods, which are common to all objects that are instances of a particular “class”. Thus the interface to objects is well defined, and allows the code implementing the methods to be changed so long as the interface remains the same.

Structured language Object-oriented programming

Taken from dictionary.die.net

Page 4: JAVA P rogramming  B asic

Structured Programming

Dividing a problem into smaller subproblem structured design. Each subproblem is then analyzed, and solution or the

subproblem is obtained. The solution to all the subproblem are then combined to solve

the overall problem. The process of implementing a strutted design is called structured

programming. Is also known as:

Top-down design, Stepwise refinement, Modular programming

Page 5: JAVA P rogramming  B asic

Object-oriented Programming

In Object-oriented Design (OOD)

The first step in the problem solving process: To identify the components called objects, form the basic of

the solution Determine how these objects interact with one another. e.g: You want to write a program that automates the video

rental process for a local video stores. Two main object: The video The customer

Page 6: JAVA P rogramming  B asic

Object-oriented Programming

After identifying the objects, the next step is: To specify the relevant data for each object and possible

operations to be performed on the data. e.g: video objects

The data might be :- movie name, actors, producer.The operation might be :- check the name of the movie, reduce the number of copies in stock by one after a copy is rented.

Page 7: JAVA P rogramming  B asic

Object-oriented Programming

In OOD The final program:

Is a collection of interacting objects A programming language that implements OOD is called an OOP. To work with objects you need to know how to combine data and

operations on that data into a single unit is called class.

Page 8: JAVA P rogramming  B asic

Object-oriented Programming

In OOP: Object

Consists of: Data The operations on those data.

Combines: Data Operations on the that data into a single unit.

Page 9: JAVA P rogramming  B asic

History of JAVA

Initially designed at Sun Microsystems by James Gosling in 1991 as a language that was embedded in consumer electronic items. The language was named as OAK.

In 1993, the growth of internet phenomena, OAK was adapted into internet to create dynamic and interactive web pages.

Sun created web browser named HotJava, was programmed using OAK language called JAVA.

JAVA not only used for web application but also as a general purpose programming language

Introduction of JAVA Application

Page 10: JAVA P rogramming  B asic

Introduction of JAVA Application

JAVASimple

Dynamic

Object Oriented

Distributed

Interpreted Robust

Secure

Portable

Performance

Multithread

Page 11: JAVA P rogramming  B asic

No Characteristic Description1. Simple Java is partially modeled on C++, but greatly simplified

and improved

2. Dynamic Java was designed to adapt to an evolving environment. New code can be loaded on the fly without recompilation.

3. Object Oriented programming in Java is centered on creating objects, manipulating objects, and making objects work together.

4. Distributed involves several computers working together on a network. Java is designed to make distributed computing easy.

5. Interpreted Java programs are compiled into the Java Virtual Machine code called bytecode, and it is machine independent.

Characteristics of JAVA

Page 12: JAVA P rogramming  B asic

Characteristics of JAVA

No Characteristic Description6. Robust Reliability because it puts a lot of emphasis on early

checking for possible errors. Java has a runtime exception-handling feature to provide programming support for robustness.

7. Secure As an Internet programming language, Java is used in a networked and distributed environment. Java implements several security mechanisms to protect your system against harm caused by stray program.

8. Portable Java is architecture neutral. It can run in any platform without being recompiled. The Java environment is portable to new hardware and operating systems

9. Performance Java’s performance is sometimes criticized compared to C++. Because Java is interpreted, the bytecode is not directly executed by the system, but is run through the interpreter.

10. Multithread a program’s capability to perform several tasks simultaneously.

Page 13: JAVA P rogramming  B asic

Executing C++ Program

Program in PCMachine language

Program in SUNMachine language

Program in MACMachine language

myProg.cpp

Source File

C++ Compiler for PC

C++ Compiler for SUN

C++ Compiler for MAC

C++ and JAVA

Page 14: JAVA P rogramming  B asic

myProg.java

JAVACompli

erSource File(Java Program)

JAVAInterpreterJVM/JRELibrary

files

myProg.class

The compiled program is in the form of bytecode – the same for all machines

C++ and JAVA

Executing JAVA program

Page 15: JAVA P rogramming  B asic

Feature C++ JAVA1 Design

goalsTo design a distributed OS For programming consumer

device

2 Designer Bjarne Stroustrup.AT&T Bell Labs in 1979

James Gosling et.al.Sun Microsystems in 1990

3 Language paradigm

Hybrid OO = structured + OO

OO paradigm only

4 Prior language influence

Syntax based on C. Efficient styles based on Simula67

Syntax based on C++, approach based on Smalltalk

5 Strengths A high performance and powerful language

Cross-platform compatibility

6 Compilation Compilation-based – like most language C++ source file -> binary file (*.exe)

Compiled + Interpreted basedJava source file -> Java bytecode -> JVM to execute

C++ vs JAVA

Page 16: JAVA P rogramming  B asic

Feature C++ JAVA7 Architecture

-neutral and portability

Platform-dependent binary code cannot be executed on a difference machine

Platform-independent bytecode can run on any machine supporting JVM

8 Simplicity More complex – pointer, operator overloading and etc.

Simpler – no pointer, no overloading and etc.

9 Performance

About 1~20 times faster than equivalent JAVA code

Much slower than C++, but good enough to run interactively for most application

10

Robustness Was not designed for robustness

Originally designed for writing highly reliable or robust software.

C++ vs JAVA

Page 17: JAVA P rogramming  B asic

Feature C++ JAVA11

Security Memory is handled at compile-time by compiler

Byte-code is verified at run-time to ensure security restrictions are not violated.Memory layout is handled at run-time by JVM.

12

Networking Not a network-capable language.Network programming : harder

A network-capable language.Network programming: easier.

13

Multi-threaded (concurrent programming)

Single-threaded – rely on external libraries for multithreading

Multi-treaded language – provides native multithreading support.

C++ vs JAVA

Page 18: JAVA P rogramming  B asic

Identifier is a name given to variable, constant and method name other than reserved word

It can be alphabet, numeric, underscore(_) or dollar sign ($) The name must begin with alphabet, underscore(_) or dollar

sign($) It is case sensitive Cannot be JAVA reserved word Example valid identifier name :

total _total $total total5

Identifiers

Page 19: JAVA P rogramming  B asic

abstract continue goto package synchronized

assert default if private this

Boolean do implements protected throw

break double import public throws

byte else instanceof return transient

case extends int short try

catch final interface static void

char finally long strictfp volatile

class float native super while

const for new switch

JAVA Reserved Words

Page 20: JAVA P rogramming  B asic

Primitive data types◦ Simple data types, also referred to as built-in types◦ Different category

Boolean type – boolean Integral type – byte, int, long, char Floating type –float, double

Reference data type◦ Either with a class, array or interface◦ Refers to object◦ Different category

Class types – such as String Array types Interface types

Constant data types◦ Declare using keyword final eg. final double PI = 3.142;◦ Constant declared inside a class using the keyword static

eg. static final double PI = 3.142;

Data Types

Page 21: JAVA P rogramming  B asic

String class is part of java.lang package which is automatically included during compilation

Some operation used in String class toUpperCase() toLowerCase() length() charAt() substring() replace()

String

Page 22: JAVA P rogramming  B asic

String name;

name = “Abraham Lincoln”;

name = name.toUpperCase(); //ABRAHAM LINCOLN

name = name.toLowerCase(); //abraham lincoln

int x = name.length(); //return the how many characters =15

name = name.charAt(2); //return a character in position 2

Name = name.substring(5); //return the whole word starting position 5

// = ham Lincoln

Name = name.substring(5, 3) //return the word of length 3 starting

// from position 5 = ham

**position in a string always starts with 0

Example of String Operations

Page 23: JAVA P rogramming  B asic

Selection structure◦ Make decision – branching statement◦ Similar to C++

if statement if…else statement nested if statement switch statement

Iteration structure◦ Repetition – similar to C++

for statement while statement do…while statement nested loop break and continue

Control Structure

Page 24: JAVA P rogramming  B asic

An array is a collection of data value An array is an indexed value of the same type Array of primitive data types

Declarationdatatype variablename []; or datatype [] variablename;

Array creation e.g. variablename = new dataype[size of array];

Array

Page 25: JAVA P rogramming  B asic

Example

double[] rainfall; //declare an arrayrainfall = new double[12]; //create array

Page 26: JAVA P rogramming  B asic

Consist of one or more individual classes that are stored in the same directory.

Those classes packaged are usually related in providing similar objects and methods

It facilitates software reuse by allowing programs to import classes from other packages libraries to be shared by many users

For example to use PrintStream class in contained in java.io package, you need to include keyword import in front of the package name

import java.io.*;Then you can use the print() and println() method provided by the PrintStream class

Packages

Page 27: JAVA P rogramming  B asic

Using I/O console◦ Using Scanner class◦ Create a Scanner object by passing an input stream to the

constructor Scanner s = new Scanner(System.in);◦ You can use these method to read the data from the keyboard :

Integer data value = nextInt() Decimal data value = nextDouble(); String data value = next();

◦ Example : Scanner s = new Scanner(System.in); int num = s.nextInt(); String name = s.next();

Input Statement

Page 28: JAVA P rogramming  B asic

Input Statement

Using dialog box You need to use javax.swing.JOptionPane package The method used is showInputDialog, and it has String parameter

which is a message displayed on the monitor. The method returns String value if user enters a value and null value if user

cancels the input The String value can be converted to numeric by the used of these method

Integer = Integer.parseInt() Double = Double.parseDouble() Foat = Float.parseFloat()

Exampleimport javax.swing.*; --

String input = JOptionPane.showInputDialog(null, “Enter an integer number “);

int num = Integer.parseInt();

Page 29: JAVA P rogramming  B asic

Using I/O Console By using System.out object through the method print() or println()

Example int total = 4 +5; System.out.print(“The total is “); System.out.println(total); System.out.println(“The total is “ + total);

Output Statement

Page 30: JAVA P rogramming  B asic

Output Statement

Using dialog box You need to use javax.swing.JOptionPane package The method used is showMessageDialog, and it has String

parameter which is a message displayed on the monitor screen

Example import javax.swing.*; -- JOptionPane.showMessageDialog(null,”Hello World!”); String s1 = “JAVA is fun”; JOptionPane.showMessageDialog(null, s1);