You are on page 1of 94

The Duke logo is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.

Java

visit www.muenggg.blogspot.com for more study material.

History of Java
1990
Group of engineers and programmers and Sun is created
James Gosling
Master programmer to create the Java Language

Partick Naughton
Designed the visual interfaces used to promote the Java environment

Sun names this team Green


visit www.muenggg.blogspot.com for more study material.

History of Java
Green Team Application Consumer Electronics Single Controller Programming a household thermostat Coordinating a VCR and TV Cable TV switchboxes 1991 Behind the Green Door document Code had to be small and tight as the devices did not have a lot of power or memory Different CPUs , not to be tied down to a single architecture. Proposed a distributed, a network of totally dissimilar devices, using byte streams to communicate with the controller.
visit www.muenggg.blogspot.com for more study material.

History of Java
Oak Language
Naughton developed visual representation interface for the new language
The user could open a cartoon TV Guide Select a movie Perform various operations on the VCR Gosling got the animation working in this new
language, which he called outside his office window.
visit www.muenggg.blogspot.com for more study material.

Oak,

after tree

History of Java
1993
Green Team is incorporated as
FirstPerson, Inc. (subsidiary of Sun) Looking to license technology
Cellular phone Industrial automation systems Interactive television CD-ROMs Commercial online services
visit www.muenggg.blogspot.com for more study material.

Each time the deal fell through

History of Java
WWW appeared on the Internet and transformed a text-based
Internet into graphical rich environment. Non Commercial Web Browser : Mosaic

Team developed a Web browser HotJava written completely


in Java. Browser capable of executing code inside Web pages.

visit www.muenggg.blogspot.com for more study material.

The Java History Timeline


1991 The Green Project Begins
MS DOS is the dominant operating system 1992 Oak" is the language *7 Debuts "Duke" is featured in the Interface 1993 The Green Project becomes FirstPerson Mosaic v1.0 is released 1994 WebRunner released the first browser that supports moving objects and dynamic executable content Java technology released to a select group on the Web. Name changed from "Oak" to "Java Announced at Sun World -- Java technology is officially born 1996 The first JavaOne Developer Conference JDK 1.0 software is released
visit www.muenggg.blogspot.com for more study material.

1995

The Java History Timeline


1997 Over 220,000 downloads of JDK 1.1 software occur in just three weeks JDK 1.1 release downloads top 2 million 1998

1999

Java 2 platform source code is released


J2EE beta software is released

2000
20002 2004

J2SE with SDK 1.3 was released


J2SE with SDK 1.4 was released Java 2 Platform, Standard Edition 5 (Project Tiger) is released Java technology celebrates its 10th birthday

2005

Approximately 4.5 million developers use Java technology Over 2.5 billion Java technology-enabled devices are available
visit www.muenggg.blogspot.com for the JRE download java.com bundles the Google Toolbar with more study material.

Purpose of Programming Languages

Source Code

Compiling/ Linking Executable Program


visit www.muenggg.blogspot.com for more study material.

Traditional Compiling Compiling/ Linking


Microsoft Windows executable Program

Source Code
Windows Environment

Source Code
Sun Environment

Compiling/ Linking

SunOS Executable Program

visit www.muenggg.blogspot.com for more study material.

Java Environment
javac classname.java

Java Source Code

Compiling

Java Bytecode

Programmers Computer
Users Computer Java Virtual Machine (Standalone or Browser)
java classname
visit www.muenggg.blogspot.com for more study material.

Compilation and deployment in Java environment


SumOneToTen.java SumOneToTen.class

Java Source Code

Compiling
javac SumOneToTen.java

Java Bytecode

Programmers Computer
Users Computer Java Virtual Machine

(Standalone or Browser)
java SumOneToTen
visit www.muenggg.blogspot.com for more study material.

JRE for Windows

Java Source Code (.java)

Java Compiler

Java Byte Code (.class)

JRE for Linux

JRE for Sun

The same .class file can execute on any platform, as long as the JRE is installed there
JRE for Mac

visit www.muenggg.blogspot.com for more study material.

What is a Virtual Machine?


A virtual machine (VM) is an abstract computer architecture Software on top of a real hardware Can run the same application on different machines where the VM is available

visit www.muenggg.blogspot.com for more study material.

The Java Virtual Machine


An abstract computing machine that executes bytecode programs
An instruction set and the meaning of those instructions the bytecodes A binary format the class file format An algorithm to verify the class file

visit www.muenggg.blogspot.com for more study material.

The Java Virtual Machine


Runtime environment for Java Runs Java .class files Has to conform to Suns specification

visit www.muenggg.blogspot.com for more study material.

Java Buzzwords
Simple Object Oriented

Interpreted
Portable Architecture neutral High Performance Robust

Secure
Multi-threaded Dynamic

Distributed

visit www.muenggg.blogspot.com for more study material.

Simple
easy to learn and use effectively cleaned up version of syntax of C++ small construction of software that can run stand alone in small machines familiar language Programmers can migrate easily to Java platform
visit www.muenggg.blogspot.com for more study material.

Object Oriented
True object oriented language almost everything is an object Program code + data reside within objects and classes extensive set of classes in packages

simple and easy to extend


visit www.muenggg.blogspot.com for more study material.

Distributed
Routines for TCP/IP protocols like HTTP and FTP Open and access objects across network with URLs with ease Networking capabilities are strong and easy to use Servlets: server side processing is efficient RMI: communication between distributed objects
visit www.muenggg.blogspot.com for more study material.

Robust
Emphasis on early checking for possible problems Also dynamic ( run-time) checking Concept of true arrays Eliminates the possibility of overwriting memory and corrupting data

visit www.muenggg.blogspot.com for more study material.

Secure
Used in networked/distributed environments
Emphasis on security Construction of virus free and tamper free systems

visit www.muenggg.blogspot.com for more study material.

Architecture neutral
Designed to support applications on networks Networks: variety of CPUs & OS Compiler generates an architecture neutral object file format : bytecode Compiled code is executable on many processors given the presence of Java run time system Java compiler does this by generating byte-code instructions.
visit www.muenggg.blogspot.com for more study material.

Portable
No implementation-dependent aspects of

specification
Java program can be easily moved from one computer system to another Size of primitive data types are fixed Behavior of arithmetic on them is fixed
visit www.muenggg.blogspot.com for more study material.

Interpreted
Can execute Java bytecodes on any machine to which the interpreter is ported.

visit www.muenggg.blogspot.com for more study material.

High Performance
Performance of interpreted byte-codes is usually more than adequate.

visit www.muenggg.blogspot.com for more study material.

Dynamic
More dynamic than C and C++ Designed to adopt to an evolving environment Libraries can add new methods and variables without any effect on their clients

visit www.muenggg.blogspot.com for more study material.

Multithreaded
Handling multiple tasks Benefits: interactive responsiveness and real-time behavior

visit www.muenggg.blogspot.com for more study material.

Features not present in Java


No structures and unions No enums (before J2SE 5.0) No typedefs , define , preprocessor No multiple inheritance No goto statement

No operator overloading
No automatic coercions No pointers

No template classes
No support for global variables No type modifiers like , auto , register , signed and unsigned visit extern www.muenggg.blogspot.com for
more study material.

Capabilities of Java
Client-Side Java: Applets AWT JFC (2D, Swing ,Acc..) Networking JavaBeans Server-Side Java: Servlets JSP JDBC Networking JavaBeans

Distributed Technologies RMI Java IDL (CORBA) JINI & JavaSpaces EJB
visit www.muenggg.blogspot.com for more study material.

Major Components of the SUN JDK Environment


Compiler-javac Interpreter-java Appletviewer-appletviewer Documentation-javadoc
visit www.muenggg.blogspot.com for more study material.

Typical Java Development Environment Phase 1 : Edit Phase 2 : compile Phase 3 : load Editor Disk

compiler
Class loader

Disk
Primary memory

Disk

Phase 4 : verify

Byte code verifier JVM


visit www.muenggg.blogspot.com for more study material.

Primary memory
Primary memory

Phase 5 : execute

Typical Java Development Environment


phase edit compile load explanation Program is created in an editor and stored on disk in a file ending with .java Compiler creates bytecodes and stores them on the disk in a file ending with .class Class loader reads .class files containing bytecodes from the disk and puts those bytecodes in memory

verify execute

Bytecode verifier confirms that all bytecodes are valid and do not violate Javas security restrictions JVM reads the bytecodes and translates them into the language the computer can understand.

visit www.muenggg.blogspot.com for more study material.

Class Loader Byte code verifier Java Class Libraries

Java Source (Java) Java Byte codes move locally or through network

Java Interpreter

Just-in-time compiler

Java Compiler

JVM

Runtime System

Java Byte codes (class)

Operating System

Hardware

Java Environment

visit www.muenggg.blogspot.com for more study material.

Steps : Java program


Create a Java source file. A source file contains text, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files. Compile the source file into a bytecode file. The Java compiler, javac, takes your source file and translates its text into instructions that the Java Virtual Machine (Java VM) can understand. The compiler puts these instructions into a bytecode file. Run the program contained in the bytecode file. The Java VM is implemented by a Java interpreter, java. This interpreter takes your bytecode file and carries out the instructions by translating them into instructions that your computer can understand.
visit www.muenggg.blogspot.com for more study material.

A Java program

visit www.muenggg.blogspot.com for more study material.

A Java program
public class HelloWorldApp {
public static void main(String [ ] args) { System.out.println("Hello World!"); } }
visit www.muenggg.blogspot.com for more study material.

A Java program
Java is case sensitive.

Name of the source file is HelloWorldApp.java


Same as class name that contains main( ) method. In Java the source file is officially a compilation unit. It is a text file that contains one or more class definitions. The Java compiler requires that the source file uses the .java filename extension.
visit www.muenggg.blogspot.com for more study material.

A Java program
public class HelloWorldApp
Keyword public is an access modifier. Keyword class begins the class definition for a class named name. Everything in Java must reside inside the class. HelloWorldApp is a Java identifier that specifies the name of the class to be defined. Every class definition in Java begins with an opening brace ({ ) and ends with a matching closing brace ( })
visit www.muenggg.blogspot.com for more study material.

A Java program
public static void main(String [ ] args)
Defines a method named main.

Starting point for the interpreter to begin execution of the program. A Java application can have any number of classes but only one of them must include a main method to initiate execution.
visit www.muenggg.blogspot.com for more study material.

A Java program
public static void main(String args[ ] ) public: an access specifier that declares the main method as unprotected and therefore making it accessible to all other classes. static : declares this method as one that belongs to the entire class and not a part of any objects of the class. The main method must always be declared as static since the interpreter uses this method before any objects are created. void : main method does not return any value. Braces mark the beginning and end of the body of the method.
visit www.muenggg.blogspot.com for more study material.

main as static?
When you execute the Java Virtual Machine (JVM) with the java command, the JVM attempts to invoke the main method of the class you specifywhen no objects of the class have been created. Declaring main as static allows the JVM to invoke main without creating an instance of the class.
visit www.muenggg.blogspot.com for more study material.

A Java program
String args[ ] declares a parameter named args which is an array of objects of class String. This array is the mechanism through which the runtime system passes information to your application. Each string in the array is called a command-line argument. The println method is a member of out object which is a static data member of visit www.muenggg.blogspot.com for System class. more study material.

A Java program

visit www.muenggg.blogspot.com for more study material.

Compiler Errors

Message : 'javac' is not recognized as an internal or external command, operable program or batch file.

Meaning :Windows cannot find the compiler (javac). Update the PATH variable
visit www.muenggg.blogspot.com for more study material.

Syntax & Semantic Errors


mistype part of a program, the compiler may issue a syntax error.

The message usually displays the type of the error, the line number where the error was detected, the code on that line, and the position of the error within the code.
In addition to verifying that your program is syntactically correct, the compiler checks for other basic correctness. e.g. testing.java:13: Variable count may not have been initialized. count++
visit www.muenggg.blogspot.com for more study material.

Runtime Errors
Message : Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp Meaning : java cannot find your bytecode file, HelloWorldApp.class. Set the CLASSPATH variable

visit www.muenggg.blogspot.com for more study material.

Identifiers in Java
Names given to entities that a programmer can manipulate in the program. Three aspects Legal identifiers Suns Java code conventions Java Beans naming standard
visit www.muenggg.blogspot.com for more study material.

Legal identifiers rules


Start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number. After the first character, identifiers can contain any combination of letters, currency characters, connecting characters, or numbers. In practice, there is no limit to the number of characters an identifier can contain. Cannot use a Java keyword as an identifier. Identifiers in Java are case-sensitive. Special characters not allowed
visit www.muenggg.blogspot.com for more study material.

Suns Java code conventions


Classes and interfaces
The first letter should be capitalized, and if several words are linked together to form the name, the first letter of the inner words should be uppercase ( "camelCase"). For classes, the names should typically be nouns. For interfaces, the names should typically be adjectives .

visit www.muenggg.blogspot.com for more study material.

Suns Java code conventions


Methods & Variables
The first letter should be lowercase, and then normal camelCase rules should be used.

Constants
Java constants are created by marking variables static and final. They should be named using uppercase letters with underscore characters as separators.

visit www.muenggg.blogspot.com for more study material.

JavaBeans Standards

visit www.muenggg.blogspot.com for more study material.

Source File Declaration Rules


Only one public class per source code file.

Comments can appear at the beginning or end of any line in the source code file
If there is a public class in a file, the name of the file must match the name of the public class. If the class is part of a package, the package statement must be the first line in the source code file, before any import statements that may be present.
visit www.muenggg.blogspot.com for more study material.

Source File Declaration Rules


If there are import statements, they must go between the package statement (if there is one) and the class declaration. If there isn't a package statement, then the import statement(s) must be the first line(s) in the source code file. If there are no package or import statements, the class declaration must be the first line in the source code file. import and package statements apply to all classes within a source code file. A file can have more than one nonpublic class.

visit www.muenggg.blogspot.com for more study material.

Data types
Strongly typed language Every variable must have a data type Eight primitive data types in Java Four integer types Two floating-point number types One character data type One Boolean (logical) data type.
visit www.muenggg.blogspot.com for more study material.

Java Integer Types


Numbers without fractional parts Signed , positive & negative values Four integer types byte , short , int , long. Range of values depends on integer data types we choose.

visit www.muenggg.blogspot.com for more study material.

Java Integer Types


Type Storage Range

int short

4 bytes 2 bytes

-2,147,483,648 to 2,147,483,647 (just over 2 billion) -32,768 to 32,767

long
byte

8 bytes
1 byte

- 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
-128 to 127

visit www.muenggg.blogspot.com for more study material.

Java Integer Types


Range of integer types do not depend on the machine on which the Java code is run. Long integer numbers have a suffix L. Hexadecimal numbers have a prefix 0x Octal numbers have a prefix 0 Java does not have unsigned data types

visit www.muenggg.blogspot.com for more study material.

Floating point types


denote numbers with fractional parts.
Type Storage Range Approx. 3.40282347E+38F (6 to 7 significant digits)

float

4 bytes

double

8 bytes

Approx. 1.79769313486231570E+308 (15 significant decimal digits)

visit www.muenggg.blogspot.com for more study material.

Floating point types


Double has twice the precision as compared to float. Numbers of type float have a suffix F. e.g. 3.402F Floating point numbers without an suffix F are always considered to be of type double.

visit www.muenggg.blogspot.com for more study material.

Floating point types


All floating point computations follow IEEE 754 specifications. Three special floating point values to denote overflows and errors positive infinity : Resulting of dividing a positive number by 0 Negative infinity NaN (not a number) : Computing 0/0 or a square root of a negative number is NaN
visit www.muenggg.blogspot.com for more study material.

Character type
To store characters. contains a single, 16-bit Unicode character. A larger range is needed to represent characters found in languages other than English. Unicode characters are actually represented by unsigned 16-bit integers, which means 216 possible values, ranging from 0 visit www.muenggg.blogspot.com forto 65535
more study material.

Boolean type
used for evaluating logical conditions. Two values : true and false Cannot convert between integers and boolean values.

visit www.muenggg.blogspot.com for more study material.

Notes : Data types


All six number types in Java are made up of a
certain number of 8-bit bytes. Signed, meaning they can be negative or positive. Leftmost bit (MSB) is used to represent the sign, where a 1 means negative and 0 means positive. The rest of the bits represent the value, using two's complement notation.
visit www.muenggg.blogspot.com for more study material.

Notes : Data types


byte
sign bit

0010011
value bits

short

111110100000011

visit www.muenggg.blogspot.com for more study material.

Variables
A container to hold a value Basic unit of storage All variables must have a name , type and an optional initializer. All variables have a scope which defines their visibility & life time. Must be declared before use.
visit www.muenggg.blogspot.com for more study material.

Variables
Syntax: type identifier [=value] [,identifier [=value ] . ]; Semicolon is necessary because declaration is a complete Java statement. a

visit www.muenggg.blogspot.com for more study material.

Examples : Variables
int count ; float x , y; double salary; byte b ; char c1 , c2, c3 ; boolean done;

visit www.muenggg.blogspot.com for more study material.

Initializing variables
Use assignment statement to give a value to a variable.
variable = value ;

x = 10 ; yes = x ; done = true ; total = 75.36

visit www.muenggg.blogspot.com for more study material.

Initializing variables
Declare and initialize the variable on the same line. type variable = value ; int m = 5 , n = 10; int days = 12 ; char yes = x double total = 75.30;
visit www.muenggg.blogspot.com for more study material.

Dynamic initialization
public class DynInit { public static void main(String [] args) { double a = 3.0 , b= 4.0; double c = Math.sqrt(a * a + b * b); System.out.println(Hypotenuse is + c); } }
visit www.muenggg.blogspot.com for more study material.

Scope of variables
Part of the program from where the variable is accessible is called the scope. 3 kinds instance variables class variables local variables
visit www.muenggg.blogspot.com for more study material.

Instance variables
Defined inside the class, but outside of any method. Only initialized when the class is instantiated. Instance variables are the fields that belong to each unique object. Have a default value depending on data type.
visit www.muenggg.blogspot.com for more study material.

Example : Instance variables


class Employee
{

private String name;


private String title;

private String manager;


}
visit www.muenggg.blogspot.com for more study material.

Example : Instance variables


Each employee instance will know its own name, title, and manager.
Each instance can have its own unique values for three fields.

visit www.muenggg.blogspot.com for more study material.

Instance variables
Can use any of the four access levels Can be marked final Can be marked transient Cannot be marked abstract Cannot be marked synchronized Cannot be marked strictfp Cannot be marked native Cannot be marked static, because then they'd become class variables.

visit www.muenggg.blogspot.com for more study material.

Local variables
Variables declared and used within a method. A local variable starts its life inside the method, it's also destroyed when the method has completed. Before a local variable can be used, it must be initialized with a value.
visit www.muenggg.blogspot.com for more study material.

Local variables
Can also be declared inside program blocks between { and } braces.

Scope from beginning of the block to the end of the block.

visit www.muenggg.blogspot.com for more study material.

Example : Local variables


class TestServer { public void logIn() { int count = 10; } } Key : local variables must be initialized before you use it. visit www.muenggg.blogspot.com for
more study material.

Example : Local variables


class TestServer { public void logIn() { int count = 10; } public void doSomething(int i) { count = i; } } Will not compile as count cannot be accessed outside method login( )
visit www.muenggg.blogspot.com for more study material.

Shadowing
class TestServer { int count = 9; // Declare an instance variable named count public void logIn() { int count = 10; // Declare a local variable named count System.out.println("local variable count is " + count); } public void count() { System.out.println("instance variable count is " + count); } public static void main(String[] args) { new TestServer().logIn(); new TestServer().count(); } visit www.muenggg.blogspot.com for }
more study material.

Variable scope class Layout { static int s = 340; // static variable int x ; // instance variable { x = 5 ; int x2 = 10; } Layout() { x +=8 ; int x3 = 6; } void dostuff() { int y = 0 ; for (int z = 0 ; z < 4 ; z++) { y += z + x; } } visit www.muenggg.blogspot.com for more study material. }

Variable scope
variable s x x2 x3 y type Static variable Instance variable Block variable Constructor variable , local variable Local variable
visit www.muenggg.blogspot.com for more study material.

Block variable

Literals
Source code representation of a fixed value e.g. 'b' 42 false 2546789.343

// char literal // int literal // boolean literal // double literal

visit www.muenggg.blogspot.com for more study material.

Integer Literal
Three ways to represent integer numbers in the Java language: decimal (base 10) octal (base 8) hexadecimal (base 16) Octal Literals Octal integers use only the digits 0 to 7. An integer in octal form is represented by placing a zero in front of the number. visit www.muenggg.blogspot.com for
more study material.

Integer Literal
Hexadecimal Literals are constructed using 16 distinct symbols.

An integer in Hex. form is represented by placing a 0x in front of the number. 0XCAFE and 0xcafe are both legal and have the same value.
visit www.muenggg.blogspot.com for more study material.

Integer Literal
All three integer literals are defined as int by default.

Can be specified as long by placing a suffix of L or l after the number. long a = 110500L long b = 0xFFFFl
visit www.muenggg.blogspot.com for more study material.

Floating point literal


Defined as a number, a decimal symbol, and more numbers representing the fraction. e.g. double d = 11301878.1234567; double (64 bits) by default.

To assign a floating-point literal to a variable of type float (32 bits), you must attach the suffix F or f to the number. visit www.muenggg.blogspot.com for
more study material.

Floating point literal


e.g.
float f = 23.467890; //Compiler error , possible loss of precision.

float f = 23.467890f;

visit www.muenggg.blogspot.com for more study material.

Boolean Literals
Source code representation for boolean values. Defined as true or false. e.g. boolean t = true ; boolean f = 0 ; //Compiler error
visit www.muenggg.blogspot.com for more study material.

Character Literals
Represented by single character in single quotes. e.g. char a = a ; char b = ? char c = 890 ; char d = 1500
visit www.muenggg.blogspot.com for more study material.

Constants
Use the keyword final to denote a constant. assign to a variable once and then its value is set once and for all. public class Constants { public static void main(String [] args) { final double CM_PER_INCH = 2.54; double w = 8.5 , h = 11.0; System.out.println(Paper size in cms : + w * CM_PER_INCH + by +h * CM_PER_INCH); } }
visit www.muenggg.blogspot.com for more study material.

Constants
constant that is made available to multiple methods inside a single class. Referred to as class constant set up a class constant with keywords static and final Declared outside of methods.

visit www.muenggg.blogspot.com for more study material.

Constants
public class Constants2 { public static void main(String [] args) { double w = 8.5 , h = 11.0; System.out.println(Paper size in cms : + w * CM_PER_INCH + by +h * CM_PER_INCH); } public static final double CM_PER_INCH = 2.54; }
visit www.muenggg.blogspot.com for more study material.

You might also like