Sei sulla pagina 1di 48

Lecture 1: Overview of Java

Object Oriented
Languages??
Object Oriented Languages are
based upon Classes and Objects.
Helps us to create Real World
Applications very easily

Javas History
Developed by Sun Microsystems (James
Gosling)

A general-purpose object-oriented language


Oak - In 1991
Java - In 1995
Hot Java First Java Enabled Browser
Netscape Navigator In 1995 to incorporate
Java Technology

Based on C/C++
Designed for easy Web/Internet applications
3

Javas Magic : Byte Code


The key that allows java to solve
both the security and the portability
problemsCompiler
(Javac)

Source Code

JVM

Byte Code

(Java Run
Time
Environm
ent)
Output

Java
Program

Java
Compiler

Source
code

Virtual
machine
Byte Code

Java
Interpreter

Byte code
Virtual Machine

Machine
code
Real Machine

Byte Code
Translating a java program into bytecode
helps makes it much easier to run a
program in a wide variety of environments.
Byte Code is interpreted (which helps to
make it secure)
Interpretation is slower but the use of
bytecode enables the java run-time system
to execute programs much faster than you
might expect.
6

Java Class Lifecycle


Java Virtual Machine (JVM)

Source File
(.java)

ClassLoader

Compiler
(javac)

Bytecode Verifier

Interpreter

Class File
(.class)

Network
or
File System

= security gateway

Security Manager

Operating System

Java Features

Complied and interpreted


java compiler generate byte-codes, not native
machine code
the compiled byte-codes are platform-independent
java byte codes are translated on the fly to
machine readable instructions in runtime (Java
Virtual Machine)

Platform independent and


Portable
the sizes of the primitive data types are machine
independent
Java compiler generates byte code instructions
that can be implemented on any machine
8

Object oriented
focus on the data (objects) and methods manipulating the data
all functions are associated with objects
potentially better code organization and reuse

Simple
fixes some clumsy features of C++
no pointers
automatic garbage collection

Multithreaded and Interactive


Handles multiple tasks simultaneously

Distributed
9

Reliable
extensive compile-time and runtime error checking
no pointers. Memory corruptions or unauthorized
memory accesses are impossible
automatic garbage collection tracks objects usage over
time

Secure
No Pointers
Byte Code Verifier

10

Java and C
Java does not include the C unique statement
keywords sizeof and typedef
Does not contain data type struct and union
Does not define the type modifier keywords Auto,
extern, register
Does not support an explicit pointer type
Does not have a pre-processor and therefore we
can not use #define, #include statement
Java requires that the function with no arguments
must be declared with empty parentheses and not
with void keyword as done in C
11

Java and C++


Java does not support operator overloading
Does not have template classes as in C++
Does not support multiple inheritance. This is
accomplished using a new feature called
interface
Does not support global variables. Every variable
and method is declared within a class and forms
part of that class
Does not use pointers
Java has replaced the destructor function with the
finalize() function
There are no header files in java
12

C++

Java

Overlapping of C, C++, and


JAVA
13

Two ways of
using Java

Java Source
code

Java Compiler
Applet type

Application
type

Java enabled
Web
browser

Java
Interpreter

Output

Output

14

Language basics (1)


Data types
8 primitive types:
boolean, byte, short, int, long, float, double, char

Class types, either provided by Java, or made by


programmers
String, Integer, Array, Frame, Object, Person, Animal,

Array types

Variables
dataType identifier [ = Expression]:
Example variable declarations and initializations:
int x;
x=5;
boolean b = true;
String x = how are you?;

Data types in java

Primitive
(intrinsic))

Numeric

Non-Primitive
(Derived)

Classes)

Non
Numeric

Boolean

Integer

Arrays)

Interface)

Character
16

Comments
English text scattered through the
code are comments
JAVA supports 3 types of comments
/* */ - Usually used from multi-line
comments
//
- Used for single line comments
/** */ - Documentation comments

Language basics (2)


Flow of control

if, if-else, if-else if


switch
for, while, do-while
break
continue

while loop
while (squared <= MAX) {
squared = lo * lo; // Calculate square
System.out.println(squared);
lo = lo + 1; /* Compute the new lo value */
}

for loop
for (int i = 1; i < MAX; i++) {
System.out.println(i); // prints 1 2 3 4 5
}

do-while loop
do {
squared = lo * lo; // Calculate square
System.out.println(squared);
lo = lo + 1; /* Compute the new lo value */
} while (squared <= MAX);

if-else loop
if ( i < 10) {
System.out.println(i is less than 10 );
}
else {
System.out.println(i is greater than or equal to 10);
}

switch statement
switch (c) {
case a:
System.out.println ( The character is a );
break;
case b:
System.out.println ( The character is b );
break;
default:
System.out.println ( The character is not a or
b );
break;
}

Getting Started: (1)


(1) Create the source file:
open a text editor, type in the code which defines a class
(HelloWorldApp) and then save it in a file
(HelloWorldApp.java)
file and class name are case sensitive and must be
matched exactly (except the .java part)
Example Code: HelloWorldApp.java
public class HelloWorldApp
{
public static void main(String[] args)
{
// Display "Hello World!"
System.out.println("Hello World!");
}
}

Java

is CASE SENSITIVE!
24

public: The keyword public is an


access specifier that declares the
main method as unprotected.
static: It says this method belongs to
the entire class and NOT a part of any
objects of class. The main must
always be declared static since the
interpreter uses this before any
objects are created.
void: The type modifier that states
that main does not return any value.

Hello World: Java and


C
S1: // HelloWorld.java: Hello World
program
S2:
S3: import java.lang.*;

class HelloWorld
{
S4:
public static void main(String args[])
{
S5:
System.out.println(Hello World);
}
}

/* helloworld.c: Hello World


program*/
#define <stdio.h>
void main()
{
printf(Hello World\n);
}

Getting Started: (2)


(2) Compile the program:
compile HelloWorldApp.java by using the following
command:
javac HelloWorldApp.java

it generates a file named HelloWorldApp.class

27

Getting Started: (3)

(3) Run the program:


run the code through:
java HelloWorldApp

Note that the command is java, not javac, and


you refer to
HelloWorldApp, not HelloWorldApp.java or
HelloWorldApp. Class

28

Manav Rachna College of


Engg.

Reading Data into the program


Data can be taken into the
program using two methods
Interactive Mode
Command Line or Non-interactive Mode

Interactive mode can be used


using two kind of classes
Scanner class of java.util package

BufferedReader class of java.io


package
29

Manav Rachna College of


Engg.

Giving input to java source code


Scanner
First create an object of Scanner class and provide the place from
where to read the data

Scanner sc=new Scanner(System.in);

Methods of Scanner class

int nextInt()

String next()

double nextDouble()

Using BufferedReader class

Data is passed by the keyboard (system.in) to another


class InputStreamReader to convert the data into
character form
The characters are passed for buffering to
BufferedReader class
Use readLine() method of BufferedReader class to read
data from temporary buffer area

InputStreamReader isr=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(isr);

System.out.print(Enter Name : );
String name=br.readLine();

31

Manav Rachna College of


Engg.

Arrays in java

An array is a list of similar things


An array has a fixed:
name
type
length

These must be declared when the


array is created.
Arrays sizes cannot be changed
during the execution of the code

myArray
=

myArray has room for 8 elements


the elements are accessed by their
index
in Java, array indices start at 0

Declaring Arrays
int myArray[];
declares myArray to be an array of
integers
myArray = new int[8];
sets up 8 integer-sized spaces in
memory, labelled myArray[0] to
myArray[7]
int myArray[] = new int[8];
combines the two statements in one
line

Assigning Values
refer to the array elements by
index to store values in them.
myArray[0] = 3;
myArray[1] = 6;
myArray[2] = 3; ...

can create and initialise in one


step:
int myArray[] = {3, 6, 3, 1, 6, 3, 4, 1};

int[] foo = {1,2,3,4,5};


String[] names = {Joe, Sam};

Arrays of Objects
So far we have looked at an array
of primitive types.
integers
could also use doubles, floats,
characters

Often want to have an array of


objects
Students, Books, Loans

Need to follow 3 steps.

Declaring the Array


1. Declare the array
Student s[];

this declares s as an object

2 .Create the array


s[] = new Student[10];
this sets up 10 spaces in memory that can
hold references to Student objects

3. Create Student objects and add


them to the array: s[0] = new
Student();

2-Dimensional Arrays
Declaration
int myArray[] [];
myArray=new int[3][4];
or
int myarray[][]=new int[3][4];

Arrays Length
Arrays are fixed length
Length is specified at create time
In java, all arrays store the
allocated size in a variable
named length.
We can access the length of
arrays as arrayName.length:
e.g. int x = students.length();

// x = 7

Strings in java

Strings represent a sequence of characters.


The
easiest way to represent a sequence of
characters
in java is by using a character array.

Example:
Char charArray[]=new char[4];
charArray[0]=j;
charArray[1]=a;
charArray[2]=v;
charArray[3]=a;

Strings may be declared and created as follows :


String stringName;
stringName=new String(string);
Eg:
String firstname;
firstname=new String(Anil);
or
String firstname=new String(anil);

Like arrays, it is possible to get the


length of
string using the length method of String
class
int m=firstname.length();
Java strings can be concatenated using
the +
Operator. Eg,
String fullName=name1+name2;

String arrays
We can create and use arrays that contain
strings.
The statement:
String itemArray[]=new String[3];
Will create an itemArray of size 3 to hold
three string
constants

String methods
String class defines a number of methods
that allow us to
accomplish a variety of string
manipulation tasks

S2=s1.toLowerCase;
// converts string s1 to
lowercase
S2=s1.toUpperCase;
// converts string s1 to
uppercase
S2=s1.replace(x, y); // replace all appearance of x
with y
S1.equals(s2);
// returns true if s1 is equal to s2
S1.equalsIgnoreCase(s2); // returns true if s1=s2 ignoring
case
S1.length();
// gives length of s1
S1.charAt(n);
// gives nth character of s1
S1.compareTo(s2) // returns ve if s1<s2, +ve if s1>s2
and 0 if
s1=s2
S1.concat(s2)
// concatenates s1 and s2

Potrebbero piacerti anche