Beruflich Dokumente
Kultur Dokumente
Introduction to Java
A language developed by Sun Microsystems A general-purpose language
High-level language
Developed initially for consumer devices Popular platform to develop enterprise applications
Finds use in internet based applications
Origins of Java
C and C++ have limitations in reliability and portability. e.g. size of data types. Java was developed by removing the sources of problems in C and C++ like pointers, multiple inheritance, array bounds etc. Milestones in history of Java 1990 Sun microsystems started developing the language to manipulate consumer electronic devices. It took 18 months to develop first working version. 1991 This language was named as Oak 1992 Demonstration of application to control home appliances 1993 Development in www. Transformation of text based internet into graphical-rich environment. Project on web applets that could run on all types of computers on internet. 1994 Development of web browser HotJava to run applets. Language became popular among internet users. 1995 Oak was renamed as Java. Netscape, Microsoft etc. announced support. 1996- JDK 1.0, 1997- JDK 1.1, 1998- SDK1.2, 1999- J2SE, J2EE, 2000- SDK 1.3, 2002- SDK 1.4, 2004- J2SE 5.0
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
recompilation
Dynamic and extensible- Dynamic linking of class libraries. Supports functions written in other languages (native methods).
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
applications distributed on networks. It can share both data and programs. This
enables multiple programmers at multiple locations to work together on a single project.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
Platform independence
Java is a language that is platform independent. A platform is the hardware and software environment in which a program runs Once compiled, code will run on any platform without recompiling or any kind of modification.
Write Once Run Anywhere
This is made possible by making use of a Java Virtual Machine commonly known as JVM
The interface that the JVM has to the .class file remains the same irrespective
of the underlying platform.
This makes platform independence possible
The JVM interprets the .class file to the machine language of the underlying
platform. The underlying platform processes the commands given by the JVM
Java Architecture:
JVM
Class Loader
Compiler (javac)
Interpreter
Operating System
Hardware
CLASSPATH
In Windows: set PATH=%PATH%;%JAVA_HOME%\lib\tools.jar;. In UNIX: set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.
PATH
Path variable is used by OS to locate executable files In Windows: set PATH=%PATH%;%JAVA_HOME%\bin In UNIX: set PATH=$PATH:$JAVA_HOME/bin
This approach helps in managing multiple versions of Java Changing JAVA_HOME will reflect on CLASSPATH and PATH as well Set these environment variables on the command prompt and type javac
Displays all the options of using javac
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
To Compile
Open a command prompt Set Environment variables (explained earlier)
If it does not say anything, and you get the prompt, then the compilation was
successful.
To execute
Type in the command prompt java HelloWorldApp
The result
Interpreter (java)
Interpreter (java)
Interpreter (java)
Win 32
Linux
Mac
Best Practices
One .java file must contain only one class declaration The name of the file must always be same as the name of the class
Stand alone Java program must have a public static void main defined
It is the starting point of the program Not all classes require public static void main
Code should be adequately commented Must follow indentation and coding standards
Java Tokens
Java program is a collection of tokens, comments and white spaces Tokens are of five types
- Reserved keywords
- Identifiers - Literals
- Operators
- Separators
Literals They are constants (represent constant values) Five types of literals
- Integer literals
- Floating point literals - Character literals
- String literals
- Boolean literals Operators It is a symbol that takes arguments Example Arithmetic operators are + - / * etc. Separators Symbols used to indicate where groups of code are divided Example - ( ) { } [ ] , ; .
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
Notes:
All numeric data types are signed The size of data types remain the same on all platforms (standardized) char data type in Java is 2 bytes because it uses UNICODE character set. By virtue of it, Java supports internationalization UNICODE is a character set which covers all known scripts and language in the world
Floating Type
float (4 bytes)
double (8 bytes)
Textual
char (2 bytes)
Logical
boolean (1 byte) (true/false)
Variables in Java
Using primitive data types is similar to other languages
int count; //Declaration count = 10; //Assignment operation
BEST PRACTICE: Declare a variable in program only when required. Do not declare variables upfront like in C.
In Java, if a local variable is used without initializing it, the compiler will show an error
Give it a try.
What will be the output of the following code snippet when you try to compile and run it?
class Sample{ public static void main (String args[]){ int count; System.out.println(count); } }
Whenever a larger type is converted to a smaller type, we have to explicitly specify the type cast operator
double d = 10 int i; i = (int) d; This prevents accidental loss of data
Type cast operator
Other Special operators : Increment operator ++ Decrement operator -Compound assignment operators += The Bitwise operators: & ! ^ ~ -= << *= >> /= >>> %=
in the division.
If left hand side variable of the assignment statement is integer, the though the right hand side expression is resulting into real number, decimal part will be truncated while assigning the value. e.g. Consider the following assignment statement : avg = (m1+m2+m3) / 3.0 ; where avg, m1, m2, m3 are int
avg will be assigned integer value and decimal part evaluated in right hand side value will be ignored. If avg is float or double, decimal part will be stored.
Relational operators
Following are the relational operators in java with sequence of precedence and meaning as given : < less than <= less than or equal to > greater than >= greater than or equal to == equal to != not equal to A simple relational expression contains a relational operator with one operand on each side left and right as follows exp1 relational-operator exp2 where exp1 and exp2 are arithmetic expressions which may be variables, constants or combination of them. The arithmetic expressions will be evaluated first and then the results will be compared to return true or false. e.g. (5+2) > (10-4) will return true a==b will return false if value of variable a is not equal to value of variable b
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
Logical Operators
Following are the logical operators in java with their precedence, symbols and meanings as given Symbol Meaning ! NOT (Logical complement operator) && AND || OR They are used to form combination of conditions / relational expressions e.g. a>b && a>c A logical expression results in value true or false according to the truth table as Operand1 Operand2 && || ! true true true true !(true) is false true false false true !(false) is true false true false true e.g. !(5>2) is true false false false false The ! (Not) operator will invert the logical value of the operand next to it.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
++a
b=a++;
Here b will be assigned value of a as 5 and then value of a will be incremented by 1. Hence after execution, b will hold value 5 and a will hold 6. But if a=5; b=++a;
then after execution, b will hold value 6 and a will hold value 6
because pre-increment will increment the value first and then will assign
a=a+5
can be written as
b=b-2
m=m*n
can be written as
can be written as
b-=2
m*=n
and so on
What appears on left-hand side need not be repeated and becomes easy to write
The statement is more concise and easier to read Use of shorthand operator results in a more efficient code
value of flag will be 2*x-5 if x is greater than 10, otherwise flag will be 2*x + 10 Though this is equivalent to an ifelse statement, the limitation is that there can be only one statement each in the form of expression1 and expression2. Whereas in ifelse, we can have any number of statement in if block and else block. Advantage of ? : is that it is more concise to understand.
Operator Precedence
Operators Postfix Unary Multiplicative Additive Shift Relational Equality logical AND logical OR Ternary Assignment Precedence expr++ expr ++expr --expr +expr -expr ~ ! * / % + << >> >>> < > <= >= instanceof == != && || ?: = += -= *= /= %=
Control Statements
The syntax of the control statements in Java are very similar to those of C language
if
if-else for while do-while switch break continue
Java Control statements control the order of execution in a java program, based on data values and conditional logic. There are three main categories of
Transfer statements:
We use control statements when we want to change the default sequential order of execution
if Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues
with the rest of the program. You can either have a single statement or a block
of code (enclosed in curly braces) within an if statement. Note that the conditional expression must be a Boolean expression. The simple if statement has the following syntax: if (<conditional expression>) <statement action> Example : int a = 10, b = 20; if (a > b) System.out.println("a > b");
if else Statement
The if/else statement is an extension of the if statement. If the condition in the if statement fails (is false), the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note
expression that equates to a non-long integral value. Following the controlling expression
is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block (until it finds a break statement). If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch.
ER/CORP/CRS/LA10SC/003 Version 1.00
case expression1:
<statement>; case expression2: <statement>;
...
... case expression_n: <statement>;
default:
<statement>; } // end switch
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
In switch statement only integer expressions are allowed for condition and
case. If you want to test on real number value, you cannot use switch. You cannot have specification of range for a particular case. For example, if you want to execute a block for the value of range between 1 to 100, another block for the value of range between 101 to 150 etc., switch is not suitable, you should use if. If the application is suitable for switch-case, then switch-case will be more
efficient than the equivalent if-else codes. It will also look more precise and
easy to understand the logic.
block of code while a condition is true. You can either have a single statement
or a block of code within the while loop. The loop will never be executed if the testing expression evaluates to false. The loop condition must be a boolean expression. The body of the loop is executed repeatedly until the condition becomes false i.e. every time before the iteration, the condition is checked and the body is executed only if condition is true. The syntax of the while loop is
do while loop
The do-while loop is similar to the while loop, except that the test is performed at the end of the loop instead of at the beginning. This ensures that the loop will be executed at least once (even if the condition is false). A do-while loop begins with the keyword do, followed by the statements that make up the body of the loop. Finally, the keyword while and the test expression completes the do-while loop. When the loop condition becomes false, the loop is terminated and execution continues with the statement immediately
following the loop. You can either have a single statement or a block of code within the
do-while loop. The syntax of the do-while loop is do <loop body> while (<loop condition>);
for loop
The for loop is a looping construct which can execute a set of instructions a specified number of times. Its a counter controlled loop. The syntax of the loop is as follows: for (<initialization>; <loop condition>; <increment/decrement expression>) { loop body } The first part of a for statement is a starting initialization, which executes once before the loop begins. The <initialization> section can also be a comma-separated list of expression statements. The second part of a for statement is a test expression. As long as the expression is true, the loop will continue. If this expression is evaluated as false the first time, the loop will never be executed. The third part of the for statement is the body of the loop. These are the instructions that are repeated each time the program executes the loop. The final part of the for statement is an increment expression that automatically executes after each repetition of the loop body. Typically, this statement changes the value of the counter, which is then tested to see if the loop should continue.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
System.out.println(count);
}
Like the initialization section, the increment/decrement section may also have more than one part separated by comma. e.g. for ( n=1, m=10; n<m; n++,m--) A compound test condition can be used e.g. for(i=1, i<10 && j>5; ++i) The initialization and increment part can have any arithmetic expression.
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
The break statement transfers control out of the enclosing loop ( for, while, do
or switch statement). You use a break statement when you want to jump immediately to the statement following the enclosing control structure. You can also provide a loop with a label, and then use the label in your break statement. The label name is optional, and is usually only used when you wish to terminate the outermost loop in a series of nested loops. The Syntax for break statement is as shown below; break; // the unlabeled form break <label>; // the labeled form
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
break;
// Rest of loop body skipped when i is 11 System.out.println(i + "\t");
continue statement when you do not want to execute the remaining statements
in the loop, but you do not want to exit the loop itself. The syntax of the continue statement is continue; // the unlabeled form continue <label>; // the labeled form You can also provide a loop with a label and then use the label in your continue statement. The label name is optional, and is usually only used when you wish to return to the outermost loop in a series of nested loops.
continue;
// Rest of loop body skipped when i is even System.out.println(i + "\t");
Nesting of loops
Any type of loop can be nested with the same type of loop or any other type of loop.
If a break statement is used in the inner loop, the control will go to the outer
loop at the place just after the completion of inner loop body. The loops should be properly indented so as to enable the reader to easily
Methods
The syntax of writing a method in Java is similar to that of a function in C language Java being an object oriented language will not permit the user to write a global
void add (int a, int b) void add (int a, float b) void add (float a, int b) void add (int a, int b, float c)
Arrays in Java
An array is a data structure that defines an ordered collection of a fixed number of homogeneous data elements
The size of an array (number of elements in the array) is fixed and cannot
increase to accommodate more elements Any element of the array can be accessed randomly using name of the array
Any one of the following syntax can be used to create a reference to an int
array
int x[]; int [] x;
A pointer has to be dereferenced using the * operator to get the value pointed by it
A reference is automatically dereferenced to give the data referred by it and no special operator is required for this
int [] x = null;
Classes in Java
The following example shows the syntax of a class in Java
public class Student { private int rollNo; private char grade; public int getRollNo (){ return rollNo; } public void printGrade(){ System.out.println(grade); } }
Methods (Behavior)
The main method may or may not be present depending on whether the class
is a starter class
The methods which expose the behavior of the object are kept public
However, we can have helper methods which are private
Access modifiers (public, private etc) will be covered in more details in the later slides
The reference s can be used for referring to any object of type Student
//Declare a reference to class Student Student s; //Create a new Student object and make s refer to the object s = new Student();
Constructors (1/4)
A constructor is a special method that is called to create a new object Calling the constructor Student s = new Student(); It is not mandatory for the coder to write a constructor for the class If no user defined constructor is provided for a class, compiler initializes member variables to its default values.
numeric data types are set to 0 char data types are set to null character(\0) boolean data types are set to false reference variables are set to null
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
Constructors (2/4)
The coder can also write a constructor in a class, if required The user defined constructor is mostly used to initialize the data members of
Constructors (3/4)
public class Counter { private int count; public Counter(){ User Defined Constructor
count = 1;
} //Other Methods } In the above example, the user defined constructor initializes count to 1 Counter c = new Counter(); //c.count is initialized to 1
Constructors (4/4)
The constructor without any parameter is called a default constructor Just like other methods, constructors also can be overloaded
public class Counter { private int count; public Counter(){ count = 1; } public Counter(int x){ count = x; } //Other Methods } Counter c1 = new Counter(); //c1.count is initialized to 1 Counter c2 = new Counter(5); //c2.count is initialized to 5
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
Data members of the class are stored in the heap along with the object. Their lifetime depends on the lifetime of the object
Local variables x and y are stored in the Stack Local variable a is stored in the Stack
Lifetime of objects (1 of 2)
obj1
heap 2
-- Objects: 2
obj1
-- Objects: 2
obj2
Lifetime of objects (2 of 2)
obj1
-- Objects: 2
obj2
obj2 = null;
-- Active References: 2
obj1
-- Abandoned objects: 1
Null reference obj2
Garbage Collection
In C language, it is the programmers responsibility to de-allocate memory allocated dynamically
free() function is used to de-allocate
An object which is not referred by any reference variable is removed from memory by the garbage collector Primitive types are not objects. They cannot be assigned null
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00
Array of Objects
An array of objects is created as follows Student [] x = new Student[3]; //3 Student references x[0], x[1] and x[2] are created //All 3 references are null for(int i = 0; i < x.length; ++i){ x[i] = new Student(); //Creating Student object }
private float real; private float imaginary; Complex add(Complex x){ Complex z = new Complex(); z.real = real + x.real; z.imaginary = imaginary + x.imaginary; return z; } public void read(){ //Read real and imaginary //from the keyboard }
}
For methods
For a block of code
of Students
The data member that holds the total number of students is common to the entire class
The static variable is initialized to 0, ONLY when the class is first loaded, NOT each time a new instance is made
Each time the constructor is invoked and an object gets created, the static variable total will be incremented thus keeping a count of the total no of Student objects created
ER/CORP/CRS/LA10SC/003 Version 1.00
return total;
} }
System.out.println(Student.getTotal());
//Prints 1 Student s2 = new Student(); System.out.println(Student.getTotal()); //Prints 2 Another example : y = Math.sqrt(x) ; // Math is a class in java.lang package and sqrt is a static method in it.
(Non static methods can access static members but static methods can
access only static members)
A static block helps to initialize the static data members just like constructors help to initialize instance members
ER/CORP/CRS/LA10SC/003 Version 1.00
Name should tell what the variable, method or class does No short form of words Variable name should start with lower case and to follow camel casing
Eg. int numberOfStudents;
Method names should begin with lowercase and follow camel casing
Eg. void displayUserChoice()
/* This java file contains a class with a method to compute the * Sum of two numbers. This method is invoked from another class * by passing the necessary values as parameters */
@param
@return Note: Do not type method name in header
/** * Computes the sum of the two integer variables passed * as parameters * @param number1 The First number * @param number2 The Second number * @return the sum of the two numbers passed as arguments */
Strings in Java
Unlike C, String is a system defined class in Java Declaring Hello World in code will create an object of type string with data Hello World and returns a reference to it. System.out.println(Hello World); Unlike C, the string is of fixed length and memory for the string is managed totally by the String class
Prevents buffer overruns (checks bounds) NULL terminator not used in strings
Unlike C, String is not a simple array of characters. They are objects of class
Arrays of strings
Example : String itemArray = new String[5] ;
s2 = s1.toLowerCase
s2 = s1.toLowerCase s1.equals(s2)
converts s1 to lowercase
converts s1 to uppercase returns true if s1 equals s2
Thank You
Copyright 2005, Infosys Technologies Ltd # ER/CORP/CRS/LA10SC/003 Version 1.00