programming in java lecture-2 java introduction. platform computing platform include hardware and...

49
Programming in java Lecture-2 Java Introduction

Upload: myron-peters

Post on 14-Jan-2016

217 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Programming in java

Lecture-2

Java Introduction

Page 2: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

PlatformComputing platform include hardware and software framework, this combination allows software to run.

Page 3: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Platform problem

Source code

Compiler(windows)

Object code

Page 4: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Platform problem

Source code

Compiler(windows)

Object code

Compiler(linux)

Compiler(mac)

Source code Source code

Object code

Object code

Page 5: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

java

JavaSource code

Compiler

Intermediate code

Phase I

Intermediate code

Interpreter

Object code

execution

Phase II

Page 6: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Byte code

Interpreter(windows)

Object code

Interpreter(linux)

Interpreter(mac)

Byte code

Object code

Object code

Page 7: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Byte code

WindowsOperating system

LinuxOperating system

MacOperating system

JVM JVM JVM

Byte Code Byte Code Byte Code

Page 8: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Byte code

JavaSource code

Compiler

Intermediate code

Phase I

Intermediate code

Interpreter

Object code

execution

Phase II

0 iload_1 1 iload_2 2 iadd 3 istore_3

A=10B=20C=A+B

Page 9: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java Features Simple

C++Java

Object oriented

Polymorphism

Inheritance

.

.multithreadi

ng

Page 10: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java’s Features Platform Independent

Page 11: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java’s Features Pure Object Oriented

Class One{ Public static void main(String arg[]) { System.out.println(“Hello World”); }}

In java everything must be inside class .

Page 12: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java’s Features Strongly typed

#include<stdio.h>Void main(){ printf(“Value of I”,&i);

}Every variable used in program must be declared.

Page 13: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java’s Features Secure

Internet

When java bytecode come from network or another machine, in that case before executing that file verifier check first.

Page 14: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java Features Multithreading

This is demo for checking multithreading concept of

java.

Developed in early c

This is demo for checking multithreading concept of

java.

Spelling checking operation running while used giving input

Developed in early java

Page 15: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java’s Features Architectural Neutral Distributed Garbage Collection

Page 16: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Garbage collection

Memory

One ob1=new One();Two ob2=new Two();

two class object

one class object

Ob1 Ob2

Ob1=ob2;

Page 17: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java Package Java package has two parts

JDK( java development Kit) JRE(java runtime environment)

Java version 1.7

Page 18: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Hello program in c

#include<stdio.h>void main(){printf(“hello world”);}

1. For including header files.

2. main function start

3. print on screen hello world

#include<stdio.h>void main(int argc , char * argv[]){printf(“hello world”);}

Page 19: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java first program Java is pure object oriented programming

language.

Class demo {

}

main funtion(arguments){print statement for hello world}

Page 20: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

First Java Program import java.lang.*; Class demo { public static void main(String arg[]) { System.out.println(“Hello World”); } }

For including libraries in java(like include statement in c)

Name of class

To print message on screen(like printf function)

Main method in java. With string type of argument

Page 21: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Commands to run Save file with name of class, which contains

main method javac demo.java

java demo

Page 22: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Creating, Compiling And Running Java Programs

javac

Java compiler

Java byte code

filename.class To compile the program at the command line type "javac filename.java"

To run the interpreter, at the command line type "java filename"

java

Java Interpreter

Type it in with the text editor of your choice

filename.java

(java file)

Java program

Page 23: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Compiling The Smallest Java Program

public class Smallest{ public static void main (String[] args) { }}

Smallest.java

javac

(Java byte code)

10000100000001000 00100100000001001

: :

Smallest.class

Type “javac Smallest.java”

Page 24: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Running The Smallest Java Program

(Java byte code)

10000100000001000 00100100000001001

: :

Smallest.class

java

Type “java Smallest”

(Platform/Operating specific binary

10100111000001000 00100111001111001

: :

Page 25: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

A Java program /*Here you describe what your program does.

*/

public class CLASS-NAME {public static void main (String args[]) {

// your program goes here

} // end of main} // end of class

Page 26: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Compiling and Running

In order to run a Java program: First you compile it

that is, you run a program called compiler that checks whether the program follows the Java syntax

if it finds errors, it lists them If there are no errors, it translates the program into Java

bytecode Example: assume you created a program called Hello.java

prompt>javac Hello.java If successful, this creates a file Hello.class which contains the

translation (Java bytecode) of Hello.java

Then you execute it That is, you call the Java Virtual Machine to interpret and

execute the Java bytecode of your program Example:

prompt>java Hello

Page 27: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Hello world program

When learning a new language, the first program people usually write is one that salutes the world :). Here is the Hello world program in Java.

/*

This program prints out “hello world!” and terminates.

*/public class Hello {

public static void main (String args[]) {

System.out.println(“Hello world!”);

} // end of main

} // end of class

Page 28: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Notes

Comments what follows after // on the same line is considered comment Or, what is in between /* this is a comment */

Indentation is for the convenience of the reader; compiler ignores all spaces and new

lines ; the delimiter for the compiler is the semicolon

All instructions end by semicolon

Lower vs. upper case matters!! Void is different than void Main is different that main

Page 29: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Writing to user (output)

System.out.println(variable-name);prints the value of variable <variable-name> to the user

System.out.println(“any message “);prints the message within quotes to the user

System.out.println(“hello” + “world” + a + “plus“ + b);assuming the value of a is 3 and of b is 7, it printshelloworld3plus7

Note: System.out.println() always prints on a new line.

Page 30: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Example

/* This program illustrates the System.out.println command.*/public class Hello {

public static void main (String args[]) {

System.out.println(“This is my first Java program!”);System.out.print(“I like Java.”); System.out.print(“I think Java is cool.”);

} // end of main} // end of class

Exercise: change the print to println above. What is the difference?

Page 31: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Variable declaration

type variable-name;

Meaning: variable <variable-name> will be a variable of type <type>

Where type can be: int //integer double //real number

Example:

int a, b, c;

double x;

int sum;

Page 32: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Example

/* Printing ages.*/public class MyFirstJavaProgram {

public static void main (String args[]) {

int myAge, myFriendAge; /* declare two integer variables */

myAge = 20; myFriendAge = myAge + 1; //one year older System.out.println(“Hello, I am “ +myAge + “years old, and my

friend is “ + myFriendAge + “ years old”);System.out.println(“Goodbye”);

} // end of main} // end of class

Page 33: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

If statements

if (condition) {//instructions

}else {

//instructions}//instructions

condition

instructions instructions

True False

instructions

Page 34: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Boolean conditions

..are built using Comparison operators

== equal!= not equal< less than> greater than<= less than or equal>= greater than or equal

Example:

int x, y; //two variables//assume they have some values if (x <= y) {

System.out.println(“x is smaller”);} else {

System.out.println(“x is larger”);}

Page 35: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Java data types

Type Description

byte 8 bit signed integer

short 16 but signed integer

int 32 bit signed integer

long 64 bit signed integer

float 32 bit signed real number

double 64 bit signed real number

char 16 bit Unicode character (ASCII and beyond)

boolean 1 bit true or false value

String A sequence of characters between double quotes ("")

Page 36: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Primitive types

Primitive type Size Minimum Maximum

boolean 1-bit — —

char 16-bit Unicode 0 Unicode 216- 1

byte 8-bit -128 +127

short 16-bit -215 +215-1

int 32-bit -231 +231-1

long 64-bit -263 +263-1

float 32-bit IEEE754 IEEE754

double 64-bit IEEE754 IEEE754

Page 37: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Default values for primitive members

When a primitive type data is a member of a class, it’s guaranteed to get a default value even if you don’t initialize it.

Not true for those local variables!! There will be compile

error if you use it without initialization

Primitive type Default

boolean false

char ‘\u0000’ (null)

byte (byte)0

short (short)0

int 0

long 0L

float 0.0f

double 0.0d

Page 38: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Example

class Hello{

public static void main ( String[] args ) {int x;System.out.println(x);

} }

>javac Hello.javaHello.java:5: variable x might not have been initialized System.out.println(x); ^1 error

Page 39: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Arrays in Java An ordered collection of something,

addressed by integer index Something can be primitive values, objects, or

even other arrays. But all the values in an array must be of the same type.

Only int or char as index long values not allowed as array index

0 based Value indexes for array “a” with length 10 a[0] – a[9];

a.length==10 Note: length is an attribute, not method

Page 40: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Arrays in Java: declaration Declaration

int[] arr; Person[] persons; Also support: int arr[]; Person persons[]; (confusing,

should be avoided) Creation

int[] arr = new int[1024]; int [][] arr = { {1,2,3}, {4,5,6} }; Person[] persons = new Person[50];

Page 41: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Arrays in Java: safety Cannot be accessed outside of its range

ArrayIndexOutOfBoundsException Guaranteed to be initialized

Array of primitive type will be initialized to their default value Zeroes the memory for the array

Array of objects: actually it’s creating an array of references, and each of them is initialized to null.

Page 42: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Arrays in Java:

second kind of reference types in Java

int[] arr = new int [5];arr

int[][] arr = new int [2][5];

arr[0]

arr[1]

arr

Page 43: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Scoping

Scope determines both the visibility and lifetime of the names defined within the scope

Scope is determined by the placement of {}, which is called block.{

int x = 10;//only x available { int y = 20; //both x and y available } //only x available, y out of scope!}

Page 44: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Scoping

Notice, you cannot do the following, although it’s legal in C/C++.

{int x = 10; { int x = 20; }}

Compile errorHello.java:6: x is already defined in main(java.lang.String[]) int x =20; ^1 error

Page 45: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Scope of objects

When you create an object using new, the object hangs around past the end of the scope, although the reference vanishes.

{String s = new String("abc");

}

Reference s vanishes, but the String object still in memory

Solution: Garbage Collector!

Page 46: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Importing library If you need any routines that defined by java

packageimport java.util.*;import java.io.*;

Put at the very beginning of the java file java.lang.* already been imported. Check javadoc for the classes

Page 47: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Static keyword Want to have only one piece of storage for

a data, regardless how many objects are created, or even no objects created

Need a method that isn’t associated with any particular object of this class

static keyword apply to both fields and methods

Can be called directly by class name Example: java.lang.Math

Non-static fields/methods must be called through an instance

Page 48: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

main()

class Hello{int num;public static void main(String[] args)

{num = 10;

}}

>javac Hello.javaHello.java:4: non-static variable num cannot be referenced from a static context num = 10; ^1 error

Page 49: Programming in java Lecture-2 Java Introduction. Platform Computing platform include hardware and software framework, this combination allows software

Main() doesn’t belong in a class

Always static Because program need a place to start, before any

object been created. Poor design decision If you need access non-static variable of

class Hello, you need to create object Hello, even if main() is in class Hello!

class Hello{int num;public static void main(String[] args){

Hello h = new Hello();h.num = 10;

}}