Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 55

Introduction to Java

Write Once, Run Anywhere


Introduction
Present
the syntax of Java
Demonstrate how to build
◦ stand-alone Java programs
◦ Java applets, which run within browsers e.g.
Netscape
Example programs
Java isn't C!

In C, almost everything is in functions


In Java, almost everything is in classes
There must be only one public class per file
The file name must be the same as the name
of that public class, but with a .java
extension
Reasons for the popularity of Java

Java is platform independent

Java provides applets and servlets for use


on the Web.

Javais an Object Oriented Programming


Language

Java is easy.
Java Advantages
Portable - Write Once, Run Anywhere
◦ The use of the same bytecode for all JVMs on all platforms
allows Java to be described as a write once, run anywhere
 programming language

Security (It’s more secure)


Robust memory management
Designed for network programming
Multi-threaded (multiple simultaneous tasks)
Dynamic & extensible (loads of libraries)
◦ Classes stored in separate files
◦ Loaded only when needed
Java
Java has some interesting features:
◦ automatic type checking.

◦ automatic garbage collection.

◦ simplifies pointers; no directly accessible


pointer to memory.

◦ simplified network access.


Applets, Servlets and Applications
An applet is designed to be embedded in
a Web page, and run by a browser
 Applets run in a sandbox with numerous
restrictions; for example, they can’t read files and
then use the network

A servlet is designed to be run by a web


server

An application is a conventional program


Different ways to write/run a Java codes are:

Application- A stand-alone program that can be invoked from


command line . A program that has a “main” method

Applet- A program embedded in a web page , to be run when the


page is browsed . A program that contains no “main” method

To run Application -Java interpreter

To run Applets- Java enabled web browser (Linked


to HTML via <APPLET> tag. in html file)
Building Standalone JAVA Programs (on
UNIX)
Prepare the file foo.java using an editor

Invoke the compiler: javac foo.java

This creates foo.class

Run the java interpreter: java foo


Total Platform Independence

JAVA COMPILER
(translator)

JAVA BYTE CODE


(same for all platforms)

JAVA INTERPRETER
(one for each different system)

Windows XP Macintosh Solaris Linux


Java Virtual Machine
The .class files generated by the compiler are
not executable binaries
◦ so Java combines compilation and interpretation

Instead,they contain “byte-codes” to be


executed by the Java Virtual Machine

This approach provides platform independence,


and greater security
Just in Time Compilation (JIL) is a method to
improve the runtime performance of 
computer programs based on byte code(
virtual machine code).

◦  It converts code at runtime prior to executing it


natively,
 For example bytecode into native machine code.
◦ i.e.  JIT compiler will produce machine code that is optimised
for running machine's cpu architecture...
Java Program Structure
Documentation Section

Package Statement
Import Statements

Interface Statements

Class Declarations
main Method Class
{
}
HelloWorld (standalone)
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

Note that String is built in


println is a member function for the
System.out
public static void main(String args[])
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 users this before any objects are
created.
void: The type modifier that states that main
does not return any value.

15
System.out.println(“Hello World”);
System is really the java.lang.System class.
This class has a public static field called out
which is an instance of the java.io.PrintStream
class.
So when we write System.out.println(), we are
really invoking the println() method of the “out”
field of the java.lang.System class.

16
Java program layout

A typical Java file looks like:


import java.awt.*;
import java.util.*;
public class SomethingOrOther {
// object definitions go here
...
}
This must be in a file named SomethingOrOther.java !
Primitive Types and Variables

 boolean, char, byte, short, int, long, float, double etc.


 These basic (or primitive) types are the only types that are
not objects.
 This means that you don’t use the new operator to create a
primitive variable.
 These data types are independent of any platform.
 Declaring primitive variables:
float initVal;
int retVal, index = 2;
double gamma = 1.2,
boolean valueOk = false;
Data types and its range
Name Width in Bits Range
byte 8 -128 to 127
short 16 -32,768 to 32767
int 32 -2,147,483,648 to 2,147,483,647
long 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 32 1.4e-045 to 3.4e+038
double 64 4.9e-324 to 1.8e+308
char 16 0 to 65,535
boolean 8 true or false

byte, short, int, long data types are singed, integral value in 2’s
complement.
float is signed, single-precision floating point value and
double is signed, double-precision floating point value.
whereas char is unsigned integral value.
Data types and its default value
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
boolean False

String (or any object)   null


Initialisation
If no value is assigned prior to use, then the
compiler will give an error.

Java sets primitive variables to zero or false in


the case of a boolean variable.

All object references are initially set to null


An array of anything is an object
◦ Set to null on declaration
◦ Elements to zero, false or null on creation
Declarations
int index = 1.2; // compiler error
boolean retOk = 1; // compiler error
double fiveFourths = 5 / 4; // no error!
float ratio = 5.8f; // correct
double fiveFourths = 5.0 / 4.0; // correct
Assignment
 All Java assignments are right associative
int a = 1, b = 2, c = 5
a=b=c
System.out.print(
“a= “ + a + “b= “ + b + “c= “ + c)

 What is the value of a, b & c


 Done right to left: a = (b = c);
Basic Mathematical Operators

* / % + - are the mathematical operators


 * / % have a higher precedence than + or -
double myVal = a + b % d – c * d / b;
 Is the same as:
double myVal = (a + (b % d)) –
((c * d) / b);
Relational Operators

== Equal (careful)
!= Not equal
>= Greater than or equal
<= Less than or equal
> Greater than
< Less than
Statements & Blocks

 A simple statement is a command terminated by a


semi-colon:
name = “Fred”;
 A block is a compound statement enclosed in curly
brackets:
{
name1 = “Fred”; name2 = “Bill”;
}
 Blocks may contain other blocks
Flow of Control
Java executes one statement after the other in
the order they are written
Many Java statements are flow control
statements:
Alternation: if, if else, switch
Looping: for, while, do while
Escapes: break, continue, return
If – The Conditional Statement
 The if statement evaluates an expression and if that
evaluation is true then the specified action is taken
if ( x < 10 ) x = 10;
 If the value of x is less than 10, make x equal to 10
 It could have been written:
if ( x < 10 )
x = 10;
 Or, alternatively:
if ( x < 10 ) { x = 10; }
If… else
 The if … else statement evaluates an expression and
performs one action if that evaluation is true or a
different action if it is false.
if (x != oldx) {
System.out.print(“x was changed”);
}
else {
System.out.print(“x is unchanged”);
}
Nested if … else

if ( myVal > 100 ) {


if ( remainderOn == true) {
myVal = mVal % 100;
}
else {
myVal = myVal / 100.0;
}
}
else
{
System.out.print(“myVal is in range”);
}
else if
 Useful for choosing between alternatives:
if ( n == 1 ) {
// execute code block #1
}
else if ( j == 2 ) {
// execute code block #2
}
else {
// if all previous tests have failed, execute
code block #3
}
The switch Statement
switch ( n ) {
case 1:
// execute code block #1
break;
case 2:
// execute code block #2
break;
default:
// if all previous tests fail then
//execute code block #4
break;
}
The for loop
 Loop n times
for ( i = 0; i < n; n++ ) {
// this code body will execute n times
// ifrom 0 to n-1
}
 Nested for:
for ( j = 0; j < 10; j++ ) {
for ( i = 0; i < 20; i++ ){
// this code body will execute 200 times
}
}
while loops

while(response == 1) {
System.out.print( “ID =” + userID[n]);
n++;
response = readInt( “Enter “);
}

What is the minimum number of times the loop


is executed?
What is the maximum number of times?
do {… } while loops

do {
System.out.print( “ID =” + userID[n] );
n++;
response = readInt( “Enter ” );
}while (response == 1);

What is the minimum number of times the loop


is executed?
What is the maximum number of times?
Break

A break statement causes an exit from the


innermost containing while, do, for or switch
statement.
for ( int i = 0; i < maxID, i++ ) {
if ( userID[i] == targetID ) {
index = i;
break;
}
} // program jumps here after break
Continue
 Can only be used with while, do or for.
 The continue statement causes the innermost loop to
start the next iteration immediately
for ( int i = 0; i < maxID; i++ ) {
if ( userID[i] != -1 ) continue;
System.out.print( “UserID ” + i + “ :” +
userID);
}
Java Development Kit
javac - The Java Compiler
java - The Java Interpreter
jdb - The Java Debugger
appletviewer -Tool to run the applets

javap - Java disassembler


javadoc - documentation generator
javah - creates C header files
Process of Building and Running Java
Programs
Text Editor

Java Source
javadoc HTML Files
Code

javac

Java Class File javah Header Files

java jdb

Outout
Comments are almost like C++
 /* This kind of comment can span multiple lines */

 // This kind is to the end of the line

 /**
* This kind of comment is a special
* ‘javadoc’ style comment
*/
What is a class?
Early languages had only arrays
◦ all elements had to be of the same type

Thenlanguages introduced structures (called


records, or structs)
◦ allowed different data types to be grouped

Then Abstract Data Types (ADTs) became


popular
◦ grouped operations along with the data
The three principles of OOP

 Encapsulation
◦ Objects hide their functions
(methods) and data
(instance variables)
 Inheritance
◦ Each subclass inherits all car Super class
variables of its superclass
 Polymorphism auto-
manual
matic Subclasses
◦ Interface same despite
different data types
draw() draw()
Naming conventions

Java is case-sensitive;
maxval, maxVal, and MaxVal are three different names

Class names begin with a capital letter

All other names begin with a lowercase letter

Subsequent words are capitalized: theBigOne

Underscores are not used in names

These are very strong conventions!


Methods
 A method is a named sequence of code that can be
invoked by other Java code.
 A method takes some parameters, performs some
computations and then optionally returns a value (or
object).
 Methods can be used as part of an expression statement.

public float convertCelsius(float tempC) {


return( ((tempC * 9.0f) / 5.0f) + 32.0 );
}
Method Signatures
 A method signature specifies:
◦ The name of the method.
◦ The type and name of each parameter.
◦ The type of the value (or object) returned by the method.
◦ The checked exceptions thrown by the method.
◦ Various method modifiers.

Syntax:
 modifiers type name ( parameter list ) [throws exceptions ]
Eg.
1) public float convertCelsius (float tCelsius ) {}

2) public boolean setUserInfo ( int i, int j, String name ) throws


IndexOutOfBoundsException {}
Reference Data Types
Java does not use pointers, it uses
references.
References are somewhat like pointers in
C, but they are different from pointers in
the sense that unlike pointers which can
point to any memory location,
references can only refer to objects (i.e.
instances of a reference type).
Reference Date Types
 References can never be made refer to any other type,
which is always possible with pointers, can be a source of
lots of errors.
 E.g.

Rectange r,
Date d1, d2;
 Here r , d1 are references(variables) of type Rectangle ,
Date respectively.

 Space allocated is same for all reference.


 Java guarantee that r can not refer to Date, and d1 can not
refer to Rectangle
The class hierarchy
 Classes are arranged in a hierarchy

 The root, or topmost, class is Object

 Every class except Object has at least one superclass

 A class may have subclasses

 Each class inherits all the fields and methods of its


(possibly numerous) superclasses
An example of a class

class Person {
String name;
int age;
void birthday ( ) {
age++;
System.out.println (name + ' is now ' + age);
}
}
Creating and using an object
Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
e.g. 2)
Simple Class and Method

Class Fruit {
int grams;
int cals_per_gram;

int total_calories() {
return(grams*cals_per_gram);
}
}
Public/private

Methods/data may be declared public or


private meaning they may or may not be
accessed by code in other classes …
Good practice:
◦ keep data private
◦ keep most methods public
well-defined interface between classes -
helps to eliminate errors
Using objects
Here,code in one class creates an instance of
another class and does something with it …
Fruit plum=new Fruit();
int cals;
cals = plum.total_calories();

Dot operator allows you to access (public)


data/methods inside Fruit class
Common System defined packages that are frequently used in the programs:

• java.lang
• Classes for various data types, running processes, strings, threads, exceptions and much more.
• They are automatically imported.

• java.util
• Utility classes for dates, vectors, random numbers etc.

• java.io
• Classes for various types of input and output.

• java.awt
• Abstract Window Toolkit (AWT) classes for the GUI interface. Such as windows, dialog
boxes, buttons and text fields and more.

• java.net
• Classes for networking, URLs/clients/server sockets.
• java.applet
• Classes for creating and implementing applets.

• java.awt.image
• Classes for managing and manipulating images.

• java.rmi, java.rmi.server, java.rmi.registry


• Packages provides all tools need to perform remote method invocation (RMI).

• java.sql
• This package encompasses java database connectivity (JDBC) enables to access RDBMS.

• java.security
• Java security packages to use encryption in java program for secure data transfer among
clients and servers.

You might also like