Introduction to Java
Overview
• History of Java
• Java Releases - Evolution
• Java Features
• Java White Paper Buzzwords
• Java & Internet
Java Features• Java is a slang term for coffee.• Java – city in Iowa in Indonesia.• SUN - Sun Microsystems, Inc. is a multinational
vendor of computers, computer components, computer software, and information technology services, founded on 24 February 1982.
• The company is headquartered in Santa Clara, California (part of Silicon Valley).
Java Features
• Java is related to C++.• Java inherited from both C and C++; Syntax
form C and Object-oriented features from C++.• Every p/l fulfilled some needs in programming.• C – need for structured, efficient, and high-
level language – to replace assembly code.
Java Features
• C++ - in structured programming – once a project reaches a certain size, its complexity exceeds what a programmer can manage.– New way of programming – OOP
• Java – WWW and Internet programming – taking features from different programming languages.
Java Features
• Java is an – object-oriented, – multi-threaded programming, – concurrent, – platform independent,– distributed programming language.
• Many of Java’s characteristics comes from other languages.
Java White Paper Buzzwords• http://java.sun.com/docs/white/
langenv/Intro.doc.html• Simple– syntax for Java cleaned up version of C++.
• Object Oriented– modern technique for programming
Java White Paper Buzzwords• Distributed– Networking capabilities of Java– Internet Programming using Java– Remote Method Invocation (RMI) using Java– Java EE – very large scale distributed applications
• Robust– Reliable application– Check for possible errors– No pointers !!!
• Secure– Virus-free
****Java White Paper Buzzwords• Architecture Neutral
– The compiler generates an architecture-neutral object file format – this can be executed on any processor that has a JVM
– Java compiler generates byte code instructions which have nothing to do with particular computer architecture – these are interpreted on any machine and easily translated into native machine code on the fly.
• Portable– No “implementation-dependent” aspects of the specification.
• Interpreted– Java can execute Java Bytecodes directly on any machine
Portability by Java
JAVA processing
Java White Paper Buzzwords• High Performance– The bytecode can be translated on the fly
• Multithreaded– multithreading are better interactive
responsiveness and real-time behavior• Dynamic– Code is added to a run time program
Java & Internet
• Users will download bytecodes form the Internet
and run them on their m/cs. Such Java program
that work on web pages are called applets.
• Client-side programming – input validation.
• Server-side programming – application servers –
scalable server applications
History of Java
• 1991 SUN (Standford University Network) engineers – Jame Gosling & Team wanted to design a small computer language for consumer electronic devices.
• These devices – manufactured by different vendors – different CPUs.
• So needed a language that is not tight to any architecture – independent.
• The project was named – “Green”.
• Main requirement – – small,
– tight, and
– p/f independent code
• They took the idea of virtual machine(VM) from PASCAL.
• A portable language that generated intermediate code for a hypothetical machine (VM) – Hence JVM
• Language syntax from C++ - Object-oriented language - Named – “Oak” – later Java.
History of Java - 2
• Initially, it was unsuccessful – as no companies were interested.
• Later, in mid 1994 – WWW part of Internet was evolving.
• The key to the Web is program (browser) that translates the hypertext page to the screen.
• SUN took this idea and built a browser – HotJava browser – executes code in the web page.
• Success of Java – 1st version was released – 1996.
History of Java - 3
Java Releases
• JDK 1.0 (January 23, 1996)• JDK 1.1 (February 19, 1997)• J2SE 1.2 (December 8, 1998) – Released with editions.
• J2SE 1.3 (May 8, 2000)• J2SE 1.4 (February 6, 2002)• J2SE 5.0 (September 30, 2004) (Java 1.5)• Java SE 6 (December 11, 2006)– 7.1 Java SE 6 Update 10
• Java SE 7
Java Programming Envt
Aum Amriteshwaryai Namah
Java Programs
• Java supports various building of various
types of programs:-
– Console Prgs
– Graphical Apps
– Applets
–Web Applications
Requirements
• To execute Java programs, the following are the requirements:- – JDK – Java Development Kit or – an IDE that sophisticates Java Development.
• To run the JDK tools, use the shell window
Installing JDK
• Download the JDK
– Visit the SUN’s site – http://java.sun.com/
– Choose the platform for which you want the JDK
– Only the installation and compilation instructions
for Java are system dependent.
– Path preferable is:- C:\jdk1.6.0_01 (Windows)
• Setting the Execution Path
– Under windows
• Control Panel>System>Advanced Tab>Environment
Variables
• Edit the Path property by adding “C:\jdk1.6.0_01\bin”.
Installing JDK
Installing JDK• Choosing a Development Environment– Basic JDK contains tools that need to be typed in
the shell window.– There are 3 choices for a Java development
environment:-• Use JDK and any text editor; Compile and launch
programs in a shell window• Use any integrated evnt such as Eclipse, NetBeans.• Use JDK and a text editor that is integrated with the
JDK eg Emacs, TextPad or JEdit. Compile and launch the programs inside the editor.
Installing JDK
• Using the Command Line Tools:-
– >javac Welcome.java
– >java Welcome
– The javac program is the Java compiler. It compiles the
file Welcome.java into the file Welcome.class. The Java
program launches the Java virtual machine. It executes
the bytecodes that the compiler placed in the class file.
FirstProgram.java/* My first Java program Author : Bri. Jayashree File Name : FirstProgram.java */public class FirstProgram{
public static void main(String args[]){
System.out.println("Aum Namah Shivaya!!!");}
}
A Closer look into the program
Java is case sensitive Keyword public is called the access
modifier; these modifiers control the level of access.
• Keyword class is used to define a container that holds code in it
• Everything in a Java program must lie inside a class.
• The name of the class is an identifier – keywords cannot be used as class names - start with uppercase
• The file name should be the name of the public class with the extension .java
• Launch the javac compiler to compile the program:-– > javac FirstProgram.java– Notice the FirstProgram.class file created by the
compiler• Launch the java interpreter to execute the
program– > java FirstProgram
A Closer look into the program
Java Execution
• When java ClassName is used to run the
program, the JVM always starts execution with
the code in the main method.
• { } – define the parts in a program.
• static
• void – return type of main()
General Program Structure
public class ClassName
{
public static void main(String args[])
{
Program statements
}
}
Program Statements• Java statements can be considered as sentences of the
language.
• Every statement must end with a semicolon.
System.out.println("Aum Namah Shivaya!!!");
• We are using the System.out object and calling its println
method.
• Object.method(parameters) -- Syntax for calling a method.
Comments
Comments – do not show up in the executable program
Java has three ways of marking comments:-1) //2) /* */3) /** */ to generate documentation
automatically.
Running the program
• Launch the shell program
• Go to the path where the file is.
• javac FirstProgram.java
• java FirstProgram
Data Types
Java is a strongly typed language – every variable must have a declared type.
There are 8 primitive types in Java:-1)4 of them integer types2)2 floating-point types3)1 as character type4)1 as Boolean type
Integer types• These are for numbers without fractional parts. • Negative values are allowed
Floating-point types
• Numbers with fractional parts.
– Float – 4 bytes
– Double – 8 bytes
char type• Java uses the 16-bit Unicode characters
boolean type
The Boolean type has two values – true and false.
No type conversion b/w integers and Boolean values.
Variables• In Java, every variable has a type.
• Syntax:- type variablename;
• A variable name must begin with a letter and must be sequence of letters or digits – reserved words cannot be used.
• All characters in the name of a variable are significant and case is also significant.
Variables• The length of a variable name is unlimited.
• Uninitialized variables cannot be used.
• Variable declaration can be kept anywhere in
the code.
Constants
final keyword is used to denote a constant.
The constant variables are assigned once
and its value cannot be changed.
Its customary to name constants in all
uppercase.
E.g. final int YEAR = 2009;
Operators• Arithmetic operators:- +,- ,*,/,%,++,--.• Relational operators - &&,||,==,!==• Conditional ternary operator:- ?:• Bitwise operators:- &,|,^,~.
Mathematical Functions and constants
Like math.h in C, in Java Math class an assortment of mathematical functions. e.g. sqrt().
pow(),sin()…Usage:- Math.function();
Conversion b/w numeric types
• Explicit type conversion is done by means of cast.
• E.g double x=9.99; int y=(int) x;
Operator Precedence
• Self Study
Control Flow
• Like other programming langs, in Java, conditional
statements and the looping statements determine
control flow.
• A block or compound statement is any Java
statements that are surrounded by a pair of braces.
• Blocks define the scope of the variables.
Conditional Statements
Syntax of if statement:-if (condition) statement else statemente.g
if (marks>50) status = ‘P’;
else status = ‘F’;
Looping Statements
• while loop executes a statement while a condition is true.
• while loop tests at the top – entry control loop• Syntax
while(condition) statementint i=10;while(i>1){
System.out.println(i +") Amma ");i--;
}
Looping Statements• do..while loop executes the statement and
then only checks for the condition• do..while is an exit control loop.• Syntax:-
do statement while(condition);
• determinate loops:– the for loop is a general construct to support
iteration that is controlled by a counter that is updated after every iteration.for(counter initialization; condition; counter updating)
Multiple Selections
• Java has same switch stmt as C,C++.switch(choice)
{case 1:break;
case 2:break;default:break;
…}
• Case labels must be integers or enumerated constants, strings cannot be used.
Control Statements
Statements that break control flow:-o break o continue :- breaks the regular flow of
control – it transfers control to the header of the innermost enclosing loop.
o goto (no recommended to use)o labeled break – when multiple loops are
used
Arrays
• An array is a data structure that stores a
collection of values of the same type.
• Individual value is accessed through an
integer index
• E.g. if a is an array of integers, then a[i] is the
ith integer in the array.
Arrays
• Array declaration syntax:-
– datatype [] name or datatype name[]
– e.g. int [] marks;
– or int marks[];
• The above statement has only declared a variable.
• It has not been initialized/ created.
Arrays
• For this we have to use the new operator to
create the array.
• int [] a= new int[100];
• Index starts with 0; here a indexes from 0-99.
Arrays
• To find the number of elements of an array user
array.length.
• Once an array is created, its size cannot be changed.
• “for each” loop
– To traverse an entire collection the following can be used
– for(variable : collection) statement
Arrays
• for (int i : marks){
sum+=i;}
• Array initializationint[] a = {1,2,3,4,5};
• Array Sorting– Arrays.sort(arrayname);
Multidimensional array
• Datatype[][] name; //declaration
• Creation two ways:-– name= new type[5][5];
– or name=new type[5][]; //then each arrays can be created individually.
– E.g
int [][] t2D=new int[3][3];
or
int [][]t2D;
t2D=new int[3][];
for(int i=0;i<3;i++)
t2D[i]=new int[3];
• Multidimensional arrays are actually arrays of arrays.
Strings in Java
• Java strings are sequences of Unicode characters.• No built-in string type.• The std Java library contains a predefined class
called – String• Each quoted string is an instance of String class Java strings are implemented as
sequences of char values. String greeting = “Hello”;
– int n= greeting.length();
Strings
• Individual characters cannot be changed – instances of string are immutable.
• To concatenate two strings, use + operator.– String greeting =”Hello ”;– String greeting2 = “All!”;– String greeting 3 = greeting + greeting2 + “Welcome to
Java Learning” + 123;– When value to be concatenated is not a string, the latter
will be converted to a string automatically.
• More on Strings? Online Documentation
String• To compare two strings, use equals() method.– boolean status = greeting.equals(greeting2);– returns true if the strings are equal and false otherwise.– == operator cannot be used for comparison, as it checks
or not the strings are stored in the same location.– Other methods:-
• equalsIgnoreCase() – same as equals() but ignores the case of the letters
• compareTo() – works exactly same as strcmp() of C.• toLowerCase() – converts the string to lowercase.• toUpperCase() – converts the string to uppercase .
Command Line Arguments• Every Java program has a main method with
String[] args as parameter.• This parameter indicates that the main method
receives an array of strings, the arguments specified on the command line.
public class CommandLineTest{
public static void main(String [] args){
int s=args.length;System.out.println("Number of arguments:"
+ s);for(String a:args){
System.out.println(a);}
}}
Input and Output• First construct a Scanner (added in 5.0
version) that is attached to the std input stream System.in.Scanner in = new Scanner(System.in);
• You need to import the class using the import statement.
• Scanner is in java.util package• To import a class from package useimport package.Classname
Input and Outputimport java.util.Scanner;
public class InputTest
{
public static void main(String arg[])
{
Scanner in = new Scanner(System.in);
//String input
System.out.print("Name? ");
String name=in.nextLine();
System.out.println("Hello " + name + "!!");
//output to console
//Interger Input
System.out.print("Age? ");
int age=in.nextInt();
System.out.println("Hello " + name + "!!" + "\n You are "+ age + " years old!!");
}
}
Input and Output
• in.nextLine() will read line of input
• in.nextInt() will read and convert the next character sequence into integer.
• in.next() will read next word
• Displaying to the console System.out.println()
Input and Output
• Formatting output– System.out.printf() – is used formatting output – similar
to C’s printf().
– E.g. System.out.printf(“%8.2f”, x); -- 8 characters in float with 2 precision.
– There are many format specifiers that start with % and is replaced with the corresponding argument.
– Conversion character that ends a format specifier indicates the type of the value to be formatted.